file_id
stringlengths
4
10
content
stringlengths
91
42.8k
repo
stringlengths
7
108
path
stringlengths
7
251
token_length
int64
34
8.19k
original_comment
stringlengths
11
11.5k
comment_type
stringclasses
2 values
detected_lang
stringclasses
1 value
prompt
stringlengths
34
42.8k
206486_10
package KBS_ICTM2n4; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; // Structure van de JSON file is als volgt: 1 Array, met daarin 6 Objects (voor elke server 1 object). // In elke serverObject zitten twee waardes, 'Amount' en 'Name'. Amount is aantal van die server, // name is de naam van die server. De volgorde van de servers is altijd gelijk DB1-DB2-DB3-WB1-WB2-WB3. public class ReadJson { // method voor het ophalen van de aantallen van de servers, heeft een designName nodig dat // overeenkomt met een file naam. public static int[] readDesign(String designName) { JSONParser jsonParser = new JSONParser(); int[] returnArray = new int[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { int counter = 0; // De file word geparsed naar een object en vervolgens naar een JSONArray // gemaakt. Object obj = jsonParser.parse(reader); JSONArray serverList = (JSONArray) obj; // For loop om door alle objects in de JSON file te gaan for (Object object : serverList) { // Verwijst naar de method die onderaan staat. int amount = parseServerObject((JSONObject) object); returnArray[counter] = amount; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // method voor het ophalen van alle file names, heeft een designName nodig dat // overeenkomt met een file naam. public static String[] readDesignNames(String designName) { JSONParser jsonParser = new JSONParser(); String[] returnArray = new String[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { Object obj = jsonParser.parse(reader); int counter = 0; JSONArray serverList = (JSONArray) obj; for (Object object : serverList) { String name = parseServerObject2((JSONObject) object); returnArray[counter] = name; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } public static String readServer(String servername, String data) { JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("src/savedServers/" + servername + ".json")) { Object obj = jsonParser.parse(reader); if(data.equals("name")){ String name = parseServerName((JSONObject) obj); return name; } else if(data.equals("ip")){ String ip = parseServerIp((JSONObject) obj); return ip; } else if(data.equals("password")){ String password = parseServerPassword((JSONObject) obj); return password; } else if(data.equals("hostname")){ String hostname = parseServerHostname((JSONObject) obj); return hostname; } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // Method om amount op te halen van Server Object in de file. private static int parseServerObject(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); return amount; } // Method om name op te halen van Server Object in de file. private static String parseServerObject2(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); if (amount != 0) { String name = (String) serverObject.get("name"); return name; } return null; } private static String parseServerName(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("name"); return name; } private static String parseServerIp(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("ip"); return name; } private static String parseServerPassword(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("password"); return name; } private static String parseServerHostname(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("hostname"); return name; } }
Milciwee/KBS_ICTM2n4
src/main/java/KBS_ICTM2n4/ReadJson.java
1,350
// Method om amount op te halen van Server Object in de file.
line_comment
nl
package KBS_ICTM2n4; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; // Structure van de JSON file is als volgt: 1 Array, met daarin 6 Objects (voor elke server 1 object). // In elke serverObject zitten twee waardes, 'Amount' en 'Name'. Amount is aantal van die server, // name is de naam van die server. De volgorde van de servers is altijd gelijk DB1-DB2-DB3-WB1-WB2-WB3. public class ReadJson { // method voor het ophalen van de aantallen van de servers, heeft een designName nodig dat // overeenkomt met een file naam. public static int[] readDesign(String designName) { JSONParser jsonParser = new JSONParser(); int[] returnArray = new int[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { int counter = 0; // De file word geparsed naar een object en vervolgens naar een JSONArray // gemaakt. Object obj = jsonParser.parse(reader); JSONArray serverList = (JSONArray) obj; // For loop om door alle objects in de JSON file te gaan for (Object object : serverList) { // Verwijst naar de method die onderaan staat. int amount = parseServerObject((JSONObject) object); returnArray[counter] = amount; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // method voor het ophalen van alle file names, heeft een designName nodig dat // overeenkomt met een file naam. public static String[] readDesignNames(String designName) { JSONParser jsonParser = new JSONParser(); String[] returnArray = new String[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { Object obj = jsonParser.parse(reader); int counter = 0; JSONArray serverList = (JSONArray) obj; for (Object object : serverList) { String name = parseServerObject2((JSONObject) object); returnArray[counter] = name; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } public static String readServer(String servername, String data) { JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("src/savedServers/" + servername + ".json")) { Object obj = jsonParser.parse(reader); if(data.equals("name")){ String name = parseServerName((JSONObject) obj); return name; } else if(data.equals("ip")){ String ip = parseServerIp((JSONObject) obj); return ip; } else if(data.equals("password")){ String password = parseServerPassword((JSONObject) obj); return password; } else if(data.equals("hostname")){ String hostname = parseServerHostname((JSONObject) obj); return hostname; } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // Method om<SUF> private static int parseServerObject(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); return amount; } // Method om name op te halen van Server Object in de file. private static String parseServerObject2(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); if (amount != 0) { String name = (String) serverObject.get("name"); return name; } return null; } private static String parseServerName(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("name"); return name; } private static String parseServerIp(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("ip"); return name; } private static String parseServerPassword(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("password"); return name; } private static String parseServerHostname(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("hostname"); return name; } }
206486_11
package KBS_ICTM2n4; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; // Structure van de JSON file is als volgt: 1 Array, met daarin 6 Objects (voor elke server 1 object). // In elke serverObject zitten twee waardes, 'Amount' en 'Name'. Amount is aantal van die server, // name is de naam van die server. De volgorde van de servers is altijd gelijk DB1-DB2-DB3-WB1-WB2-WB3. public class ReadJson { // method voor het ophalen van de aantallen van de servers, heeft een designName nodig dat // overeenkomt met een file naam. public static int[] readDesign(String designName) { JSONParser jsonParser = new JSONParser(); int[] returnArray = new int[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { int counter = 0; // De file word geparsed naar een object en vervolgens naar een JSONArray // gemaakt. Object obj = jsonParser.parse(reader); JSONArray serverList = (JSONArray) obj; // For loop om door alle objects in de JSON file te gaan for (Object object : serverList) { // Verwijst naar de method die onderaan staat. int amount = parseServerObject((JSONObject) object); returnArray[counter] = amount; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // method voor het ophalen van alle file names, heeft een designName nodig dat // overeenkomt met een file naam. public static String[] readDesignNames(String designName) { JSONParser jsonParser = new JSONParser(); String[] returnArray = new String[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { Object obj = jsonParser.parse(reader); int counter = 0; JSONArray serverList = (JSONArray) obj; for (Object object : serverList) { String name = parseServerObject2((JSONObject) object); returnArray[counter] = name; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } public static String readServer(String servername, String data) { JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("src/savedServers/" + servername + ".json")) { Object obj = jsonParser.parse(reader); if(data.equals("name")){ String name = parseServerName((JSONObject) obj); return name; } else if(data.equals("ip")){ String ip = parseServerIp((JSONObject) obj); return ip; } else if(data.equals("password")){ String password = parseServerPassword((JSONObject) obj); return password; } else if(data.equals("hostname")){ String hostname = parseServerHostname((JSONObject) obj); return hostname; } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // Method om amount op te halen van Server Object in de file. private static int parseServerObject(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); return amount; } // Method om name op te halen van Server Object in de file. private static String parseServerObject2(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); if (amount != 0) { String name = (String) serverObject.get("name"); return name; } return null; } private static String parseServerName(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("name"); return name; } private static String parseServerIp(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("ip"); return name; } private static String parseServerPassword(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("password"); return name; } private static String parseServerHostname(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("hostname"); return name; } }
Milciwee/KBS_ICTM2n4
src/main/java/KBS_ICTM2n4/ReadJson.java
1,350
// Method om name op te halen van Server Object in de file.
line_comment
nl
package KBS_ICTM2n4; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; // Structure van de JSON file is als volgt: 1 Array, met daarin 6 Objects (voor elke server 1 object). // In elke serverObject zitten twee waardes, 'Amount' en 'Name'. Amount is aantal van die server, // name is de naam van die server. De volgorde van de servers is altijd gelijk DB1-DB2-DB3-WB1-WB2-WB3. public class ReadJson { // method voor het ophalen van de aantallen van de servers, heeft een designName nodig dat // overeenkomt met een file naam. public static int[] readDesign(String designName) { JSONParser jsonParser = new JSONParser(); int[] returnArray = new int[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { int counter = 0; // De file word geparsed naar een object en vervolgens naar een JSONArray // gemaakt. Object obj = jsonParser.parse(reader); JSONArray serverList = (JSONArray) obj; // For loop om door alle objects in de JSON file te gaan for (Object object : serverList) { // Verwijst naar de method die onderaan staat. int amount = parseServerObject((JSONObject) object); returnArray[counter] = amount; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // method voor het ophalen van alle file names, heeft een designName nodig dat // overeenkomt met een file naam. public static String[] readDesignNames(String designName) { JSONParser jsonParser = new JSONParser(); String[] returnArray = new String[6]; try (FileReader reader = new FileReader("src/savedDesigns/" + designName + ".json")) { Object obj = jsonParser.parse(reader); int counter = 0; JSONArray serverList = (JSONArray) obj; for (Object object : serverList) { String name = parseServerObject2((JSONObject) object); returnArray[counter] = name; counter++; } return returnArray; } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } public static String readServer(String servername, String data) { JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("src/savedServers/" + servername + ".json")) { Object obj = jsonParser.parse(reader); if(data.equals("name")){ String name = parseServerName((JSONObject) obj); return name; } else if(data.equals("ip")){ String ip = parseServerIp((JSONObject) obj); return ip; } else if(data.equals("password")){ String password = parseServerPassword((JSONObject) obj); return password; } else if(data.equals("hostname")){ String hostname = parseServerHostname((JSONObject) obj); return hostname; } } catch (FileNotFoundException e) { System.out.println("File not found"); } catch (IOException e) { System.out.println("Invalid permissions"); } catch (ParseException e) { System.out.println("Parsing went wrong"); } return null; } // Method om amount op te halen van Server Object in de file. private static int parseServerObject(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); return amount; } // Method om<SUF> private static String parseServerObject2(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); int amount = ((Number) serverObject.get("amount")).intValue(); if (amount != 0) { String name = (String) serverObject.get("name"); return name; } return null; } private static String parseServerName(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("name"); return name; } private static String parseServerIp(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("ip"); return name; } private static String parseServerPassword(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("password"); return name; } private static String parseServerHostname(JSONObject server) { JSONObject serverObject = (JSONObject) server.get("server"); String name = (String) serverObject.get("hostname"); return name; } }
206502_0
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/CarResource.java
655
/** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een<SUF>*/ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
206502_1
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/CarResource.java
655
/** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request<SUF>*/ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
206502_3
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/CarResource.java
655
/** * Http delete request om auto's aan de hand van hun * licenceplate te verwijderen. * @param licencePlate * @author Tom */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.services.CarService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/car") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class CarResource { private CarService service; public CarResource(CarService service) { this.service = service; } //POST FUNCTIES /** * Post-request om een Auto aan te maken * @param json JSON-file met daarin de definitie v/d auto. * @return nieuw auto object */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Car createCar(final CarJSON json) { Car c = new Car( json.licencePlate, json.ownerID, json.carName, json.carBrand, json.carType, json.carColor, json.fuelType); return service.save(c); } //GET FUNCTIES /** * Http get request om auto per kentekenplaat op te zoeken. * @param licencePlate * @return auto * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarByLicence/"+"{licencePlate}") public Car getCarByLicence(@PathParam("licencePlate") String licencePlate) { return service.getCarByLicence(licencePlate); } /** * Http get request om alle auto's per ownerID op te vragen * @param ownerID * @return ArrayList met alle auto's * @author Ole */ @GET @Produces("application/json") @UnitOfWork @Path("/getCarsByOwnerID/" + "{ownerID}") public ArrayList<Car> getCarsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getCarsByOwnerID(ownerID); } /** * Http delete request<SUF>*/ @DELETE @UnitOfWork @Path("/delete/" + "{licencePlate}") public void deleteCarByLicence(@PathParam("licencePlate") String licencePlate) { service.deleteCarByLicence(licencePlate); } }
206503_0
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ClientResource.java
629
/** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request<SUF>*/ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
206503_1
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ClientResource.java
629
/** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om<SUF>*/ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
206503_2
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ClientResource.java
629
/** * Http delete request om klanten aan de hand van hun * id te verwijderen. * @param clientName * @author Tom */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.db.ClientDAO; import com.DigitaleFactuur.json.CarJSON; import com.DigitaleFactuur.json.ClientJSON; import com.DigitaleFactuur.models.Car; import com.DigitaleFactuur.models.Client; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.google.common.base.Optional; import com.mysql.cj.MysqlConnection; import io.dropwizard.auth.Auth; import io.dropwizard.hibernate.UnitOfWork; import io.dropwizard.jersey.params.IntParam; import io.dropwizard.jersey.params.LongParam; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.sql.SQLException; import java.util.List; @Path("/client") //https://localhost:8443/client @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ClientResource { private ClientService service; public ClientResource(ClientService service) { this.service = service; } /** * Http get request om auto per klantnaam op te zoeken. * @param clientName * @return client * @author Richard */ @GET @Path("/get/" + "{clientName}") @Produces("application/json") @UnitOfWork public Client getClientByName(@PathParam("clientName") String clientName){ return service.getClientByName(clientName); } /** * Post request om een Klant aan te maken * @param json - JSON-file met daarin de definitie v/d klant. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Client saveClient(final ClientJSON json) { Client c = new Client( json.ownerID, json.clientName, json.clientPostalCode, json.clientHouseNumber, json.clientCity, json.clientCountry ); return service.save(c); } /** * Http delete request<SUF>*/ @DELETE @UnitOfWork @Path("/deleteClientByName/" + "{clientName}") public void deleteClientByName(@PathParam("clientName") String clientName) { service.deleteClientByName(clientName); } }
206505_0
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ProjectResource.java
639
/** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om<SUF>*/ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
206505_1
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ProjectResource.java
639
/** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request<SUF>*/ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
206505_3
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/resources/ProjectResource.java
639
/** * Http delete request om projecten aan de hand van hun * projectnaam te verwijderen. * @param projectName * @author Tom */
block_comment
nl
package com.DigitaleFactuur.resources; import com.DigitaleFactuur.json.ProjectJSON; import com.DigitaleFactuur.json.UserJSON; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.DigitaleFactuur.services.ClientService; import com.DigitaleFactuur.services.ProjectService; import io.dropwizard.hibernate.UnitOfWork; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import java.util.ArrayList; @Path("/project") //https://localhost:8443/declaration @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public class ProjectResource { private ProjectService service; public ProjectResource(ProjectService service) { this.service = service; } /** * Post request om een Project aan te maken * @param json - JSON-file met daarin de definitie v/d project. * @author Richard */ @POST @Consumes("application/json") @UnitOfWork @Path("/create") public Project saveUser(final ProjectJSON json) { Project p = new Project(json.ownerID, json.projectName, json.projectDesc, json.projectStartDate, json.projectEndDate); return service.save(p); } /** * Http get request om project per projectnaam op te zoeken. * @param projectName * @return project * @author Richard */ @GET @Path("/get/" + "{projectName}") @Produces("application/json") @UnitOfWork public Project getProjectByName(@PathParam("projectName") String projectName){ return service.getProjectByName(projectName); } /** * Http get request om alle projecten per ownerID op te vragen * @param ownerID * @return ArrayList met alle projecten * @author Richard */ @GET @Produces("application/json") @UnitOfWork @Path("/getProjectsByOwnerID/" + "{ownerID}") public ArrayList<Project> getProjectsByOwnerID(@PathParam("ownerID") int ownerID){ return service.getProjectsByOwnerID(ownerID); } /** * Http delete request<SUF>*/ @DELETE @UnitOfWork @Path("/deleteProjectByName/" + "{projectName}") public void deleteProjectByName(@PathParam("projectName") String projectName) { service.deleteProjectByName(projectName); } }
206506_1
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/CarDAO.java
898
/** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */
block_comment
nl
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit<SUF>*/ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
206506_2
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/CarDAO.java
898
/** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */
block_comment
nl
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v.<SUF>*/ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
206506_3
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/CarDAO.java
898
/** * Get alle auto's die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van de auto * @return ArrayList met daarin alle auto's * @author Ole */
block_comment
nl
package com.DigitaleFactuur.db; import com.google.common.base.Optional; import com.DigitaleFactuur.models.Car; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import java.sql.*; import java.util.ArrayList; public class CarDAO extends AbstractDAO<Car> { Connection con; public CarDAO(SessionFactory sessionFactory) { super(sessionFactory); } //GETCAR BY LICENCE private String SQLgetCarByLicence(String licence){ return "SELECT * FROM car WHERE licencePlate = '" + licence+ "'"; } private String SQLgetCarsByOwnerID(int ownerID){ return "SELECT * FROM car WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteCarByLicence(String licence){ return "DELETE FROM car WHERE licencePlate='" + licence + "';"; } public Optional<Car> findByID(long id) { return Optional.fromNullable(get(id)); } public Car save(Car car) { return persist(car); } /** * Delete car uit de database aan de hand van een * prepared SQl Statement waarin de auto zijn * licenceplate meegegeven wordt. * @param licence * @author Tom */ public void deleteCarByLicence(String licence) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteCarByLicence(licence)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } /** * Get car d.m.v. het kentekenplaat op te zoeken. * @param licencePlate - kentekenplaat * @return auto * @author Ole */ public Car getCarByLicence(String licencePlate){ Car requestedCar = new Car("a", "a", "a", "a", "a", "a"); try{ con = DatabaseConnector.getConnection(); String getCarByLicencecePlate = SQLgetCarByLicence(licencePlate); PreparedStatement getCarByLicencePlate = con.prepareStatement(getCarByLicencecePlate); ResultSet rs = getCarByLicencePlate.executeQuery(); if (rs.next()){ requestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); } }catch(SQLException e){ } return requestedCar; } /** * Get alle auto's<SUF>*/ public ArrayList<Car> getCarsByOwnerID(int ownerID){ ArrayList<Car> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getCarsByOwnerID = SQLgetCarsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getCarsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Car reqeuestedCar = new Car( rs.getString("licencePlate"), rs.getString("carName"), rs.getString("carBrand"), rs.getString("carType"), rs.getString("carColor"), rs.getString("fuelType")); autos.add(reqeuestedCar); } }catch(SQLException e){ } return autos; } }
206514_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin de classes die nodig zijn voor het afleiden van de A-laag. */ package nl.bzk.algemeenbrp.dal.domein.brp.alaag;
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/algemeen/alg-dal-entiteiten/src/main/java/nl/bzk/algemeenbrp/dal/domein/brp/alaag/package-info.java
137
/** * Package met daarin de classes die nodig zijn voor het afleiden van de A-laag. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin<SUF>*/ package nl.bzk.algemeenbrp.dal.domein.brp.alaag;
206516_0
package com.DigitaleFactuur.db; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.google.common.base.Optional; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import java.sql.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; public class ProjectDAO extends AbstractDAO<Project> { Connection con; public ProjectDAO(SessionFactory sessionFactory) { super(sessionFactory); } private String SQLgetProjectByName(String name){ return "SELECT * FROM project WHERE projectName = '" + name+ "'"; } private String SQLgetProjectsByOwnerID(int ownerID){ return "SELECT * FROM project WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteProjectByName(String projectName){ return "DELETE FROM project WHERE projectName='" + projectName + "';"; } public Optional<Project> findByID(long id) { return Optional.fromNullable(get(id)); } public Project save(Project project) { return persist(project); } public void delete(Project client) { namedQuery("com.udemy.core.Client.remove") .setParameter("id", client.getProjectID()) .executeUpdate(); } /** * Get project d.m.v. de projectnaam op te zoeken. * @param projectName - projectnaam * @return project * @author Richard */ public Project getProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); String getProjectByProjectNameStatement = SQLgetProjectByName(projectName); PreparedStatement getProjectByProjectName = con.prepareStatement(getProjectByProjectNameStatement); ResultSet result = getProjectByProjectName.executeQuery(); while (result.next()) { // DateTime projectStartDateTime = new DateTime(result.getDate("projectStartDate")); // DateTime projectEndDateTime = new DateTime(result.getDate("projectEndDate")); Project project = new Project( result.getString("projectName"), result.getString("projectDesc"), result.getString("projectStartDate"), result.getString("projectEndDate")); return project; } }catch(SQLException e) { } return null; } /** * Get alle projecten die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van het project * @return ArrayList met daarin alle projecten * @author Richard */ public ArrayList<Project> getProjectsByOwnerID(int ownerID){ ArrayList<Project> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getProjectsByOwnerID = SQLgetProjectsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getProjectsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Project requestedProject = new Project( rs.getString("projectName"), rs.getString("projectDesc"), rs.getString("projectStartDate"), rs.getString("projectEndDate")); autos.add(requestedProject); } }catch(SQLException e){ } return autos; } public void deleteProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteProjectByName(projectName)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/ProjectDAO.java
889
/** * Get project d.m.v. de projectnaam op te zoeken. * @param projectName - projectnaam * @return project * @author Richard */
block_comment
nl
package com.DigitaleFactuur.db; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.google.common.base.Optional; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import java.sql.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; public class ProjectDAO extends AbstractDAO<Project> { Connection con; public ProjectDAO(SessionFactory sessionFactory) { super(sessionFactory); } private String SQLgetProjectByName(String name){ return "SELECT * FROM project WHERE projectName = '" + name+ "'"; } private String SQLgetProjectsByOwnerID(int ownerID){ return "SELECT * FROM project WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteProjectByName(String projectName){ return "DELETE FROM project WHERE projectName='" + projectName + "';"; } public Optional<Project> findByID(long id) { return Optional.fromNullable(get(id)); } public Project save(Project project) { return persist(project); } public void delete(Project client) { namedQuery("com.udemy.core.Client.remove") .setParameter("id", client.getProjectID()) .executeUpdate(); } /** * Get project d.m.v.<SUF>*/ public Project getProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); String getProjectByProjectNameStatement = SQLgetProjectByName(projectName); PreparedStatement getProjectByProjectName = con.prepareStatement(getProjectByProjectNameStatement); ResultSet result = getProjectByProjectName.executeQuery(); while (result.next()) { // DateTime projectStartDateTime = new DateTime(result.getDate("projectStartDate")); // DateTime projectEndDateTime = new DateTime(result.getDate("projectEndDate")); Project project = new Project( result.getString("projectName"), result.getString("projectDesc"), result.getString("projectStartDate"), result.getString("projectEndDate")); return project; } }catch(SQLException e) { } return null; } /** * Get alle projecten die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van het project * @return ArrayList met daarin alle projecten * @author Richard */ public ArrayList<Project> getProjectsByOwnerID(int ownerID){ ArrayList<Project> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getProjectsByOwnerID = SQLgetProjectsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getProjectsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Project requestedProject = new Project( rs.getString("projectName"), rs.getString("projectDesc"), rs.getString("projectStartDate"), rs.getString("projectEndDate")); autos.add(requestedProject); } }catch(SQLException e){ } return autos; } public void deleteProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteProjectByName(projectName)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
206516_3
package com.DigitaleFactuur.db; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.google.common.base.Optional; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import java.sql.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; public class ProjectDAO extends AbstractDAO<Project> { Connection con; public ProjectDAO(SessionFactory sessionFactory) { super(sessionFactory); } private String SQLgetProjectByName(String name){ return "SELECT * FROM project WHERE projectName = '" + name+ "'"; } private String SQLgetProjectsByOwnerID(int ownerID){ return "SELECT * FROM project WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteProjectByName(String projectName){ return "DELETE FROM project WHERE projectName='" + projectName + "';"; } public Optional<Project> findByID(long id) { return Optional.fromNullable(get(id)); } public Project save(Project project) { return persist(project); } public void delete(Project client) { namedQuery("com.udemy.core.Client.remove") .setParameter("id", client.getProjectID()) .executeUpdate(); } /** * Get project d.m.v. de projectnaam op te zoeken. * @param projectName - projectnaam * @return project * @author Richard */ public Project getProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); String getProjectByProjectNameStatement = SQLgetProjectByName(projectName); PreparedStatement getProjectByProjectName = con.prepareStatement(getProjectByProjectNameStatement); ResultSet result = getProjectByProjectName.executeQuery(); while (result.next()) { // DateTime projectStartDateTime = new DateTime(result.getDate("projectStartDate")); // DateTime projectEndDateTime = new DateTime(result.getDate("projectEndDate")); Project project = new Project( result.getString("projectName"), result.getString("projectDesc"), result.getString("projectStartDate"), result.getString("projectEndDate")); return project; } }catch(SQLException e) { } return null; } /** * Get alle projecten die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van het project * @return ArrayList met daarin alle projecten * @author Richard */ public ArrayList<Project> getProjectsByOwnerID(int ownerID){ ArrayList<Project> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getProjectsByOwnerID = SQLgetProjectsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getProjectsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Project requestedProject = new Project( rs.getString("projectName"), rs.getString("projectDesc"), rs.getString("projectStartDate"), rs.getString("projectEndDate")); autos.add(requestedProject); } }catch(SQLException e){ } return autos; } public void deleteProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteProjectByName(projectName)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
RobinUit/hsleiden-ikrefact
KilometerRegistratieAPIBackend/src/main/java/com/DigitaleFactuur/db/ProjectDAO.java
889
/** * Get alle projecten die gelinkt zijn aan een owner via ownerID. * @param ownerID owner van het project * @return ArrayList met daarin alle projecten * @author Richard */
block_comment
nl
package com.DigitaleFactuur.db; import com.DigitaleFactuur.models.Project; import com.DigitaleFactuur.models.User; import com.google.common.base.Optional; import io.dropwizard.hibernate.AbstractDAO; import org.hibernate.SessionFactory; import org.joda.time.DateTime; import java.sql.*; import java.time.LocalDate; import java.time.ZoneId; import java.util.ArrayList; import java.util.Calendar; public class ProjectDAO extends AbstractDAO<Project> { Connection con; public ProjectDAO(SessionFactory sessionFactory) { super(sessionFactory); } private String SQLgetProjectByName(String name){ return "SELECT * FROM project WHERE projectName = '" + name+ "'"; } private String SQLgetProjectsByOwnerID(int ownerID){ return "SELECT * FROM project WHERE ownerID = '" + ownerID + "'"; } public String SQLdeleteProjectByName(String projectName){ return "DELETE FROM project WHERE projectName='" + projectName + "';"; } public Optional<Project> findByID(long id) { return Optional.fromNullable(get(id)); } public Project save(Project project) { return persist(project); } public void delete(Project client) { namedQuery("com.udemy.core.Client.remove") .setParameter("id", client.getProjectID()) .executeUpdate(); } /** * Get project d.m.v. de projectnaam op te zoeken. * @param projectName - projectnaam * @return project * @author Richard */ public Project getProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); String getProjectByProjectNameStatement = SQLgetProjectByName(projectName); PreparedStatement getProjectByProjectName = con.prepareStatement(getProjectByProjectNameStatement); ResultSet result = getProjectByProjectName.executeQuery(); while (result.next()) { // DateTime projectStartDateTime = new DateTime(result.getDate("projectStartDate")); // DateTime projectEndDateTime = new DateTime(result.getDate("projectEndDate")); Project project = new Project( result.getString("projectName"), result.getString("projectDesc"), result.getString("projectStartDate"), result.getString("projectEndDate")); return project; } }catch(SQLException e) { } return null; } /** * Get alle projecten<SUF>*/ public ArrayList<Project> getProjectsByOwnerID(int ownerID){ ArrayList<Project> autos = new ArrayList<>(); try{ con = DatabaseConnector.getConnection(); String getProjectsByOwnerID = SQLgetProjectsByOwnerID(ownerID); PreparedStatement CarsByOwnerID = con.prepareStatement(getProjectsByOwnerID); ResultSet rs = CarsByOwnerID.executeQuery(); while (rs.next()){ Project requestedProject = new Project( rs.getString("projectName"), rs.getString("projectDesc"), rs.getString("projectStartDate"), rs.getString("projectEndDate")); autos.add(requestedProject); } }catch(SQLException e){ } return autos; } public void deleteProjectByName(String projectName) { try { con = DatabaseConnector.getConnection(); PreparedStatement deleteCarByLicence = con.prepareStatement(SQLdeleteProjectByName(projectName)); deleteCarByLicence.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } } }
206521_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin de annotaties die gebruikt worden in de entiteiten. */ package nl.bzk.algemeenbrp.dal.domein.brp.annotation;
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/algemeen/alg-dal-entiteiten/src/main/java/nl/bzk/algemeenbrp/dal/domein/brp/annotation/package-info.java
132
/** * Package met daarin de annotaties die gebruikt worden in de entiteiten. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin<SUF>*/ package nl.bzk.algemeenbrp.dal.domein.brp.annotation;
206523_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin de classes die nodig zijn voor het maken en maskeren/ontmaskeren van een object sleutel. */ package nl.bzk.algemeenbrp.services.objectsleutel;
DDDNL/OperatieBRP
Broncode/operatiebrp-code-145.3/algemeen/alg-services-objectsleutel/src/main/java/nl/bzk/algemeenbrp/services/objectsleutel/package-info.java
137
/** * Package met daarin de classes die nodig zijn voor het maken en maskeren/ontmaskeren van een object sleutel. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at www.github.com/MinBZK/operatieBRP. */ /** * Package met daarin<SUF>*/ package nl.bzk.algemeenbrp.services.objectsleutel;
206530_1
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * geeft het scherm voor de Administrator weer */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm<SUF>*/ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206530_2
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * geeft het Loginscherm weer */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm<SUF>*/ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206530_3
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * geeft het Hoofdscherm voor de reguliere gebruikers weer */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm<SUF>*/ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206530_4
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of<SUF>*/ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206530_8
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * geeft de loginPagina weer */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina<SUF>*/ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206530_9
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
djmbritt/FYS-Mercury
Mercury/src/main/java/hva/fys/mercury/controllers/LoginController.java
1,807
/** * Laadt een fxml bestand in een Parent object en geeft dat terug * @param fxmlFileName naam van het fxml bestand die op het scherm ingeladen moet worden * @return een Parent object met daarin de informatie van het fxml bestand indien er geen bestand is geselecteerd geeft het null terug */
block_comment
nl
package hva.fys.mercury.controllers; import hva.fys.mercury.DAO.GebruikerDAO; import hva.fys.mercury.MainApp; import static hva.fys.mercury.MainApp.stage1; import java.io.IOException; import java.net.URL; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.util.Locale; import java.util.ResourceBundle; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.Alert; import javafx.scene.control.PasswordField; import javafx.scene.control.TextField; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; /** * FXML Controller class die de login pagina beheert * * @author José Niemel * @author David Britt */ public class LoginController implements Initializable, ParentControllerContext { @FXML BorderPane parentNode; @FXML GridPane workspace; @FXML private TextField loginTextField; @FXML private PasswordField passwordField; //parentNode @FXML private AnchorPane loginAnchor; //childNodeAdminPanel @FXML private AnchorPane adminPanel; //childNodeAdminController @FXML private AdminPanelController adminPanelController; //childNodeContentPane @FXML private AnchorPane content; //childnodeContentController @FXML private ContentController contentController; public static Locale locale; GebruikerDAO gebruikerDAO = new GebruikerDAO(); /** * geeft het scherm voor de Administrator weer */ public void showAdminPane() { System.out.println("loading Admin Pane"); System.out.println("loginAnchor: " + this.loginAnchor); System.out.println("adminPanel: " + this.adminPanel); this.parentNode.setVisible(false); this.adminPanel.setVisible(true); } /** * geeft het Loginscherm weer */ public void showLoginPane() { if (this.adminPanel.visibleProperty().getValue()) { this.adminPanel.setVisible(false); } if (this.content.visibleProperty().getValue()) { this.content.setVisible(false); } this.parentNode.setVisible(true); } /** * geeft het Hoofdscherm voor de reguliere gebruikers weer */ private void showContent() { this.parentNode.setVisible(false); this.content.setVisible(true); } /** * Gaat na of de ingevoerde informatie overeenkomt met de informatie in de database. * @param event * @throws InvalidKeyException * @throws NoSuchAlgorithmException */ @FXML private void loginAction(ActionEvent event) throws InvalidKeyException, NoSuchAlgorithmException { System.out.println("Logging IN"); if (loginTextField.getText().isEmpty() && passwordField.getText().isEmpty()) { Alert emptyAlert = new Alert(Alert.AlertType.WARNING); emptyAlert.setContentText("Voer in je [email protected] en wachtwoord AUB."); emptyAlert.showAndWait(); return; } String emailLogin = loginTextField.getText(); String userRoll = gebruikerDAO.getUserRoll(emailLogin); String passwordLogin = passwordField.getText(); String passwordDB = gebruikerDAO.getPassword(emailLogin); System.out.printf("UserRoll: %s\nPasswordDB: %s\nLoginPassword: %s\n", emailLogin, passwordDB, passwordLogin); if (userRoll == null) { Alert noUserAlert = new Alert(Alert.AlertType.ERROR); noUserAlert.setContentText("Deze gebruiker bestaat niet."); noUserAlert.showAndWait(); return; } if (passwordLogin.equals(passwordDB)) { if (userRoll.equalsIgnoreCase("admin")) { showAdminPane(); adminPanelController.setParentContext(this); } else { showContent(); contentController.setParentContext(this); } } else { Alert wrongPassAlert = new Alert(Alert.AlertType.WARNING); wrongPassAlert.setContentText("Wrong password"); wrongPassAlert.showAndWait(); System.out.println("Something went wrong"); } } @FXML private void naarNl(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("nl", "NL"); restartStage(); } @FXML private void naarEn(ActionEvent event) throws IOException { MainApp.stage1.close(); this.locale = new Locale("en", "US"); restartStage(); } private void restartStage() throws IOException { ResourceBundle bundle = ResourceBundle.getBundle("UIResources", this.locale); FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml"), bundle); Parent root = loader.load(); // FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/Login.fxml")); // Parent root = loader.load(); Scene scene = new Scene(root); scene.getStylesheets().add("/styles/Styles.css"); stage1.setTitle("Mercury"); stage1.getIcons().add(new Image("/images/corendon_icon.png")); stage1.setMaximized(false); // stage.setResizable(false); stage1.setScene(scene); stage1.show(); } @Override public void initialize(URL url, ResourceBundle rb) { // this.locale = new Locale("en", "US"); } /** * geeft de loginPagina weer */ @Override public void notifyCloseChild() { System.out.println("Closing child pane: childpane"); showLoginPane(); } @Override public void displayStatusMessage(String message) { // statusMessage.setText(message); } /** * Laadt een fxml<SUF>*/ private Parent loadFXMLFile(String fxmlFileName) { try { return FXMLLoader.load(getClass().getResource(fxmlFileName)); } catch (IOException ex) { System.out.printf("\n%s: %s\n", ex.getClass().getName(), ex.getMessage()); return null; } } @Override public void notifyChildHasUpdated() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void transferObject(Object o) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void deleteLastElement() { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
206531_0
package com.eringa.Reversi.service; import com.eringa.Reversi.domain.ERole; import com.eringa.Reversi.domain.Role; import com.eringa.Reversi.domain.Score; import com.eringa.Reversi.domain.User; import com.eringa.Reversi.payload.request.LoginRequest; import com.eringa.Reversi.payload.request.SignupRequest; import com.eringa.Reversi.payload.response.JwtResponse; import com.eringa.Reversi.payload.response.MessageResponse; import com.eringa.Reversi.persistence.RoleRepository; import com.eringa.Reversi.persistence.UserRepository; import com.eringa.Reversi.persistence.ScoreRepository; import com.eringa.Reversi.service.Security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service @Validated public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private ScoreRepository scoreRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setScoreRepository(ScoreRepository scoreRepository) { this.scoreRepository = scoreRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This username is already taken! Please choose another.")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This emailaddress is already in use! Please use it to login.")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } //create the initial scores in the score table. Score initialscore = new Score(); initialscore.setGamesPlayed(0); initialscore.setGamesWon(0); initialscore.setStoneswon(0); user.setRoles(roles); userRepository.save(user); scoreRepository.save(initialscore); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
Made-by-DJ/reversi4
src/main/java/com/eringa/Reversi/service/AuthorizationService.java
1,572
/** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */
block_comment
nl
package com.eringa.Reversi.service; import com.eringa.Reversi.domain.ERole; import com.eringa.Reversi.domain.Role; import com.eringa.Reversi.domain.Score; import com.eringa.Reversi.domain.User; import com.eringa.Reversi.payload.request.LoginRequest; import com.eringa.Reversi.payload.request.SignupRequest; import com.eringa.Reversi.payload.response.JwtResponse; import com.eringa.Reversi.payload.response.MessageResponse; import com.eringa.Reversi.persistence.RoleRepository; import com.eringa.Reversi.persistence.UserRepository; import com.eringa.Reversi.persistence.ScoreRepository; import com.eringa.Reversi.service.Security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service @Validated public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private ScoreRepository scoreRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setScoreRepository(ScoreRepository scoreRepository) { this.scoreRepository = scoreRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt<SUF>*/ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This username is already taken! Please choose another.")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This emailaddress is already in use! Please use it to login.")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } //create the initial scores in the score table. Score initialscore = new Score(); initialscore.setGamesPlayed(0); initialscore.setGamesWon(0); initialscore.setStoneswon(0); user.setRoles(roles); userRepository.save(user); scoreRepository.save(initialscore); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
206531_3
package com.eringa.Reversi.service; import com.eringa.Reversi.domain.ERole; import com.eringa.Reversi.domain.Role; import com.eringa.Reversi.domain.Score; import com.eringa.Reversi.domain.User; import com.eringa.Reversi.payload.request.LoginRequest; import com.eringa.Reversi.payload.request.SignupRequest; import com.eringa.Reversi.payload.response.JwtResponse; import com.eringa.Reversi.payload.response.MessageResponse; import com.eringa.Reversi.persistence.RoleRepository; import com.eringa.Reversi.persistence.UserRepository; import com.eringa.Reversi.persistence.ScoreRepository; import com.eringa.Reversi.service.Security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service @Validated public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private ScoreRepository scoreRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setScoreRepository(ScoreRepository scoreRepository) { this.scoreRepository = scoreRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This username is already taken! Please choose another.")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This emailaddress is already in use! Please use it to login.")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } //create the initial scores in the score table. Score initialscore = new Score(); initialscore.setGamesPlayed(0); initialscore.setGamesWon(0); initialscore.setStoneswon(0); user.setRoles(roles); userRepository.save(user); scoreRepository.save(initialscore); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */ public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
Made-by-DJ/reversi4
src/main/java/com/eringa/Reversi/service/AuthorizationService.java
1,572
/** * Deze methode controleert de ontvangen username en wachtwoord. Het gebruikt hiervoor de * AuthenticationManager. I.a.w. Spring security doet dit allemaal voor ons. * * Wanneer de gebruikersnaam/wachtwoord combinatie niet klopt, wordt er een Runtime exception gegooid: * 401 Unauthorized. Deze wordt gegooid door * {@link com.eringa.Reversi.service.Security.jwt.AuthEntryPointJwt} * * * @param loginRequest De payload met username en password. * @return een HTTP-response met daarin de JWT-token. */
block_comment
nl
package com.eringa.Reversi.service; import com.eringa.Reversi.domain.ERole; import com.eringa.Reversi.domain.Role; import com.eringa.Reversi.domain.Score; import com.eringa.Reversi.domain.User; import com.eringa.Reversi.payload.request.LoginRequest; import com.eringa.Reversi.payload.request.SignupRequest; import com.eringa.Reversi.payload.response.JwtResponse; import com.eringa.Reversi.payload.response.MessageResponse; import com.eringa.Reversi.persistence.RoleRepository; import com.eringa.Reversi.persistence.UserRepository; import com.eringa.Reversi.persistence.ScoreRepository; import com.eringa.Reversi.service.Security.jwt.JwtUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.ResponseEntity; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; import javax.validation.Valid; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; @Service @Validated public class AuthorizationService { private static final String ROLE_NOT_FOUND_ERROR = "Error: Role is not found."; private UserRepository userRepository; private PasswordEncoder encoder; private RoleRepository roleRepository; private ScoreRepository scoreRepository; private AuthenticationManager authenticationManager; private JwtUtils jwtUtils; @Autowired public void setUserRepository(UserRepository userRepository) { this.userRepository = userRepository; } @Autowired public void setEncoder(PasswordEncoder passwordEncoder) { this.encoder = passwordEncoder; } @Autowired public void setRoleRepository(RoleRepository roleRepository) { this.roleRepository = roleRepository; } @Autowired public void setScoreRepository(ScoreRepository scoreRepository) { this.scoreRepository = scoreRepository; } @Autowired public void setAuthenticationManager(AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Autowired public void setJwtUtils(JwtUtils jwtUtils) { this.jwtUtils = jwtUtils; } /** * * Deze methode verwerkt de gebruiker die wil registreren. De username en e-mail worden gecheckt. Eventuele rollen * worden toegevoegd en de gebruiker wordt opgeslagen in de database. * * @param signUpRequest de payload signup-request met gebruikersnaam en wachtwoord. * @return een HTTP response met daarin een succesbericht. */ public ResponseEntity<MessageResponse> registerUser(@Valid SignupRequest signUpRequest) { if (Boolean.TRUE.equals(userRepository.existsByUsername(signUpRequest.getUsername()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This username is already taken! Please choose another.")); } if (Boolean.TRUE.equals(userRepository.existsByEmail(signUpRequest.getEmail()))) { return ResponseEntity .badRequest() .body(new MessageResponse("This emailaddress is already in use! Please use it to login.")); } // Create new user's account User user = new User(signUpRequest.getUsername(), signUpRequest.getEmail(), encoder.encode(signUpRequest.getPassword())); Set<String> strRoles = signUpRequest.getRole(); Set<Role> roles = new HashSet<>(); if (strRoles == null) { Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } else { strRoles.forEach(role -> { switch (role) { case "admin": Role adminRole = roleRepository.findByName(ERole.ROLE_ADMIN) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(adminRole); break; case "mod": Role modRole = roleRepository.findByName(ERole.ROLE_MODERATOR) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(modRole); break; default: Role userRole = roleRepository.findByName(ERole.ROLE_USER) .orElseThrow(() -> new RuntimeException(ROLE_NOT_FOUND_ERROR)); roles.add(userRole); } }); } //create the initial scores in the score table. Score initialscore = new Score(); initialscore.setGamesPlayed(0); initialscore.setGamesWon(0); initialscore.setStoneswon(0); user.setRoles(roles); userRepository.save(user); scoreRepository.save(initialscore); return ResponseEntity.ok(new MessageResponse("User registered successfully!")); } /** * Deze methode controleert<SUF>*/ public ResponseEntity<JwtResponse> authenticateUser(@Valid LoginRequest loginRequest) { Authentication authentication = authenticationManager.authenticate( new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword())); SecurityContextHolder.getContext().setAuthentication(authentication); String jwt = jwtUtils.generateJwtToken(authentication); UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal(); List<String> roles = userDetails.getAuthorities().stream() .map(item -> item.getAuthority()) .collect(Collectors.toList()); return ResponseEntity.ok(new JwtResponse(jwt, userDetails.getId(), userDetails.getUsername(), userDetails.getEmail(), roles)); } }
206533_1
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
545
/** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response<SUF>*/ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
206533_2
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
545
/** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. <SUF>*/ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
206533_3
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
545
/** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de<SUF>*/ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
206533_4
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
545
/** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde<SUF>*/ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
206533_5
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
EdwinSmink/OperatieBRP
02 Software/01 Broncode/operatiebrp-code-145.3/migratie/migr-ggo-viewer/src/main/java/nl/bzk/migratiebrp/ggo/viewer/ViewerResponse.java
545
/** * Geef de waarde van fout regels. * @return Een lijst met fouten die hebben plaatsgevonden tijdens het inlezen. */
block_comment
nl
/** * This file is copyright 2017 State of the Netherlands (Ministry of Interior Affairs and Kingdom Relations). * It is made available under the terms of the GNU Affero General Public License, version 3 as published by the Free Software Foundation. * The project of which this file is part, may be found at https://github.com/MinBZK/operatieBRP. */ package nl.bzk.migratiebrp.ggo.viewer; import java.util.List; import nl.bzk.migratiebrp.ggo.viewer.model.GgoFoutRegel; import nl.bzk.migratiebrp.ggo.viewer.model.GgoPersoonslijstGroep; /** * Het JSON response object, met daarin de PersoonsijstGroepen (met daarin de PLs en controles). Bevat ook de * foutmeldingen van de verwerking (als foutRegels) */ public class ViewerResponse { private final List<GgoPersoonslijstGroep> persoonslijstGroepen; private final List<GgoFoutRegel> foutRegels; /** * Constructor. * @param persoonslijstGroepen De lijst met persoonslijstgroepen. * @param list De lijst met foutRegels. */ public ViewerResponse(final List<GgoPersoonslijstGroep> persoonslijstGroepen, final List<GgoFoutRegel> list) { this.persoonslijstGroepen = persoonslijstGroepen; foutRegels = list; } /** * Dit heeft de Upload JS nodig om te bevestigen dat de upload gelukt is. * @return String met daarin true. */ public final String getSuccess() { return "true"; } /** * Geef de waarde van persoonslijst groepen. * @return De persoonslijstGroepen lijst. */ public final List<GgoPersoonslijstGroep> getPersoonslijstGroepen() { return persoonslijstGroepen; } /** * Geef de waarde<SUF>*/ public final List<GgoFoutRegel> getFoutRegels() { return foutRegels; } }
206535_1
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
geertplaisier/kargeotool
src/main/java/nl/b3p/kar/stripes/SearchActionBean.java
4,269
/** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */
block_comment
nl
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke<SUF>*/ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
206535_2
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
geertplaisier/kargeotool
src/main/java/nl/b3p/kar/stripes/SearchActionBean.java
4,269
// niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn
line_comment
nl
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk:<SUF> private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
206535_5
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
geertplaisier/kargeotool
src/main/java/nl/b3p/kar/stripes/SearchActionBean.java
4,269
/** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */
block_comment
nl
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7<SUF>*/ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
206535_6
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker */ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
geertplaisier/kargeotool
src/main/java/nl/b3p/kar/stripes/SearchActionBean.java
4,269
/** * * @return De gebruiker */
block_comment
nl
/** * Geo-OV - applicatie voor het registreren van KAR meldpunten * * Copyright (C) 2009-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, either version 3 of the License, or (at your option) any * later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.kar.stripes; import com.vividsolutions.jts.geom.Envelope; import com.vividsolutions.jts.geom.Geometry; import com.vividsolutions.jts.geom.GeometryFactory; import com.vividsolutions.jts.geom.PrecisionModel; import com.vividsolutions.jts.io.ParseException; import com.vividsolutions.jts.io.WKTReader; import java.io.ByteArrayInputStream; import java.io.StringReader; import java.net.URLEncoder; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.directory.SearchResult; import javax.persistence.EntityManager; import javax.sql.DataSource; import net.sourceforge.stripes.action.*; import net.sourceforge.stripes.validation.Validate; import nl.b3p.kar.hibernate.*; import org.apache.commons.dbutils.DbUtils; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.ResultSetHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import org.apache.commons.lang.exception.ExceptionUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrServerException; import org.apache.solr.client.solrj.impl.HttpSolrServer; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocument; import org.apache.solr.common.SolrDocumentList; import org.geotools.geometry.jts.WKTReader2; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.criterion.Disjunction; import org.hibernate.criterion.MatchMode; import org.hibernate.criterion.Restrictions; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * Stripes klasse welke de zoek functionaliteit regelt. * * @author Meine Toonen [email protected] */ @StrictBinding @UrlBinding("/action/search") public class SearchActionBean implements ActionBean { private static final String GEOCODER_URL = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm="; private static final Log log = LogFactory.getLog(SearchActionBean.class); private ActionBeanContext context; @Validate private String term; @Validate(required = false) // niet noodzakelijk: extra filter voor buslijnen, maar hoeft niet ingevuld te zijn private String dataOwner; private static final String KV7NETWERK_JNDI_NAME = "java:comp/env/jdbc/kv7netwerk"; private static final String CODE_SEARCH_PREFIX = ":"; @Validate private String vehicleType; private final WKTReader2 wkt = new WKTReader2(); /** * * @return De rseq * @throws Exception The error */ public Resolution rseq() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); Criteria criteria = sess.createCriteria(RoadsideEquipment.class); if(term != null){ boolean validAddressSearch = false; if(term.startsWith(CODE_SEARCH_PREFIX)) { try { int karAddress = Integer.parseInt(term.substring(CODE_SEARCH_PREFIX.length())); criteria.add(Restrictions.eq("karAddress", karAddress)); validAddressSearch = true; } catch(NumberFormatException e) { } } if(!validAddressSearch) { Disjunction dis = Restrictions.disjunction(); dis.add(Restrictions.ilike("description", term, MatchMode.ANYWHERE)); try { int karAddress = Integer.parseInt(term); dis.add(Restrictions.eq("karAddress", karAddress)); } catch (NumberFormatException e) { } dis.add(Restrictions.ilike("crossingCode", term, MatchMode.ANYWHERE)); criteria.add(dis); } } List<RoadsideEquipment> l = criteria.list(); JSONArray rseqs = new JSONArray(); for (RoadsideEquipment roadsideEquipment : l) { if(getGebruiker().canRead(roadsideEquipment)) { if(vehicleType == null || roadsideEquipment.hasSignalForVehicleType(vehicleType) ){ rseqs.put(roadsideEquipment.getRseqGeoJSON()); } } } info.put("rseqs", rseqs); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search rseq exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gevonden wegen * @throws Exception The error */ public Resolution road() throws Exception { EntityManager em = Stripersist.getEntityManager(); JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); try { Session sess = (Session) em.getDelegate(); String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } Query q = sess.createSQLQuery("SELECT ref,name,astext(st_union(geometry)) FROM Road where ref ilike :ref group by ref,name"); q.setParameter("ref", param); List<Object[]> l = (List<Object[]>) q.list(); JSONArray roads = new JSONArray(); GeometryFactory gf = new GeometryFactory(new PrecisionModel(), 28992); WKTReader reader = new WKTReader(gf); for (Object[] road : l) { JSONObject jRoad = new JSONObject(); jRoad.put("weg", road[0]); if (road[1] != null) { jRoad.put("name", road[1]); } try { Geometry g = reader.read((String) road[2]); Envelope env = g.getEnvelopeInternal(); if (env != null) { JSONObject jEnv = new JSONObject(); jEnv.put("minx", env.getMinX()); jEnv.put("miny", env.getMinY()); jEnv.put("maxx", env.getMaxX()); jEnv.put("maxy", env.getMaxY()); jRoad.put("envelope", jEnv); } } catch (ParseException ex) { } roads.put(jRoad); } info.put("roads", roads); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("search road exception", e); info.put("error", ExceptionUtils.getMessage(e)); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * Doorzoekt de KV7 database. Gebruikt de parameter term voor publicnumber * en linename uit de line tabel. Alleen resultaten met een geometrie worden * teruggegeven. * * @return Resolution Resolution met daarin een JSONObject met de gevonden * buslijnen (bij succes) of een fout (bij falen). * @throws Exception De error * */ public Resolution busline() throws Exception { JSONObject info = new JSONObject(); info.put("success", Boolean.FALSE); Connection c = getConnection(); try { String schema = new QueryRunner().query(c, "select schema from data.netwerk where state = 'active' order by processed_date desc limit 1", new ScalarHandler<String>()); JSONArray lines = new JSONArray(); if(schema != null) { String sql = "select linepublicnumber,linename, min(st_xmin(the_geom)), min(st_ymin(the_geom)), max(st_xmax(the_geom)), " + "max(st_ymax(the_geom)), dataownercode " + "from " + schema + ".map_line " + "where the_geom is not null and (linepublicnumber ilike ? or linename ilike ?)"; if (dataOwner != null) { sql += " and dataownercode = ?"; } sql += " group by linepublicnumber,linename, dataownercode order by linename"; ResultSetHandler<JSONArray> h = new ResultSetHandler<JSONArray>() { public JSONArray handle(ResultSet rs) throws SQLException { JSONArray lines = new JSONArray(); while (rs.next()) { JSONObject line = new JSONObject(); try { line.put("publicnumber", rs.getString(1)); line.put("name", rs.getString(2)); JSONObject jEnv = new JSONObject(); jEnv.put("minx", rs.getDouble(3)); jEnv.put("miny", rs.getDouble(4)); jEnv.put("maxx", rs.getDouble(5)); jEnv.put("maxy", rs.getDouble(6)); line.put("envelope", jEnv); line.put("dataowner", rs.getString(7)); lines.put(line); } catch (JSONException je) { log.error("Kan geen buslijn ophalen: ", je); } } return lines; } }; if (term == null) { term = ""; } JSONObject s = new JSONObject(); s.put("schema", schema); JSONArray matchedLines; String param; if(term.startsWith(CODE_SEARCH_PREFIX)) { param = term.substring(CODE_SEARCH_PREFIX.length()); } else { param = "%" + term + "%"; } if (dataOwner != null) { matchedLines = new QueryRunner().query(c, sql, h, param, param, dataOwner); } else { matchedLines = new QueryRunner().query(c, sql, h, param, param); } s.put("lines", matchedLines); if(matchedLines.length() != 0) { lines.put(s); } } info.put("buslines", lines); info.put("success", Boolean.TRUE); } catch (Exception e) { log.error("Cannot execute query:", e); } finally { DbUtils.closeQuietly(c); } StreamingResolution res =new StreamingResolution("application/json", new StringReader(info.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } /** * * @return De gebruiker <SUF>*/ public Gebruiker getGebruiker() { final String attribute = this.getClass().getName() + "_GEBRUIKER"; Gebruiker g = (Gebruiker) getContext().getRequest().getAttribute(attribute); if (g != null) { return g; } Gebruiker principal = (Gebruiker) context.getRequest().getUserPrincipal(); g = Stripersist.getEntityManager().find(Gebruiker.class, principal.getId()); getContext().getRequest().setAttribute(attribute, g); return g; } /** * * @return Stripes Resolution geocode * @throws Exception De fout */ public Resolution geocode() throws Exception { HttpSolrServer server = new HttpSolrServer("http://geodata.nationaalgeoregister.nl/locatieserver"); JSONObject result = new JSONObject(); try { JSONArray respDocs = new JSONArray(); SolrQuery query = new SolrQuery(); // add asterisk to make it match partial queries (for autosuggest) term += "*"; query.setQuery(term); query.setRequestHandler("/free"); QueryResponse rsp = server.query(query); SolrDocumentList list = rsp.getResults(); for (SolrDocument solrDocument : list) { JSONObject doc = solrDocumentToResult(solrDocument); if (doc != null) { respDocs.put(doc); } } result.put("results", respDocs); result.put("numResults", list.size()); } catch (SolrServerException ex) { log.error("Cannot search:",ex); } StreamingResolution res = new StreamingResolution("text/xml", new StringReader(result.toString(4))); res.setCharacterEncoding("UTF-8"); return res; } private JSONObject solrDocumentToResult(SolrDocument doc){ JSONObject result = null; try { Map<String, Object> values = doc.getFieldValueMap(); result = new JSONObject(); for (String key : values.keySet()) { result.put(key, values.get(key)); } String centroide = (String)doc.getFieldValue("centroide_rd"); String geom = centroide; if(values.containsKey("geometrie_rd")){ geom = (String) values.get("geometrie_rd"); } Geometry g = wkt.read(geom); Envelope env = g.getEnvelopeInternal(); if (centroide != null) { Map bbox = new HashMap(); bbox.put("minx", env.getMinX()); bbox.put("miny", env.getMinY()); bbox.put("maxx", env.getMaxX()); bbox.put("maxy", env.getMaxY()); result.put("location", bbox); } result.put("label", values.get("weergavenaam")); } catch (JSONException ex) { log.error(ex); }catch( ParseException ex){ log.error(ex); } return result; } // <editor-fold desc="Getters and Setters"> /** * * @return De context */ public ActionBeanContext getContext() { return context; } /** * * @param context context */ public void setContext(ActionBeanContext context) { this.context = context; } /** * * @return dataowner */ public String getDataOwner() { return dataOwner; } /** * * @param dataOwner dataowner */ public void setDataOwner(String dataOwner) { this.dataOwner = dataOwner; } /** * * @return vehicletype */ public String getVehicleType() { return vehicleType; } /** * * @param vehicleType vehicleType */ public void setVehicleType(String vehicleType) { this.vehicleType = vehicleType; } /** * * @return term */ public String getTerm() { return term; } /** * * @param term term */ public void setTerm(String term) { this.term = term; } private Connection getConnection() throws NamingException, SQLException { Context initCtx = new InitialContext(); DataSource ds = (DataSource) initCtx.lookup(KV7NETWERK_JNDI_NAME); return ds.getConnection(); } // </editor-fold> }
206537_14
package ie.ucd.srg.koa.kr.beans; import ie.ucd.srg.koa.constants.FunctionalProps; /** * Bean implementation class for Enterprise Bean: Kiezers */ public class KiezersBean implements javax.ejb.EntityBean { private javax.ejb.EntityContext myEntityCtx; /** * Implemetation field for persistent attribute: stemcode */ public java.lang.String stemcode; /** * Implemetation field for persistent attribute: kiezeridentificatie */ public java.lang.String kiezeridentificatie; /** * Implemetation field for persistent attribute: hashedwachtwoord */ public java.lang.String hashedwachtwoord; /** * Implemetation field for persistent attribute: districtnummer */ public java.lang.String districtnummer; /** * Implemetation field for persistent attribute: kieskringnummer */ public java.lang.String kieskringnummer; /** * Implemetation field for persistent attribute: reedsgestemd */ public java.lang.Boolean reedsgestemd; /** * Implemetation field for persistent attribute: invalidlogins */ public java.lang.Integer invalidlogins; /** * Implemetation field for persistent attribute: loginattemptsleft */ public java.lang.Integer loginattemptsleft; /** * Implemetation field for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp timelastsuccesfullogin; /** * Implemetation field for persistent attribute: accountlocked */ public java.lang.Boolean accountlocked; /** * Implemetation field for persistent attribute: timestampunlock */ public java.sql.Timestamp timestampunlock; /** * Implemetation field for persistent attribute: timestampvoted */ public java.sql.Timestamp timestampgestemd; /** * Implemetation field for persistent attribute: modaliteit */ public java.lang.String modaliteit; /** * Implemetation field for persistent attribute: verwijderd */ public java.lang.Boolean verwijderd; /** * Implemetation field for persistent attribute: transactienummer */ public java.lang.String transactienummer; /** * Implemetation field for persistent attribute: validlogins */ public java.lang.Integer validlogins; /** * getEntityContext */ public javax.ejb.EntityContext getEntityContext() { return myEntityCtx; } /** * setEntityContext */ public void setEntityContext(javax.ejb.EntityContext ctx) { myEntityCtx = ctx; } /** * unsetEntityContext */ public void unsetEntityContext() { myEntityCtx = null; } /** * ejbActivate */ public void ejbActivate() { _initLinks(); } /** * ejbCreate method for a CMP entity bean. */ public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate() throws javax.ejb.CreateException { _initLinks(); this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { _initLinks(); this.stemcode = sStemcode; this.kiezeridentificatie = sKiezersidentificatie; this.hashedwachtwoord = sHashedWachtwoord; this.districtnummer = sDistrictnummer; this.kieskringnummer = sKieskringnummer; this.transactienummer = sTransactienummer; this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } /** * ejbLoad */ public void ejbLoad() { _initLinks(); } /** * ejbPassivate */ public void ejbPassivate() { } /** * ejbPostCreate */ public void ejbPostCreate() throws javax.ejb.CreateException { } /** * ejbPostCreate */ public void ejbPostCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { } /** * ejbRemove */ public void ejbRemove() throws javax.ejb.RemoveException { try { _removeLinks(); } catch (java.rmi.RemoteException e) { throw new javax.ejb.RemoveException(e.getMessage()); } } /** * ejbStore */ public void ejbStore() { } /** * This method was generated for supporting the associations. */ protected void _initLinks() { } /** * This method was generated for supporting the associations. */ protected java.util.Vector _getLinks() { java.util.Vector links = new java.util.Vector(); return links; } /** * This method was generated for supporting the associations. */ protected void _removeLinks() throws java.rmi.RemoteException, javax.ejb.RemoveException { java.util.List links = _getLinks(); for (int i = 0; i < links.size(); i++) { try { ((ie.ucd.srg.ivj.ejb.associations.interfaces.Link) links.get(i)) .remove(); } catch (javax.ejb.FinderException e) { } //Consume Finder error since I am going away } } /** * Get accessor for persistent attribute: stemcode */ public java.lang.String getStemcode() { return stemcode; } /** * Set accessor for persistent attribute: stemcode */ public void setStemcode(java.lang.String newStemcode) { stemcode = newStemcode; } /** * Get accessor for persistent attribute: kiezeridentificatie */ public java.lang.String getKiezeridentificatie() { return kiezeridentificatie; } /** * Set accessor for persistent attribute: kiezeridentificatie */ public void setKiezeridentificatie(java.lang.String newKiezeridentificatie) { kiezeridentificatie = newKiezeridentificatie; } /** * Get accessor for persistent attribute: hashedwachtwoord */ public java.lang.String getHashedwachtwoord() { return hashedwachtwoord; } /** * Set accessor for persistent attribute: hashedwachtwoord */ public void setHashedwachtwoord(java.lang.String newHashedwachtwoord) { hashedwachtwoord = newHashedwachtwoord; } /** * Get accessor for persistent attribute: districtnummer */ public java.lang.String getDistrictnummer() { return districtnummer; } /** * Set accessor for persistent attribute: districtnummer */ public void setDistrictnummer(java.lang.String newDistrictnummer) { districtnummer = newDistrictnummer; } /** * Get accessor for persistent attribute: kieskringnummer */ public java.lang.String getKieskringnummer() { return kieskringnummer; } /** * Set accessor for persistent attribute: kieskringnummer */ public void setKieskringnummer(java.lang.String newKieskringnummer) { kieskringnummer = newKieskringnummer; } /** * Get accessor for persistent attribute: reedsgestemd */ public java.lang.Boolean getReedsgestemd() { return reedsgestemd; } /** * Set accessor for persistent attribute: reedsgestemd */ public void setReedsgestemd(java.lang.Boolean newReedsgestemd) { reedsgestemd = newReedsgestemd; } /** * Get accessor for persistent attribute: invalidlogins */ public java.lang.Integer getInvalidlogins() { return invalidlogins; } /** * Set accessor for persistent attribute: invalidlogins */ public void setInvalidlogins(java.lang.Integer newInvalidlogins) { invalidlogins = newInvalidlogins; } /** * Get accessor for persistent attribute: loginattemptsleft */ public java.lang.Integer getLoginattemptsleft() { return loginattemptsleft; } /** * Set accessor for persistent attribute: loginattemptsleft */ public void setLoginattemptsleft(java.lang.Integer newLoginattemptsleft) { loginattemptsleft = newLoginattemptsleft; } /** * Get accessor for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp getTimelastsuccesfullogin() { return timelastsuccesfullogin; } /** * Set accessor for persistent attribute: timelastsuccesfullogin */ public void setTimelastsuccesfullogin( java.sql.Timestamp newTimelastsuccesfullogin) { timelastsuccesfullogin = newTimelastsuccesfullogin; } /** * Get accessor for persistent attribute: accountlocked */ public java.lang.Boolean getAccountlocked() { return accountlocked; } /** * Set accessor for persistent attribute: accountlocked */ public void setAccountlocked(java.lang.Boolean newAccountlocked) { accountlocked = newAccountlocked; } /** * Get accessor for persistent attribute: timestampunlock */ public java.sql.Timestamp getTimestampunlock() { return timestampunlock; } /** * Set accessor for persistent attribute: timestampunlock */ public void setTimestampunlock(java.sql.Timestamp newTimestampunlock) { timestampunlock = newTimestampunlock; } /** * Get accessor for persistent attribute: verwijderd */ public java.lang.Boolean getVerwijderd() { return verwijderd; } /** * Set accessor for persistent attribute: verwijderd */ public void setVerwijderd(java.lang.Boolean newVerwijderd) { verwijderd = newVerwijderd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.sql.Timestamp getTimestampGestemd() { return timestampgestemd; } /** * Set accessor for persistent attribute: timestampvoted */ public void setTimestampGestemd(java.sql.Timestamp newTimestampgestemd) { timestampgestemd = newTimestampgestemd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.lang.String getModaliteit() { return modaliteit; } /** * Set accessor for persistent attribute: timestampvoted */ public void setModaliteit(java.lang.String newModaliteit) { modaliteit = newModaliteit; } /** * Get accessor for persistent attribute: transactienummer */ public java.lang.String getTransactienummer() { return transactienummer; } /** * Set accessor for persistent attribute: transactienummer */ public void setTransactienummer(java.lang.String newTransactienummer) { transactienummer = newTransactienummer; } /** * Get accessor for persistent attribute: validlogins */ public java.lang.Integer getValidlogins() { return validlogins; } /** * Set accessor for persistent attribute: validlogins */ public void setValidlogins(java.lang.Integer newValidlogins) { validlogins = newValidlogins; } }
FreeAndFair/KOA
infrastructure/source/WebVotingSystem/src/ie/ucd/srg/koa/kr/beans/KiezersBean.java
3,363
/** * Implemetation field for persistent attribute: verwijderd */
block_comment
nl
package ie.ucd.srg.koa.kr.beans; import ie.ucd.srg.koa.constants.FunctionalProps; /** * Bean implementation class for Enterprise Bean: Kiezers */ public class KiezersBean implements javax.ejb.EntityBean { private javax.ejb.EntityContext myEntityCtx; /** * Implemetation field for persistent attribute: stemcode */ public java.lang.String stemcode; /** * Implemetation field for persistent attribute: kiezeridentificatie */ public java.lang.String kiezeridentificatie; /** * Implemetation field for persistent attribute: hashedwachtwoord */ public java.lang.String hashedwachtwoord; /** * Implemetation field for persistent attribute: districtnummer */ public java.lang.String districtnummer; /** * Implemetation field for persistent attribute: kieskringnummer */ public java.lang.String kieskringnummer; /** * Implemetation field for persistent attribute: reedsgestemd */ public java.lang.Boolean reedsgestemd; /** * Implemetation field for persistent attribute: invalidlogins */ public java.lang.Integer invalidlogins; /** * Implemetation field for persistent attribute: loginattemptsleft */ public java.lang.Integer loginattemptsleft; /** * Implemetation field for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp timelastsuccesfullogin; /** * Implemetation field for persistent attribute: accountlocked */ public java.lang.Boolean accountlocked; /** * Implemetation field for persistent attribute: timestampunlock */ public java.sql.Timestamp timestampunlock; /** * Implemetation field for persistent attribute: timestampvoted */ public java.sql.Timestamp timestampgestemd; /** * Implemetation field for persistent attribute: modaliteit */ public java.lang.String modaliteit; /** * Implemetation field for<SUF>*/ public java.lang.Boolean verwijderd; /** * Implemetation field for persistent attribute: transactienummer */ public java.lang.String transactienummer; /** * Implemetation field for persistent attribute: validlogins */ public java.lang.Integer validlogins; /** * getEntityContext */ public javax.ejb.EntityContext getEntityContext() { return myEntityCtx; } /** * setEntityContext */ public void setEntityContext(javax.ejb.EntityContext ctx) { myEntityCtx = ctx; } /** * unsetEntityContext */ public void unsetEntityContext() { myEntityCtx = null; } /** * ejbActivate */ public void ejbActivate() { _initLinks(); } /** * ejbCreate method for a CMP entity bean. */ public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate() throws javax.ejb.CreateException { _initLinks(); this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { _initLinks(); this.stemcode = sStemcode; this.kiezeridentificatie = sKiezersidentificatie; this.hashedwachtwoord = sHashedWachtwoord; this.districtnummer = sDistrictnummer; this.kieskringnummer = sKieskringnummer; this.transactienummer = sTransactienummer; this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } /** * ejbLoad */ public void ejbLoad() { _initLinks(); } /** * ejbPassivate */ public void ejbPassivate() { } /** * ejbPostCreate */ public void ejbPostCreate() throws javax.ejb.CreateException { } /** * ejbPostCreate */ public void ejbPostCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { } /** * ejbRemove */ public void ejbRemove() throws javax.ejb.RemoveException { try { _removeLinks(); } catch (java.rmi.RemoteException e) { throw new javax.ejb.RemoveException(e.getMessage()); } } /** * ejbStore */ public void ejbStore() { } /** * This method was generated for supporting the associations. */ protected void _initLinks() { } /** * This method was generated for supporting the associations. */ protected java.util.Vector _getLinks() { java.util.Vector links = new java.util.Vector(); return links; } /** * This method was generated for supporting the associations. */ protected void _removeLinks() throws java.rmi.RemoteException, javax.ejb.RemoveException { java.util.List links = _getLinks(); for (int i = 0; i < links.size(); i++) { try { ((ie.ucd.srg.ivj.ejb.associations.interfaces.Link) links.get(i)) .remove(); } catch (javax.ejb.FinderException e) { } //Consume Finder error since I am going away } } /** * Get accessor for persistent attribute: stemcode */ public java.lang.String getStemcode() { return stemcode; } /** * Set accessor for persistent attribute: stemcode */ public void setStemcode(java.lang.String newStemcode) { stemcode = newStemcode; } /** * Get accessor for persistent attribute: kiezeridentificatie */ public java.lang.String getKiezeridentificatie() { return kiezeridentificatie; } /** * Set accessor for persistent attribute: kiezeridentificatie */ public void setKiezeridentificatie(java.lang.String newKiezeridentificatie) { kiezeridentificatie = newKiezeridentificatie; } /** * Get accessor for persistent attribute: hashedwachtwoord */ public java.lang.String getHashedwachtwoord() { return hashedwachtwoord; } /** * Set accessor for persistent attribute: hashedwachtwoord */ public void setHashedwachtwoord(java.lang.String newHashedwachtwoord) { hashedwachtwoord = newHashedwachtwoord; } /** * Get accessor for persistent attribute: districtnummer */ public java.lang.String getDistrictnummer() { return districtnummer; } /** * Set accessor for persistent attribute: districtnummer */ public void setDistrictnummer(java.lang.String newDistrictnummer) { districtnummer = newDistrictnummer; } /** * Get accessor for persistent attribute: kieskringnummer */ public java.lang.String getKieskringnummer() { return kieskringnummer; } /** * Set accessor for persistent attribute: kieskringnummer */ public void setKieskringnummer(java.lang.String newKieskringnummer) { kieskringnummer = newKieskringnummer; } /** * Get accessor for persistent attribute: reedsgestemd */ public java.lang.Boolean getReedsgestemd() { return reedsgestemd; } /** * Set accessor for persistent attribute: reedsgestemd */ public void setReedsgestemd(java.lang.Boolean newReedsgestemd) { reedsgestemd = newReedsgestemd; } /** * Get accessor for persistent attribute: invalidlogins */ public java.lang.Integer getInvalidlogins() { return invalidlogins; } /** * Set accessor for persistent attribute: invalidlogins */ public void setInvalidlogins(java.lang.Integer newInvalidlogins) { invalidlogins = newInvalidlogins; } /** * Get accessor for persistent attribute: loginattemptsleft */ public java.lang.Integer getLoginattemptsleft() { return loginattemptsleft; } /** * Set accessor for persistent attribute: loginattemptsleft */ public void setLoginattemptsleft(java.lang.Integer newLoginattemptsleft) { loginattemptsleft = newLoginattemptsleft; } /** * Get accessor for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp getTimelastsuccesfullogin() { return timelastsuccesfullogin; } /** * Set accessor for persistent attribute: timelastsuccesfullogin */ public void setTimelastsuccesfullogin( java.sql.Timestamp newTimelastsuccesfullogin) { timelastsuccesfullogin = newTimelastsuccesfullogin; } /** * Get accessor for persistent attribute: accountlocked */ public java.lang.Boolean getAccountlocked() { return accountlocked; } /** * Set accessor for persistent attribute: accountlocked */ public void setAccountlocked(java.lang.Boolean newAccountlocked) { accountlocked = newAccountlocked; } /** * Get accessor for persistent attribute: timestampunlock */ public java.sql.Timestamp getTimestampunlock() { return timestampunlock; } /** * Set accessor for persistent attribute: timestampunlock */ public void setTimestampunlock(java.sql.Timestamp newTimestampunlock) { timestampunlock = newTimestampunlock; } /** * Get accessor for persistent attribute: verwijderd */ public java.lang.Boolean getVerwijderd() { return verwijderd; } /** * Set accessor for persistent attribute: verwijderd */ public void setVerwijderd(java.lang.Boolean newVerwijderd) { verwijderd = newVerwijderd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.sql.Timestamp getTimestampGestemd() { return timestampgestemd; } /** * Set accessor for persistent attribute: timestampvoted */ public void setTimestampGestemd(java.sql.Timestamp newTimestampgestemd) { timestampgestemd = newTimestampgestemd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.lang.String getModaliteit() { return modaliteit; } /** * Set accessor for persistent attribute: timestampvoted */ public void setModaliteit(java.lang.String newModaliteit) { modaliteit = newModaliteit; } /** * Get accessor for persistent attribute: transactienummer */ public java.lang.String getTransactienummer() { return transactienummer; } /** * Set accessor for persistent attribute: transactienummer */ public void setTransactienummer(java.lang.String newTransactienummer) { transactienummer = newTransactienummer; } /** * Get accessor for persistent attribute: validlogins */ public java.lang.Integer getValidlogins() { return validlogins; } /** * Set accessor for persistent attribute: validlogins */ public void setValidlogins(java.lang.Integer newValidlogins) { validlogins = newValidlogins; } }
206537_55
package ie.ucd.srg.koa.kr.beans; import ie.ucd.srg.koa.constants.FunctionalProps; /** * Bean implementation class for Enterprise Bean: Kiezers */ public class KiezersBean implements javax.ejb.EntityBean { private javax.ejb.EntityContext myEntityCtx; /** * Implemetation field for persistent attribute: stemcode */ public java.lang.String stemcode; /** * Implemetation field for persistent attribute: kiezeridentificatie */ public java.lang.String kiezeridentificatie; /** * Implemetation field for persistent attribute: hashedwachtwoord */ public java.lang.String hashedwachtwoord; /** * Implemetation field for persistent attribute: districtnummer */ public java.lang.String districtnummer; /** * Implemetation field for persistent attribute: kieskringnummer */ public java.lang.String kieskringnummer; /** * Implemetation field for persistent attribute: reedsgestemd */ public java.lang.Boolean reedsgestemd; /** * Implemetation field for persistent attribute: invalidlogins */ public java.lang.Integer invalidlogins; /** * Implemetation field for persistent attribute: loginattemptsleft */ public java.lang.Integer loginattemptsleft; /** * Implemetation field for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp timelastsuccesfullogin; /** * Implemetation field for persistent attribute: accountlocked */ public java.lang.Boolean accountlocked; /** * Implemetation field for persistent attribute: timestampunlock */ public java.sql.Timestamp timestampunlock; /** * Implemetation field for persistent attribute: timestampvoted */ public java.sql.Timestamp timestampgestemd; /** * Implemetation field for persistent attribute: modaliteit */ public java.lang.String modaliteit; /** * Implemetation field for persistent attribute: verwijderd */ public java.lang.Boolean verwijderd; /** * Implemetation field for persistent attribute: transactienummer */ public java.lang.String transactienummer; /** * Implemetation field for persistent attribute: validlogins */ public java.lang.Integer validlogins; /** * getEntityContext */ public javax.ejb.EntityContext getEntityContext() { return myEntityCtx; } /** * setEntityContext */ public void setEntityContext(javax.ejb.EntityContext ctx) { myEntityCtx = ctx; } /** * unsetEntityContext */ public void unsetEntityContext() { myEntityCtx = null; } /** * ejbActivate */ public void ejbActivate() { _initLinks(); } /** * ejbCreate method for a CMP entity bean. */ public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate() throws javax.ejb.CreateException { _initLinks(); this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { _initLinks(); this.stemcode = sStemcode; this.kiezeridentificatie = sKiezersidentificatie; this.hashedwachtwoord = sHashedWachtwoord; this.districtnummer = sDistrictnummer; this.kieskringnummer = sKieskringnummer; this.transactienummer = sTransactienummer; this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } /** * ejbLoad */ public void ejbLoad() { _initLinks(); } /** * ejbPassivate */ public void ejbPassivate() { } /** * ejbPostCreate */ public void ejbPostCreate() throws javax.ejb.CreateException { } /** * ejbPostCreate */ public void ejbPostCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { } /** * ejbRemove */ public void ejbRemove() throws javax.ejb.RemoveException { try { _removeLinks(); } catch (java.rmi.RemoteException e) { throw new javax.ejb.RemoveException(e.getMessage()); } } /** * ejbStore */ public void ejbStore() { } /** * This method was generated for supporting the associations. */ protected void _initLinks() { } /** * This method was generated for supporting the associations. */ protected java.util.Vector _getLinks() { java.util.Vector links = new java.util.Vector(); return links; } /** * This method was generated for supporting the associations. */ protected void _removeLinks() throws java.rmi.RemoteException, javax.ejb.RemoveException { java.util.List links = _getLinks(); for (int i = 0; i < links.size(); i++) { try { ((ie.ucd.srg.ivj.ejb.associations.interfaces.Link) links.get(i)) .remove(); } catch (javax.ejb.FinderException e) { } //Consume Finder error since I am going away } } /** * Get accessor for persistent attribute: stemcode */ public java.lang.String getStemcode() { return stemcode; } /** * Set accessor for persistent attribute: stemcode */ public void setStemcode(java.lang.String newStemcode) { stemcode = newStemcode; } /** * Get accessor for persistent attribute: kiezeridentificatie */ public java.lang.String getKiezeridentificatie() { return kiezeridentificatie; } /** * Set accessor for persistent attribute: kiezeridentificatie */ public void setKiezeridentificatie(java.lang.String newKiezeridentificatie) { kiezeridentificatie = newKiezeridentificatie; } /** * Get accessor for persistent attribute: hashedwachtwoord */ public java.lang.String getHashedwachtwoord() { return hashedwachtwoord; } /** * Set accessor for persistent attribute: hashedwachtwoord */ public void setHashedwachtwoord(java.lang.String newHashedwachtwoord) { hashedwachtwoord = newHashedwachtwoord; } /** * Get accessor for persistent attribute: districtnummer */ public java.lang.String getDistrictnummer() { return districtnummer; } /** * Set accessor for persistent attribute: districtnummer */ public void setDistrictnummer(java.lang.String newDistrictnummer) { districtnummer = newDistrictnummer; } /** * Get accessor for persistent attribute: kieskringnummer */ public java.lang.String getKieskringnummer() { return kieskringnummer; } /** * Set accessor for persistent attribute: kieskringnummer */ public void setKieskringnummer(java.lang.String newKieskringnummer) { kieskringnummer = newKieskringnummer; } /** * Get accessor for persistent attribute: reedsgestemd */ public java.lang.Boolean getReedsgestemd() { return reedsgestemd; } /** * Set accessor for persistent attribute: reedsgestemd */ public void setReedsgestemd(java.lang.Boolean newReedsgestemd) { reedsgestemd = newReedsgestemd; } /** * Get accessor for persistent attribute: invalidlogins */ public java.lang.Integer getInvalidlogins() { return invalidlogins; } /** * Set accessor for persistent attribute: invalidlogins */ public void setInvalidlogins(java.lang.Integer newInvalidlogins) { invalidlogins = newInvalidlogins; } /** * Get accessor for persistent attribute: loginattemptsleft */ public java.lang.Integer getLoginattemptsleft() { return loginattemptsleft; } /** * Set accessor for persistent attribute: loginattemptsleft */ public void setLoginattemptsleft(java.lang.Integer newLoginattemptsleft) { loginattemptsleft = newLoginattemptsleft; } /** * Get accessor for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp getTimelastsuccesfullogin() { return timelastsuccesfullogin; } /** * Set accessor for persistent attribute: timelastsuccesfullogin */ public void setTimelastsuccesfullogin( java.sql.Timestamp newTimelastsuccesfullogin) { timelastsuccesfullogin = newTimelastsuccesfullogin; } /** * Get accessor for persistent attribute: accountlocked */ public java.lang.Boolean getAccountlocked() { return accountlocked; } /** * Set accessor for persistent attribute: accountlocked */ public void setAccountlocked(java.lang.Boolean newAccountlocked) { accountlocked = newAccountlocked; } /** * Get accessor for persistent attribute: timestampunlock */ public java.sql.Timestamp getTimestampunlock() { return timestampunlock; } /** * Set accessor for persistent attribute: timestampunlock */ public void setTimestampunlock(java.sql.Timestamp newTimestampunlock) { timestampunlock = newTimestampunlock; } /** * Get accessor for persistent attribute: verwijderd */ public java.lang.Boolean getVerwijderd() { return verwijderd; } /** * Set accessor for persistent attribute: verwijderd */ public void setVerwijderd(java.lang.Boolean newVerwijderd) { verwijderd = newVerwijderd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.sql.Timestamp getTimestampGestemd() { return timestampgestemd; } /** * Set accessor for persistent attribute: timestampvoted */ public void setTimestampGestemd(java.sql.Timestamp newTimestampgestemd) { timestampgestemd = newTimestampgestemd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.lang.String getModaliteit() { return modaliteit; } /** * Set accessor for persistent attribute: timestampvoted */ public void setModaliteit(java.lang.String newModaliteit) { modaliteit = newModaliteit; } /** * Get accessor for persistent attribute: transactienummer */ public java.lang.String getTransactienummer() { return transactienummer; } /** * Set accessor for persistent attribute: transactienummer */ public void setTransactienummer(java.lang.String newTransactienummer) { transactienummer = newTransactienummer; } /** * Get accessor for persistent attribute: validlogins */ public java.lang.Integer getValidlogins() { return validlogins; } /** * Set accessor for persistent attribute: validlogins */ public void setValidlogins(java.lang.Integer newValidlogins) { validlogins = newValidlogins; } }
FreeAndFair/KOA
infrastructure/source/WebVotingSystem/src/ie/ucd/srg/koa/kr/beans/KiezersBean.java
3,363
/** * Set accessor for persistent attribute: verwijderd */
block_comment
nl
package ie.ucd.srg.koa.kr.beans; import ie.ucd.srg.koa.constants.FunctionalProps; /** * Bean implementation class for Enterprise Bean: Kiezers */ public class KiezersBean implements javax.ejb.EntityBean { private javax.ejb.EntityContext myEntityCtx; /** * Implemetation field for persistent attribute: stemcode */ public java.lang.String stemcode; /** * Implemetation field for persistent attribute: kiezeridentificatie */ public java.lang.String kiezeridentificatie; /** * Implemetation field for persistent attribute: hashedwachtwoord */ public java.lang.String hashedwachtwoord; /** * Implemetation field for persistent attribute: districtnummer */ public java.lang.String districtnummer; /** * Implemetation field for persistent attribute: kieskringnummer */ public java.lang.String kieskringnummer; /** * Implemetation field for persistent attribute: reedsgestemd */ public java.lang.Boolean reedsgestemd; /** * Implemetation field for persistent attribute: invalidlogins */ public java.lang.Integer invalidlogins; /** * Implemetation field for persistent attribute: loginattemptsleft */ public java.lang.Integer loginattemptsleft; /** * Implemetation field for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp timelastsuccesfullogin; /** * Implemetation field for persistent attribute: accountlocked */ public java.lang.Boolean accountlocked; /** * Implemetation field for persistent attribute: timestampunlock */ public java.sql.Timestamp timestampunlock; /** * Implemetation field for persistent attribute: timestampvoted */ public java.sql.Timestamp timestampgestemd; /** * Implemetation field for persistent attribute: modaliteit */ public java.lang.String modaliteit; /** * Implemetation field for persistent attribute: verwijderd */ public java.lang.Boolean verwijderd; /** * Implemetation field for persistent attribute: transactienummer */ public java.lang.String transactienummer; /** * Implemetation field for persistent attribute: validlogins */ public java.lang.Integer validlogins; /** * getEntityContext */ public javax.ejb.EntityContext getEntityContext() { return myEntityCtx; } /** * setEntityContext */ public void setEntityContext(javax.ejb.EntityContext ctx) { myEntityCtx = ctx; } /** * unsetEntityContext */ public void unsetEntityContext() { myEntityCtx = null; } /** * ejbActivate */ public void ejbActivate() { _initLinks(); } /** * ejbCreate method for a CMP entity bean. */ public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate() throws javax.ejb.CreateException { _initLinks(); this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } public ie.ucd.srg.koa.kr.beans.KiezersKey ejbCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { _initLinks(); this.stemcode = sStemcode; this.kiezeridentificatie = sKiezersidentificatie; this.hashedwachtwoord = sHashedWachtwoord; this.districtnummer = sDistrictnummer; this.kieskringnummer = sKieskringnummer; this.transactienummer = sTransactienummer; this.verwijderd = new Boolean(false); this.reedsgestemd = new Boolean(false); this.accountlocked = new Boolean(false); try { this.loginattemptsleft = new Integer( FunctionalProps.getIntProperty( FunctionalProps.LOGIN_NR_TIMES_LOGIN)); } catch (Exception e) { this.loginattemptsleft = new Integer(3); // default value } return null; } /** * ejbLoad */ public void ejbLoad() { _initLinks(); } /** * ejbPassivate */ public void ejbPassivate() { } /** * ejbPostCreate */ public void ejbPostCreate() throws javax.ejb.CreateException { } /** * ejbPostCreate */ public void ejbPostCreate( String sStemcode, String sKiezersidentificatie, String sHashedWachtwoord, String sDistrictnummer, String sKieskringnummer, String sTransactienummer) throws javax.ejb.CreateException { } /** * ejbRemove */ public void ejbRemove() throws javax.ejb.RemoveException { try { _removeLinks(); } catch (java.rmi.RemoteException e) { throw new javax.ejb.RemoveException(e.getMessage()); } } /** * ejbStore */ public void ejbStore() { } /** * This method was generated for supporting the associations. */ protected void _initLinks() { } /** * This method was generated for supporting the associations. */ protected java.util.Vector _getLinks() { java.util.Vector links = new java.util.Vector(); return links; } /** * This method was generated for supporting the associations. */ protected void _removeLinks() throws java.rmi.RemoteException, javax.ejb.RemoveException { java.util.List links = _getLinks(); for (int i = 0; i < links.size(); i++) { try { ((ie.ucd.srg.ivj.ejb.associations.interfaces.Link) links.get(i)) .remove(); } catch (javax.ejb.FinderException e) { } //Consume Finder error since I am going away } } /** * Get accessor for persistent attribute: stemcode */ public java.lang.String getStemcode() { return stemcode; } /** * Set accessor for persistent attribute: stemcode */ public void setStemcode(java.lang.String newStemcode) { stemcode = newStemcode; } /** * Get accessor for persistent attribute: kiezeridentificatie */ public java.lang.String getKiezeridentificatie() { return kiezeridentificatie; } /** * Set accessor for persistent attribute: kiezeridentificatie */ public void setKiezeridentificatie(java.lang.String newKiezeridentificatie) { kiezeridentificatie = newKiezeridentificatie; } /** * Get accessor for persistent attribute: hashedwachtwoord */ public java.lang.String getHashedwachtwoord() { return hashedwachtwoord; } /** * Set accessor for persistent attribute: hashedwachtwoord */ public void setHashedwachtwoord(java.lang.String newHashedwachtwoord) { hashedwachtwoord = newHashedwachtwoord; } /** * Get accessor for persistent attribute: districtnummer */ public java.lang.String getDistrictnummer() { return districtnummer; } /** * Set accessor for persistent attribute: districtnummer */ public void setDistrictnummer(java.lang.String newDistrictnummer) { districtnummer = newDistrictnummer; } /** * Get accessor for persistent attribute: kieskringnummer */ public java.lang.String getKieskringnummer() { return kieskringnummer; } /** * Set accessor for persistent attribute: kieskringnummer */ public void setKieskringnummer(java.lang.String newKieskringnummer) { kieskringnummer = newKieskringnummer; } /** * Get accessor for persistent attribute: reedsgestemd */ public java.lang.Boolean getReedsgestemd() { return reedsgestemd; } /** * Set accessor for persistent attribute: reedsgestemd */ public void setReedsgestemd(java.lang.Boolean newReedsgestemd) { reedsgestemd = newReedsgestemd; } /** * Get accessor for persistent attribute: invalidlogins */ public java.lang.Integer getInvalidlogins() { return invalidlogins; } /** * Set accessor for persistent attribute: invalidlogins */ public void setInvalidlogins(java.lang.Integer newInvalidlogins) { invalidlogins = newInvalidlogins; } /** * Get accessor for persistent attribute: loginattemptsleft */ public java.lang.Integer getLoginattemptsleft() { return loginattemptsleft; } /** * Set accessor for persistent attribute: loginattemptsleft */ public void setLoginattemptsleft(java.lang.Integer newLoginattemptsleft) { loginattemptsleft = newLoginattemptsleft; } /** * Get accessor for persistent attribute: timelastsuccesfullogin */ public java.sql.Timestamp getTimelastsuccesfullogin() { return timelastsuccesfullogin; } /** * Set accessor for persistent attribute: timelastsuccesfullogin */ public void setTimelastsuccesfullogin( java.sql.Timestamp newTimelastsuccesfullogin) { timelastsuccesfullogin = newTimelastsuccesfullogin; } /** * Get accessor for persistent attribute: accountlocked */ public java.lang.Boolean getAccountlocked() { return accountlocked; } /** * Set accessor for persistent attribute: accountlocked */ public void setAccountlocked(java.lang.Boolean newAccountlocked) { accountlocked = newAccountlocked; } /** * Get accessor for persistent attribute: timestampunlock */ public java.sql.Timestamp getTimestampunlock() { return timestampunlock; } /** * Set accessor for persistent attribute: timestampunlock */ public void setTimestampunlock(java.sql.Timestamp newTimestampunlock) { timestampunlock = newTimestampunlock; } /** * Get accessor for persistent attribute: verwijderd */ public java.lang.Boolean getVerwijderd() { return verwijderd; } /** * Set accessor for<SUF>*/ public void setVerwijderd(java.lang.Boolean newVerwijderd) { verwijderd = newVerwijderd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.sql.Timestamp getTimestampGestemd() { return timestampgestemd; } /** * Set accessor for persistent attribute: timestampvoted */ public void setTimestampGestemd(java.sql.Timestamp newTimestampgestemd) { timestampgestemd = newTimestampgestemd; } /** * Get accessor for persistent attribute: timestampvoted */ public java.lang.String getModaliteit() { return modaliteit; } /** * Set accessor for persistent attribute: timestampvoted */ public void setModaliteit(java.lang.String newModaliteit) { modaliteit = newModaliteit; } /** * Get accessor for persistent attribute: transactienummer */ public java.lang.String getTransactienummer() { return transactienummer; } /** * Set accessor for persistent attribute: transactienummer */ public void setTransactienummer(java.lang.String newTransactienummer) { transactienummer = newTransactienummer; } /** * Get accessor for persistent attribute: validlogins */ public java.lang.Integer getValidlogins() { return validlogins; } /** * Set accessor for persistent attribute: validlogins */ public void setValidlogins(java.lang.Integer newValidlogins) { validlogins = newValidlogins; } }
206541_0
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/components/dialogs/DeleteProcedure.java
1,481
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */
block_comment
nl
/* * Copyright 2021 -<SUF>*/ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
206541_1
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/components/dialogs/DeleteProcedure.java
1,481
/** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> *<SUF>*/ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
206541_2
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/components/dialogs/DeleteProcedure.java
1,481
/** * Opent window in window naar keuze. Je kunt geen window openen in subwindow */
block_comment
nl
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.dialogs; import static nl.procura.standard.exceptions.ProExceptionSeverity.WARNING; import java.text.MessageFormat; import java.util.ArrayList; import java.util.List; import com.vaadin.ui.Window; import nl.procura.gba.web.components.layouts.table.GbaTable; import nl.procura.standard.exceptions.ProException; import nl.procura.vaadin.component.dialog.ConfirmDialog; import nl.procura.vaadin.component.table.indexed.IndexedTable.Record; import nl.procura.vaadin.component.window.Message; /** * <p> * 2012 * <p> * Standaardprocedure, inclusief melding bij geen geselecteerde records, voor het verwijderen van records uit een tabel. */ public class DeleteProcedure<T> { private static final int EEN = 1; protected String MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN = "Er zijn geen records om te verwijderen"; protected final String GEEN_RECORDS_GESELECTEERD = "Geen records geselecteerd"; protected String RECORD_VERWIJDEREN = "Het {0} record verwijderen?"; protected String RECORDS_VERWIJDEREN = "De {0} records verwijderen?"; protected String RECORD_IS_VERWIJDERD = "Het record is verwijderd"; protected String RECORDS_ZIJN_VERWIJDERD = "De records zijn verwijderd"; /** * Opent window in<SUF>*/ public DeleteProcedure(GbaTable table) { this(table, false); } public DeleteProcedure(GbaTable table, boolean askAll) { updateMessages(); Window window = table.getWindow(); if (window.isModal() && window.getParent() != null) { window = window.getParent(); } List<Record> records = new ArrayList<>(); if (table.getRecords().isEmpty()) { throw new ProException(WARNING, MELDING_GEEN_RECORDS_OM_TE_VERWIJDEREN); } else if (table.isSelectedRecords()) { records.addAll(table.getSelectedRecords()); } else { if (askAll) { records.addAll(table.getRecords()); } else { throw new ProException(WARNING, GEEN_RECORDS_GESELECTEERD); } } for (Record r : records) { beforeDelete((T) r.getObject()); } String message = getMessage(records.size(), table.isSelectedRecords()); window.addWindow(new DeleteDialog(table, message, records)); } protected void afterDelete() { } protected void beforeDelete() { } @SuppressWarnings("unused") protected void beforeDelete(T object) { } @SuppressWarnings("unused") protected void deleteValue(T value) { } // Override @SuppressWarnings("unused") protected void deleteValues(List<T> values) { } protected void updateMessages() { } private String getMessage(int count, boolean selected) { String sel = selected ? "geselecteerde " : " "; switch (count) { case EEN: return MessageFormat.format(RECORD_VERWIJDEREN, sel); default: if (selected) { return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } return MessageFormat.format(RECORDS_VERWIJDEREN, count + " " + sel); } } public class DeleteDialog extends ConfirmDialog { private final GbaTable table; private final List<Record> records; private DeleteDialog(GbaTable table, String message, List<Record> records) { super(message); this.records = records; this.table = table; } @SuppressWarnings("unchecked") @Override public void buttonYes() { beforeDelete(); List<T> list = new ArrayList<>(); for (Record r : records) { list.add((T) r.getObject()); } deleteValues(list); for (Record r : records) { deleteValue((T) r.getObject()); table.deleteRecord(r); } table.init(); afterDelete(); new Message(getWindow().getParent(), (records.size() > 1) ? RECORDS_ZIJN_VERWIJDERD : RECORD_IS_VERWIJDERD, Message.TYPE_SUCCESS); close(); } } }
206545_0
import java.util.*; import java.util.stream.Collectors; /** * Vincent Verboven * 12/12/2022 */ public class Dubbels { private List<String> stringList; public Dubbels(List<String> list){ stringList = new ArrayList<>(); stringList.addAll(list); } public void verwijderDubbels(){ Set<String> geenDubbel = new HashSet<>(stringList); stringList = new ArrayList<>(geenDubbel); Collections.sort(stringList); } @Override public String toString() { StringBuilder string = new StringBuilder(); for (int i = 1; i <= stringList.size(); i++) { string.append(String.format("%-15s",stringList.get(i-1))); if(i % 4 == 0){ string.append("\n"); } } return string.toString() ; } }
Meastro85/OOPROG-Java1
P2W5/P2W5/Dubbels/src/Dubbels.java
238
/** * Vincent Verboven * 12/12/2022 */
block_comment
nl
import java.util.*; import java.util.stream.Collectors; /** * Vincent Verboven <SUF>*/ public class Dubbels { private List<String> stringList; public Dubbels(List<String> list){ stringList = new ArrayList<>(); stringList.addAll(list); } public void verwijderDubbels(){ Set<String> geenDubbel = new HashSet<>(stringList); stringList = new ArrayList<>(geenDubbel); Collections.sort(stringList); } @Override public String toString() { StringBuilder string = new StringBuilder(); for (int i = 1; i <= stringList.size(); i++) { string.append(String.format("%-15s",stringList.get(i-1))); if(i % 4 == 0){ string.append("\n"); } } return string.toString() ; } }
206550_1
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
/** * * @author marcolangebeeke */
block_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke <SUF>*/ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_16
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
// TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt
line_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding<SUF> // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_28
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
// get the aanwezig values from a resource array with aanwezig values
line_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the<SUF> mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_48
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
// check koopman is a vervanger
line_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman<SUF> if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_63
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
// update aanwezig status to vervanger_met_toestemming
line_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig<SUF> mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_67
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
/** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */
block_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item<SUF>*/ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206550_74
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman status String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
tiltshiftnl/makkelijkemarkt-androidapp
app/src/main/java/com/amsterdam/marktbureau/makkelijkemarkt/DagvergunningFragmentKoopman.java
7,212
// check koopman status
line_comment
nl
/** * Copyright (C) 2016 X Gemeente * X Amsterdam * X Onderzoek, Informatie en Statistiek * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/ */ package com.amsterdam.marktbureau.makkelijkemarkt; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.ContextCompat; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.ErkenningsnummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.adapters.SollicitatienummerAdapter; import com.amsterdam.marktbureau.makkelijkemarkt.api.ApiGetKoopmanByErkenningsnummer; import com.amsterdam.marktbureau.makkelijkemarkt.data.MakkelijkeMarktProvider; import com.bumptech.glide.Glide; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick; import butterknife.OnEditorAction; import butterknife.OnItemSelected; /** * * @author marcolangebeeke */ public class DagvergunningFragmentKoopman extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { // use classname when logging private static final String LOG_TAG = DagvergunningFragmentKoopman.class.getSimpleName(); // unique id for the koopman loader private static final int KOOPMAN_LOADER = 5; // koopman selection methods public static final String KOOPMAN_SELECTION_METHOD_HANDMATIG = "handmatig"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_BARCODE = "scan-barcode"; public static final String KOOPMAN_SELECTION_METHOD_SCAN_NFC = "scan-nfc"; // intent bundle extra koopmanid name public static final String VERVANGER_INTENT_EXTRA_VERVANGER_ID = "vervangerId"; // intent bundle extra koopmanid name public static final String VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID = "koopmanId"; // unique id to recognize the callback when receiving the result from the vervanger dialog public static final int VERVANGER_DIALOG_REQUEST_CODE = 0x00006666; // bind layout elements @Bind(R.id.erkenningsnummer_layout) RelativeLayout mErkenningsnummerLayout; @Bind(R.id.search_erkenningsnummer) AutoCompleteTextView mErkenningsnummerEditText; @Bind(R.id.sollicitatienummer_layout) RelativeLayout mSollicitatienummerLayout; @Bind(R.id.search_sollicitatienummer) AutoCompleteTextView mSollicitatienummerEditText; @Bind(R.id.scanbuttons_layout) LinearLayout mScanbuttonsLayout; @Bind(R.id.scan_barcode_button) Button mScanBarcodeButton; @Bind(R.id.scan_nfctag_button) Button mScanNfcTagButton; @Bind(R.id.koopman_detail) LinearLayout mKoopmanDetail; @Bind(R.id.vervanger_detail) LinearLayout mVervangerDetail; // bind dagvergunning list item layout include elements @Bind(R.id.koopman_foto) ImageView mKoopmanFotoImage; @Bind(R.id.koopman_voorletters_achternaam) TextView mKoopmanVoorlettersAchternaamText; @Bind(R.id.dagvergunning_registratie_datumtijd) TextView mRegistratieDatumtijdText; @Bind(R.id.erkenningsnummer) TextView mErkenningsnummerText; @Bind(R.id.notitie) TextView mNotitieText; @Bind(R.id.dagvergunning_totale_lente) TextView mTotaleLengte; @Bind(R.id.account_naam) TextView mAccountNaam; @Bind(R.id.aanwezig_spinner) Spinner mAanwezigSpinner; @Bind(R.id.vervanger_foto) ImageView mVervangerFotoImage; @Bind(R.id.vervanger_voorletters_achternaam) TextView mVervangerVoorlettersAchternaamText; @Bind(R.id.vervanger_erkenningsnummer) TextView mVervangerErkenningsnummerText; // existing dagvergunning id public int mDagvergunningId = -1; // koopman id & erkenningsnummer public int mKoopmanId = -1; public String mErkenningsnummer; // vervanger id & erkenningsnummer public int mVervangerId = -1; public String mVervangerErkenningsnummer; // keep track of how we selected the koopman public String mKoopmanSelectionMethod; // string array and adapter for the aanwezig spinner private String[] mAanwezigKeys; String mAanwezigSelectedValue; // sollicitatie default producten data public HashMap<String, Integer> mProducten = new HashMap<>(); // meldingen boolean mMeldingMultipleDagvergunningen = false; boolean mMeldingNoValidSollicitatie = false; boolean mMeldingVerwijderd = false; // TODO: melding toevoegen wanneer een koopman vandaag al een vergunning heeft op een andere dan de geselecteerde markt // common toast object private Toast mToast; /** * Constructor */ public DagvergunningFragmentKoopman() { } /** * Callback interface so we can talk to the activity */ public interface Callback { void onKoopmanFragmentReady(); void onKoopmanFragmentUpdated(); void onMeldingenUpdated(); void setProgressbarVisibility(int visibility); } /** * Inflate the dagvergunning koopman fragment and initialize the view elements and its handlers * @param inflater * @param container * @param savedInstanceState * @return */ @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View mainView = inflater.inflate(R.layout.dagvergunning_fragment_koopman, container, false); // bind the elements to the view ButterKnife.bind(this, mainView); // Create an onitemclick listener that will catch the clicked koopman from the autocomplete // lists (not using butterknife here because it does not support for @OnItemClick on // AutoCompleteTextView: https://github.com/JakeWharton/butterknife/pull/242 AdapterView.OnItemClickListener autoCompleteItemClickListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Cursor koopman = (Cursor) parent.getAdapter().getItem(position); // select the koopman and update the fragment selectKoopman( koopman.getInt(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ID)), KOOPMAN_SELECTION_METHOD_HANDMATIG); } }; // create the custom cursor adapter that will query for an erkenningsnummer and show an autocomplete list ErkenningsnummerAdapter searchErkenningAdapter = new ErkenningsnummerAdapter(getContext()); mErkenningsnummerEditText.setAdapter(searchErkenningAdapter); mErkenningsnummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // create the custom cursor adapter that will query for a sollicitatienummer and show an autocomplete list SollicitatienummerAdapter searchSollicitatieAdapter = new SollicitatienummerAdapter(getContext()); mSollicitatienummerEditText.setAdapter(searchSollicitatieAdapter); mSollicitatienummerEditText.setOnItemClickListener(autoCompleteItemClickListener); // disable uppercasing of the button text mScanBarcodeButton.setTransformationMethod(null); mScanNfcTagButton.setTransformationMethod(null); // get the aanwezig values from a resource array with aanwezig values mAanwezigKeys = getResources().getStringArray(R.array.array_aanwezig_key); // populate the aanwezig spinner from a resource array with aanwezig titles ArrayAdapter<CharSequence> aanwezigAdapter = ArrayAdapter.createFromResource(getContext(), R.array.array_aanwezig_title, android.R.layout.simple_spinner_dropdown_item); aanwezigAdapter.setDropDownViewResource(android.R.layout.simple_list_item_activated_1); mAanwezigSpinner.setAdapter(aanwezigAdapter); return mainView; } /** * Inform the activity that the koopman fragment is ready so it can be manipulated by the * dagvergunning fragment * @param savedInstanceState saved fragment state */ @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); // initialize the producten values String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // call the activity ((Callback) getActivity()).onKoopmanFragmentReady(); } /** * Trigger the autocomplete onclick on the erkennings- en sollicitatenummer search buttons, or * query api with full erkenningsnummer if nothing found in selected markt * @param view the clicked button */ @OnClick({ R.id.search_erkenningsnummer_button, R.id.search_sollicitatienummer_button }) public void onClick(ImageButton view) { if (view.getId() == R.id.search_erkenningsnummer_button) { // erkenningsnummer if (mErkenningsnummerEditText.getText().toString().length() < mErkenningsnummerEditText.getThreshold()) { // enter minimum 2 digits Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } else if (mErkenningsnummerEditText.getAdapter().getCount() > 0) { // show results found in selected markt showDropdown(mErkenningsnummerEditText); } else { // query api in all markten if (mErkenningsnummerEditText.getText().toString().length() == getResources().getInteger(R.integer.erkenningsnummer_maxlength)) { // show the progressbar ((Callback) getActivity()).setProgressbarVisibility(View.VISIBLE); // query api for koopman by erkenningsnummer ApiGetKoopmanByErkenningsnummer getKoopman = new ApiGetKoopmanByErkenningsnummer(getContext(), LOG_TAG); getKoopman.setErkenningsnummer(mErkenningsnummerEditText.getText().toString()); getKoopman.enqueue(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found_on_selected_markt)); } } } else if (view.getId() == R.id.search_sollicitatienummer_button) { // sollicitatienummer showDropdown(mSollicitatienummerEditText); } } /** * Trigger the autocomplete on enter on the erkennings- en sollicitatenummer search textviews * @param view the autocomplete textview * @param actionId the type of action * @param event the type of keyevent */ @OnEditorAction({ R.id.search_erkenningsnummer, R.id.search_sollicitatienummer }) public boolean onAutoCompleteEnter(AutoCompleteTextView view, int actionId, KeyEvent event) { if (( (event != null) && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) { showDropdown(view); } return true; } /** * On selecting an item from the spinner update the member var with the value * @param position the selected position */ @OnItemSelected(R.id.aanwezig_spinner) public void onAanwezigItemSelected(int position) { mAanwezigSelectedValue = mAanwezigKeys[position]; } /** * Select the koopman and update the fragment * @param koopmanId the id of the koopman * @param selectionMethod the method in which the koopman was selected */ public void selectKoopman(int koopmanId, String selectionMethod) { mVervangerId = -1; mVervangerErkenningsnummer = null; mKoopmanId = koopmanId; mKoopmanSelectionMethod = selectionMethod; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); // hide the keyboard on item selection Utility.hideKeyboard(getActivity()); } /** * Set the koopman id and init the loader * @param koopmanId id of the koopman */ public void setKoopman(int koopmanId, int dagvergunningId) { // load selected koopman to get the status Cursor koopman = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, null, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? AND " + MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_STATUS + " = ? ", new String[] { String.valueOf(koopmanId), "Vervanger" }, null); // check koopman is a vervanger if (koopman != null && koopman.moveToFirst()) { // set the vervanger id and erkenningsnummer mVervangerId = koopmanId; mVervangerErkenningsnummer = koopman.getString(koopman.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); // if so, open dialogfragment containing a list of koopmannen that vervanger kan work for Intent intent = new Intent(getActivity(), VervangerDialogActivity.class); intent.putExtra(VERVANGER_INTENT_EXTRA_VERVANGER_ID, koopmanId); startActivityForResult(intent, VERVANGER_DIALOG_REQUEST_CODE); } else { // else, set the koopman mKoopmanId = koopmanId; if (dagvergunningId != -1) { mDagvergunningId = dagvergunningId; } // load the koopman using the loader getLoaderManager().restartLoader(KOOPMAN_LOADER, null, this); // load & show the vervanger and toggle the aanwezig spinner if set if (mVervangerId > 0) { mAanwezigSpinner.setVisibility(View.GONE); setVervanger(); } else { mAanwezigSpinner.setVisibility(View.VISIBLE); mVervangerDetail.setVisibility(View.GONE); } } if (koopman != null) { koopman.close(); } } /** * Load a vervanger and populate the details */ public void setVervanger() { if (mVervangerId > 0) { // load the vervanger from the database Cursor vervanger = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriKoopman, new String[] { MakkelijkeMarktProvider.Koopman.COL_FOTO_URL, MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS, MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM }, MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? ", new String[] { String.valueOf(mVervangerId), }, null); // populate the vervanger layout item if (vervanger != null) { if (vervanger.moveToFirst()) { // show the details layout mVervangerDetail.setVisibility(View.VISIBLE); // vervanger photo Glide.with(getContext()) .load(vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mVervangerFotoImage); // vervanger naam String naam = vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + vervanger.getString(vervanger.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mVervangerVoorlettersAchternaamText.setText(naam); // vervanger erkenningsnummer mVervangerErkenningsnummerText.setText(mVervangerErkenningsnummer); } vervanger.close(); } } } /** * Catch the selected koopman of vervanger from dialogactivity result * @param requestCode * @param resultCode * @param data */ @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { // check for the vervanger dialog request code if (requestCode == VERVANGER_DIALOG_REQUEST_CODE) { if (resultCode == Activity.RESULT_OK) { // get the id of the selected koopman from the intent int koopmanId = data.getIntExtra(VERVANGER_RETURN_INTENT_EXTRA_KOOPMAN_ID, 0); if (koopmanId != 0) { // set the koopman that was selected in the dialog mKoopmanId = koopmanId; // reset the default amount of products before loading the koopman String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, -1); } // update aanwezig status to vervanger_met_toestemming mAanwezigSelectedValue = getString(R.string.item_vervanger_met_toestemming_aanwezig); setAanwezig(getString(R.string.item_vervanger_met_toestemming_aanwezig)); // inform the dagvergunningfragment that the koopman has changed, get the new values, // and populate our layout with the new koopman ((Callback) getActivity()).onKoopmanFragmentUpdated(); } } else if (resultCode == Activity.RESULT_CANCELED) { // clear the selection by restarting the activity Intent intent = getActivity().getIntent(); getActivity().finish(); startActivity(intent); } } } /** * Select an item by value in the aanwezig spinner * @param value the aanwezig value */ public void setAanwezig(CharSequence value) { for(int i=0 ; i< mAanwezigKeys.length; i++) { if (mAanwezigKeys[i].equals(value)) { mAanwezigSpinner.setSelection(i); break; } } } /** * Show the autocomplete dropdown or a notice when the entered text is smaller then the threshold * @param view autocomplete textview */ private void showDropdown(AutoCompleteTextView view) { if (view.getText() != null && !view.getText().toString().trim().equals("") && view.getText().toString().length() >= view.getThreshold()) { view.showDropDown(); } else { Utility.showToast(getContext(), mToast, getString(R.string.notice_autocomplete_minimum)); } } /** * Create the cursor loader that will load the koopman from the database */ @Override public Loader<Cursor> onCreateLoader(int id, Bundle args) { // load the koopman with given id in the arguments bundle and where doorgehaald is false if (mKoopmanId != -1) { CursorLoader loader = new CursorLoader(getActivity()); loader.setUri(MakkelijkeMarktProvider.mUriKoopmanJoined); loader.setSelection( MakkelijkeMarktProvider.mTableKoopman + "." + MakkelijkeMarktProvider.Koopman.COL_ID + " = ? " ); loader.setSelectionArgs(new String[] { String.valueOf(mKoopmanId) }); return loader; } return null; } /** * Populate the koopman fragment item details item when the loader has finished * @param loader the cursor loader * @param data data object containing one or more koopman rows with joined sollicitatie data */ @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { if (data != null && data.moveToFirst()) { boolean validSollicitatie = false; // get the markt id from the sharedprefs SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext()); int marktId = settings.getInt(getContext().getString(R.string.sharedpreferences_key_markt_id), 0); // make the koopman details visible mKoopmanDetail.setVisibility(View.VISIBLE); // check koopman<SUF> String koopmanStatus = data.getString(data.getColumnIndex("koopman_status")); mMeldingVerwijderd = koopmanStatus.equals(getString(R.string.koopman_status_verwijderd)); // koopman photo Glide.with(getContext()) .load(data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_FOTO_URL))) .error(R.drawable.no_koopman_image) .into(mKoopmanFotoImage); // koopman naam String naam = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_VOORLETTERS)) + " " + data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ACHTERNAAM)); mKoopmanVoorlettersAchternaamText.setText(naam); // koopman erkenningsnummer mErkenningsnummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Koopman.COL_ERKENNINGSNUMMER)); mErkenningsnummerText.setText(mErkenningsnummer); // koopman sollicitaties View view = getView(); if (view != null) { LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE); LinearLayout placeholderLayout = (LinearLayout) view.findViewById(R.id.sollicitaties_placeholder); placeholderLayout.removeAllViews(); // get vaste producten for selected markt, and add multiple markt sollicitatie views to the koopman items while (!data.isAfterLast()) { // get vaste producten for selected markt if (marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { String[] productParams = getResources().getStringArray(R.array.array_product_param); for (String product : productParams) { mProducten.put(product, data.getInt(data.getColumnIndex(product))); } } // inflate sollicitatie layout and populate its view items View childLayout = layoutInflater.inflate(R.layout.dagvergunning_koopman_item_sollicitatie, null); // highlight the sollicitatie for the current markt if (data.getCount() > 1 && marktId > 0 && marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { childLayout.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.primary)); } // markt afkorting String marktAfkorting = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Markt.COL_AFKORTING)); TextView marktAfkortingText = (TextView) childLayout.findViewById(R.id.sollicitatie_markt_afkorting); marktAfkortingText.setText(marktAfkorting); // koopman sollicitatienummer String sollicitatienummer = data.getString(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_SOLLICITATIE_NUMMER)); TextView sollicitatienummerText = (TextView) childLayout.findViewById(R.id.sollicitatie_sollicitatie_nummer); sollicitatienummerText.setText(sollicitatienummer); // koopman sollicitatie status String sollicitatieStatus = data.getString(data.getColumnIndex("sollicitatie_status")); TextView sollicitatieStatusText = (TextView) childLayout.findViewById(R.id.sollicitatie_status); sollicitatieStatusText.setText(sollicitatieStatus); if (sollicitatieStatus != null && !sollicitatieStatus.equals("?") && !sollicitatieStatus.equals("")) { sollicitatieStatusText.setTextColor(ContextCompat.getColor(getContext(), android.R.color.white)); sollicitatieStatusText.setBackgroundColor(ContextCompat.getColor( getContext(), Utility.getSollicitatieStatusColor(getContext(), sollicitatieStatus))); // check if koopman has at least one valid sollicitatie on selected markt if (marktId == data.getInt(data.getColumnIndex(MakkelijkeMarktProvider.Sollicitatie.COL_MARKT_ID))) { validSollicitatie = true; } } // add view and move cursor to next placeholderLayout.addView(childLayout, data.getPosition()); data.moveToNext(); } } // check valid sollicitatie mMeldingNoValidSollicitatie = !validSollicitatie; // get the date of today for the dag param SimpleDateFormat sdf = new SimpleDateFormat(getString(R.string.date_format_dag)); String dag = sdf.format(new Date()); // check multiple dagvergunningen Cursor dagvergunningen = getContext().getContentResolver().query( MakkelijkeMarktProvider.mUriDagvergunningJoined, null, "dagvergunning_doorgehaald != '1' AND " + MakkelijkeMarktProvider.mTableDagvergunning + "." + MakkelijkeMarktProvider.Dagvergunning.COL_MARKT_ID + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_DAG + " = ? AND " + MakkelijkeMarktProvider.Dagvergunning.COL_ERKENNINGSNUMMER_INVOER_WAARDE + " = ? ", new String[] { String.valueOf(marktId), dag, mErkenningsnummer, }, null); mMeldingMultipleDagvergunningen = (dagvergunningen != null && dagvergunningen.moveToFirst()) && (dagvergunningen.getCount() > 1 || mDagvergunningId == -1); if (dagvergunningen != null) { dagvergunningen.close(); } // callback to dagvergunning activity to updaten the meldingen view ((Callback) getActivity()).onMeldingenUpdated(); } } @Override public void onLoaderReset(Loader<Cursor> loader) { } /** * Handle response event from api get koopman request onresponse method to update our ui * @param event the received event */ @Subscribe public void onGetKoopmanResponseEvent(ApiGetKoopmanByErkenningsnummer.OnResponseEvent event) { if (event.mCaller.equals(LOG_TAG)) { // hide progressbar ((Callback) getActivity()).setProgressbarVisibility(View.GONE); // select the found koopman, or show an error if nothing found if (event.mKoopman != null) { selectKoopman(event.mKoopman.getId(), KOOPMAN_SELECTION_METHOD_HANDMATIG); } else { mToast = Utility.showToast(getContext(), mToast, getString(R.string.notice_koopman_not_found)); } } } /** * Register eventbus handlers */ @Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } /** * Unregister eventbus handlers */ @Override public void onStop() { EventBus.getDefault().unregister(this); super.onStop(); } }
206551_1
/******************************************************************************* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package atd.home; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import atd.services.BerichtenService; /** * @author martijn * */ public class DeletePost extends HttpServlet { private BerichtenService berichtenService = new BerichtenService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.valueOf(req.getParameter("id")); berichtenService.removeBericht(id); RequestDispatcher rd = null; rd = req.getRequestDispatcher("/index.jsp"); Logger.getLogger("atd.log").info("Bericht: " + id + " is verwijderd"); rd.forward(req, resp); } }
martijnboers/Thema-Opdracht-Web
ATD-WEBSITE/src/atd/home/DeletePost.java
397
/** * @author martijn * */
block_comment
nl
/******************************************************************************* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package atd.home; import java.io.IOException; import java.util.logging.Logger; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import atd.services.BerichtenService; /** * @author martijn <SUF>*/ public class DeletePost extends HttpServlet { private BerichtenService berichtenService = new BerichtenService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int id = Integer.valueOf(req.getParameter("id")); berichtenService.removeBericht(id); RequestDispatcher rd = null; rd = req.getRequestDispatcher("/index.jsp"); Logger.getLogger("atd.log").info("Bericht: " + id + " is verwijderd"); rd.forward(req, resp); } }
206564_1
/* * Copyright (C) 2012-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.admin.stripes; import java.io.IOException; import java.text.MessageFormat; import java.util.Date; import java.util.List; import javax.annotation.security.RolesAllowed; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.FileBean; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.StreamingResolution; import net.sourceforge.stripes.action.StrictBinding; import net.sourceforge.stripes.action.UrlBinding; import net.sourceforge.stripes.util.HtmlUtil; import net.sourceforge.stripes.validation.Validate; import nl.b3p.viewer.config.app.Resource; import nl.b3p.viewer.config.security.Group; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan */ @UrlBinding("/action/imageupload") @StrictBinding @RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN}) public class ImageUploadActionBean extends ApplicationActionBean { private static final Log log = LogFactory.getLog(ImageUploadActionBean.class); private static final String IMAGE_ACTIONBEAN_URL = "/action/image/"; private static final String VIEWER_URL_PARAM = "viewer.url"; @Validate private FileBean upload; @Validate private String action; @Validate private Integer page; @Validate private Integer start; @Validate private Integer limit; @Validate private String image; //<editor-fold defaultstate="collapsed" desc="getters and setters"> public FileBean getUpload() { return upload; } public void setUpload(FileBean upload) { this.upload = upload; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getStart() { return start; } public void setStart(Integer start) { this.start = start; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } //</editor-fold> private String url(Resource r) { return getContext().getServletContext().getInitParameter(VIEWER_URL_PARAM) + IMAGE_ACTIONBEAN_URL + r.getName(); } @DefaultHandler public Resolution upload() throws JSONException { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); if(upload == null) { j.put("errors", getBundle().getString("viewer_admin.imageuploadactionbean.noupload")); } else { if(Stripersist.getEntityManager().find(Resource.class, upload.getFileName()) != null) { j.put("errors", getBundle().getString("viewer_admin.imageuploadactionbean.namedup")); } else { try { Resource r = new Resource(); r.setName(upload.getFileName()); r.setContentType(upload.getContentType()); r.setDataContent(upload.getInputStream(), upload.getSize()); r.setSize(upload.getSize()); r.setModified(new Date()); Stripersist.getEntityManager().persist(r); Stripersist.getEntityManager().getTransaction().commit(); j.put("message", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.imguploaded"), r.getName())); JSONObject data = new JSONObject(); data.put("src", url(r)); j.put("data", data); j.put("total", 1); j.put("success", true); } catch(Exception e) { j.put("errors", e.toString()); } finally { try { upload.delete(); } catch(IOException e) { log.error("Error deleting upload", e); } } } } // text/html and HTML encode because of http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Connection // requirements (WTF???) return new StreamingResolution("text/html", HtmlUtil.encode(j.toString(4))); } public Resolution manage() throws JSONException { if("imagesList".equals(action)) { return imagesList(); } else if("delete".equals(action)) { return delete(); } else { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); j.put("errors", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.unkaction"), action)); return new StreamingResolution("application/json", j.toString(4)); } } public Resolution imagesList() throws JSONException { JSONObject j = new JSONObject(); try { JSONArray data = new JSONArray(); j.put("data", data); j.put("total", Stripersist.getEntityManager().createQuery("select count(*) from Resource").getSingleResult()); List<Resource> resources = Stripersist.getEntityManager().createQuery( "from Resource order by name") .setFirstResult(start) .setMaxResults(limit) .getResultList(); for(Resource r: resources) { JSONObject file = new JSONObject(); file.put("src", url(r)); file.put("name", r.getName()); file.put("fullname", r.getName()); data.put(file); } j.put("success", true); j.put("message", "Success"); } catch(Exception e) { j.put("success", false); j.put("message", "Fout"); j.put("errors", e.toString()); } return new StreamingResolution("application/json", j.toString(4)); } public Resolution delete() throws JSONException { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); try { Resource r = Stripersist.getEntityManager().find(Resource.class, image); if(r == null) { j.put("errors", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.notfound"), image )); } else { Stripersist.getEntityManager().remove(r); Stripersist.getEntityManager().getTransaction().commit(); } j.put("success", true); j.put("message", "Verwijderd"); } catch(Exception e) { j.put("errors", e.toString()); } return new StreamingResolution("application/json", j.toString(4)); } }
B3Partners/tailormap
viewer-admin/src/main/java/nl/b3p/viewer/admin/stripes/ImageUploadActionBean.java
2,032
/** * * @author Matthijs Laan */
block_comment
nl
/* * Copyright (C) 2012-2013 B3Partners B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package nl.b3p.viewer.admin.stripes; import java.io.IOException; import java.text.MessageFormat; import java.util.Date; import java.util.List; import javax.annotation.security.RolesAllowed; import net.sourceforge.stripes.action.DefaultHandler; import net.sourceforge.stripes.action.FileBean; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.StreamingResolution; import net.sourceforge.stripes.action.StrictBinding; import net.sourceforge.stripes.action.UrlBinding; import net.sourceforge.stripes.util.HtmlUtil; import net.sourceforge.stripes.validation.Validate; import nl.b3p.viewer.config.app.Resource; import nl.b3p.viewer.config.security.Group; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.stripesstuff.stripersist.Stripersist; /** * * @author Matthijs Laan<SUF>*/ @UrlBinding("/action/imageupload") @StrictBinding @RolesAllowed({Group.ADMIN,Group.APPLICATION_ADMIN}) public class ImageUploadActionBean extends ApplicationActionBean { private static final Log log = LogFactory.getLog(ImageUploadActionBean.class); private static final String IMAGE_ACTIONBEAN_URL = "/action/image/"; private static final String VIEWER_URL_PARAM = "viewer.url"; @Validate private FileBean upload; @Validate private String action; @Validate private Integer page; @Validate private Integer start; @Validate private Integer limit; @Validate private String image; //<editor-fold defaultstate="collapsed" desc="getters and setters"> public FileBean getUpload() { return upload; } public void setUpload(FileBean upload) { this.upload = upload; } public String getAction() { return action; } public void setAction(String action) { this.action = action; } public Integer getLimit() { return limit; } public void setLimit(Integer limit) { this.limit = limit; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } public Integer getStart() { return start; } public void setStart(Integer start) { this.start = start; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } //</editor-fold> private String url(Resource r) { return getContext().getServletContext().getInitParameter(VIEWER_URL_PARAM) + IMAGE_ACTIONBEAN_URL + r.getName(); } @DefaultHandler public Resolution upload() throws JSONException { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); if(upload == null) { j.put("errors", getBundle().getString("viewer_admin.imageuploadactionbean.noupload")); } else { if(Stripersist.getEntityManager().find(Resource.class, upload.getFileName()) != null) { j.put("errors", getBundle().getString("viewer_admin.imageuploadactionbean.namedup")); } else { try { Resource r = new Resource(); r.setName(upload.getFileName()); r.setContentType(upload.getContentType()); r.setDataContent(upload.getInputStream(), upload.getSize()); r.setSize(upload.getSize()); r.setModified(new Date()); Stripersist.getEntityManager().persist(r); Stripersist.getEntityManager().getTransaction().commit(); j.put("message", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.imguploaded"), r.getName())); JSONObject data = new JSONObject(); data.put("src", url(r)); j.put("data", data); j.put("total", 1); j.put("success", true); } catch(Exception e) { j.put("errors", e.toString()); } finally { try { upload.delete(); } catch(IOException e) { log.error("Error deleting upload", e); } } } } // text/html and HTML encode because of http://docs.sencha.com/ext-js/4-1/#!/api/Ext.data.Connection // requirements (WTF???) return new StreamingResolution("text/html", HtmlUtil.encode(j.toString(4))); } public Resolution manage() throws JSONException { if("imagesList".equals(action)) { return imagesList(); } else if("delete".equals(action)) { return delete(); } else { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); j.put("errors", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.unkaction"), action)); return new StreamingResolution("application/json", j.toString(4)); } } public Resolution imagesList() throws JSONException { JSONObject j = new JSONObject(); try { JSONArray data = new JSONArray(); j.put("data", data); j.put("total", Stripersist.getEntityManager().createQuery("select count(*) from Resource").getSingleResult()); List<Resource> resources = Stripersist.getEntityManager().createQuery( "from Resource order by name") .setFirstResult(start) .setMaxResults(limit) .getResultList(); for(Resource r: resources) { JSONObject file = new JSONObject(); file.put("src", url(r)); file.put("name", r.getName()); file.put("fullname", r.getName()); data.put(file); } j.put("success", true); j.put("message", "Success"); } catch(Exception e) { j.put("success", false); j.put("message", "Fout"); j.put("errors", e.toString()); } return new StreamingResolution("application/json", j.toString(4)); } public Resolution delete() throws JSONException { JSONObject j = new JSONObject(); j.put("success", false); j.put("message", "Fout"); try { Resource r = Stripersist.getEntityManager().find(Resource.class, image); if(r == null) { j.put("errors", MessageFormat.format(getBundle().getString("viewer_admin.imageuploadactionbean.notfound"), image )); } else { Stripersist.getEntityManager().remove(r); Stripersist.getEntityManager().getTransaction().commit(); } j.put("success", true); j.put("message", "Verwijderd"); } catch(Exception e) { j.put("errors", e.toString()); } return new StreamingResolution("application/json", j.toString(4)); } }
206578_0
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
/** @author Elias De Hondt * 24/10/2022 */
block_comment
nl
/** @author Elias De<SUF>*/ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_1
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// De array wordt gecreëerd.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array<SUF> this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_2
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal<SUF> // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_3
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Als de maximumcapaciteit overschreden werd, wordt false teruggegeven.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de<SUF> if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_4
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Geeft het aantal elementen in de lijst terug.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het<SUF> return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_5
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Geeft het i-de element terug of -1 als het niet bestaat.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het<SUF> if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_6
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Gevorderd: kan je deze methode aanvullen?
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan<SUF> public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_7
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Deze methode verwijdert het element op de gegevenplaats.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode<SUF> this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_8
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// Alle elementen hierna moeten dus 1 plaats opgeschoven worden.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen<SUF> for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
206578_9
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return value geeft weer of het element bestond en succesvol verwijderd is. return index >= 0 && index < this.numbers.length; } }
EliasDeHondt/ComputerProgramming1-OOConcepts
W6P1/W6P1 FlexibeleLijst/src/List.java
492
// De return value geeft weer of het element bestond en succesvol verwijderd is.
line_comment
nl
/** @author Elias De Hondt * 24/10/2022 */ public class List { // Attributen private int[] numbers; private int size; // Constructor public List(int capacity) { // De array wordt gecreëerd. this.numbers = new int[capacity]; this.size = 0; } // Methode public boolean add(int i, int number) { // Het getal wordt op het einde in de array gestockeerd en size wordt verhoogd. // Als de maximumcapaciteit overschreden werd, wordt false teruggegeven. if (i >= this.numbers.length) { return false; } else { this.numbers[(this.numbers.length - 1) - i] = number; this.size++; return true; } } public int size() { // Geeft het aantal elementen in de lijst terug. return this.size; } public int get(int i) { // Geeft het i-de element terug of -1 als het niet bestaat. if (i >= this.numbers.length) { return -1; } else { return numbers[(this.numbers.length - 1) - i]; } } // Gevorderd: kan je deze methode aanvullen? public boolean remove(int index) { // Deze methode verwijdert het element op de gegevenplaats. this.numbers[this.numbers.length - index - 1] = 0; size--; // Alle elementen hierna moeten dus 1 plaats opgeschoven worden. for (int i = this.numbers.length - index - 1; i > 0; i--) { this.numbers[i] = this.numbers[i -1]; } // De return<SUF> return index >= 0 && index < this.numbers.length; } }
206583_0
package nello.controller; import nello.model.NetworkMember; import nello.model.User; import nello.model.UsersTabModel; import nello.observer.UsersTabObserver; import nello.view.AlertBox; import nello.view.ProfileView; import javax.ws.rs.core.Response; import java.util.logging.Level; public class UsersTabController implements IController { private MainController mainController; private UsersTabModel usersTabModel; public UsersTabController(MainController mainController, UsersTabModel usersTabModel) { this.mainController = mainController; this.usersTabModel = usersTabModel; } public void registerObserver(UsersTabObserver o){ usersTabModel.registerObserver(o); } public void onEditButtonClick(long id) { HTTPController http = mainController.getHttpController(); Response response = http.get("/users/" + id); switch (response.getStatus()){ case 200: User u = response.readEntity(User.class); mainController.getProfileController().setUser(u); mainController.getStageController().displayView(new ProfileView()); break; case 401: mainController.getStageController().displayPopup(new AlertBox("Opgegeven ID is onbekend.", Level.FINE, 3)); break; } } public void onDeleteButtonClick(long id) { HTTPController http = mainController.getHttpController(); Response response = http.delete("/users/" + id); System.out.println(response.getStatus()); switch (response.getStatus()){ case 200: mainController.getUsersTabController().getUsersTabModel().setUserList(mainController.getUserController().listUsers()); // mainController.getStageController().displayPopup(new AlertBox("Gebruiker is verwijderd.", Level.FINE, 3)); break; } } public UsersTabModel getUsersTabModel() { return usersTabModel; } }
VisserSanne/IPSEN2-Frontend
src/main/java/nello/controller/UsersTabController.java
489
// mainController.getStageController().displayPopup(new AlertBox("Gebruiker is verwijderd.", Level.FINE, 3));
line_comment
nl
package nello.controller; import nello.model.NetworkMember; import nello.model.User; import nello.model.UsersTabModel; import nello.observer.UsersTabObserver; import nello.view.AlertBox; import nello.view.ProfileView; import javax.ws.rs.core.Response; import java.util.logging.Level; public class UsersTabController implements IController { private MainController mainController; private UsersTabModel usersTabModel; public UsersTabController(MainController mainController, UsersTabModel usersTabModel) { this.mainController = mainController; this.usersTabModel = usersTabModel; } public void registerObserver(UsersTabObserver o){ usersTabModel.registerObserver(o); } public void onEditButtonClick(long id) { HTTPController http = mainController.getHttpController(); Response response = http.get("/users/" + id); switch (response.getStatus()){ case 200: User u = response.readEntity(User.class); mainController.getProfileController().setUser(u); mainController.getStageController().displayView(new ProfileView()); break; case 401: mainController.getStageController().displayPopup(new AlertBox("Opgegeven ID is onbekend.", Level.FINE, 3)); break; } } public void onDeleteButtonClick(long id) { HTTPController http = mainController.getHttpController(); Response response = http.delete("/users/" + id); System.out.println(response.getStatus()); switch (response.getStatus()){ case 200: mainController.getUsersTabController().getUsersTabModel().setUserList(mainController.getUserController().listUsers()); // mainController.getStageController().displayPopup(new AlertBox("Gebruiker<SUF> break; } } public UsersTabModel getUsersTabModel() { return usersTabModel; } }
206605_1
/* * Neon, a roguelike engine. * Copyright (C) 2013 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.narrative; import java.util.*; import neon.core.Engine; import neon.core.event.TurnEvent; import neon.entities.Creature; import neon.resources.quest.Conversation; import neon.resources.quest.RQuest; import neon.resources.quest.Topic; import neon.util.fsm.TransitionEvent; import net.engio.mbassy.listener.Handler; public class QuestTracker { private LinkedList<String> objects = new LinkedList<>(); private HashMap<String, Quest> quests = new HashMap<>(); // tijdelijke map voor quests die voor dialogmodule zijn geladen private HashMap<String, Quest> temp = new HashMap<>(); public QuestTracker() { } /** * Return all dialog topics for the given creature. The caller of this * method should take care to properly initialize the scripting engine: * the {@code NPC} variable should be made to refer to the given creature * before calling this method. * * @param speaker the creature that is spoken to * @return a {@code Vector} with all {@code Topic}s for the given creature */ public Vector<Topic> getDialog(Creature speaker) { Vector<Topic> dialog = new Vector<Topic>(); for(Quest quest : getQuests(speaker)) { for(Conversation conversation : quest.getConversations()) { dialog.add(conversation.getRootTopic()); } } return dialog; } public Vector<Topic> getSubtopics(Topic topic) { Vector<Topic> dialog = new Vector<Topic>(); Quest quest = quests.get(topic.questID); for(Conversation c : quest.getConversations()) { if(c.id.equals(topic.conversationID)) { dialog.addAll(c.getTopics(topic)); break; } } return dialog; } public void doAction(Topic topic) { HashMap<String, Object> objects = new HashMap<>(); // if(quests.containsKey(topic.quest)) { // objects.putAll(quests.get(topic.quest).getObjects()); // } else if(temp.containsKey(topic.quest)) { // objects.putAll(temp.get(topic.quest).getObjects()); // } for(Map.Entry<String, Object> entry : objects.entrySet()) { Engine.getScriptEngine().put(entry.getKey(), entry.getValue()); } if(topic.action != null) { Engine.execute(topic.action); } } /** * Start the quest with the given id. * * @param id */ public void startQuest(String id) { if(temp.containsKey(id)) { Quest quest = temp.remove(id); quests.put(id, quest); } else if(!quests.containsKey(id)) { RQuest quest = (RQuest)Engine.getResources().getResource(id, "quest"); quests.put(id, new Quest(quest)); } } /** * Finish the quest with the given id. * * @param id */ public void finishQuest(String id) { if(quests.containsKey(id)) { Quest quest = quests.get(id); quest.finish(); if(quest.template.repeat) { // repeat quests worden verwijderd om opnieuw kunnen starten quests.remove(id); } } } private Collection<Quest> getQuests(Creature speaker) { ArrayList<Quest> list = new ArrayList<Quest>(); for(Quest quest : quests.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } for(Quest quest : temp.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } return list; } public String getNextRequestedObject() { return objects.poll(); } void addObject(String object) { objects.add(object); } void checkTransition(TransitionEvent te) { } @Handler public void start(TurnEvent te) { if(te.isStart()) { for(RQuest quest : Engine.getResources().getResources(RQuest.class)) { if(quest.initial) { startQuest(quest.id); } } } } }
kba/neon
src/main/java/neon/narrative/QuestTracker.java
1,355
// tijdelijke map voor quests die voor dialogmodule zijn geladen
line_comment
nl
/* * Neon, a roguelike engine. * Copyright (C) 2013 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.narrative; import java.util.*; import neon.core.Engine; import neon.core.event.TurnEvent; import neon.entities.Creature; import neon.resources.quest.Conversation; import neon.resources.quest.RQuest; import neon.resources.quest.Topic; import neon.util.fsm.TransitionEvent; import net.engio.mbassy.listener.Handler; public class QuestTracker { private LinkedList<String> objects = new LinkedList<>(); private HashMap<String, Quest> quests = new HashMap<>(); // tijdelijke map<SUF> private HashMap<String, Quest> temp = new HashMap<>(); public QuestTracker() { } /** * Return all dialog topics for the given creature. The caller of this * method should take care to properly initialize the scripting engine: * the {@code NPC} variable should be made to refer to the given creature * before calling this method. * * @param speaker the creature that is spoken to * @return a {@code Vector} with all {@code Topic}s for the given creature */ public Vector<Topic> getDialog(Creature speaker) { Vector<Topic> dialog = new Vector<Topic>(); for(Quest quest : getQuests(speaker)) { for(Conversation conversation : quest.getConversations()) { dialog.add(conversation.getRootTopic()); } } return dialog; } public Vector<Topic> getSubtopics(Topic topic) { Vector<Topic> dialog = new Vector<Topic>(); Quest quest = quests.get(topic.questID); for(Conversation c : quest.getConversations()) { if(c.id.equals(topic.conversationID)) { dialog.addAll(c.getTopics(topic)); break; } } return dialog; } public void doAction(Topic topic) { HashMap<String, Object> objects = new HashMap<>(); // if(quests.containsKey(topic.quest)) { // objects.putAll(quests.get(topic.quest).getObjects()); // } else if(temp.containsKey(topic.quest)) { // objects.putAll(temp.get(topic.quest).getObjects()); // } for(Map.Entry<String, Object> entry : objects.entrySet()) { Engine.getScriptEngine().put(entry.getKey(), entry.getValue()); } if(topic.action != null) { Engine.execute(topic.action); } } /** * Start the quest with the given id. * * @param id */ public void startQuest(String id) { if(temp.containsKey(id)) { Quest quest = temp.remove(id); quests.put(id, quest); } else if(!quests.containsKey(id)) { RQuest quest = (RQuest)Engine.getResources().getResource(id, "quest"); quests.put(id, new Quest(quest)); } } /** * Finish the quest with the given id. * * @param id */ public void finishQuest(String id) { if(quests.containsKey(id)) { Quest quest = quests.get(id); quest.finish(); if(quest.template.repeat) { // repeat quests worden verwijderd om opnieuw kunnen starten quests.remove(id); } } } private Collection<Quest> getQuests(Creature speaker) { ArrayList<Quest> list = new ArrayList<Quest>(); for(Quest quest : quests.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } for(Quest quest : temp.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } return list; } public String getNextRequestedObject() { return objects.poll(); } void addObject(String object) { objects.add(object); } void checkTransition(TransitionEvent te) { } @Handler public void start(TurnEvent te) { if(te.isStart()) { for(RQuest quest : Engine.getResources().getResources(RQuest.class)) { if(quest.initial) { startQuest(quest.id); } } } } }
206605_7
/* * Neon, a roguelike engine. * Copyright (C) 2013 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.narrative; import java.util.*; import neon.core.Engine; import neon.core.event.TurnEvent; import neon.entities.Creature; import neon.resources.quest.Conversation; import neon.resources.quest.RQuest; import neon.resources.quest.Topic; import neon.util.fsm.TransitionEvent; import net.engio.mbassy.listener.Handler; public class QuestTracker { private LinkedList<String> objects = new LinkedList<>(); private HashMap<String, Quest> quests = new HashMap<>(); // tijdelijke map voor quests die voor dialogmodule zijn geladen private HashMap<String, Quest> temp = new HashMap<>(); public QuestTracker() { } /** * Return all dialog topics for the given creature. The caller of this * method should take care to properly initialize the scripting engine: * the {@code NPC} variable should be made to refer to the given creature * before calling this method. * * @param speaker the creature that is spoken to * @return a {@code Vector} with all {@code Topic}s for the given creature */ public Vector<Topic> getDialog(Creature speaker) { Vector<Topic> dialog = new Vector<Topic>(); for(Quest quest : getQuests(speaker)) { for(Conversation conversation : quest.getConversations()) { dialog.add(conversation.getRootTopic()); } } return dialog; } public Vector<Topic> getSubtopics(Topic topic) { Vector<Topic> dialog = new Vector<Topic>(); Quest quest = quests.get(topic.questID); for(Conversation c : quest.getConversations()) { if(c.id.equals(topic.conversationID)) { dialog.addAll(c.getTopics(topic)); break; } } return dialog; } public void doAction(Topic topic) { HashMap<String, Object> objects = new HashMap<>(); // if(quests.containsKey(topic.quest)) { // objects.putAll(quests.get(topic.quest).getObjects()); // } else if(temp.containsKey(topic.quest)) { // objects.putAll(temp.get(topic.quest).getObjects()); // } for(Map.Entry<String, Object> entry : objects.entrySet()) { Engine.getScriptEngine().put(entry.getKey(), entry.getValue()); } if(topic.action != null) { Engine.execute(topic.action); } } /** * Start the quest with the given id. * * @param id */ public void startQuest(String id) { if(temp.containsKey(id)) { Quest quest = temp.remove(id); quests.put(id, quest); } else if(!quests.containsKey(id)) { RQuest quest = (RQuest)Engine.getResources().getResource(id, "quest"); quests.put(id, new Quest(quest)); } } /** * Finish the quest with the given id. * * @param id */ public void finishQuest(String id) { if(quests.containsKey(id)) { Quest quest = quests.get(id); quest.finish(); if(quest.template.repeat) { // repeat quests worden verwijderd om opnieuw kunnen starten quests.remove(id); } } } private Collection<Quest> getQuests(Creature speaker) { ArrayList<Quest> list = new ArrayList<Quest>(); for(Quest quest : quests.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } for(Quest quest : temp.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } return list; } public String getNextRequestedObject() { return objects.poll(); } void addObject(String object) { objects.add(object); } void checkTransition(TransitionEvent te) { } @Handler public void start(TurnEvent te) { if(te.isStart()) { for(RQuest quest : Engine.getResources().getResources(RQuest.class)) { if(quest.initial) { startQuest(quest.id); } } } } }
kba/neon
src/main/java/neon/narrative/QuestTracker.java
1,355
// repeat quests worden verwijderd om opnieuw kunnen starten
line_comment
nl
/* * Neon, a roguelike engine. * Copyright (C) 2013 - Maarten Driesen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package neon.narrative; import java.util.*; import neon.core.Engine; import neon.core.event.TurnEvent; import neon.entities.Creature; import neon.resources.quest.Conversation; import neon.resources.quest.RQuest; import neon.resources.quest.Topic; import neon.util.fsm.TransitionEvent; import net.engio.mbassy.listener.Handler; public class QuestTracker { private LinkedList<String> objects = new LinkedList<>(); private HashMap<String, Quest> quests = new HashMap<>(); // tijdelijke map voor quests die voor dialogmodule zijn geladen private HashMap<String, Quest> temp = new HashMap<>(); public QuestTracker() { } /** * Return all dialog topics for the given creature. The caller of this * method should take care to properly initialize the scripting engine: * the {@code NPC} variable should be made to refer to the given creature * before calling this method. * * @param speaker the creature that is spoken to * @return a {@code Vector} with all {@code Topic}s for the given creature */ public Vector<Topic> getDialog(Creature speaker) { Vector<Topic> dialog = new Vector<Topic>(); for(Quest quest : getQuests(speaker)) { for(Conversation conversation : quest.getConversations()) { dialog.add(conversation.getRootTopic()); } } return dialog; } public Vector<Topic> getSubtopics(Topic topic) { Vector<Topic> dialog = new Vector<Topic>(); Quest quest = quests.get(topic.questID); for(Conversation c : quest.getConversations()) { if(c.id.equals(topic.conversationID)) { dialog.addAll(c.getTopics(topic)); break; } } return dialog; } public void doAction(Topic topic) { HashMap<String, Object> objects = new HashMap<>(); // if(quests.containsKey(topic.quest)) { // objects.putAll(quests.get(topic.quest).getObjects()); // } else if(temp.containsKey(topic.quest)) { // objects.putAll(temp.get(topic.quest).getObjects()); // } for(Map.Entry<String, Object> entry : objects.entrySet()) { Engine.getScriptEngine().put(entry.getKey(), entry.getValue()); } if(topic.action != null) { Engine.execute(topic.action); } } /** * Start the quest with the given id. * * @param id */ public void startQuest(String id) { if(temp.containsKey(id)) { Quest quest = temp.remove(id); quests.put(id, quest); } else if(!quests.containsKey(id)) { RQuest quest = (RQuest)Engine.getResources().getResource(id, "quest"); quests.put(id, new Quest(quest)); } } /** * Finish the quest with the given id. * * @param id */ public void finishQuest(String id) { if(quests.containsKey(id)) { Quest quest = quests.get(id); quest.finish(); if(quest.template.repeat) { // repeat quests<SUF> quests.remove(id); } } } private Collection<Quest> getQuests(Creature speaker) { ArrayList<Quest> list = new ArrayList<Quest>(); for(Quest quest : quests.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } for(Quest quest : temp.values()) { if(QuestUtils.checkQuest(quest.template)) { list.add(quest); } } return list; } public String getNextRequestedObject() { return objects.poll(); } void addObject(String object) { objects.add(object); } void checkTransition(TransitionEvent te) { } @Handler public void start(TurnEvent te) { if(te.isStart()) { for(RQuest quest : Engine.getResources().getResources(RQuest.class)) { if(quest.initial) { startQuest(quest.id); } } } } }
206742_4
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package controlador.Utiles; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.URI; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class Utiles { //Codigo para validar la cedula public static boolean validadorDeCedula(String cedula) { boolean cedulaCorrecta = false; try { if (cedula.length() == 10) // ConstantesApp.LongitudCedula { int tercerDigito = Integer.parseInt(cedula.substring(2, 3)); if (tercerDigito < 6) { // Coeficientes de validación cédula // El decimo digito se lo considera dígito verificador int[] coefValCedula = {2, 1, 2, 1, 2, 1, 2, 1, 2}; int verificador = Integer.parseInt(cedula.substring(9, 10)); int suma = 0; int digito = 0; for (int i = 0; i < (cedula.length() - 1); i++) { digito = Integer.parseInt(cedula.substring(i, i + 1)) * coefValCedula[i]; suma += ((digito % 10) + (digito / 10)); } if ((suma % 10 == 0) && (suma % 10 == verificador)) { cedulaCorrecta = true; } else if ((10 - (suma % 10)) == verificador) { cedulaCorrecta = true; } else { cedulaCorrecta = false; } } else { cedulaCorrecta = false; } } else { cedulaCorrecta = false; } } catch (NumberFormatException nfe) { cedulaCorrecta = false; } catch (Exception err) { System.out.println("Una excepcion ocurrio en el proceso de validadcion"); cedulaCorrecta = false; } if (!cedulaCorrecta) { System.out.println("La Cédula ingresada es Incorrecta"); } return cedulaCorrecta; } public static Field getField(Class clazz, String atribute) { Field field = null; //Field[] fileds = clazz.getFields(); for (Field f : clazz.getSuperclass().getDeclaredFields()) { if (f.getName().equalsIgnoreCase(atribute)) { field = f; break; } } for (Field f : clazz.getDeclaredFields()) { if (f.getName().equalsIgnoreCase(atribute)) { field = f; break; } } return field; } public static String getDirPoject() { return System.getProperty("user.dir"); } public static String getOS() { return System.getProperty("os.name"); } // // public static void abrirNavegadorPredeterminadorWindows(String url) throws Exception { // Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); // } public static void abrirNavegadorPredeterminadoWindows(String url) { try { ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "start", url); builder.start(); } catch (IOException e) { e.printStackTrace(); } } public static void abrirNavegadorPredeterminadorLinux(String url) throws Exception { Runtime.getRuntime().exec("xdg-open " + url); } public static void abrirNavegadorPredeterminadorMacOsx(String url) throws Exception { Runtime.getRuntime().exec("open " + url); } public static String extension(String fileName) { String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } return extension; } public static void copiarArchivo(File origen, File destino) throws Exception { Files.copy(origen.toPath(), (destino).toPath(), StandardCopyOption.REPLACE_EXISTING); } public static double coordGpsToKm(double lat1, double lon1, double lat2, double lon2) { double lat1rad = Math.toRadians(lat1); double lon1rad = Math.toRadians(lon1); double lat2rad = Math.toRadians(lat2); double lon2rad = Math.toRadians(lon2); double difLatitud = lat1rad - lat2rad; double difLongitud = lon1rad - lon2rad; double a = Math.pow(Math.sin(difLatitud / 2), 2) + Math.cos(lat1rad) * Math.cos(lat2rad) * Math.pow(Math.sin(difLongitud / 2), 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double radioTierraKm = 6378.0; double distancia = radioTierraKm * c; return distancia; } public static Double redonder(Double x){ return Math.round(x * 100.0) / 100.0; } }
jcbastianl/PracticaFinal1
src/controlador/Utiles/Utiles.java
1,435
//Field[] fileds = clazz.getFields();
line_comment
nl
/* * Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license * Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template */ package controlador.Utiles; import java.awt.Desktop; import java.io.File; import java.io.IOException; import java.lang.reflect.Field; import java.net.URI; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class Utiles { //Codigo para validar la cedula public static boolean validadorDeCedula(String cedula) { boolean cedulaCorrecta = false; try { if (cedula.length() == 10) // ConstantesApp.LongitudCedula { int tercerDigito = Integer.parseInt(cedula.substring(2, 3)); if (tercerDigito < 6) { // Coeficientes de validación cédula // El decimo digito se lo considera dígito verificador int[] coefValCedula = {2, 1, 2, 1, 2, 1, 2, 1, 2}; int verificador = Integer.parseInt(cedula.substring(9, 10)); int suma = 0; int digito = 0; for (int i = 0; i < (cedula.length() - 1); i++) { digito = Integer.parseInt(cedula.substring(i, i + 1)) * coefValCedula[i]; suma += ((digito % 10) + (digito / 10)); } if ((suma % 10 == 0) && (suma % 10 == verificador)) { cedulaCorrecta = true; } else if ((10 - (suma % 10)) == verificador) { cedulaCorrecta = true; } else { cedulaCorrecta = false; } } else { cedulaCorrecta = false; } } else { cedulaCorrecta = false; } } catch (NumberFormatException nfe) { cedulaCorrecta = false; } catch (Exception err) { System.out.println("Una excepcion ocurrio en el proceso de validadcion"); cedulaCorrecta = false; } if (!cedulaCorrecta) { System.out.println("La Cédula ingresada es Incorrecta"); } return cedulaCorrecta; } public static Field getField(Class clazz, String atribute) { Field field = null; //Field[] fileds<SUF> for (Field f : clazz.getSuperclass().getDeclaredFields()) { if (f.getName().equalsIgnoreCase(atribute)) { field = f; break; } } for (Field f : clazz.getDeclaredFields()) { if (f.getName().equalsIgnoreCase(atribute)) { field = f; break; } } return field; } public static String getDirPoject() { return System.getProperty("user.dir"); } public static String getOS() { return System.getProperty("os.name"); } // // public static void abrirNavegadorPredeterminadorWindows(String url) throws Exception { // Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url); // } public static void abrirNavegadorPredeterminadoWindows(String url) { try { ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", "start", url); builder.start(); } catch (IOException e) { e.printStackTrace(); } } public static void abrirNavegadorPredeterminadorLinux(String url) throws Exception { Runtime.getRuntime().exec("xdg-open " + url); } public static void abrirNavegadorPredeterminadorMacOsx(String url) throws Exception { Runtime.getRuntime().exec("open " + url); } public static String extension(String fileName) { String extension = ""; int i = fileName.lastIndexOf('.'); if (i > 0) { extension = fileName.substring(i + 1); } return extension; } public static void copiarArchivo(File origen, File destino) throws Exception { Files.copy(origen.toPath(), (destino).toPath(), StandardCopyOption.REPLACE_EXISTING); } public static double coordGpsToKm(double lat1, double lon1, double lat2, double lon2) { double lat1rad = Math.toRadians(lat1); double lon1rad = Math.toRadians(lon1); double lat2rad = Math.toRadians(lat2); double lon2rad = Math.toRadians(lon2); double difLatitud = lat1rad - lat2rad; double difLongitud = lon1rad - lon2rad; double a = Math.pow(Math.sin(difLatitud / 2), 2) + Math.cos(lat1rad) * Math.cos(lat2rad) * Math.pow(Math.sin(difLongitud / 2), 2); double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); double radioTierraKm = 6378.0; double distancia = radioTierraKm * c; return distancia; } public static Double redonder(Double x){ return Math.round(x * 100.0) / 100.0; } }
206782_6
import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual put, get, contains, * delete, size, and is-empty methods. * It also provides ordered methods for finding the minimum, * maximum, floor, and ceiling. * It also provides a keys method for iterating over all of the keys. * A symbol table implements the associative array abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * This implementation uses a left-leaning red-black BST. It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * The put, contains, remove, minimum, * maximum, ceiling, and floor operations each take * logarithmic time in the worst case, if the tree becomes unbalanced. * The size, and is-empty operations take constant time. * Construction takes constant time. * For other implementations of the same API, see {@link ST}, {@link BinarySearchST}, * {@link SequentialSearchST}, {@link BST}, * {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}. * @author Robert Sedgewick * @author Kevin Wayne */ public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int size; // subtree count public Node(Key key, Value val, boolean color, int size) { this.key = key; this.val = val; this.color = color; this.size = size; } } /** * Initializes an empty symbol table. */ public RedBlackBST() { } /*************************************************************************** * Node helper methods. ***************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return x.color == RED; } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.size; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } /** * Is this symbol table empty? * @return {@code true} if this symbol table is empty and {@code false} otherwise */ public boolean isEmpty() { return root == null; } /*************************************************************************** * Standard BST search. ***************************************************************************/ /** * Returns the value associated with the given key. * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Does this symbol table contain the given key? * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { return get(key) != null; } /*************************************************************************** * Red-black tree insertion. ***************************************************************************/ /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ //<Crucial public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } root = put(root, key, val); root.color = BLACK; // assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } // /Crucial> /*************************************************************************** * Red-black tree deletion. ***************************************************************************/ /** * Removes the smallest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null)//no key is less than h, h is min. return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } /** * Removes the largest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (!contains(key)) return; // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { // assert get(h, key) != null; if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /*************************************************************************** * Red-black tree helper functions. ***************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { // assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { // assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children // assert (h != null) && (h.left != null) && (h.right != null); // assert (!isRed(h) && isRed(h.left) && isRed(h.right)) // || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); flipColors(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); flipColors(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { // assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } /*************************************************************************** * Utility functions. ***************************************************************************/ /** * Returns the height of the BST (for debugging). * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in the symbol table. * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { // assert x != null; if (x.left == null) return x; else return min(x.left); } /** * Returns the largest key in the symbol table. * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { // assert x != null; if (x.right == null) return x; else return max(x.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table"); Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table"); Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } /** * Return the kth smallest key in the symbol table. * @param k the order statistic * @return the {@code k}th smallest key in the symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * n–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { // assert x != null; // assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*************************************************************************** * Range count and range search. ***************************************************************************/ /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * @return all keys in the symbol table as an {@code Iterable} */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) as an {@code Iterable} * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /*************************************************************************** * Check integrity of red-black tree data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.size != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /** * Unit tests the {@code RedBlackBST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
mxc19912008/Key-Algorithms
Chapter 3 查找 Searching/3.4 red-black tree.java
6,849
/*************************************************************************** * Node helper methods. ***************************************************************************/
block_comment
nl
import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual put, get, contains, * delete, size, and is-empty methods. * It also provides ordered methods for finding the minimum, * maximum, floor, and ceiling. * It also provides a keys method for iterating over all of the keys. * A symbol table implements the associative array abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * This implementation uses a left-leaning red-black BST. It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * The put, contains, remove, minimum, * maximum, ceiling, and floor operations each take * logarithmic time in the worst case, if the tree becomes unbalanced. * The size, and is-empty operations take constant time. * Construction takes constant time. * For other implementations of the same API, see {@link ST}, {@link BinarySearchST}, * {@link SequentialSearchST}, {@link BST}, * {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}. * @author Robert Sedgewick * @author Kevin Wayne */ public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int size; // subtree count public Node(Key key, Value val, boolean color, int size) { this.key = key; this.val = val; this.color = color; this.size = size; } } /** * Initializes an empty symbol table. */ public RedBlackBST() { } /*************************************************************************** * Node helper methods.<SUF>*/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return x.color == RED; } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.size; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } /** * Is this symbol table empty? * @return {@code true} if this symbol table is empty and {@code false} otherwise */ public boolean isEmpty() { return root == null; } /*************************************************************************** * Standard BST search. ***************************************************************************/ /** * Returns the value associated with the given key. * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Does this symbol table contain the given key? * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { return get(key) != null; } /*************************************************************************** * Red-black tree insertion. ***************************************************************************/ /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ //<Crucial public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } root = put(root, key, val); root.color = BLACK; // assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } // /Crucial> /*************************************************************************** * Red-black tree deletion. ***************************************************************************/ /** * Removes the smallest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null)//no key is less than h, h is min. return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } /** * Removes the largest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (!contains(key)) return; // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { // assert get(h, key) != null; if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /*************************************************************************** * Red-black tree helper functions. ***************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { // assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { // assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children // assert (h != null) && (h.left != null) && (h.right != null); // assert (!isRed(h) && isRed(h.left) && isRed(h.right)) // || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); flipColors(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); flipColors(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { // assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } /*************************************************************************** * Utility functions. ***************************************************************************/ /** * Returns the height of the BST (for debugging). * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in the symbol table. * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { // assert x != null; if (x.left == null) return x; else return min(x.left); } /** * Returns the largest key in the symbol table. * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { // assert x != null; if (x.right == null) return x; else return max(x.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table"); Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table"); Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } /** * Return the kth smallest key in the symbol table. * @param k the order statistic * @return the {@code k}th smallest key in the symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * n–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { // assert x != null; // assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*************************************************************************** * Range count and range search. ***************************************************************************/ /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * @return all keys in the symbol table as an {@code Iterable} */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) as an {@code Iterable} * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /*************************************************************************** * Check integrity of red-black tree data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.size != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /** * Unit tests the {@code RedBlackBST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
206782_31
import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual put, get, contains, * delete, size, and is-empty methods. * It also provides ordered methods for finding the minimum, * maximum, floor, and ceiling. * It also provides a keys method for iterating over all of the keys. * A symbol table implements the associative array abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * This implementation uses a left-leaning red-black BST. It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * The put, contains, remove, minimum, * maximum, ceiling, and floor operations each take * logarithmic time in the worst case, if the tree becomes unbalanced. * The size, and is-empty operations take constant time. * Construction takes constant time. * For other implementations of the same API, see {@link ST}, {@link BinarySearchST}, * {@link SequentialSearchST}, {@link BST}, * {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}. * @author Robert Sedgewick * @author Kevin Wayne */ public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int size; // subtree count public Node(Key key, Value val, boolean color, int size) { this.key = key; this.val = val; this.color = color; this.size = size; } } /** * Initializes an empty symbol table. */ public RedBlackBST() { } /*************************************************************************** * Node helper methods. ***************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return x.color == RED; } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.size; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } /** * Is this symbol table empty? * @return {@code true} if this symbol table is empty and {@code false} otherwise */ public boolean isEmpty() { return root == null; } /*************************************************************************** * Standard BST search. ***************************************************************************/ /** * Returns the value associated with the given key. * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Does this symbol table contain the given key? * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { return get(key) != null; } /*************************************************************************** * Red-black tree insertion. ***************************************************************************/ /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ //<Crucial public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } root = put(root, key, val); root.color = BLACK; // assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } // /Crucial> /*************************************************************************** * Red-black tree deletion. ***************************************************************************/ /** * Removes the smallest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null)//no key is less than h, h is min. return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } /** * Removes the largest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (!contains(key)) return; // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { // assert get(h, key) != null; if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /*************************************************************************** * Red-black tree helper functions. ***************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { // assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { // assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children // assert (h != null) && (h.left != null) && (h.right != null); // assert (!isRed(h) && isRed(h.left) && isRed(h.right)) // || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); flipColors(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); flipColors(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { // assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } /*************************************************************************** * Utility functions. ***************************************************************************/ /** * Returns the height of the BST (for debugging). * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in the symbol table. * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { // assert x != null; if (x.left == null) return x; else return min(x.left); } /** * Returns the largest key in the symbol table. * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { // assert x != null; if (x.right == null) return x; else return max(x.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table"); Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table"); Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } /** * Return the kth smallest key in the symbol table. * @param k the order statistic * @return the {@code k}th smallest key in the symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * n–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { // assert x != null; // assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*************************************************************************** * Range count and range search. ***************************************************************************/ /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * @return all keys in the symbol table as an {@code Iterable} */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) as an {@code Iterable} * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /*************************************************************************** * Check integrity of red-black tree data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.size != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /** * Unit tests the {@code RedBlackBST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
mxc19912008/Key-Algorithms
Chapter 3 查找 Searching/3.4 red-black tree.java
6,849
// h.val = get(h.right, min(h.right).key);
line_comment
nl
import java.util.NoSuchElementException; /** * The {@code BST} class represents an ordered symbol table of generic * key-value pairs. * It supports the usual put, get, contains, * delete, size, and is-empty methods. * It also provides ordered methods for finding the minimum, * maximum, floor, and ceiling. * It also provides a keys method for iterating over all of the keys. * A symbol table implements the associative array abstraction: * when associating a value with a key that is already in the symbol table, * the convention is to replace the old value with the new value. * Unlike {@link java.util.Map}, this class uses the convention that * values cannot be {@code null}—setting the * value associated with a key to {@code null} is equivalent to deleting the key * from the symbol table. * This implementation uses a left-leaning red-black BST. It requires that * the key type implements the {@code Comparable} interface and calls the * {@code compareTo()} and method to compare two keys. It does not call either * {@code equals()} or {@code hashCode()}. * The put, contains, remove, minimum, * maximum, ceiling, and floor operations each take * logarithmic time in the worst case, if the tree becomes unbalanced. * The size, and is-empty operations take constant time. * Construction takes constant time. * For other implementations of the same API, see {@link ST}, {@link BinarySearchST}, * {@link SequentialSearchST}, {@link BST}, * {@link SeparateChainingHashST}, {@link LinearProbingHashST}, and {@link AVLTreeST}. * @author Robert Sedgewick * @author Kevin Wayne */ public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int size; // subtree count public Node(Key key, Value val, boolean color, int size) { this.key = key; this.val = val; this.color = color; this.size = size; } } /** * Initializes an empty symbol table. */ public RedBlackBST() { } /*************************************************************************** * Node helper methods. ***************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return x.color == RED; } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.size; } /** * Returns the number of key-value pairs in this symbol table. * @return the number of key-value pairs in this symbol table */ public int size() { return size(root); } /** * Is this symbol table empty? * @return {@code true} if this symbol table is empty and {@code false} otherwise */ public boolean isEmpty() { return root == null; } /*************************************************************************** * Standard BST search. ***************************************************************************/ /** * Returns the value associated with the given key. * @param key the key * @return the value associated with the given key if the key is in the symbol table * and {@code null} if the key is not in the symbol table * @throws IllegalArgumentException if {@code key} is {@code null} */ public Value get(Key key) { if (key == null) throw new IllegalArgumentException("argument to get() is null"); return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } /** * Does this symbol table contain the given key? * @param key the key * @return {@code true} if this symbol table contains {@code key} and * {@code false} otherwise * @throws IllegalArgumentException if {@code key} is {@code null} */ public boolean contains(Key key) { return get(key) != null; } /*************************************************************************** * Red-black tree insertion. ***************************************************************************/ /** * Inserts the specified key-value pair into the symbol table, overwriting the old * value with the new value if the symbol table already contains the specified key. * Deletes the specified key (and its associated value) from this symbol table * if the specified value is {@code null}. * * @param key the key * @param val the value * @throws IllegalArgumentException if {@code key} is {@code null} */ //<Crucial public void put(Key key, Value val) { if (key == null) throw new IllegalArgumentException("first argument to put() is null"); if (val == null) { delete(key); return; } root = put(root, key, val); root.color = BLACK; // assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } // /Crucial> /*************************************************************************** * Red-black tree deletion. ***************************************************************************/ /** * Removes the smallest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null)//no key is less than h, h is min. return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } /** * Removes the largest key and associated value from the symbol table. * @throws NoSuchElementException if the symbol table is empty */ public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } /** * Removes the specified key and its associated value from this symbol table * (if the key is in this symbol table). * * @param key the key * @throws IllegalArgumentException if {@code key} is {@code null} */ public void delete(Key key) { if (key == null) throw new IllegalArgumentException("argument to delete() is null"); if (!contains(key)) return; // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; // assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { // assert get(h, key) != null; if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val =<SUF> // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /*************************************************************************** * Red-black tree helper functions. ***************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { // assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { // assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.size = h.size; h.size = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children // assert (h != null) && (h.left != null) && (h.right != null); // assert (!isRed(h) && isRed(h.left) && isRed(h.right)) // || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); flipColors(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { // assert (h != null); // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); flipColors(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { // assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.size = size(h.left) + size(h.right) + 1; return h; } /*************************************************************************** * Utility functions. ***************************************************************************/ /** * Returns the height of the BST (for debugging). * @return the height of the BST (a 1-node tree has height 0) */ public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /*************************************************************************** * Ordered symbol table methods. ***************************************************************************/ /** * Returns the smallest key in the symbol table. * @return the smallest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key min() { if (isEmpty()) throw new NoSuchElementException("called min() with empty symbol table"); return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { // assert x != null; if (x.left == null) return x; else return min(x.left); } /** * Returns the largest key in the symbol table. * @return the largest key in the symbol table * @throws NoSuchElementException if the symbol table is empty */ public Key max() { if (isEmpty()) throw new NoSuchElementException("called max() with empty symbol table"); return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { // assert x != null; if (x.right == null) return x; else return max(x.right); } /** * Returns the largest key in the symbol table less than or equal to {@code key}. * @param key the key * @return the largest key in the symbol table less than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key floor(Key key) { if (key == null) throw new IllegalArgumentException("argument to floor() is null"); if (isEmpty()) throw new NoSuchElementException("called floor() with empty symbol table"); Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } /** * Returns the smallest key in the symbol table greater than or equal to {@code key}. * @param key the key * @return the smallest key in the symbol table greater than or equal to {@code key} * @throws NoSuchElementException if there is no such key * @throws IllegalArgumentException if {@code key} is {@code null} */ public Key ceiling(Key key) { if (key == null) throw new IllegalArgumentException("argument to ceiling() is null"); if (isEmpty()) throw new NoSuchElementException("called ceiling() with empty symbol table"); Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } /** * Return the kth smallest key in the symbol table. * @param k the order statistic * @return the {@code k}th smallest key in the symbol table * @throws IllegalArgumentException unless {@code k} is between 0 and * n–1 */ public Key select(int k) { if (k < 0 || k >= size()) { throw new IllegalArgumentException("called select() with invalid argument: " + k); } Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { // assert x != null; // assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } /** * Return the number of keys in the symbol table strictly less than {@code key}. * @param key the key * @return the number of keys in the symbol table strictly less than {@code key} * @throws IllegalArgumentException if {@code key} is {@code null} */ public int rank(Key key) { if (key == null) throw new IllegalArgumentException("argument to rank() is null"); return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*************************************************************************** * Range count and range search. ***************************************************************************/ /** * Returns all keys in the symbol table as an {@code Iterable}. * To iterate over all of the keys in the symbol table named {@code st}, * use the foreach notation: {@code for (Key key : st.keys())}. * @return all keys in the symbol table as an {@code Iterable} */ public Iterable<Key> keys() { if (isEmpty()) return new Queue<Key>(); return keys(min(), max()); } /** * Returns all keys in the symbol table in the given range, * as an {@code Iterable}. * * @param lo minimum endpoint * @param hi maximum endpoint * @return all keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) as an {@code Iterable} * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public Iterable<Key> keys(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to keys() is null"); if (hi == null) throw new IllegalArgumentException("second argument to keys() is null"); Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } /** * Returns the number of keys in the symbol table in the given range. * * @param lo minimum endpoint * @param hi maximum endpoint * @return the number of keys in the sybol table between {@code lo} * (inclusive) and {@code hi} (inclusive) * @throws IllegalArgumentException if either {@code lo} or {@code hi} * is {@code null} */ public int size(Key lo, Key hi) { if (lo == null) throw new IllegalArgumentException("first argument to size() is null"); if (hi == null) throw new IllegalArgumentException("second argument to size() is null"); if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /*************************************************************************** * Check integrity of red-black tree data structure. ***************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.size != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /** * Unit tests the {@code RedBlackBST} data type. * * @param args the command-line arguments */ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
206787_12
/************************************************************************* * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: http://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int N; // number of nodes in subtree public Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // return number of key-value pairs in BST public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node x) { if (x == null) return 0; else return x.N; } /*********************************************************************** * Search BST for given key, and return associated value if found, * return null if not found ***********************************************************************/ // does there exist a key-value pair with given key? public boolean contains(Key key) { return get(key) != null; } // return value associated with the given key, or null if no such key exists public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.val; } /*********************************************************************** * Insert key-value pair into BST * If key already exists, update with new value ***********************************************************************/ public void put(Key key, Value val) { if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node x, Key key, Value val) { if (x == null) return new Node(key, val, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, val); else if (cmp > 0) x.right = put(x.right, key, val); else x.val = val; x.N = 1 + size(x.left) + size(x.right); return x; } /*********************************************************************** * Delete ***********************************************************************/ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = size(x.left) + size(x.right) + 1; return x; } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = size(x.left) + size(x.right) + 1; return x; } public void delete(Key key) { root = delete(root, key); assert check(); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = size(x.left) + size(x.right) + 1; return x; } /*********************************************************************** * Min, max, floor, and ceiling ***********************************************************************/ public Key min() { if (isEmpty()) return null; return min(root).key; } private Node min(Node x) { if (x.left == null) return x; else return min(x.left); } public Key max() { if (isEmpty()) return null; return max(root).key; } private Node max(Node x) { if (x.right == null) return x; else return max(x.right); } public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) { Node t = ceiling(x.left, key); if (t != null) return t; else return x; } return ceiling(x.right, key); } /*********************************************************************** * Rank and selection ***********************************************************************/ public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // Return key of rank k. private Node select(Node x, int k) { if (x == null) return null; int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } public int rank(Key key) { return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ public Iterable<Key> keys() { return keys(min(), max()); } public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } // height of this BST (one-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } // level order traversal public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node x = queue.dequeue(); if (x == null) continue; keys.enqueue(x.key); queue.enqueue(x.left); queue.enqueue(x.right); } return keys; } /************************************************************************* * Check integrity of BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
flovera1/AI
dfsbfssearch/BST.java
3,302
/*********************************************************************** * Delete ***********************************************************************/
block_comment
nl
/************************************************************************* * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: http://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int N; // number of nodes in subtree public Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // return number of key-value pairs in BST public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node x) { if (x == null) return 0; else return x.N; } /*********************************************************************** * Search BST for given key, and return associated value if found, * return null if not found ***********************************************************************/ // does there exist a key-value pair with given key? public boolean contains(Key key) { return get(key) != null; } // return value associated with the given key, or null if no such key exists public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.val; } /*********************************************************************** * Insert key-value pair into BST * If key already exists, update with new value ***********************************************************************/ public void put(Key key, Value val) { if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node x, Key key, Value val) { if (x == null) return new Node(key, val, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, val); else if (cmp > 0) x.right = put(x.right, key, val); else x.val = val; x.N = 1 + size(x.left) + size(x.right); return x; } /*********************************************************************** * Delete <SUF>*/ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = size(x.left) + size(x.right) + 1; return x; } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = size(x.left) + size(x.right) + 1; return x; } public void delete(Key key) { root = delete(root, key); assert check(); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = size(x.left) + size(x.right) + 1; return x; } /*********************************************************************** * Min, max, floor, and ceiling ***********************************************************************/ public Key min() { if (isEmpty()) return null; return min(root).key; } private Node min(Node x) { if (x.left == null) return x; else return min(x.left); } public Key max() { if (isEmpty()) return null; return max(root).key; } private Node max(Node x) { if (x.right == null) return x; else return max(x.right); } public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) { Node t = ceiling(x.left, key); if (t != null) return t; else return x; } return ceiling(x.right, key); } /*********************************************************************** * Rank and selection ***********************************************************************/ public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // Return key of rank k. private Node select(Node x, int k) { if (x == null) return null; int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } public int rank(Key key) { return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ public Iterable<Key> keys() { return keys(min(), max()); } public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } // height of this BST (one-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } // level order traversal public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node x = queue.dequeue(); if (x == null) continue; keys.enqueue(x.key); queue.enqueue(x.left); queue.enqueue(x.right); } return keys; } /************************************************************************* * Check integrity of BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
206807_12
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: http://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int N; // number of nodes in subtree public Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // return number of key-value pairs in BST public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node x) { if (x == null) return 0; else return x.N; } /*********************************************************************** * Search BST for given key, and return associated value if found, * return null if not found ***********************************************************************/ // does there exist a key-value pair with given key? public boolean contains(Key key) { return get(key) != null; } // return value associated with the given key, or null if no such key exists public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.val; } /*********************************************************************** * Insert key-value pair into BST * If key already exists, update with new value ***********************************************************************/ public void put(Key key, Value val) { if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node x, Key key, Value val) { if (x == null) return new Node(key, val, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, val); else if (cmp > 0) x.right = put(x.right, key, val); else x.val = val; x.N = 1 + size(x.left) + size(x.right); return x; } /*********************************************************************** * Delete ***********************************************************************/ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = size(x.left) + size(x.right) + 1; return x; } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = size(x.left) + size(x.right) + 1; return x; } public void delete(Key key) { root = delete(root, key); assert check(); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = size(x.left) + size(x.right) + 1; return x; } /*********************************************************************** * Min, max, floor, and ceiling ***********************************************************************/ public Key min() { if (isEmpty()) return null; return min(root).key; } private Node min(Node x) { if (x.left == null) return x; else return min(x.left); } public Key max() { if (isEmpty()) return null; return max(root).key; } private Node max(Node x) { if (x.right == null) return x; else return max(x.right); } public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) { Node t = ceiling(x.left, key); if (t != null) return t; else return x; } return ceiling(x.right, key); } /*********************************************************************** * Rank and selection ***********************************************************************/ public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // Return key of rank k. private Node select(Node x, int k) { if (x == null) return null; int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } public int rank(Key key) { return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ public Iterable<Key> keys() { return keys(min(), max()); } public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } // height of this BST (one-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } // level order traversal public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node x = queue.dequeue(); if (x == null) continue; keys.enqueue(x.key); queue.enqueue(x.left); queue.enqueue(x.right); } return keys; } /************************************************************************* * Check integrity of BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
fracpete/princeton-java-algorithms
src/main/java/edu/princeton/cs/algorithms/BST.java
3,335
/*********************************************************************** * Delete ***********************************************************************/
block_comment
nl
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac BST.java * Execution: java BST * Dependencies: StdIn.java StdOut.java Queue.java * Data files: http://algs4.cs.princeton.edu/32bst/tinyST.txt * * A symbol table implemented with a binary search tree. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java BST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class BST<Key extends Comparable<Key>, Value> { private Node root; // root of BST private class Node { private Key key; // sorted by key private Value val; // associated data private Node left, right; // left and right subtrees private int N; // number of nodes in subtree public Node(Key key, Value val, int N) { this.key = key; this.val = val; this.N = N; } } // is the symbol table empty? public boolean isEmpty() { return size() == 0; } // return number of key-value pairs in BST public int size() { return size(root); } // return number of key-value pairs in BST rooted at x private int size(Node x) { if (x == null) return 0; else return x.N; } /*********************************************************************** * Search BST for given key, and return associated value if found, * return null if not found ***********************************************************************/ // does there exist a key-value pair with given key? public boolean contains(Key key) { return get(key) != null; } // return value associated with the given key, or null if no such key exists public Value get(Key key) { return get(root, key); } private Value get(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) return get(x.left, key); else if (cmp > 0) return get(x.right, key); else return x.val; } /*********************************************************************** * Insert key-value pair into BST * If key already exists, update with new value ***********************************************************************/ public void put(Key key, Value val) { if (val == null) { delete(key); return; } root = put(root, key, val); assert check(); } private Node put(Node x, Key key, Value val) { if (x == null) return new Node(key, val, 1); int cmp = key.compareTo(x.key); if (cmp < 0) x.left = put(x.left, key, val); else if (cmp > 0) x.right = put(x.right, key, val); else x.val = val; x.N = 1 + size(x.left) + size(x.right); return x; } /*********************************************************************** * Delete <SUF>*/ public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMin(root); assert check(); } private Node deleteMin(Node x) { if (x.left == null) return x.right; x.left = deleteMin(x.left); x.N = size(x.left) + size(x.right) + 1; return x; } public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("Symbol table underflow"); root = deleteMax(root); assert check(); } private Node deleteMax(Node x) { if (x.right == null) return x.left; x.right = deleteMax(x.right); x.N = size(x.left) + size(x.right) + 1; return x; } public void delete(Key key) { root = delete(root, key); assert check(); } private Node delete(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp < 0) x.left = delete(x.left, key); else if (cmp > 0) x.right = delete(x.right, key); else { if (x.right == null) return x.left; if (x.left == null) return x.right; Node t = x; x = min(t.right); x.right = deleteMin(t.right); x.left = t.left; } x.N = size(x.left) + size(x.right) + 1; return x; } /*********************************************************************** * Min, max, floor, and ceiling ***********************************************************************/ public Key min() { if (isEmpty()) return null; return min(root).key; } private Node min(Node x) { if (x.left == null) return x; else return min(x.left); } public Key max() { if (isEmpty()) return null; return max(root).key; } private Node max(Node x) { if (x.right == null) return x; else return max(x.right); } public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) { Node t = ceiling(x.left, key); if (t != null) return t; else return x; } return ceiling(x.right, key); } /*********************************************************************** * Rank and selection ***********************************************************************/ public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // Return key of rank k. private Node select(Node x, int k) { if (x == null) return null; int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } public int rank(Key key) { return rank(key, root); } // Number of keys in the subtree less than key. private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ public Iterable<Key> keys() { return keys(min(), max()); } public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); keys(root, queue, lo, hi); return queue; } private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } // height of this BST (one-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } // level order traversal public Iterable<Key> levelOrder() { Queue<Key> keys = new Queue<Key>(); Queue<Node> queue = new Queue<Node>(); queue.enqueue(root); while (!queue.isEmpty()) { Node x = queue.dequeue(); if (x == null) continue; keys.enqueue(x.key); queue.enqueue(x.left); queue.enqueue(x.right); } return keys; } /************************************************************************* * Check integrity of BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); return isBST() && isSizeConsistent() && isRankConsistent(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { BST<String, Integer> st = new BST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.levelOrder()) StdOut.println(s + " " + st.get(s)); StdOut.println(); for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); } }
206812_11
/* * Copyright (C) 2010, Stefan Klanke * Donders Institute for Donders Institute for Brain, Cognition and Behaviour, * Centre for Cognitive Neuroimaging, Radboud University Nijmegen, * Kapittelweg 29, 6525 EN Nijmegen, The Netherlands * * Simple demo of how to stream audio signals to a Fieldtrip buffer * */ package nl.dcc.buffer_bci; import java.io.*; import nl.fcdonders.fieldtrip.bufferclient.*; import javax.sound.sampled.*; public class AudioToBuffer { BufferClient ftClient; TargetDataLine lineIn; String host="localhost"; int port=1972; float fSample=44100.0f; int blockSize=-1; // neg size means compute default for 50Hz buffer packet rate int nByte =0; int nSample=0; int nBlk =0; int audioDevID=-1; boolean run=true; public AudioToBuffer() { ftClient = new BufferClient(); } public AudioToBuffer(float fSample){ if ( fSample>0 ) this.fSample=fSample; if ( blockSize<0 ) blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize<0 ) blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample, int blockSize){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize>0 ) this.blockSize=blockSize; if ( this.blockSize<0 ) this.blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample, int blockSize, int audioDevID){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize>0 ) this.blockSize=blockSize; if ( this.blockSize<0 ) this.blockSize=(int)(this.fSample/50.0); this.audioDevID=audioDevID; ftClient = new BufferClient(); } void initHostport(String hostport){ host = hostport; int sep = host.indexOf(':'); if ( sep>0 ) { port=Integer.parseInt(host.substring(sep+1,host.length())); host=host.substring(0,sep); } } public void disconnect() { try { ftClient.disconnect(); } catch (IOException e) {} } public boolean connect(String host, int port) { int sep = host.indexOf(':'); if ( sep>0 ) { // override port with part of the host string port=Integer.parseInt(host.substring(sep+1,host.length())); host=host.substring(0,sep); } try { ftClient.connect(host,port); } catch (IOException e) { System.out.println("Cannot connect to FieldTrip buffer @ " + host + ":" + port); return false; } return true; } public void listDevices() { Mixer.Info[] mixInfo = AudioSystem.getMixerInfo(); System.out.println("AUDIO devices available on this machine:"); for (int i = 0; i < mixInfo.length; i++) { System.out.print((i+1)+": "); System.out.println(mixInfo[i]); Mixer mixer = AudioSystem.getMixer(mixInfo[i]); Line.Info[] lineInfo = mixer.getTargetLineInfo(); for (int j=0; j < lineInfo.length; j++) { System.out.print(" " + (j+1)+": "); System.out.println(" " + lineInfo[j]); } } } public boolean start() { AudioFormat fmt = new AudioFormat(fSample, 16, 2, true, false); try { if ( audioDevID<0 ){ // use the default device System.out.print("Trying to open default AUDIO IN device..."); lineIn = AudioSystem.getTargetDataLine(fmt); } else { // use the specified mixer Mixer.Info[] mixInfo = AudioSystem.getMixerInfo(); System.out.println("Trying to open mixer: " + mixInfo[audioDevID-1]); Mixer mixer = AudioSystem.getMixer(mixInfo[audioDevID-1]); lineIn = (TargetDataLine)mixer.getLine(new DataLine.Info(TargetDataLine.class,fmt)); } lineIn.open(fmt); lineIn.start(); } catch (LineUnavailableException e) { System.out.println("Open Audio failed"); System.out.println(e); return false; } Header hdr = new Header(2, fSample, DataType.INT16); try { ftClient.putHeader(hdr); } catch (IOException e) { System.out.println("PutHeader failed"); System.out.println(e); return false; } return true; } public void stop() { System.out.println("Closing..."); run=false; lineIn.stop(); } public static void main(String[] args) { String hostport="localhost:1972"; if (args.length > 0 && "--help".equals(args[0])) { System.out.println("Usage: java AudioToBuffer hostname:port fSample audioDevID blockSize"); return; } if ( args.length>0 ) { hostport=args[0]; } System.out.println("HostPort="+hostport); float fSample=-1; if ( args.length>=2 ) { try { fSample = Float.parseFloat(args[1]); } catch (NumberFormatException e) { } } System.out.println("fSample ="+fSample); int audioDevID=-1; if ( args.length>=3 ) { try { audioDevID = Integer.parseInt(args[2]); } catch (NumberFormatException e) { } } System.out.println("audioDevID ="+audioDevID); int blockSize=-1; if ( args.length>=4 ) { try { blockSize = Integer.parseInt(args[3]); } catch (NumberFormatException e) { } } System.out.println("Blocksize ="+blockSize); AudioToBuffer a2b = new AudioToBuffer(hostport,fSample,blockSize,audioDevID); a2b.mainloop(); a2b.stop(); } public void mainloop(){ System.out.println("fSample="+fSample+" blockSize="+blockSize); run = true; if (connect(host,port)==false) return; listDevices(); if (!start()) return; System.out.println("success.."); System.out.println("Now streaming audio. Press q and <enter> to quit.\n"); nByte = 0; nSample = 0; nBlk = 0; long t0 = System.currentTimeMillis(); long printTime = 0; long t = t0; while (run) { // read in the data from the audio int na = lineIn.available();// number samples available to read if ( na>0 ){ byte[] buf = new byte[na*4]; lineIn.read(buf, 0, na*4); // Send to the buffer try { ftClient.putRawData(na, 2, DataType.INT16, buf); } catch (IOException e) { System.out.println(e); } // Track how much we have sent nSample = nSample + na; nBlk = nBlk+1; } else { // Sleep a block of samples should be ready try { Thread.sleep((long)(blockSize*1000.0/fSample)); } catch (InterruptedException e){ System.out.println(e); } } t = System.currentTimeMillis() - t0; // current time since start if (t >= printTime) { System.out.print(nBlk + " " + nSample + " 0 " + (t/1000) + " (blk,samp,event,sec)\r"); printTime = t + 5000; // 5s between prints } // Check for key-presses try { if (System.in.available() > 0) { int key = System.in.read(); if (key == 'q') break; } } catch (java.io.IOException e) {} } } }
bopjesvla/BCI
java/audio2ft/AudioToBuffer.java
2,422
// 5s between prints
line_comment
nl
/* * Copyright (C) 2010, Stefan Klanke * Donders Institute for Donders Institute for Brain, Cognition and Behaviour, * Centre for Cognitive Neuroimaging, Radboud University Nijmegen, * Kapittelweg 29, 6525 EN Nijmegen, The Netherlands * * Simple demo of how to stream audio signals to a Fieldtrip buffer * */ package nl.dcc.buffer_bci; import java.io.*; import nl.fcdonders.fieldtrip.bufferclient.*; import javax.sound.sampled.*; public class AudioToBuffer { BufferClient ftClient; TargetDataLine lineIn; String host="localhost"; int port=1972; float fSample=44100.0f; int blockSize=-1; // neg size means compute default for 50Hz buffer packet rate int nByte =0; int nSample=0; int nBlk =0; int audioDevID=-1; boolean run=true; public AudioToBuffer() { ftClient = new BufferClient(); } public AudioToBuffer(float fSample){ if ( fSample>0 ) this.fSample=fSample; if ( blockSize<0 ) blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize<0 ) blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample, int blockSize){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize>0 ) this.blockSize=blockSize; if ( this.blockSize<0 ) this.blockSize=(int)(this.fSample/50.0); ftClient = new BufferClient(); } public AudioToBuffer(String hostport,float fSample, int blockSize, int audioDevID){ host=hostport; if ( fSample>0 ) this.fSample=fSample; if ( blockSize>0 ) this.blockSize=blockSize; if ( this.blockSize<0 ) this.blockSize=(int)(this.fSample/50.0); this.audioDevID=audioDevID; ftClient = new BufferClient(); } void initHostport(String hostport){ host = hostport; int sep = host.indexOf(':'); if ( sep>0 ) { port=Integer.parseInt(host.substring(sep+1,host.length())); host=host.substring(0,sep); } } public void disconnect() { try { ftClient.disconnect(); } catch (IOException e) {} } public boolean connect(String host, int port) { int sep = host.indexOf(':'); if ( sep>0 ) { // override port with part of the host string port=Integer.parseInt(host.substring(sep+1,host.length())); host=host.substring(0,sep); } try { ftClient.connect(host,port); } catch (IOException e) { System.out.println("Cannot connect to FieldTrip buffer @ " + host + ":" + port); return false; } return true; } public void listDevices() { Mixer.Info[] mixInfo = AudioSystem.getMixerInfo(); System.out.println("AUDIO devices available on this machine:"); for (int i = 0; i < mixInfo.length; i++) { System.out.print((i+1)+": "); System.out.println(mixInfo[i]); Mixer mixer = AudioSystem.getMixer(mixInfo[i]); Line.Info[] lineInfo = mixer.getTargetLineInfo(); for (int j=0; j < lineInfo.length; j++) { System.out.print(" " + (j+1)+": "); System.out.println(" " + lineInfo[j]); } } } public boolean start() { AudioFormat fmt = new AudioFormat(fSample, 16, 2, true, false); try { if ( audioDevID<0 ){ // use the default device System.out.print("Trying to open default AUDIO IN device..."); lineIn = AudioSystem.getTargetDataLine(fmt); } else { // use the specified mixer Mixer.Info[] mixInfo = AudioSystem.getMixerInfo(); System.out.println("Trying to open mixer: " + mixInfo[audioDevID-1]); Mixer mixer = AudioSystem.getMixer(mixInfo[audioDevID-1]); lineIn = (TargetDataLine)mixer.getLine(new DataLine.Info(TargetDataLine.class,fmt)); } lineIn.open(fmt); lineIn.start(); } catch (LineUnavailableException e) { System.out.println("Open Audio failed"); System.out.println(e); return false; } Header hdr = new Header(2, fSample, DataType.INT16); try { ftClient.putHeader(hdr); } catch (IOException e) { System.out.println("PutHeader failed"); System.out.println(e); return false; } return true; } public void stop() { System.out.println("Closing..."); run=false; lineIn.stop(); } public static void main(String[] args) { String hostport="localhost:1972"; if (args.length > 0 && "--help".equals(args[0])) { System.out.println("Usage: java AudioToBuffer hostname:port fSample audioDevID blockSize"); return; } if ( args.length>0 ) { hostport=args[0]; } System.out.println("HostPort="+hostport); float fSample=-1; if ( args.length>=2 ) { try { fSample = Float.parseFloat(args[1]); } catch (NumberFormatException e) { } } System.out.println("fSample ="+fSample); int audioDevID=-1; if ( args.length>=3 ) { try { audioDevID = Integer.parseInt(args[2]); } catch (NumberFormatException e) { } } System.out.println("audioDevID ="+audioDevID); int blockSize=-1; if ( args.length>=4 ) { try { blockSize = Integer.parseInt(args[3]); } catch (NumberFormatException e) { } } System.out.println("Blocksize ="+blockSize); AudioToBuffer a2b = new AudioToBuffer(hostport,fSample,blockSize,audioDevID); a2b.mainloop(); a2b.stop(); } public void mainloop(){ System.out.println("fSample="+fSample+" blockSize="+blockSize); run = true; if (connect(host,port)==false) return; listDevices(); if (!start()) return; System.out.println("success.."); System.out.println("Now streaming audio. Press q and <enter> to quit.\n"); nByte = 0; nSample = 0; nBlk = 0; long t0 = System.currentTimeMillis(); long printTime = 0; long t = t0; while (run) { // read in the data from the audio int na = lineIn.available();// number samples available to read if ( na>0 ){ byte[] buf = new byte[na*4]; lineIn.read(buf, 0, na*4); // Send to the buffer try { ftClient.putRawData(na, 2, DataType.INT16, buf); } catch (IOException e) { System.out.println(e); } // Track how much we have sent nSample = nSample + na; nBlk = nBlk+1; } else { // Sleep a block of samples should be ready try { Thread.sleep((long)(blockSize*1000.0/fSample)); } catch (InterruptedException e){ System.out.println(e); } } t = System.currentTimeMillis() - t0; // current time since start if (t >= printTime) { System.out.print(nBlk + " " + nSample + " 0 " + (t/1000) + " (blk,samp,event,sec)\r"); printTime = t + 5000; // 5s between<SUF> } // Check for key-presses try { if (System.in.available() > 0) { int key = System.in.read(); if (key == 'q') break; } } catch (java.io.IOException e) {} } } }
206820_5
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods *************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods *************************************************************************/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
fracpete/princeton-java-algorithms
src/main/java/edu/princeton/cs/algorithms/RedBlackBST.java
5,400
/************************************************************************* * Node helper methods *************************************************************************/
block_comment
nl
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods<SUF>*/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods *************************************************************************/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
206820_8
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods *************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods *************************************************************************/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
fracpete/princeton-java-algorithms
src/main/java/edu/princeton/cs/algorithms/RedBlackBST.java
5,400
/************************************************************************* * Size methods *************************************************************************/
block_comment
nl
package edu.princeton.cs.algorithms; /************************************************************************* * Compilation: javac RedBlackBST.java * Execution: java RedBlackBST < input.txt * Dependencies: StdIn.java StdOut.java * Data files: http://algs4.cs.princeton.edu/33balanced/tinyST.txt * * A symbol table implemented using a left-leaning red-black BST. * This is the 2-3 version. * * % more tinyST.txt * S E A R C H E X A M P L E * * % java RedBlackBST < tinyST.txt * A 8 * C 4 * E 12 * H 5 * L 11 * M 9 * P 10 * R 3 * S 0 * X 7 * *************************************************************************/ import java.util.NoSuchElementException; import edu.princeton.cs.introcs.StdIn; import edu.princeton.cs.introcs.StdOut; public class RedBlackBST<Key extends Comparable<Key>, Value> { private static final boolean RED = true; private static final boolean BLACK = false; private Node root; // root of the BST // BST helper node data type private class Node { private Key key; // key private Value val; // associated data private Node left, right; // links to left and right subtrees private boolean color; // color of parent link private int N; // subtree count public Node(Key key, Value val, boolean color, int N) { this.key = key; this.val = val; this.color = color; this.N = N; } } /************************************************************************* * Node helper methods *************************************************************************/ // is node x red; false if x is null ? private boolean isRed(Node x) { if (x == null) return false; return (x.color == RED); } // number of node in subtree rooted at x; 0 if x is null private int size(Node x) { if (x == null) return 0; return x.N; } /************************************************************************* * Size methods <SUF>*/ // return number of key-value pairs in this symbol table public int size() { return size(root); } // is this symbol table empty? public boolean isEmpty() { return root == null; } /************************************************************************* * Standard BST search *************************************************************************/ // value associated with the given key; null if no such key public Value get(Key key) { return get(root, key); } // value associated with the given key in subtree rooted at x; null if no such key private Value get(Node x, Key key) { while (x != null) { int cmp = key.compareTo(x.key); if (cmp < 0) x = x.left; else if (cmp > 0) x = x.right; else return x.val; } return null; } // is there a key-value pair with the given key? public boolean contains(Key key) { return (get(key) != null); } // is there a key-value pair with the given key in the subtree rooted at x? private boolean contains(Node x, Key key) { return (get(x, key) != null); } /************************************************************************* * Red-black insertion *************************************************************************/ // insert the key-value pair; overwrite the old value with the new value // if the key is already present public void put(Key key, Value val) { root = put(root, key, val); root.color = BLACK; assert check(); } // insert the key-value pair in the subtree rooted at h private Node put(Node h, Key key, Value val) { if (h == null) return new Node(key, val, RED, 1); int cmp = key.compareTo(h.key); if (cmp < 0) h.left = put(h.left, key, val); else if (cmp > 0) h.right = put(h.right, key, val); else h.val = val; // fix-up any right-leaning links if (isRed(h.right) && !isRed(h.left)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Red-black deletion *************************************************************************/ // delete the key-value pair with the minimum key public void deleteMin() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMin(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the minimum key rooted at h private Node deleteMin(Node h) { if (h.left == null) return null; if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = deleteMin(h.left); return balance(h); } // delete the key-value pair with the maximum key public void deleteMax() { if (isEmpty()) throw new NoSuchElementException("BST underflow"); // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = deleteMax(root); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the maximum key rooted at h private Node deleteMax(Node h) { if (isRed(h.left)) h = rotateRight(h); if (h.right == null) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); h.right = deleteMax(h.right); return balance(h); } // delete the key-value pair with the given key public void delete(Key key) { if (!contains(key)) { System.err.println("symbol table does not contain " + key); return; } // if both children of root are black, set root to red if (!isRed(root.left) && !isRed(root.right)) root.color = RED; root = delete(root, key); if (!isEmpty()) root.color = BLACK; assert check(); } // delete the key-value pair with the given key rooted at h private Node delete(Node h, Key key) { assert contains(h, key); if (key.compareTo(h.key) < 0) { if (!isRed(h.left) && !isRed(h.left.left)) h = moveRedLeft(h); h.left = delete(h.left, key); } else { if (isRed(h.left)) h = rotateRight(h); if (key.compareTo(h.key) == 0 && (h.right == null)) return null; if (!isRed(h.right) && !isRed(h.right.left)) h = moveRedRight(h); if (key.compareTo(h.key) == 0) { Node x = min(h.right); h.key = x.key; h.val = x.val; // h.val = get(h.right, min(h.right).key); // h.key = min(h.right).key; h.right = deleteMin(h.right); } else h.right = delete(h.right, key); } return balance(h); } /************************************************************************* * red-black tree helper functions *************************************************************************/ // make a left-leaning link lean to the right private Node rotateRight(Node h) { assert (h != null) && isRed(h.left); Node x = h.left; h.left = x.right; x.right = h; x.color = x.right.color; x.right.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // make a right-leaning link lean to the left private Node rotateLeft(Node h) { assert (h != null) && isRed(h.right); Node x = h.right; h.right = x.left; x.left = h; x.color = x.left.color; x.left.color = RED; x.N = h.N; h.N = size(h.left) + size(h.right) + 1; return x; } // flip the colors of a node and its two children private void flipColors(Node h) { // h must have opposite color of its two children assert (h != null) && (h.left != null) && (h.right != null); assert (!isRed(h) && isRed(h.left) && isRed(h.right)) || (isRed(h) && !isRed(h.left) && !isRed(h.right)); h.color = !h.color; h.left.color = !h.left.color; h.right.color = !h.right.color; } // Assuming that h is red and both h.left and h.left.left // are black, make h.left or one of its children red. private Node moveRedLeft(Node h) { assert (h != null); assert isRed(h) && !isRed(h.left) && !isRed(h.left.left); flipColors(h); if (isRed(h.right.left)) { h.right = rotateRight(h.right); h = rotateLeft(h); } return h; } // Assuming that h is red and both h.right and h.right.left // are black, make h.right or one of its children red. private Node moveRedRight(Node h) { assert (h != null); assert isRed(h) && !isRed(h.right) && !isRed(h.right.left); flipColors(h); if (isRed(h.left.left)) { h = rotateRight(h); } return h; } // restore red-black tree invariant private Node balance(Node h) { assert (h != null); if (isRed(h.right)) h = rotateLeft(h); if (isRed(h.left) && isRed(h.left.left)) h = rotateRight(h); if (isRed(h.left) && isRed(h.right)) flipColors(h); h.N = size(h.left) + size(h.right) + 1; return h; } /************************************************************************* * Utility functions *************************************************************************/ // height of tree (1-node tree has height 0) public int height() { return height(root); } private int height(Node x) { if (x == null) return -1; return 1 + Math.max(height(x.left), height(x.right)); } /************************************************************************* * Ordered symbol table methods. *************************************************************************/ // the smallest key; null if no such key public Key min() { if (isEmpty()) return null; return min(root).key; } // the smallest key in subtree rooted at x; null if no such key private Node min(Node x) { assert x != null; if (x.left == null) return x; else return min(x.left); } // the largest key; null if no such key public Key max() { if (isEmpty()) return null; return max(root).key; } // the largest key in the subtree rooted at x; null if no such key private Node max(Node x) { assert x != null; if (x.right == null) return x; else return max(x.right); } // the largest key less than or equal to the given key public Key floor(Key key) { Node x = floor(root, key); if (x == null) return null; else return x.key; } // the largest key in the subtree rooted at x less than or equal to the given key private Node floor(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp < 0) return floor(x.left, key); Node t = floor(x.right, key); if (t != null) return t; else return x; } // the smallest key greater than or equal to the given key public Key ceiling(Key key) { Node x = ceiling(root, key); if (x == null) return null; else return x.key; } // the smallest key in the subtree rooted at x greater than or equal to the given key private Node ceiling(Node x, Key key) { if (x == null) return null; int cmp = key.compareTo(x.key); if (cmp == 0) return x; if (cmp > 0) return ceiling(x.right, key); Node t = ceiling(x.left, key); if (t != null) return t; else return x; } // the key of rank k public Key select(int k) { if (k < 0 || k >= size()) return null; Node x = select(root, k); return x.key; } // the key of rank k in the subtree rooted at x private Node select(Node x, int k) { assert x != null; assert k >= 0 && k < size(x); int t = size(x.left); if (t > k) return select(x.left, k); else if (t < k) return select(x.right, k-t-1); else return x; } // number of keys less than key public int rank(Key key) { return rank(key, root); } // number of keys less than key in the subtree rooted at x private int rank(Key key, Node x) { if (x == null) return 0; int cmp = key.compareTo(x.key); if (cmp < 0) return rank(key, x.left); else if (cmp > 0) return 1 + size(x.left) + rank(key, x.right); else return size(x.left); } /*********************************************************************** * Range count and range search. ***********************************************************************/ // all of the keys, as an Iterable public Iterable<Key> keys() { return keys(min(), max()); } // the keys between lo and hi, as an Iterable public Iterable<Key> keys(Key lo, Key hi) { Queue<Key> queue = new Queue<Key>(); // if (isEmpty() || lo.compareTo(hi) > 0) return queue; keys(root, queue, lo, hi); return queue; } // add the keys between lo and hi in the subtree rooted at x // to the queue private void keys(Node x, Queue<Key> queue, Key lo, Key hi) { if (x == null) return; int cmplo = lo.compareTo(x.key); int cmphi = hi.compareTo(x.key); if (cmplo < 0) keys(x.left, queue, lo, hi); if (cmplo <= 0 && cmphi >= 0) queue.enqueue(x.key); if (cmphi > 0) keys(x.right, queue, lo, hi); } // number keys between lo and hi public int size(Key lo, Key hi) { if (lo.compareTo(hi) > 0) return 0; if (contains(hi)) return rank(hi) - rank(lo) + 1; else return rank(hi) - rank(lo); } /************************************************************************* * Check integrity of red-black BST data structure *************************************************************************/ private boolean check() { if (!isBST()) StdOut.println("Not in symmetric order"); if (!isSizeConsistent()) StdOut.println("Subtree counts not consistent"); if (!isRankConsistent()) StdOut.println("Ranks not consistent"); if (!is23()) StdOut.println("Not a 2-3 tree"); if (!isBalanced()) StdOut.println("Not balanced"); return isBST() && isSizeConsistent() && isRankConsistent() && is23() && isBalanced(); } // does this binary tree satisfy symmetric order? // Note: this test also ensures that data structure is a binary tree since order is strict private boolean isBST() { return isBST(root, null, null); } // is the tree rooted at x a BST with all keys strictly between min and max // (if min or max is null, treat as empty constraint) // Credit: Bob Dondero's elegant solution private boolean isBST(Node x, Key min, Key max) { if (x == null) return true; if (min != null && x.key.compareTo(min) <= 0) return false; if (max != null && x.key.compareTo(max) >= 0) return false; return isBST(x.left, min, x.key) && isBST(x.right, x.key, max); } // are the size fields correct? private boolean isSizeConsistent() { return isSizeConsistent(root); } private boolean isSizeConsistent(Node x) { if (x == null) return true; if (x.N != size(x.left) + size(x.right) + 1) return false; return isSizeConsistent(x.left) && isSizeConsistent(x.right); } // check that ranks are consistent private boolean isRankConsistent() { for (int i = 0; i < size(); i++) if (i != rank(select(i))) return false; for (Key key : keys()) if (key.compareTo(select(rank(key))) != 0) return false; return true; } // Does the tree have no red right links, and at most one (left) // red links in a row on any path? private boolean is23() { return is23(root); } private boolean is23(Node x) { if (x == null) return true; if (isRed(x.right)) return false; if (x != root && isRed(x) && isRed(x.left)) return false; return is23(x.left) && is23(x.right); } // do all paths from root to leaf have same number of black edges? private boolean isBalanced() { int black = 0; // number of black links on path from root to min Node x = root; while (x != null) { if (!isRed(x)) black++; x = x.left; } return isBalanced(root, black); } // does every path from the root to a leaf have the given number of black links? private boolean isBalanced(Node x, int black) { if (x == null) return black == 0; if (!isRed(x)) black--; return isBalanced(x.left, black) && isBalanced(x.right, black); } /***************************************************************************** * Test client *****************************************************************************/ public static void main(String[] args) { RedBlackBST<String, Integer> st = new RedBlackBST<String, Integer>(); for (int i = 0; !StdIn.isEmpty(); i++) { String key = StdIn.readString(); st.put(key, i); } for (String s : st.keys()) StdOut.println(s + " " + st.get(s)); StdOut.println(); } }
206821_58
/** * @file Orchestrator.java * @brief Orchestrator for the Pelion bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2018. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.pelion.bridge.coordinator; // Processors import com.arm.pelion.bridge.coordinator.processors.arm.PelionProcessor; import com.arm.pelion.bridge.coordinator.processors.factories.WatsonIoTPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.MSIoTHubPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.AWSIoTPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.GenericMQTTPeerProcessorFactory; import com.arm.pelion.bridge.core.ApiResponse; import com.arm.pelion.bridge.coordinator.processors.factories.GoogleCloudPeerProcessorFactory; // Core import com.arm.pelion.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.pelion.bridge.core.ErrorLogger; import com.arm.pelion.bridge.json.JSONGenerator; import com.arm.pelion.bridge.json.JSONParser; import com.arm.pelion.bridge.json.JSONGeneratorFactory; import com.arm.pelion.bridge.preferences.PreferenceManager; import com.arm.pelion.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.pelion.bridge.data.DatabaseConnector; import com.arm.pelion.bridge.coordinator.processors.interfaces.PeerProcessorInterface; import com.arm.pelion.bridge.servlet.Manager; import com.arm.pelion.bridge.coordinator.processors.interfaces.PelionProcessorInterface; import com.arm.pelion.bridge.coordinator.processors.core.EndpointTypeManager; import com.arm.pelion.bridge.coordinator.processors.core.PeerProcessor; import com.arm.pelion.bridge.coordinator.processors.factories.SAMPLEPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.TreasureDataPeerProcessorFactory; import com.arm.pelion.bridge.health.HealthCheckServiceProvider; import com.arm.pelion.bridge.health.interfaces.HealthCheckServiceInterface; import com.arm.pelion.bridge.health.interfaces.HealthStatisticListenerInterface; /** * This the primary orchestrator for the pelion bridge * * @author Doug Anson */ public class Orchestrator implements PelionProcessorInterface, PeerProcessorInterface, HealthStatisticListenerInterface { // default Tenant ID private static final String DEFAULT_TENANT_ID = "1000000000000000000000000"; // default Tenant name private static final String DEFAULT_TENANT_NAME = "pelion_org_name"; // Default Health Check Service Provider Sleep time in MS private static final int DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS = (60000 * 10); // 10 minutes // Health Stats Key public static final String HEALTH_STATS_KEY = "[HEALTH_STATS]"; // database table delimiter private static String DEF_TABLENAME_DELIMITER = "_"; // our servlet private final HttpServlet m_servlet = null; // Logging and preferences... private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // Pelion processor (1 only...) private PelionProcessorInterface m_pelion_processor = null; // Peer processor list (n-way...default is 1 though...) private ArrayList<PeerProcessorInterface> m_peer_processor_list = null; // Health Check Services Provider/Manager private boolean m_enable_health_checks = true; // true: enabled, false: disabled private HealthCheckServiceProvider m_health_check_service_provider = null; private Thread m_health_check_service_provider_thread = null; // Health Check Services Provider Sleep time (in ms) private int m_health_check_service_provider_sleep_time_ms = DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS; // Health Check Shadow Count private int m_shadow_count = 0; // our HTTP transport interface //private HttpTransport m_http = null; // JSON support private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; // listeners initialized status... private boolean m_listeners_initialized = false; // persist preferences and configuration private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node // our primary manager private Manager m_manager = null; // primary endpoint type manager for the bridge private EndpointTypeManager m_endpoint_type_manager = null; // Tenant ID private String m_tenant_id = null; private String m_tenant_name = null; private boolean m_tenant_id_pull_attempted = false; private boolean m_tenant_name_pull_attempted = false; // primary constructor public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // we are parent this.m_error_logger.setParent(this); // Create an endpoint type manager this.m_endpoint_type_manager = new EndpointTypeManager(this); // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // We always create the Pelion processor (1 only) this.m_pelion_processor = new PelionProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager)); // initialize our peer processors... (n-way... but default is just 1...) this.initPeerProcessorList(); // Get the health check service provider sleep time if (this.m_enable_health_checks == true) { this.m_health_check_service_provider_sleep_time_ms = preferences().intValueOf("heath_check_sleep_time_ms"); if (this.m_health_check_service_provider_sleep_time_ms <= 0) { this.m_health_check_service_provider_sleep_time_ms = DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS; } // DEBUG this.errorLogger().warning("Orchestrator: Stats Check Sleep Interval (ms): " + this.m_health_check_service_provider_sleep_time_ms); // create our health check service provider and its runtime thread... this.m_health_check_service_provider = new HealthCheckServiceProvider(this,this.m_health_check_service_provider_sleep_time_ms); this.m_health_check_service_provider.initialize(); this.m_health_check_service_provider.addListener(this); } else { // not enabled this.errorLogger().warning("Orchestrator: Stats Checking DISABLED"); } // start device discovery in Pelion... this.initDeviceDiscovery(); } // get the tenant Name public String getTenantName() { if (this.m_tenant_name == null) { if (this.m_tenant_name_pull_attempted == false) { this.m_tenant_name = this.m_pelion_processor.getTenantName(); this.m_tenant_name_pull_attempted = true; } } if (this.m_tenant_name == null) { return DEFAULT_TENANT_NAME; } return this.m_tenant_name; } // get the tenant ID public String getTenantID() { if (this.m_tenant_id == null) { if (this.m_tenant_id_pull_attempted == false) { this.m_tenant_id = this.m_pelion_processor.getTenantID(); this.m_tenant_id_pull_attempted = true; } } if (this.m_tenant_id == null) { return DEFAULT_TENANT_ID; } return this.m_tenant_id; } // get the endpoint type manager @Override public EndpointTypeManager getEndpointTypeManager() { return this.m_endpoint_type_manager; } // start the health check provider thread to monitor and provide statistics public void startStatisticsMonitoring() { if (this.m_enable_health_checks == true) { try { // DEBUG this.errorLogger().warning("Orchestrator: Statistics and health monitoring starting..."); this.m_health_check_service_provider_thread = new Thread(this.m_health_check_service_provider); if (this.m_health_check_service_provider_thread != null) { this.m_health_check_service_provider_thread.start(); } } catch (Exception ex) { this.errorLogger().critical("Orchestrator: Exception caught while starting health check provider: " + ex.getMessage()); } } } // get the health check provider public HealthCheckServiceInterface getHealthCheckServiceProvider() { return (HealthCheckServiceInterface)this.m_health_check_service_provider; } // set our manager public void setManager(Manager manager) { this.m_manager = manager; } // shutdown/reset our instance public void reset() { if (this.m_manager != null) { this.m_manager.reset(); } } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM WatsonIoT/MQTT this.errorLogger().info("Orchestrator: Adding IBM WatsonIoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT this.errorLogger().info("Orchestrator: Adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.awsPeerEnabled()) { // Amazon AWSIoT/MQTT this.errorLogger().info("Orchestrator: Adding AWSIoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.googleCloudPeerEnabled()) { // Google CloudIoT/MQTT this.errorLogger().info("Orchestrator: Adding Google CloudIoT MQTT Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.genericMQTTPeerEnabled()) { // Generic MQTT this.errorLogger().info("Orchestrator: Adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.treasureDataPeerEnabled()) { // TreasureData this.errorLogger().info("Orchestrator: Adding TreasureData Processor"); this.m_peer_processor_list.add(TreasureDataPeerProcessorFactory.createPeerProcessor(this)); } // TEMPLATE FOR SAMPLE Peer if (this.SAMPLEPeerEnabled()) { // SAMPLE this.errorLogger().info("Orchestrator: Adding SAMPLE Processor"); this.m_peer_processor_list.add(SAMPLEPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } } // use SAMPLE peer processor? private Boolean SAMPLEPeerEnabled() { return (this.preferences().booleanValueOf("SAMPLE_enable_addon")); } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // use TreasureData peer processor? private Boolean treasureDataPeerEnabled() { return this.preferences().booleanValueOf("enable_td_addon"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the Pelion notification channel public void initializeNotificationChannel() { if (this.m_pelion_processor != null) { this.m_pelion_processor.initializeNotificationChannel(); } } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the peer processor list public ArrayList<PeerProcessorInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the pelion processor public PelionProcessorInterface pelion_processor() { return this.m_pelion_processor; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerProcessorInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { if (this.m_pelion_processor != null) { return this.pelion_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } return null; } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { if (this.m_pelion_processor != null) { this.pelion_processor().processNotificationMessage(request, response); } } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processDeviceDeletions(endpoints); } this.refreshHealthStats(); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processDeregistrations(endpoints); } this.refreshHealthStats(); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processRegistrationsExpired(endpoints); } this.refreshHealthStats(); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { if (this.m_pelion_processor != null) { return this.pelion_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } return null; } @Override public synchronized void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { if (this.m_pelion_processor != null) { this.pelion_processor().pullDeviceMetadata(endpoint, processor); } } // PeerProcessorInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public synchronized void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public synchronized void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } this.refreshHealthStats(); } // Message: reg-updates @Override public synchronized void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } this.refreshHealthStats(); } // Message: device-deletions (mbed Cloud) @Override public synchronized String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public synchronized String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public synchronized String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public synchronized void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public synchronized void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public boolean deviceRemovedOnDeRegistration() { if (this.pelion_processor() != null) { return this.pelion_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } // init any device discovery @Override public void initDeviceDiscovery() { this.pelion_processor().initDeviceDiscovery(); } // orchestrator processing the publication of statistics @Override public void publish(String json) { // dump to error logger with a KEY that the properties-editor will detect this.errorLogger().critical(HEALTH_STATS_KEY + json); // note in log so that log moves... this.errorLogger().info("Health Stats: Updated (OK)."); } // get the active thread count public int getActiveThreadCount() { if (this.m_manager != null) { return this.m_manager.getActiveThreadCount(); } else { // log... but not to worry... will get set later... this.errorLogger().info("Orchestrator: Manager is NULL for getting active thread count (OK)."); } return 1; } // get the shadow count public int getShadowCount() { int shadow_count = 0; for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { PeerProcessor p = (PeerProcessor)this.peerProcessor(i); shadow_count += p.getCurrentEndpointCount(); } return shadow_count; } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message this.errorLogger().info("Orchestrator: EVENT (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.pelion_processor().processNotificationMessage(request, response); } // process the inbound command messsage for a peer @Override public void processCommandMessage(HttpServletRequest request, HttpServletResponse response) { // process the received Peer Command message this.errorLogger().info("Orchestrator: COMMAND (REST-" + request.getMethod() + "): " + request.getRequestURI()); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processCommandMessage(request, response); } } // manual refresh the health stats private void refreshHealthStats() { if (this.m_health_check_service_provider != null) { this.m_health_check_service_provider.refreshHealthStats(); } } // reset the notifications channel @Override public void resetNotificationChannel() { if (this.m_pelion_processor != null) { this.pelion_processor().resetNotificationChannel(); } } }
PelionIoT/pelion-bridge
src/main/java/com/arm/pelion/bridge/coordinator/Orchestrator.java
7,322
// get the HttpServlet
line_comment
nl
/** * @file Orchestrator.java * @brief Orchestrator for the Pelion bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2018. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.pelion.bridge.coordinator; // Processors import com.arm.pelion.bridge.coordinator.processors.arm.PelionProcessor; import com.arm.pelion.bridge.coordinator.processors.factories.WatsonIoTPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.MSIoTHubPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.AWSIoTPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.GenericMQTTPeerProcessorFactory; import com.arm.pelion.bridge.core.ApiResponse; import com.arm.pelion.bridge.coordinator.processors.factories.GoogleCloudPeerProcessorFactory; // Core import com.arm.pelion.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.pelion.bridge.core.ErrorLogger; import com.arm.pelion.bridge.json.JSONGenerator; import com.arm.pelion.bridge.json.JSONParser; import com.arm.pelion.bridge.json.JSONGeneratorFactory; import com.arm.pelion.bridge.preferences.PreferenceManager; import com.arm.pelion.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.pelion.bridge.data.DatabaseConnector; import com.arm.pelion.bridge.coordinator.processors.interfaces.PeerProcessorInterface; import com.arm.pelion.bridge.servlet.Manager; import com.arm.pelion.bridge.coordinator.processors.interfaces.PelionProcessorInterface; import com.arm.pelion.bridge.coordinator.processors.core.EndpointTypeManager; import com.arm.pelion.bridge.coordinator.processors.core.PeerProcessor; import com.arm.pelion.bridge.coordinator.processors.factories.SAMPLEPeerProcessorFactory; import com.arm.pelion.bridge.coordinator.processors.factories.TreasureDataPeerProcessorFactory; import com.arm.pelion.bridge.health.HealthCheckServiceProvider; import com.arm.pelion.bridge.health.interfaces.HealthCheckServiceInterface; import com.arm.pelion.bridge.health.interfaces.HealthStatisticListenerInterface; /** * This the primary orchestrator for the pelion bridge * * @author Doug Anson */ public class Orchestrator implements PelionProcessorInterface, PeerProcessorInterface, HealthStatisticListenerInterface { // default Tenant ID private static final String DEFAULT_TENANT_ID = "1000000000000000000000000"; // default Tenant name private static final String DEFAULT_TENANT_NAME = "pelion_org_name"; // Default Health Check Service Provider Sleep time in MS private static final int DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS = (60000 * 10); // 10 minutes // Health Stats Key public static final String HEALTH_STATS_KEY = "[HEALTH_STATS]"; // database table delimiter private static String DEF_TABLENAME_DELIMITER = "_"; // our servlet private final HttpServlet m_servlet = null; // Logging and preferences... private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // Pelion processor (1 only...) private PelionProcessorInterface m_pelion_processor = null; // Peer processor list (n-way...default is 1 though...) private ArrayList<PeerProcessorInterface> m_peer_processor_list = null; // Health Check Services Provider/Manager private boolean m_enable_health_checks = true; // true: enabled, false: disabled private HealthCheckServiceProvider m_health_check_service_provider = null; private Thread m_health_check_service_provider_thread = null; // Health Check Services Provider Sleep time (in ms) private int m_health_check_service_provider_sleep_time_ms = DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS; // Health Check Shadow Count private int m_shadow_count = 0; // our HTTP transport interface //private HttpTransport m_http = null; // JSON support private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; // listeners initialized status... private boolean m_listeners_initialized = false; // persist preferences and configuration private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node // our primary manager private Manager m_manager = null; // primary endpoint type manager for the bridge private EndpointTypeManager m_endpoint_type_manager = null; // Tenant ID private String m_tenant_id = null; private String m_tenant_name = null; private boolean m_tenant_id_pull_attempted = false; private boolean m_tenant_name_pull_attempted = false; // primary constructor public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // we are parent this.m_error_logger.setParent(this); // Create an endpoint type manager this.m_endpoint_type_manager = new EndpointTypeManager(this); // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // We always create the Pelion processor (1 only) this.m_pelion_processor = new PelionProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager)); // initialize our peer processors... (n-way... but default is just 1...) this.initPeerProcessorList(); // Get the health check service provider sleep time if (this.m_enable_health_checks == true) { this.m_health_check_service_provider_sleep_time_ms = preferences().intValueOf("heath_check_sleep_time_ms"); if (this.m_health_check_service_provider_sleep_time_ms <= 0) { this.m_health_check_service_provider_sleep_time_ms = DEF_HEALTH_CHECK_SERVICE_PROVIDER_SLEEP_TIME_MS; } // DEBUG this.errorLogger().warning("Orchestrator: Stats Check Sleep Interval (ms): " + this.m_health_check_service_provider_sleep_time_ms); // create our health check service provider and its runtime thread... this.m_health_check_service_provider = new HealthCheckServiceProvider(this,this.m_health_check_service_provider_sleep_time_ms); this.m_health_check_service_provider.initialize(); this.m_health_check_service_provider.addListener(this); } else { // not enabled this.errorLogger().warning("Orchestrator: Stats Checking DISABLED"); } // start device discovery in Pelion... this.initDeviceDiscovery(); } // get the tenant Name public String getTenantName() { if (this.m_tenant_name == null) { if (this.m_tenant_name_pull_attempted == false) { this.m_tenant_name = this.m_pelion_processor.getTenantName(); this.m_tenant_name_pull_attempted = true; } } if (this.m_tenant_name == null) { return DEFAULT_TENANT_NAME; } return this.m_tenant_name; } // get the tenant ID public String getTenantID() { if (this.m_tenant_id == null) { if (this.m_tenant_id_pull_attempted == false) { this.m_tenant_id = this.m_pelion_processor.getTenantID(); this.m_tenant_id_pull_attempted = true; } } if (this.m_tenant_id == null) { return DEFAULT_TENANT_ID; } return this.m_tenant_id; } // get the endpoint type manager @Override public EndpointTypeManager getEndpointTypeManager() { return this.m_endpoint_type_manager; } // start the health check provider thread to monitor and provide statistics public void startStatisticsMonitoring() { if (this.m_enable_health_checks == true) { try { // DEBUG this.errorLogger().warning("Orchestrator: Statistics and health monitoring starting..."); this.m_health_check_service_provider_thread = new Thread(this.m_health_check_service_provider); if (this.m_health_check_service_provider_thread != null) { this.m_health_check_service_provider_thread.start(); } } catch (Exception ex) { this.errorLogger().critical("Orchestrator: Exception caught while starting health check provider: " + ex.getMessage()); } } } // get the health check provider public HealthCheckServiceInterface getHealthCheckServiceProvider() { return (HealthCheckServiceInterface)this.m_health_check_service_provider; } // set our manager public void setManager(Manager manager) { this.m_manager = manager; } // shutdown/reset our instance public void reset() { if (this.m_manager != null) { this.m_manager.reset(); } } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM WatsonIoT/MQTT this.errorLogger().info("Orchestrator: Adding IBM WatsonIoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT this.errorLogger().info("Orchestrator: Adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.awsPeerEnabled()) { // Amazon AWSIoT/MQTT this.errorLogger().info("Orchestrator: Adding AWSIoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.googleCloudPeerEnabled()) { // Google CloudIoT/MQTT this.errorLogger().info("Orchestrator: Adding Google CloudIoT MQTT Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.genericMQTTPeerEnabled()) { // Generic MQTT this.errorLogger().info("Orchestrator: Adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } if (this.treasureDataPeerEnabled()) { // TreasureData this.errorLogger().info("Orchestrator: Adding TreasureData Processor"); this.m_peer_processor_list.add(TreasureDataPeerProcessorFactory.createPeerProcessor(this)); } // TEMPLATE FOR SAMPLE Peer if (this.SAMPLEPeerEnabled()) { // SAMPLE this.errorLogger().info("Orchestrator: Adding SAMPLE Processor"); this.m_peer_processor_list.add(SAMPLEPeerProcessorFactory.createPeerProcessor(this, new HttpTransport(this.m_error_logger, this.m_preference_manager))); } } // use SAMPLE peer processor? private Boolean SAMPLEPeerEnabled() { return (this.preferences().booleanValueOf("SAMPLE_enable_addon")); } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // use TreasureData peer processor? private Boolean treasureDataPeerEnabled() { return this.preferences().booleanValueOf("enable_td_addon"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the Pelion notification channel public void initializeNotificationChannel() { if (this.m_pelion_processor != null) { this.m_pelion_processor.initializeNotificationChannel(); } } // get the<SUF> public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the peer processor list public ArrayList<PeerProcessorInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the pelion processor public PelionProcessorInterface pelion_processor() { return this.m_pelion_processor; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerProcessorInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { if (this.m_pelion_processor != null) { return this.pelion_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } return null; } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { if (this.m_pelion_processor != null) { this.pelion_processor().processNotificationMessage(request, response); } } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processDeviceDeletions(endpoints); } this.refreshHealthStats(); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processDeregistrations(endpoints); } this.refreshHealthStats(); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { if (this.m_pelion_processor != null) { this.pelion_processor().processRegistrationsExpired(endpoints); } this.refreshHealthStats(); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { if (this.m_pelion_processor != null) { return this.pelion_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } return null; } @Override public synchronized void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { if (this.m_pelion_processor != null) { this.pelion_processor().pullDeviceMetadata(endpoint, processor); } } // PeerProcessorInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public synchronized void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public synchronized void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } this.refreshHealthStats(); } // Message: reg-updates @Override public synchronized void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } this.refreshHealthStats(); } // Message: device-deletions (mbed Cloud) @Override public synchronized String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public synchronized String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public synchronized String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public synchronized void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public synchronized void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public boolean deviceRemovedOnDeRegistration() { if (this.pelion_processor() != null) { return this.pelion_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } // init any device discovery @Override public void initDeviceDiscovery() { this.pelion_processor().initDeviceDiscovery(); } // orchestrator processing the publication of statistics @Override public void publish(String json) { // dump to error logger with a KEY that the properties-editor will detect this.errorLogger().critical(HEALTH_STATS_KEY + json); // note in log so that log moves... this.errorLogger().info("Health Stats: Updated (OK)."); } // get the active thread count public int getActiveThreadCount() { if (this.m_manager != null) { return this.m_manager.getActiveThreadCount(); } else { // log... but not to worry... will get set later... this.errorLogger().info("Orchestrator: Manager is NULL for getting active thread count (OK)."); } return 1; } // get the shadow count public int getShadowCount() { int shadow_count = 0; for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { PeerProcessor p = (PeerProcessor)this.peerProcessor(i); shadow_count += p.getCurrentEndpointCount(); } return shadow_count; } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message this.errorLogger().info("Orchestrator: EVENT (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.pelion_processor().processNotificationMessage(request, response); } // process the inbound command messsage for a peer @Override public void processCommandMessage(HttpServletRequest request, HttpServletResponse response) { // process the received Peer Command message this.errorLogger().info("Orchestrator: COMMAND (REST-" + request.getMethod() + "): " + request.getRequestURI()); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processCommandMessage(request, response); } } // manual refresh the health stats private void refreshHealthStats() { if (this.m_health_check_service_provider != null) { this.m_health_check_service_provider.refreshHealthStats(); } } // reset the notifications channel @Override public void resetNotificationChannel() { if (this.m_pelion_processor != null) { this.pelion_processor().resetNotificationChannel(); } } }
206822_34
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
PelionIoT/connector-bridge
src/main/java/com/arm/connector/bridge/coordinator/Orchestrator.java
5,780
// initialize peer listener
line_comment
nl
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer<SUF> public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
206822_38
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
PelionIoT/connector-bridge
src/main/java/com/arm/connector/bridge/coordinator/Orchestrator.java
5,780
// begin validation polling
line_comment
nl
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation<SUF> this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
206822_39
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
PelionIoT/connector-bridge
src/main/java/com/arm/connector/bridge/coordinator/Orchestrator.java
5,780
// reset mbed Device Server webhook
line_comment
nl
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed<SUF> public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
206822_46
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
PelionIoT/connector-bridge
src/main/java/com/arm/connector/bridge/coordinator/Orchestrator.java
5,780
// get the HttpServlet
line_comment
nl
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the<SUF> public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
206822_47
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the ErrorLogger public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
PelionIoT/connector-bridge
src/main/java/com/arm/connector/bridge/coordinator/Orchestrator.java
5,780
// get the ErrorLogger
line_comment
nl
/** * @file orchestrator.java * @brief orchestrator for the connector bridge * @author Doug Anson * @version 1.0 * @see * * Copyright 2015. ARM Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.arm.connector.bridge.coordinator; import com.arm.connector.bridge.console.ConsoleManager; // Interfaces import com.arm.connector.bridge.coordinator.processors.interfaces.PeerInterface; // Processors import com.arm.connector.bridge.coordinator.processors.arm.mbedDeviceServerProcessor; import com.arm.connector.bridge.coordinator.processors.arm.GenericMQTTProcessor; import com.arm.connector.bridge.coordinator.processors.sample.Sample3rdPartyProcessor; import com.arm.connector.bridge.coordinator.processors.ibm.WatsonIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.ms.MSIoTHubPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.aws.AWSIoTPeerProcessorFactory; import com.arm.connector.bridge.coordinator.processors.core.ApiResponse; import com.arm.connector.bridge.coordinator.processors.google.GoogleCloudPeerProcessorFactory; // Core import com.arm.connector.bridge.coordinator.processors.interfaces.AsyncResponseProcessor; import com.arm.connector.bridge.coordinator.processors.interfaces.SubscriptionManager; import com.arm.connector.bridge.core.ErrorLogger; import com.arm.connector.bridge.json.JSONGenerator; import com.arm.connector.bridge.json.JSONParser; import com.arm.connector.bridge.json.JSONGeneratorFactory; import com.arm.connector.bridge.preferences.PreferenceManager; import com.arm.connector.bridge.transport.HttpTransport; import java.util.ArrayList; import java.util.Map; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.arm.connector.bridge.coordinator.processors.interfaces.mbedDeviceServerInterface; import com.arm.connector.bridge.data.DatabaseConnector; /** * This the primary orchestrator for the connector bridge * * @author Doug Anson */ public class Orchestrator implements mbedDeviceServerInterface, PeerInterface { private static String DEF_TABLENAME_DELIMITER = "_"; private final HttpServlet m_servlet = null; private ErrorLogger m_error_logger = null; private PreferenceManager m_preference_manager = null; // mDS processor private mbedDeviceServerInterface m_mbed_device_server_processor = null; // Peer processor list private ArrayList<PeerInterface> m_peer_processor_list = null; private ConsoleManager m_console_manager = null; private HttpTransport m_http = null; private JSONGeneratorFactory m_json_factory = null; private JSONGenerator m_json_generator = null; private JSONParser m_json_parser = null; private boolean m_listeners_initialized = false; private String m_mds_domain = null; private DatabaseConnector m_db = null; private String m_tablename_delimiter = null; private boolean m_is_master_node = true; // default is to be a master node public Orchestrator(ErrorLogger error_logger, PreferenceManager preference_manager, String domain) { // save the error handler this.m_error_logger = error_logger; this.m_preference_manager = preference_manager; // MDS domain is required if (domain != null && domain.equalsIgnoreCase(this.preferences().valueOf("mds_def_domain")) == false) { this.m_mds_domain = domain; } // get our master node designation this.m_is_master_node = this.m_preference_manager.booleanValueOf("is_master_node"); // initialize the database connector boolean enable_distributed_db_cache = this.preferences().booleanValueOf("enable_distributed_db_cache"); if (enable_distributed_db_cache == true) { this.m_tablename_delimiter = this.preferences().valueOf("distributed_db_tablename_delimiter"); if (this.m_tablename_delimiter == null || this.m_tablename_delimiter.length() == 0) { this.m_tablename_delimiter = DEF_TABLENAME_DELIMITER; } String db_ip_address = this.preferences().valueOf("distributed_db_ip_address"); int db_port = this.preferences().intValueOf("distributed_db_port"); String db_username = this.preferences().valueOf("distributed_db_username"); String db_pw = this.preferences().valueOf("distributed_db_password"); this.m_db = new DatabaseConnector(this,db_ip_address,db_port,db_username,db_pw); } // finalize the preferences manager this.m_preference_manager.initializeCache(this.m_db,this.m_is_master_node); // JSON Factory this.m_json_factory = JSONGeneratorFactory.getInstance(); // create the JSON Generator this.m_json_generator = this.m_json_factory.newJsonGenerator(); // create the JSON Parser this.m_json_parser = this.m_json_factory.newJsonParser(); // build out the HTTP transport this.m_http = new HttpTransport(this.m_error_logger, this.m_preference_manager); // REQUIRED: We always create the mDS REST processor this.m_mbed_device_server_processor = new mbedDeviceServerProcessor(this, this.m_http); // initialize our peer processor list this.initPeerProcessorList(); // create the console manager this.m_console_manager = new ConsoleManager(this); // start any needed device discovery this.initDeviceDiscovery(); } // get the tablename delimiter public String getTablenameDelimiter() { return this.m_tablename_delimiter; } // get the database connector public DatabaseConnector getDatabaseConnector() { return this.m_db; } // initialize our peer processor private void initPeerProcessorList() { // initialize the list this.m_peer_processor_list = new ArrayList<>(); // add peer processors if (this.ibmPeerEnabled()) { // IBM/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding IBM Watson IoT MQTT Processor"); this.m_peer_processor_list.add(WatsonIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.msPeerEnabled()) { // MS IoTHub/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding MS IoTHub MQTT Processor"); this.m_peer_processor_list.add(MSIoTHubPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.awsPeerEnabled()) { // AWS IoT/MQTT: create the MQTT processor manager this.errorLogger().info("Orchestrator: adding AWS IoT MQTT Processor"); this.m_peer_processor_list.add(AWSIoTPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.googleCloudPeerEnabled()) { // Google Cloud: create the Google Cloud peer processor... this.errorLogger().info("Orchestrator: adding Google Cloud Processor"); this.m_peer_processor_list.add(GoogleCloudPeerProcessorFactory.createPeerProcessor(this, this.m_http)); } if (this.genericMQTTPeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding Generic MQTT Processor"); this.m_peer_processor_list.add(GenericMQTTProcessor.createPeerProcessor(this, this.m_http)); } if (this.samplePeerEnabled()) { // Create the sample peer processor... this.errorLogger().info("Orchestrator: adding 3rd Party Sample REST Processor"); this.m_peer_processor_list.add(Sample3rdPartyProcessor.createPeerProcessor(this, this.m_http)); } } // use IBM peer processor? private Boolean ibmPeerEnabled() { return (this.preferences().booleanValueOf("enable_iotf_addon") || this.preferences().booleanValueOf("enable_starterkit_addon")); } // use MS peer processor? private Boolean msPeerEnabled() { return (this.preferences().booleanValueOf("enable_iot_event_hub_addon")); } // use AWS peer processor? private Boolean awsPeerEnabled() { return (this.preferences().booleanValueOf("enable_aws_iot_gw_addon")); } // use Google Cloud peer processor? private Boolean googleCloudPeerEnabled() { return (this.preferences().booleanValueOf("enable_google_cloud_addon")); } // use sample 3rd Party peer processor? private Boolean samplePeerEnabled() { return this.preferences().booleanValueOf("enable_3rd_party_rest_processor"); } // use generic MQTT peer processor? private Boolean genericMQTTPeerEnabled() { return this.preferences().booleanValueOf("enable_generic_mqtt_processor"); } // are the listeners active? public boolean peerListenerActive() { return this.m_listeners_initialized; } // initialize peer listener public void initPeerListener() { if (!this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).initListener(); } this.m_listeners_initialized = true; } } // stop the peer listener public void stopPeerListener() { if (this.m_listeners_initialized) { // MQTT Listener for (int i = 0; i < this.m_peer_processor_list.size(); ++i) { this.m_peer_processor_list.get(i).stopListener(); } this.m_listeners_initialized = false; } } // initialize the mbed Device Server webhook public void initializeDeviceServerWebhook() { if (this.m_mbed_device_server_processor != null) { // set the webhook this.m_mbed_device_server_processor.setWebhook(); // begin validation polling this.beginValidationPolling(); } } // reset mbed Device Server webhook public void resetDeviceServerWebhook() { // REST (mDS) if (this.m_mbed_device_server_processor != null) { this.m_mbed_device_server_processor.resetWebhook(); } } // process the mbed Device Server inbound message public void processIncomingDeviceServerMessage(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("events (REST-" + request.getMethod() + "): " + request.getRequestURI()); this.device_server_processor().processNotificationMessage(request, response); } // process the Console request/event public void processConsoleEvent(HttpServletRequest request, HttpServletResponse response) { // process the received REST message //this.errorLogger().info("console (REST-" + request.getMethod() + "): " + request.getServletPath()); this.console_manager().processConsole(request, response); } // get the HttpServlet public HttpServlet getServlet() { return this.m_servlet; } // get the<SUF> public ErrorLogger errorLogger() { return this.m_error_logger; } // get he Preferences manager public final PreferenceManager preferences() { return this.m_preference_manager; } // get the Peer processor public ArrayList<PeerInterface> peer_processor_list() { return this.m_peer_processor_list; } // get the mDS processor public mbedDeviceServerInterface device_server_processor() { return this.m_mbed_device_server_processor; } // get the console manager public ConsoleManager console_manager() { return this.m_console_manager; } // get our mDS domain public String getDomain() { return this.m_mds_domain; } // get the JSON parser instance public JSONParser getJSONParser() { return this.m_json_parser; } // get the JSON generation instance public JSONGenerator getJSONGenerator() { return this.m_json_generator; } // get our ith peer processor private PeerInterface peerProcessor(int index) { if (index >= 0 && this.m_peer_processor_list != null && index < this.m_peer_processor_list.size()) { return this.m_peer_processor_list.get(index); } return null; } // Message: API Request @Override public ApiResponse processApiRequestOperation(String uri,String data,String options,String verb,int request_id,String api_key,String caller_id, String content_type) { return this.device_server_processor().processApiRequestOperation(uri, data, options, verb, request_id, api_key, caller_id, content_type); } // Message: notifications @Override public void processNotificationMessage(HttpServletRequest request, HttpServletResponse response) { this.device_server_processor().processNotificationMessage(request, response); } // Message: device-deletions (mbed Cloud) @Override public void processDeviceDeletions(String[] endpoints) { this.device_server_processor().processDeviceDeletions(endpoints); } // Message: de-registrations @Override public void processDeregistrations(String[] endpoints) { this.device_server_processor().processDeregistrations(endpoints); } // Message: registrations-expired @Override public void processRegistrationsExpired(String[] endpoints) { this.device_server_processor().processRegistrationsExpired(endpoints); } @Override public String subscribeToEndpointResource(String uri, Map options, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(uri, options, init_webhook); } @Override public String subscribeToEndpointResource(String ep_name, String uri, Boolean init_webhook) { return this.device_server_processor().subscribeToEndpointResource(ep_name, uri, init_webhook); } @Override public String unsubscribeFromEndpointResource(String uri, Map options) { return this.device_server_processor().unsubscribeFromEndpointResource(uri, options); } @Override public String processEndpointResourceOperation(String verb, String ep_name, String uri, String value, String options) { return this.device_server_processor().processEndpointResourceOperation(verb, ep_name, uri, value, options); } @Override public void setWebhook() { this.device_server_processor().setWebhook(); } @Override public void resetWebhook() { this.device_server_processor().resetWebhook(); } @Override public void pullDeviceMetadata(Map endpoint, AsyncResponseProcessor processor) { this.device_server_processor().pullDeviceMetadata(endpoint, processor); } // PeerInterface Orchestration @Override public String createAuthenticationHash() { StringBuilder buf = new StringBuilder(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { buf.append(this.peerProcessor(i).createAuthenticationHash()); } return buf.toString(); } @Override public void recordAsyncResponse(String response, String uri, Map ep, AsyncResponseProcessor processor) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).recordAsyncResponse(response, uri, ep, processor); } } // Message: registration @Override public void processNewRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNewRegistration(message); } } // Message: reg-updates @Override public void processReRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processReRegistration(message); } } // Message: device-deletions (mbed Cloud) @Override public String[] processDeviceDeletions(Map message) { ArrayList<String> deletions = new ArrayList<>(); for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deletions = this.peerProcessor(i).processDeviceDeletions(message); for (int j = 0; ith_deletions != null && j < ith_deletions.length; ++j) { boolean add = deletions.add(ith_deletions[j]); } } String[] deletion_str_array = new String[deletions.size()]; return deletions.toArray(deletion_str_array); } // Message: de-registrations @Override public String[] processDeregistrations(Map message) { ArrayList<String> deregistrations = new ArrayList<>(); // loop through the list and process the de-registrations for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_deregistrations = this.peerProcessor(i).processDeregistrations(message); for (int j = 0; ith_deregistrations != null && j < ith_deregistrations.length; ++j) { boolean add = deregistrations.add(ith_deregistrations[j]); } } String[] dereg_str_array = new String[deregistrations.size()]; return deregistrations.toArray(dereg_str_array); } // Message: registrations-expired @Override public String[] processRegistrationsExpired(Map message) { ArrayList<String> registrations_expired = new ArrayList<>(); // only if devices are removed on de-regsistration for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { String[] ith_reg_expired = this.peerProcessor(i).processRegistrationsExpired(message); for (int j = 0; ith_reg_expired != null && j < ith_reg_expired.length; ++j) { boolean add = registrations_expired.add(ith_reg_expired[j]); } } String[] regexpired_str_array = new String[registrations_expired.size()]; return registrations_expired.toArray(regexpired_str_array); } // complete new device registration @Override public void completeNewDeviceRegistration(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).completeNewDeviceRegistration(message); } } @Override public void processAsyncResponses(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processAsyncResponses(message); } } @Override public void processNotification(Map message) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).processNotification(message); } } public void removeSubscription(String domain, String endpoint, String ep_type, String uri) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().removeSubscription(domain,endpoint,ep_type,uri); } } public void addSubscription(String domain, String endpoint, String ep_type, String uri, boolean is_observable) { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).subscriptionsManager().addSubscription(domain,endpoint,ep_type,uri,is_observable); } } @Override public void initListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).initListener(); } } @Override public void stopListener() { for (int i = 0; this.m_peer_processor_list != null && i < this.m_peer_processor_list.size(); ++i) { this.peerProcessor(i).stopListener(); } } @Override public void beginValidationPolling() { this.device_server_processor().beginValidationPolling(); } @Override public String createSubscriptionURI(String ep_name, String resource_uri) { return this.device_server_processor().createSubscriptionURI(ep_name, resource_uri); } @Override public boolean deviceRemovedOnDeRegistration() { if (this.device_server_processor() != null) { return this.device_server_processor().deviceRemovedOnDeRegistration(); } // default is false return false; } @Override public boolean usingMbedCloud() { if (this.device_server_processor() != null) { return this.device_server_processor().usingMbedCloud(); } // default is false return false; } @Override public SubscriptionManager subscriptionsManager() { // unused return null; } @Override public void initDeviceDiscovery() { this.device_server_processor().initDeviceDiscovery(); } }
206940_5
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
xorgate/TabSwitcherExtreme
src/org/intellij/ideaplugins/tabswitcherextreme/ListManager.java
4,355
// separator between filenamelist
line_comment
nl
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between<SUF> GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
206940_16
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
xorgate/TabSwitcherExtreme
src/org/intellij/ideaplugins/tabswitcherextreme/ListManager.java
4,355
//Utils.log("we zittne op lijst " + curListIndex);
line_comment
nl
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne<SUF> // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
206940_18
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou de index zijn op " + targetListIndex); //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
xorgate/TabSwitcherExtreme
src/org/intellij/ideaplugins/tabswitcherextreme/ListManager.java
4,355
//Utils.log("Wat zou de index zijn op " + targetListIndex);
line_comment
nl
package org.intellij.ideaplugins.tabswitcherextreme; import com.intellij.openapi.editor.markup.EffectType; import com.intellij.openapi.editor.markup.TextAttributes; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Iconable; import com.intellij.openapi.vcs.FileStatus; import com.intellij.openapi.vcs.FileStatusManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.ui.ColoredListCellRenderer; import com.intellij.ui.SimpleTextAttributes; import com.intellij.uiDesigner.core.GridConstraints; import com.intellij.uiDesigner.core.GridLayoutManager; import com.intellij.util.IconUtil; import java.awt.*; import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import javax.swing.*; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class ListManager { public List<ListDescription> mListDescriptions; private int mActiveListIndex = 0; public int mDesiredIndexInList; private Project mProject; public List<VirtualFile> mRecentFiles; public ListManager(Project project, List<VirtualFile> recentFiles) { mListDescriptions = new ArrayList<ListDescription>(); mProject = project; mRecentFiles = cleanupRecentFiles(recentFiles); } public List<VirtualFile> cleanupRecentFiles(List<VirtualFile> recentFiles) { mRecentFiles = new ArrayList<VirtualFile>(); for (VirtualFile file : recentFiles) { if (!mRecentFiles.contains(file)) { mRecentFiles.add(file); } } return mRecentFiles; } public void generateFileLists(List<VirtualFile> allFiles) { // copy the list, and if found one, remove from shadowlist. If any left, make a new list with leftovers Collections.sort(allFiles, new Comparator <VirtualFile>() { public int compare(VirtualFile a, VirtualFile b) { return a.getName().compareTo(b.getName()); } }); List<VirtualFile> controlList = new ArrayList<VirtualFile>(allFiles.size()); controlList.addAll(allFiles); List<String> controlListStrings = new ArrayList<String> (allFiles.size()); for (VirtualFile f : controlList) { controlListStrings.add(f.getPath()); } List<ListDescription> removeList = new ArrayList<ListDescription>(); for (ListDescription desc : mListDescriptions) { List<VirtualFile> filtered = new ArrayList<VirtualFile>(); for (VirtualFile f : allFiles) { String filename = f.getPath(); // don't keep doubles if (controlListStrings.contains(filename)) { //Utils.log("Controllist bevat niet " + filename); if (filename.matches(desc.mMatchRegex)) { filtered.add(f); controlList.remove(f); controlListStrings.remove(filename); } } } if (filtered.isEmpty()) { removeList.add(desc); } else { desc.setFilteredFileList(filtered); } } for (ListDescription desc : removeList) { mListDescriptions.remove(desc); } // check if we have some lost souls if (!controlList.isEmpty()) { ListDescription leftovers = new ListDescription(".*", "Other", ".xml"); leftovers.mFilteredFileList = controlList; mListDescriptions.add(leftovers); } } public JList getActiveList() { return getListFromIndex(mActiveListIndex); } public int getActiveListIndex() { return mActiveListIndex; } public void setActiveListIndex(int listIndex) { mActiveListIndex = Utils.modulo(listIndex, getListCount()); } public int getListCount() { return mListDescriptions.size(); } public JList getListFromIndex(int index) { int correctedIndex = Utils.modulo(index, getListCount()); return mListDescriptions.get(correctedIndex).mList; } public void addListDescription(String pattern, String description, String removerRegex) { ListDescription desc = new ListDescription(pattern, description, removerRegex); mListDescriptions.add(desc); } public VirtualFile getSelectedFile() { return (VirtualFile) getActiveList().getSelectedValue(); } public void insertIntoPanel(JPanel panel, JLabel pathLabel) { int rows = 2; // header + list int cols = getListCount() * 2 - 1; // separator between filenamelist GridLayoutManager manager = new GridLayoutManager(rows, cols); panel.setLayout(manager); // add them in for (int i = 0; i < getListCount(); i++) { int rowNr = i; ListDescription desc = mListDescriptions.get(i); // label GridConstraints labelConstraints = new GridConstraints(); labelConstraints.setRow(0); labelConstraints.setColumn(rowNr); panel.add(desc.getLabel(), labelConstraints); // list GridConstraints listConstraints = new GridConstraints(); listConstraints.setRow(1); listConstraints.setColumn(rowNr); listConstraints.setFill(GridConstraints.FILL_VERTICAL); panel.add(desc.getList(), listConstraints); setListData(desc, desc.mFilteredFileList, pathLabel); } } private void setListData(ListManager.ListDescription desc, final List<VirtualFile> filtered, JLabel pathLabel) { desc.mList.setModel(new AbstractListModel() { public int getSize() { return filtered.size(); } public Object getElementAt(int index) { return filtered.get(index); } }); desc.mList.setCellRenderer(getRenderer(mProject)); desc.mList.getSelectionModel().addListSelectionListener(getListener(desc.mList, pathLabel)); desc.mList.setVisibleRowCount(filtered.size()); } private static ListSelectionListener getListener(final JList list, final JLabel path) { return new ListSelectionListener() { public void valueChanged(ListSelectionEvent event) { SwingUtilities.invokeLater(new Runnable() { public void run() { updatePath(list, path); } }); } }; } private static void updatePath(JList list, JLabel path) { String text = " "; final Object[] values = list.getSelectedValues(); if ((values != null) && (values.length == 1)) { final VirtualFile parent = ((VirtualFile) values[0]).getParent(); if (parent != null) { text = parent.getPresentableUrl(); final FontMetrics metrics = path.getFontMetrics(path.getFont()); while ((metrics.stringWidth(text) > path.getWidth()) && (text.indexOf(File.separatorChar, 4) > 0)) { text = "..." + text.substring(text.indexOf(File.separatorChar, 4)); } } } path.setText(text); } private static ListCellRenderer getRenderer(final Project project) { return new ColoredListCellRenderer() { @Override protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) { if (value instanceof VirtualFile) { final VirtualFile file = (VirtualFile) value; setIcon(IconUtil.getIcon(file, Iconable.ICON_FLAG_READ_STATUS, project)); final FileStatus status = FileStatusManager.getInstance(project).getStatus(file); final TextAttributes attributes = new TextAttributes(status.getColor(), null, null, EffectType.LINE_UNDERSCORE, Font.PLAIN); String filename = file.getName(); String remover = (( ListDescription.JMyList) list).mRemoveRegex; if (null != remover) { filename = filename.replaceAll(remover, ""); } append(filename, SimpleTextAttributes.fromTextAttributes(attributes)); } } }; } public class ListDescription { private class JMyList extends JList { public String mRemoveRegex; } private JMyList mList; private JLabel mLabel; String mMatchRegex; String mDescription; List<VirtualFile> mFilteredFileList; public ListDescription(String matchString, String description, String removeRegex ) { mDescription = description; mMatchRegex = matchString; mFilteredFileList = new ArrayList<VirtualFile>(); //noinspection UndesirableClassUsage mList = new JMyList(); if (!"".equals(removeRegex)) { mList.mRemoveRegex = removeRegex; } mLabel = new JLabel("<html><b>" + description + "</b></html>", SwingConstants.CENTER); } public void setFilteredFileList(List<VirtualFile> filteredList) { mFilteredFileList = filteredList; } public JList getList() { return mList; } public JLabel getLabel() { return mLabel; } } public void updateSelection(NavigateCommand nav) { int previousListIndex = getActiveListIndex(); JList previousList = getActiveList(); int previousIndexInList = previousList.getSelectedIndex(); // logic is done in here FilePosition targetFilePosition = getTargetFilePosition(previousListIndex, previousIndexInList, nav); // no move possible? Just abort if (targetFilePosition == null) { return; } JList nextList = getListFromIndex(targetFilePosition.getListIndex()); int nextIndexInList = targetFilePosition.getIndexInList(); nextList.setSelectedIndex(nextIndexInList); nextList.ensureIndexIsVisible(nextIndexInList); if (targetFilePosition.getListIndex() != previousListIndex ) { setActiveListIndex(targetFilePosition.getListIndex()); // clear the previous one previousList.clearSelection(); } } private VirtualFile nextRecentFile(Project proj, VirtualFile current, boolean wantOlder) { //final VirtualFile[] recentFilesArr = mRecentFiles; final FileEditorManager manager = FileEditorManager.getInstance(proj); List<VirtualFile> recentFilesList = new ArrayList<VirtualFile>(mRecentFiles.size()); //Collections.addAll(recentFilesList, mRecentFiles); for (VirtualFile file : mRecentFiles) { recentFilesList.add(file); } Utils.log("Recent files : " + recentFilesList.size()); //Utils.log("Current file: " + current.getName()); for (VirtualFile file : recentFilesList) { Utils.log(file.getName() + (file.equals(current) ? " <-- " : "")); } if (!wantOlder) { Utils.log("want older"); Collections.reverse(recentFilesList); } else { Utils.log("want newer"); } for (VirtualFile lister : recentFilesList) { if (manager.isFileOpen(lister)) { Utils.log("- " + lister.getName()); } } boolean currentFound = false; for (VirtualFile file : recentFilesList) { if (file.equals(current)) { currentFound = true; } else { if (currentFound) { if (manager.isFileOpen(file)) { Utils.log("-- next is " + file.getName()); return file; } } } } // if not found, try again and get first available file for (VirtualFile f : recentFilesList) { if (manager.isFileOpen(f)) { return f; } } return null; } private FilePosition getNextInHistory(int curListIndex, int curIndexInList, boolean wantNewer) { VirtualFile cur = getSelectedFile(); VirtualFile other = nextRecentFile(mProject, cur, wantNewer); return getFilePosition(other); } private FilePosition getTargetFilePosition(int curListIndex, int curIndexInList, NavigateCommand navCmd) { // selection is in a certain list, press a key, figure out where the next selection will be. // loop around to this current list again = no action if (navCmd == NavigateCommand.TAB) { Utils.log("TAB"); return getNextInHistory(curListIndex, curIndexInList, false); } if (navCmd == NavigateCommand.SHIFTTAB) { Utils.log("SHIFTTAB"); return getNextInHistory(curListIndex, curIndexInList, true); } // if targetlist is empty, try one beyond if (curIndexInList == -1) { Utils.log("Aangeroepen op lijst " + curListIndex + " waar niks in zit..."); return null; } // updown if (navCmd == NavigateCommand.UP || navCmd == NavigateCommand.DOWN) { JList curList = getListFromIndex(curListIndex); int size = curList.getModel().getSize(); Utils.log("Aantal in lijst: " + size); int offset = navCmd == NavigateCommand.DOWN ? 1 : -1; Utils.log("Offset: " + offset); int newIndexInList = Utils.modulo(curIndexInList + offset, size); Utils.log("Van " + curIndexInList + " naar " + newIndexInList); if (newIndexInList == curIndexInList) { return null; } mDesiredIndexInList = newIndexInList; return new FilePosition(curListIndex, newIndexInList); } else if (navCmd == NavigateCommand.LEFT || navCmd == NavigateCommand.RIGHT) { int direction = navCmd == NavigateCommand.LEFT ? -1 : 1; int targetListIndex = curListIndex; //Utils.log("we zittne op lijst " + curListIndex); // find the first list that is not empty, in specified direction int targetIndexInList; do { targetListIndex = Utils.modulo(targetListIndex + direction, getListCount()); //Utils.log("Wat zou<SUF> //targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, curIndexInList); targetIndexInList = getActualTargetIndexInOtherList(targetListIndex, mDesiredIndexInList); //Utils.log(" nou, " + targetIndexInList); } while (targetIndexInList == -1); if (targetListIndex != curListIndex) { return new FilePosition(targetListIndex, targetIndexInList); } Utils.log("We komen bij onszelf uit"); } else if (navCmd == NavigateCommand.PAGE_UP || navCmd == NavigateCommand.PAGE_DOWN) { JList curList = getListFromIndex(curListIndex); int targetIndexInList; if (navCmd == NavigateCommand.PAGE_UP) { targetIndexInList = 0; Utils.log("Pageup naar 0"); } else { targetIndexInList = curList.getModel().getSize() - 1; Utils.log("Pagedown naar " + targetIndexInList); } mDesiredIndexInList = targetIndexInList; if (targetIndexInList != curIndexInList) { return new FilePosition(curListIndex, targetIndexInList); } } return null; } private int getActualTargetIndexInOtherList(int listIndex, int requestedIndexInList) { // returns -1 if empty JList targetList = getListFromIndex(listIndex); int size = targetList.getModel().getSize(); if (size == 0) { return -1; } else { return Math.min( size-1, Math.max(0, requestedIndexInList)); } } public FilePosition getFilePosition(VirtualFile f) { int initialListIndex = 0; int initialIndexInList = 0; if (f != null) { Utils.log("get position for: " + f.getName()); int foundListIndex = -1; int foundIndexInList = -1; for (int i =0; i< mListDescriptions.size(); i++) { ListManager.ListDescription desc = mListDescriptions.get(i); List<VirtualFile> list = desc.mFilteredFileList; int index = list.indexOf(f); if (index != -1) { foundListIndex = i; foundIndexInList = index; break; } } if (foundIndexInList != -1) { initialListIndex = foundListIndex; initialIndexInList = foundIndexInList; } else { Utils.log("NIET GEVONDEN: " + f.getName()); } } return new FilePosition(initialListIndex, initialIndexInList); } public class FilePosition { private int mListIndex; private int mIndexInList; FilePosition(int listIndex, int indexInList) { mListIndex = listIndex; mIndexInList = indexInList; } int getListIndex() { return mListIndex; } int getIndexInList() { return mIndexInList; } } public enum NavigateCommand { LEFT, RIGHT, UP, DOWN, PAGE_UP, PAGE_DOWN, TAB, SHIFTTAB } }
206983_60
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed start element. // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns) { // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/shredder/XMLImport.java
2,329
// * Current parsed start element.
line_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed<SUF> // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns) { // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
206983_63
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed start element. // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns) { // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/shredder/XMLImport.java
2,329
// RevNode... mTsns) {
line_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.shredder; /** * <h1>XMLImport</h1> * * <p> * Import of temporal data, which is either available as exactly one file which includes several revisions or * many files, whereas one file represents exactly one revision. Beforehand one or more <code>RevNode</code> * have to be instanciated. * </p> * * <p> * Usage example: * * <code><pre> * final File file = new File("database.xml"); * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * * <code><pre> * final List<File> list = new ArrayList<File>(); * list.add("rev1.xml"); * list.add("rev2.xml"); * ... * new XMLImport(file).check(new RevNode(new QName("timestamp"))); * </pre></code> * </p> * * @author Johannes Lichtenberger, University of Konstanz * */ public final class XMLImport { // /** // * Log wrapper for better output. // */ // private static final LogWrapper LOGWRAPPER = new // LogWrapper(LoggerFactory.getLogger(XMLImport.class)); // // /** {@link Session}. */ // private transient ISession mSession; // // /** {@link WriteTransaction}. */ // private transient IWriteTransaction mWtx; // // /** Path to Treetank storage. */ // private transient File mTT; // // /** Log helper. */ // private transient LogWrapper mLog; // // /** Revision nodes {@link RevNode}. */ // private transient List<RevNode> mNodes; // // /** File to shredder. */ // private transient File mXml; // // /** // * Constructor. // * // * @param mTt // * Treetank file. // */ // public XMLImport(final File mTt) { // try { // mTT = mTt; // mNodes = new ArrayList<RevNode>(); // final IStorage database = Storage.openDatabase(mTT); // mSession = database.getSession(); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // // @SuppressWarnings("unchecked") // @Override // public void check(final Object mBackend, final Object mObj) { // try { // // Setup executor service. // final ExecutorService execService = // Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); // // if (mBackend instanceof File) { // // Single file. // mXml = (File)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // } // execService.submit(this); // } else if (mBackend instanceof List<?>) { // // List of files. // final List<?> files = (List<?>)mBackend; // if (mObj instanceof RevNode) { // mNodes.add((RevNode)mObj); // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } else if (mObj instanceof List<?>) { // mNodes = (List<RevNode>)mObj; // for (final File xmlFile : files.toArray(new File[files.size()])) { // mXml = xmlFile; // execService.submit(this); // } // } // } // // // Shutdown executor service. // execService.shutdown(); // execService.awaitTermination(10, TimeUnit.MINUTES); // } catch (final InterruptedException e) { // LOGWRAPPER.error(e); // } finally { // try { // mWtx.close(); // mSession.close(); // Storage.forceCloseDatabase(mTT); // } catch (final TreetankException e) { // LOGWRAPPER.error(e); // } // } // } // // @Override // public Void call() throws Exception { // // Setup StAX parser. // final XMLEventReader reader = XMLShredder.createReader(mXml); // final XMLEvent mEvent = reader.nextEvent(); // final IWriteTransaction wtx = mSession.beginWriteTransaction(); // // // Parse file. // boolean first = true; // do { // mLog.debug(mEvent.toString()); // // if (XMLStreamConstants.START_ELEMENT == mEvent.getEventType() // && checkTimestampNodes((StartElement)mEvent, mNodes.toArray(new // RevNode[mNodes.size()]))) { // // Found revision node. // wtx.moveToDocumentRoot(); // // if (first) { // first = false; // // // Initial shredding. // new XMLShredder(wtx, reader, true).call(); // } else { // // Subsequent shredding. // // new XMLUpdateShredder(wtx, reader, true, true).call(); // } // } // // reader.nextEvent(); // } while (reader.hasNext()); // return null; // } // // /** // * Check if current start element matches one of the timestamp/revision // * nodes. // * // * @param mEvent // * Current parsed start element. // * @param mTsns // * Timestamp nodes. // * @return true if they match, otherwise false. // */ // private boolean checkTimestampNodes(final StartElement mEvent, final // RevNode... mTsns)<SUF> // boolean mRetVal = false; // // for (final RevNode tsn : mTsns) { // tsn.toString(); // // TODO // } // // return mRetVal; // } // // /** // * <h1>RevNode</h1> // * // * <p> // * Container which holds the full qualified name of a "timestamp" node. // * </p> // * // * @author Johannes Lichtenberger, University of Konstanz // * // */ // final static class RevNode { // /** QName of the node, which has the timestamp attribute. */ // private transient final QName mQName; // // /** Attribute which specifies the timestamp value. */ // private transient final Attribute mAttribute; // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // */ // public RevNode(final QName mQName) { // this(mQName, null); // } // // /** // * Constructor. // * // * @param mQName // * Full qualified name of the timestamp node. // * @param mAtt // * Attribute which specifies the timestamp value. // */ // public RevNode(final QName mQName, final Attribute mAtt) { // this.mQName = mQName; // this.mAttribute = mAtt; // } // // /** // * Get mQName. // * // * @return the full qualified name. // */ // public QName getQName() { // return mQName; // } // // /** // * Get attribute. // * // * @return the attribute. // */ // public Attribute getAttribute() { // return mAttribute; // } // } }
207003_12
/* *********************************************************************** * * project: org.matsim.* * EditRoutesTest.java * * * *********************************************************************** * * * * copyright : (C) 2020 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.run.modules; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.episim.EpisimConfigGroup; import org.matsim.episim.EpisimUtils; import org.matsim.episim.VaccinationConfigGroup; import org.matsim.episim.model.*; import org.matsim.episim.model.activity.ActivityParticipationModel; import org.matsim.episim.model.activity.DefaultParticipationModel; import org.matsim.episim.model.activity.LocationBasedParticipationModel; import org.matsim.episim.model.input.CreateAdjustedRestrictionsFromCSV; import org.matsim.episim.model.input.CreateRestrictionsFromCSV; import org.matsim.episim.model.input.RestrictionInput; import org.matsim.episim.model.listener.HouseholdSusceptibility; import org.matsim.episim.model.progression.AgeDependentDiseaseStatusTransitionModel; import org.matsim.episim.model.progression.DiseaseStatusTransitionModel; import org.matsim.episim.model.vaccination.VaccinationFromData; import org.matsim.episim.model.vaccination.VaccinationModel; import org.matsim.episim.policy.AdjustedPolicy; import org.matsim.episim.policy.FixedPolicy; import org.matsim.episim.policy.Restriction; import org.matsim.episim.policy.ShutdownPolicy; import javax.inject.Singleton; import java.nio.file.Path; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; /** * Scenario for Berlin using Senozon events for different weekdays. */ public final class SnzBerlinProductionScenario extends SnzProductionScenario { public static class Builder extends SnzProductionScenario.Builder<SnzBerlinProductionScenario> { private Snapshot snapshot = Snapshot.no; public Builder setSnapshot(Snapshot snapshot) { this.snapshot = snapshot; return this; } @Override public SnzBerlinProductionScenario build() { return new SnzBerlinProductionScenario(this); } } public enum Snapshot {no, episim_snapshot_060_2020_04_24, episim_snapshot_120_2020_06_23, episim_snapshot_180_2020_08_22, episim_snapshot_240_2020_10_21} private final int sample; private final int importOffset; private final DiseaseImport diseaseImport; private final Restrictions restrictions; private final AdjustRestrictions adjustRestrictions; private final Masks masks; private final Tracing tracing; private final Snapshot snapshot; private final Vaccinations vaccinations; private final ChristmasModel christmasModel; private final EasterModel easterModel; private final WeatherModel weatherModel; private final Class<? extends InfectionModel> infectionModel; private final Class<? extends VaccinationModel> vaccinationModel; private final EpisimConfigGroup.ActivityHandling activityHandling; private final double imprtFctMult; private final double importFactorBeforeJune; private final double importFactorAfterJune; private final LocationBasedRestrictions locationBasedRestrictions; /** * Path pointing to the input folder. Can be configured at runtime with EPISIM_INPUT variable. */ public static final Path INPUT = EpisimUtils.resolveInputPath("../shared-svn/projects/episim/matsim-files/snz/BerlinV2/episim-input"); /** * Empty constructor is needed for running scenario from command line. */ @SuppressWarnings("unused") private SnzBerlinProductionScenario() { this(new Builder()); } private SnzBerlinProductionScenario(Builder builder) { this.sample = builder.sample; this.diseaseImport = builder.diseaseImport; this.restrictions = builder.restrictions; this.adjustRestrictions = builder.adjustRestrictions; this.masks = builder.masks; this.tracing = builder.tracing; this.snapshot = builder.snapshot; this.activityHandling = builder.activityHandling; this.infectionModel = builder.infectionModel; this.importOffset = builder.importOffset; this.vaccinationModel = builder.vaccinationModel; this.vaccinations = builder.vaccinations; this.christmasModel = builder.christmasModel; this.weatherModel = builder.weatherModel; this.imprtFctMult = builder.imprtFctMult; this.importFactorBeforeJune = builder.importFactorBeforeJune; this.importFactorAfterJune = builder.importFactorAfterJune; this.easterModel = builder.easterModel; this.locationBasedRestrictions = builder.locationBasedRestrictions; } /** * Resolve input for sample size. Smaller than 25pt samples are in a different subfolder. */ private static String inputForSample(String base, int sample) { Path folder = (sample == 100 | sample == 25) ? INPUT : INPUT.resolve("samples"); return folder.resolve(String.format(base, sample)).toString(); } @Override protected void configure() { bind(ContactModel.class).to(SymmetricContactModel.class).in(Singleton.class); bind(DiseaseStatusTransitionModel.class).to(AgeDependentDiseaseStatusTransitionModel.class).in(Singleton.class); bind(InfectionModel.class).to(infectionModel).in(Singleton.class); bind(VaccinationModel.class).to(vaccinationModel).in(Singleton.class); //TODO: this is not in the cologne prod scenario, is it still needed? if (adjustRestrictions == AdjustRestrictions.yes) bind(ShutdownPolicy.class).to(AdjustedPolicy.class).in(Singleton.class); else bind(ShutdownPolicy.class).to(FixedPolicy.class).in(Singleton.class); if (activityHandling == EpisimConfigGroup.ActivityHandling.startOfDay) { if (locationBasedRestrictions == LocationBasedRestrictions.yes) { bind(ActivityParticipationModel.class).to(LocationBasedParticipationModel.class); } else { bind(ActivityParticipationModel.class).to(DefaultParticipationModel.class); } } bind(VaccinationFromData.Config.class).toInstance( VaccinationFromData.newConfig("11000") .withAgeGroup("05-11", 237886.9) .withAgeGroup("12-17", 182304.4) .withAgeGroup("18-59", 2138015) .withAgeGroup("60+", 915851) ); // TODO: from Cologne, do we need? // Multibinder.newSetBinder(binder(), SimulationListener.class) // .addBinding().to(HouseholdSusceptibility.class); } @Provides @Singleton public Config config() { // if (this.sample != 25 && this.sample != 100) // throw new RuntimeException("Sample size not calibrated! Currently only 25% is calibrated. Comment this line out to continue."); //general config Config config = ConfigUtils.createConfig(new EpisimConfigGroup()); config.global().setRandomSeed(7564655870752979346L); config.vehicles().setVehiclesFile(INPUT.resolve("de_2020-vehicles.xml").toString()); config.plans().setInputFile(inputForSample("be_2020-week_snz_entirePopulation_emptyPlans_withDistricts_%dpt_split.xml.gz", sample)); //episim config EpisimConfigGroup episimConfig = ConfigUtils.addOrGetModule(config, EpisimConfigGroup.class); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_wt_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_sa_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.SATURDAY); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_so_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.SUNDAY); episimConfig.setActivityHandling(activityHandling); // episimConfig.setThreads(6); // TODO: check repeat from below // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_wt_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY); // // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_sa_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.SATURDAY); // // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_so_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.SUNDAY); episimConfig.setCalibrationParameter(1.7E-5 * 0.8); episimConfig.setStartDate("2020-02-25"); episimConfig.setFacilitiesHandling(EpisimConfigGroup.FacilitiesHandling.snz); episimConfig.setSampleSize(this.sample / 100.); episimConfig.setHospitalFactor(0.5); episimConfig.setThreads(8); episimConfig.setDaysInfectious(Integer.MAX_VALUE); //progression model // episimConfig.setProgressionConfig(AbstractSnzScenario2020.baseProgressionConfig(Transition.config()).build()); episimConfig.setProgressionConfig(SnzProductionScenario.progressionConfig(Transition.config()).build()); //snapshot if (this.snapshot != Snapshot.no) episimConfig.setStartFromSnapshot(INPUT.resolve("snapshots/" + snapshot + ".zip").toString()); //inital infections and import // TODO: this is done differently in Cologne episimConfig.setInitialInfections(Integer.MAX_VALUE); if (this.diseaseImport != DiseaseImport.no) { SnzProductionScenario.configureDiseaseImport( episimConfig, diseaseImport, importOffset, imprtFctMult, importFactorBeforeJune, importFactorAfterJune ); } else { episimConfig.setInitialInfectionDistrict("Berlin"); episimConfig.setCalibrationParameter(2.54e-5); } //age-dependent infection model if (this.infectionModel != AgeDependentInfectionModelWithSeasonality.class) { if (this.diseaseImport == DiseaseImport.yes) { episimConfig.setCalibrationParameter(1.6E-5); // TODO: setting calibration param in multiple places may be error-prone } else { episimConfig.setCalibrationParameter(1.6E-5 * 2.54e-5 / 1.7E-5); } } //contact intensities SnzProductionScenario.configureContactIntensities(episimConfig); //restrictions and masks RestrictionInput activityParticipation; SnzBerlinScenario25pct2020.BasePolicyBuilder basePolicyBuilder = new SnzBerlinScenario25pct2020.BasePolicyBuilder(episimConfig); // TODO: should SnzBerlinScenario25pct2020 be absorbed into this class to match Cologne if (adjustRestrictions == AdjustRestrictions.yes) { activityParticipation = new CreateAdjustedRestrictionsFromCSV(); } else { activityParticipation = new CreateRestrictionsFromCSV(episimConfig); } String untilDate = "20220204"; activityParticipation.setInput(INPUT.resolve("BerlinSnzData_daily_until20220204.csv")); //location based restrictions if (locationBasedRestrictions == LocationBasedRestrictions.yes) { config.facilities().setInputFile(INPUT.resolve("be_2020-facilities_assigned_simplified_grid_WithNeighborhoodAndPLZ.xml.gz").toString()); episimConfig.setDistrictLevelRestrictions(EpisimConfigGroup.DistrictLevelRestrictions.yes); episimConfig.setDistrictLevelRestrictionsAttribute("subdistrict"); if (activityParticipation instanceof CreateRestrictionsFromCSV) { List<String> subdistricts = Arrays.asList("Spandau", "Neukoelln", "Reinickendorf", "Charlottenburg_Wilmersdorf", "Marzahn_Hellersdorf", "Mitte", "Pankow", "Friedrichshain_Kreuzberg", "Tempelhof_Schoeneberg", "Treptow_Koepenick", "Lichtenberg", "Steglitz_Zehlendorf"); Map<String, Path> subdistrictInputs = new HashMap<>(); for (String subdistrict : subdistricts) { subdistrictInputs.put(subdistrict, INPUT.resolve("perNeighborhood/" + subdistrict + "SnzData_daily_until" + untilDate + ".csv")); } ((CreateRestrictionsFromCSV) activityParticipation).setDistrictInputs(subdistrictInputs); } } basePolicyBuilder.setActivityParticipation(activityParticipation); if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.onlyEdu) { basePolicyBuilder.setActivityParticipation(null); } if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.allExceptEdu || this.restrictions == Restrictions.allExceptSchoolsAndDayCare) { basePolicyBuilder.setRestrictSchoolsAndDayCare(false); } if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.allExceptEdu || this.restrictions == Restrictions.allExceptUniversities) { basePolicyBuilder.setRestrictUniversities(false); } if (this.masks == Masks.no) basePolicyBuilder.setMaskCompliance(0); basePolicyBuilder.setCiCorrections(Map.of()); FixedPolicy.ConfigBuilder builder = basePolicyBuilder.buildFixed(); //curfew TODO: when is the restriction of closing hours lifted? (also for Cologne) builder.restrict("2021-04-24", Restriction.ofClosingHours(22, 5), "leisure", "visit"); Map<LocalDate, Double> curfewCompliance = new HashMap<LocalDate, Double>(); curfewCompliance.put(LocalDate.parse("2021-04-24"), 1.0);//https://www.berlin.de/aktuelles/berlin/6522691-958092-naechtliche-ausgangsbeschraenkungen-ab-s.html curfewCompliance.put(LocalDate.parse("2021-05-19"), 0.0); //https://www.berlin.de/aktuelles/berlin/6593002-958092-ausgangsbeschraenkungen-gelten-mittwoch-.html episimConfig.setCurfewCompliance(curfewCompliance); //tracing if (this.tracing == Tracing.yes) { SnzProductionScenario.configureTracing(config, 1.0); } //christmas and easter models Map<LocalDate, DayOfWeek> inputDays = new HashMap<>(); if (this.christmasModel != ChristmasModel.no) { SnzProductionScenario.configureChristmasModel(christmasModel, inputDays, builder); } if (this.easterModel == EasterModel.yes) { SnzProductionScenario.configureEasterModel(inputDays, builder); } episimConfig.setInputDays(inputDays); //outdoorFractions if (this.weatherModel != WeatherModel.no) { SnzProductionScenario.configureWeather(episimConfig, weatherModel, INPUT.resolve("tempelhofWeatherUntil20220208.csv").toFile(), INPUT.resolve("temeplhofWeatherDataAvg2000-2020.csv").toFile(), 1.0) ; } else { episimConfig.setLeisureOutdoorFraction(Map.of( LocalDate.of(2020, 1, 1), 0.) ); } //leisure & work factor double leisureFactor = 1.6; if (this.restrictions != Restrictions.no) { builder.applyToRf("2020-10-15", "2020-12-14", (d, e) -> 1 - leisureFactor * (1 - e), "leisure"); double workVacFactor = 0.92; BiFunction<LocalDate, Double, Double> f = (d, e) -> workVacFactor * e; //WorkVac Factors are applied from last school day -> last vacation day (Saturday not Sunday, // if vacation ends on weekend, b/c new restrictions for following week are always set sundays) builder.applyToRf("2020-04-03", "2020-04-17", f, "work", "business"); //Sommerferien builder.applyToRf("2020-06-26", "2020-08-07", f, "work", "business"); //Herbstferien builder.applyToRf("2020-10-09", "2020-10-23", f, "work", "business"); //Weihnachtsferien builder.applyToRf("2020-12-18", "2021-01-01", f, "work", "business"); //Winterferien builder.applyToRf("2021-01-29", "2021-02-05", f, "work", "business"); //Osterferien builder.applyToRf("2021-03-26", "2021-04-09", f, "work", "business"); //Sommerfeirien builder.applyToRf("2021-06-25", "2021-08-06", f, "work", "business"); //Herbstferien builder.applyToRf("2021-10-08", "2021-10-22", f, "work", "business"); //Weihnachtsferien builder.applyToRf("2021-12-17", "2022-01-04", f, "work", "business"); //Winterferien builder.applyToRf("2022-01-28", "2022-02-04", f, "work", "business"); // future //Osterferien builder.restrict(LocalDate.parse("2022-04-08"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-04-23"), 1.0, "work", "business"); //Sommerferien builder.restrict(LocalDate.parse("2022-07-07"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-08-19"), 1.0, "work", "business"); //Herbstferien builder.restrict(LocalDate.parse("2022-10-21"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-11-05"), 1.0, "work", "business"); //Weihnachtsferien builder.restrict(LocalDate.parse("2022-12-22"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2023-01-02"), 1.0, "work", "business"); } //vaccinations if (this.vaccinations.equals(Vaccinations.yes)) { VaccinationConfigGroup vaccinationConfig = ConfigUtils.addOrGetModule(config, VaccinationConfigGroup.class); SnzProductionScenario.configureVaccines(vaccinationConfig, 4_800_000); } episimConfig.setPolicy(builder.build()); config.controler().setOutputDirectory("output-snzWeekScenario-" + sample + "%"); return config; } }
matsim-org/matsim-episim-libs
src/main/java/org/matsim/run/modules/SnzBerlinProductionScenario.java
5,329
//age-dependent infection model
line_comment
nl
/* *********************************************************************** * * project: org.matsim.* * EditRoutesTest.java * * * *********************************************************************** * * * * copyright : (C) 2020 by the members listed in the COPYING, * * LICENSE and WARRANTY file. * * email : info at matsim dot org * * * * *********************************************************************** * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * See also COPYING, LICENSE and WARRANTY file * * * * *********************************************************************** */ package org.matsim.run.modules; import com.google.inject.Provides; import com.google.inject.multibindings.Multibinder; import org.matsim.core.config.Config; import org.matsim.core.config.ConfigUtils; import org.matsim.episim.EpisimConfigGroup; import org.matsim.episim.EpisimUtils; import org.matsim.episim.VaccinationConfigGroup; import org.matsim.episim.model.*; import org.matsim.episim.model.activity.ActivityParticipationModel; import org.matsim.episim.model.activity.DefaultParticipationModel; import org.matsim.episim.model.activity.LocationBasedParticipationModel; import org.matsim.episim.model.input.CreateAdjustedRestrictionsFromCSV; import org.matsim.episim.model.input.CreateRestrictionsFromCSV; import org.matsim.episim.model.input.RestrictionInput; import org.matsim.episim.model.listener.HouseholdSusceptibility; import org.matsim.episim.model.progression.AgeDependentDiseaseStatusTransitionModel; import org.matsim.episim.model.progression.DiseaseStatusTransitionModel; import org.matsim.episim.model.vaccination.VaccinationFromData; import org.matsim.episim.model.vaccination.VaccinationModel; import org.matsim.episim.policy.AdjustedPolicy; import org.matsim.episim.policy.FixedPolicy; import org.matsim.episim.policy.Restriction; import org.matsim.episim.policy.ShutdownPolicy; import javax.inject.Singleton; import java.nio.file.Path; import java.time.DayOfWeek; import java.time.LocalDate; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.BiFunction; /** * Scenario for Berlin using Senozon events for different weekdays. */ public final class SnzBerlinProductionScenario extends SnzProductionScenario { public static class Builder extends SnzProductionScenario.Builder<SnzBerlinProductionScenario> { private Snapshot snapshot = Snapshot.no; public Builder setSnapshot(Snapshot snapshot) { this.snapshot = snapshot; return this; } @Override public SnzBerlinProductionScenario build() { return new SnzBerlinProductionScenario(this); } } public enum Snapshot {no, episim_snapshot_060_2020_04_24, episim_snapshot_120_2020_06_23, episim_snapshot_180_2020_08_22, episim_snapshot_240_2020_10_21} private final int sample; private final int importOffset; private final DiseaseImport diseaseImport; private final Restrictions restrictions; private final AdjustRestrictions adjustRestrictions; private final Masks masks; private final Tracing tracing; private final Snapshot snapshot; private final Vaccinations vaccinations; private final ChristmasModel christmasModel; private final EasterModel easterModel; private final WeatherModel weatherModel; private final Class<? extends InfectionModel> infectionModel; private final Class<? extends VaccinationModel> vaccinationModel; private final EpisimConfigGroup.ActivityHandling activityHandling; private final double imprtFctMult; private final double importFactorBeforeJune; private final double importFactorAfterJune; private final LocationBasedRestrictions locationBasedRestrictions; /** * Path pointing to the input folder. Can be configured at runtime with EPISIM_INPUT variable. */ public static final Path INPUT = EpisimUtils.resolveInputPath("../shared-svn/projects/episim/matsim-files/snz/BerlinV2/episim-input"); /** * Empty constructor is needed for running scenario from command line. */ @SuppressWarnings("unused") private SnzBerlinProductionScenario() { this(new Builder()); } private SnzBerlinProductionScenario(Builder builder) { this.sample = builder.sample; this.diseaseImport = builder.diseaseImport; this.restrictions = builder.restrictions; this.adjustRestrictions = builder.adjustRestrictions; this.masks = builder.masks; this.tracing = builder.tracing; this.snapshot = builder.snapshot; this.activityHandling = builder.activityHandling; this.infectionModel = builder.infectionModel; this.importOffset = builder.importOffset; this.vaccinationModel = builder.vaccinationModel; this.vaccinations = builder.vaccinations; this.christmasModel = builder.christmasModel; this.weatherModel = builder.weatherModel; this.imprtFctMult = builder.imprtFctMult; this.importFactorBeforeJune = builder.importFactorBeforeJune; this.importFactorAfterJune = builder.importFactorAfterJune; this.easterModel = builder.easterModel; this.locationBasedRestrictions = builder.locationBasedRestrictions; } /** * Resolve input for sample size. Smaller than 25pt samples are in a different subfolder. */ private static String inputForSample(String base, int sample) { Path folder = (sample == 100 | sample == 25) ? INPUT : INPUT.resolve("samples"); return folder.resolve(String.format(base, sample)).toString(); } @Override protected void configure() { bind(ContactModel.class).to(SymmetricContactModel.class).in(Singleton.class); bind(DiseaseStatusTransitionModel.class).to(AgeDependentDiseaseStatusTransitionModel.class).in(Singleton.class); bind(InfectionModel.class).to(infectionModel).in(Singleton.class); bind(VaccinationModel.class).to(vaccinationModel).in(Singleton.class); //TODO: this is not in the cologne prod scenario, is it still needed? if (adjustRestrictions == AdjustRestrictions.yes) bind(ShutdownPolicy.class).to(AdjustedPolicy.class).in(Singleton.class); else bind(ShutdownPolicy.class).to(FixedPolicy.class).in(Singleton.class); if (activityHandling == EpisimConfigGroup.ActivityHandling.startOfDay) { if (locationBasedRestrictions == LocationBasedRestrictions.yes) { bind(ActivityParticipationModel.class).to(LocationBasedParticipationModel.class); } else { bind(ActivityParticipationModel.class).to(DefaultParticipationModel.class); } } bind(VaccinationFromData.Config.class).toInstance( VaccinationFromData.newConfig("11000") .withAgeGroup("05-11", 237886.9) .withAgeGroup("12-17", 182304.4) .withAgeGroup("18-59", 2138015) .withAgeGroup("60+", 915851) ); // TODO: from Cologne, do we need? // Multibinder.newSetBinder(binder(), SimulationListener.class) // .addBinding().to(HouseholdSusceptibility.class); } @Provides @Singleton public Config config() { // if (this.sample != 25 && this.sample != 100) // throw new RuntimeException("Sample size not calibrated! Currently only 25% is calibrated. Comment this line out to continue."); //general config Config config = ConfigUtils.createConfig(new EpisimConfigGroup()); config.global().setRandomSeed(7564655870752979346L); config.vehicles().setVehiclesFile(INPUT.resolve("de_2020-vehicles.xml").toString()); config.plans().setInputFile(inputForSample("be_2020-week_snz_entirePopulation_emptyPlans_withDistricts_%dpt_split.xml.gz", sample)); //episim config EpisimConfigGroup episimConfig = ConfigUtils.addOrGetModule(config, EpisimConfigGroup.class); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_wt_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_sa_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.SATURDAY); episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_so_%dpt_split.xml.gz", sample)) .addDays(DayOfWeek.SUNDAY); episimConfig.setActivityHandling(activityHandling); // episimConfig.setThreads(6); // TODO: check repeat from below // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_wt_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY); // // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_sa_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.SATURDAY); // // episimConfig.addInputEventsFile(inputForSample("be_2020-week_snz_episim_events_so_%dpt_split.xml.gz", sample)) // .addDays(DayOfWeek.SUNDAY); episimConfig.setCalibrationParameter(1.7E-5 * 0.8); episimConfig.setStartDate("2020-02-25"); episimConfig.setFacilitiesHandling(EpisimConfigGroup.FacilitiesHandling.snz); episimConfig.setSampleSize(this.sample / 100.); episimConfig.setHospitalFactor(0.5); episimConfig.setThreads(8); episimConfig.setDaysInfectious(Integer.MAX_VALUE); //progression model // episimConfig.setProgressionConfig(AbstractSnzScenario2020.baseProgressionConfig(Transition.config()).build()); episimConfig.setProgressionConfig(SnzProductionScenario.progressionConfig(Transition.config()).build()); //snapshot if (this.snapshot != Snapshot.no) episimConfig.setStartFromSnapshot(INPUT.resolve("snapshots/" + snapshot + ".zip").toString()); //inital infections and import // TODO: this is done differently in Cologne episimConfig.setInitialInfections(Integer.MAX_VALUE); if (this.diseaseImport != DiseaseImport.no) { SnzProductionScenario.configureDiseaseImport( episimConfig, diseaseImport, importOffset, imprtFctMult, importFactorBeforeJune, importFactorAfterJune ); } else { episimConfig.setInitialInfectionDistrict("Berlin"); episimConfig.setCalibrationParameter(2.54e-5); } //age-dependent infection<SUF> if (this.infectionModel != AgeDependentInfectionModelWithSeasonality.class) { if (this.diseaseImport == DiseaseImport.yes) { episimConfig.setCalibrationParameter(1.6E-5); // TODO: setting calibration param in multiple places may be error-prone } else { episimConfig.setCalibrationParameter(1.6E-5 * 2.54e-5 / 1.7E-5); } } //contact intensities SnzProductionScenario.configureContactIntensities(episimConfig); //restrictions and masks RestrictionInput activityParticipation; SnzBerlinScenario25pct2020.BasePolicyBuilder basePolicyBuilder = new SnzBerlinScenario25pct2020.BasePolicyBuilder(episimConfig); // TODO: should SnzBerlinScenario25pct2020 be absorbed into this class to match Cologne if (adjustRestrictions == AdjustRestrictions.yes) { activityParticipation = new CreateAdjustedRestrictionsFromCSV(); } else { activityParticipation = new CreateRestrictionsFromCSV(episimConfig); } String untilDate = "20220204"; activityParticipation.setInput(INPUT.resolve("BerlinSnzData_daily_until20220204.csv")); //location based restrictions if (locationBasedRestrictions == LocationBasedRestrictions.yes) { config.facilities().setInputFile(INPUT.resolve("be_2020-facilities_assigned_simplified_grid_WithNeighborhoodAndPLZ.xml.gz").toString()); episimConfig.setDistrictLevelRestrictions(EpisimConfigGroup.DistrictLevelRestrictions.yes); episimConfig.setDistrictLevelRestrictionsAttribute("subdistrict"); if (activityParticipation instanceof CreateRestrictionsFromCSV) { List<String> subdistricts = Arrays.asList("Spandau", "Neukoelln", "Reinickendorf", "Charlottenburg_Wilmersdorf", "Marzahn_Hellersdorf", "Mitte", "Pankow", "Friedrichshain_Kreuzberg", "Tempelhof_Schoeneberg", "Treptow_Koepenick", "Lichtenberg", "Steglitz_Zehlendorf"); Map<String, Path> subdistrictInputs = new HashMap<>(); for (String subdistrict : subdistricts) { subdistrictInputs.put(subdistrict, INPUT.resolve("perNeighborhood/" + subdistrict + "SnzData_daily_until" + untilDate + ".csv")); } ((CreateRestrictionsFromCSV) activityParticipation).setDistrictInputs(subdistrictInputs); } } basePolicyBuilder.setActivityParticipation(activityParticipation); if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.onlyEdu) { basePolicyBuilder.setActivityParticipation(null); } if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.allExceptEdu || this.restrictions == Restrictions.allExceptSchoolsAndDayCare) { basePolicyBuilder.setRestrictSchoolsAndDayCare(false); } if (this.restrictions == Restrictions.no || this.restrictions == Restrictions.allExceptEdu || this.restrictions == Restrictions.allExceptUniversities) { basePolicyBuilder.setRestrictUniversities(false); } if (this.masks == Masks.no) basePolicyBuilder.setMaskCompliance(0); basePolicyBuilder.setCiCorrections(Map.of()); FixedPolicy.ConfigBuilder builder = basePolicyBuilder.buildFixed(); //curfew TODO: when is the restriction of closing hours lifted? (also for Cologne) builder.restrict("2021-04-24", Restriction.ofClosingHours(22, 5), "leisure", "visit"); Map<LocalDate, Double> curfewCompliance = new HashMap<LocalDate, Double>(); curfewCompliance.put(LocalDate.parse("2021-04-24"), 1.0);//https://www.berlin.de/aktuelles/berlin/6522691-958092-naechtliche-ausgangsbeschraenkungen-ab-s.html curfewCompliance.put(LocalDate.parse("2021-05-19"), 0.0); //https://www.berlin.de/aktuelles/berlin/6593002-958092-ausgangsbeschraenkungen-gelten-mittwoch-.html episimConfig.setCurfewCompliance(curfewCompliance); //tracing if (this.tracing == Tracing.yes) { SnzProductionScenario.configureTracing(config, 1.0); } //christmas and easter models Map<LocalDate, DayOfWeek> inputDays = new HashMap<>(); if (this.christmasModel != ChristmasModel.no) { SnzProductionScenario.configureChristmasModel(christmasModel, inputDays, builder); } if (this.easterModel == EasterModel.yes) { SnzProductionScenario.configureEasterModel(inputDays, builder); } episimConfig.setInputDays(inputDays); //outdoorFractions if (this.weatherModel != WeatherModel.no) { SnzProductionScenario.configureWeather(episimConfig, weatherModel, INPUT.resolve("tempelhofWeatherUntil20220208.csv").toFile(), INPUT.resolve("temeplhofWeatherDataAvg2000-2020.csv").toFile(), 1.0) ; } else { episimConfig.setLeisureOutdoorFraction(Map.of( LocalDate.of(2020, 1, 1), 0.) ); } //leisure & work factor double leisureFactor = 1.6; if (this.restrictions != Restrictions.no) { builder.applyToRf("2020-10-15", "2020-12-14", (d, e) -> 1 - leisureFactor * (1 - e), "leisure"); double workVacFactor = 0.92; BiFunction<LocalDate, Double, Double> f = (d, e) -> workVacFactor * e; //WorkVac Factors are applied from last school day -> last vacation day (Saturday not Sunday, // if vacation ends on weekend, b/c new restrictions for following week are always set sundays) builder.applyToRf("2020-04-03", "2020-04-17", f, "work", "business"); //Sommerferien builder.applyToRf("2020-06-26", "2020-08-07", f, "work", "business"); //Herbstferien builder.applyToRf("2020-10-09", "2020-10-23", f, "work", "business"); //Weihnachtsferien builder.applyToRf("2020-12-18", "2021-01-01", f, "work", "business"); //Winterferien builder.applyToRf("2021-01-29", "2021-02-05", f, "work", "business"); //Osterferien builder.applyToRf("2021-03-26", "2021-04-09", f, "work", "business"); //Sommerfeirien builder.applyToRf("2021-06-25", "2021-08-06", f, "work", "business"); //Herbstferien builder.applyToRf("2021-10-08", "2021-10-22", f, "work", "business"); //Weihnachtsferien builder.applyToRf("2021-12-17", "2022-01-04", f, "work", "business"); //Winterferien builder.applyToRf("2022-01-28", "2022-02-04", f, "work", "business"); // future //Osterferien builder.restrict(LocalDate.parse("2022-04-08"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-04-23"), 1.0, "work", "business"); //Sommerferien builder.restrict(LocalDate.parse("2022-07-07"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-08-19"), 1.0, "work", "business"); //Herbstferien builder.restrict(LocalDate.parse("2022-10-21"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2022-11-05"), 1.0, "work", "business"); //Weihnachtsferien builder.restrict(LocalDate.parse("2022-12-22"), 0.92, "work", "business"); builder.restrict(LocalDate.parse("2023-01-02"), 1.0, "work", "business"); } //vaccinations if (this.vaccinations.equals(Vaccinations.yes)) { VaccinationConfigGroup vaccinationConfig = ConfigUtils.addOrGetModule(config, VaccinationConfigGroup.class); SnzProductionScenario.configureVaccines(vaccinationConfig, 4_800_000); } episimConfig.setPolicy(builder.build()); config.controler().setOutputDirectory("output-snzWeekScenario-" + sample + "%"); return config; } }
207012_5
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been inserted. */ INSERTED, /** Node has been deleted. */ DELETED, /** Node has been updated. */ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/DiffFactory.java
1,649
/** Node has been inserted. */
block_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been<SUF>*/ INSERTED, /** Node has been deleted. */ DELETED, /** Node has been updated. */ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
207012_6
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been inserted. */ INSERTED, /** Node has been deleted. */ DELETED, /** Node has been updated. */ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/DiffFactory.java
1,649
/** Node has been deleted. */
block_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been inserted. */ INSERTED, /** Node has been<SUF>*/ DELETED, /** Node has been updated. */ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
207012_7
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been inserted. */ INSERTED, /** Node has been deleted. */ DELETED, /** Node has been updated. */ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/DiffFactory.java
1,649
/** Node has been updated. */
block_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static com.google.common.base.Preconditions.checkState; import java.util.Set; import org.treetank.api.ISession; import org.treetank.exception.TTException; /** * Wrapper for public access. * * @author Johannes Lichtenberger, University of Konstanz * */ public final class DiffFactory { public static final String RESOURCENAME = "bla"; /** * Possible kinds of differences between two nodes. */ public enum EDiff { /** Nodes are the same. */ SAME, /** * Nodes are the same (including subtrees), internally used for * optimizations. */ SAMEHASH, /** Node has been inserted. */ INSERTED, /** Node has been deleted. */ DELETED, /** Node has been<SUF>*/ UPDATED } /** * Determines if an optimized diff calculation should be done, which is * faster. */ public enum EDiffOptimized { /** Normal diff. */ NO, /** Optimized diff. */ HASHED } /** Determines the kind of diff to invoke. */ private enum DiffKind { /** Full diff. */ FULL { @Override void invoke(final Builder paramBuilder) throws TTException { final FullDiff diff = new FullDiff(paramBuilder); diff.diffMovement(); } }, /** * Structural diff (doesn't recognize differences in namespace and * attribute nodes. */ STRUCTURAL { @Override void invoke(final Builder paramBuilder) throws TTException { final StructuralDiff diff = new StructuralDiff(paramBuilder); diff.diffMovement(); } }; /** * Invoke diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if anything while diffing goes wrong related to Treetank */ abstract void invoke(final Builder paramBuilder) throws TTException; } /** Builder to simplify static methods. */ public static final class Builder { /** {@link ISession} reference. */ final ISession mSession; /** Start key. */ final long mKey; /** New revision. */ final long mNewRev; /** Old revision. */ final long mOldRev; /** Depth of "root" node in new revision. */ transient int mNewDepth; /** Depth of "root" node in old revision. */ transient int mOldDepth; /** Diff kind. */ final EDiffOptimized mKind; /** {@link Set} of {@link IDiffObserver}s. */ final Set<IDiffObserver> mObservers; /** * Constructor. * * @param paramDb * {@link ISession} instance * @param paramKey * key of start node * @param paramNewRev * new revision to compare * @param paramOldRev * old revision to compare * @param paramDiffKind * kind of diff (optimized or not) * @param paramObservers * {@link Set} of observers */ public Builder(final ISession paramDb, final long paramKey, final long paramNewRev, final long paramOldRev, final EDiffOptimized paramDiffKind, final Set<IDiffObserver> paramObservers) { mSession = paramDb; mKey = paramKey; mNewRev = paramNewRev; mOldRev = paramOldRev; mKind = paramDiffKind; mObservers = paramObservers; } } /** * Private constructor. */ private DiffFactory() { // No instantiation allowed. throw new AssertionError("No instantiation allowed!"); } /** * Do a full diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeFullDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.FULL.invoke(paramBuilder); } /** * Do a structural diff. * * @param paramBuilder * {@link Builder} reference * @throws TTException */ public static synchronized void invokeStructuralDiff(final Builder paramBuilder) throws TTException { checkParams(paramBuilder); DiffKind.STRUCTURAL.invoke(paramBuilder); } /** * Check parameters for validity and assign global static variables. * * @param paramBuilder * {@link Builder} reference */ private static void checkParams(final Builder paramBuilder) { checkState(paramBuilder.mSession != null && paramBuilder.mKey >= 0 && paramBuilder.mNewRev >= 0 && paramBuilder.mOldRev >= 0 && paramBuilder.mObservers != null && paramBuilder.mKind != null, "No valid arguments specified!"); checkState( paramBuilder.mNewRev != paramBuilder.mOldRev && paramBuilder.mNewRev >= paramBuilder.mOldRev, "Revision numbers must not be the same and the new revision must have a greater number than the old revision!"); } }
207026_25
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static org.treetank.data.IConstants.ELEMENT; import static org.treetank.data.IConstants.ROOT; import static org.treetank.data.IConstants.ROOT_NODE; import static org.treetank.data.IConstants.TEXT; import javax.xml.namespace.QName; import org.treetank.access.NodeReadTrx; import org.treetank.access.NodeWriteTrx.HashKind; import org.treetank.api.INodeReadTrx; import org.treetank.data.interfaces.ITreeStructData; import org.treetank.exception.TTException; import org.treetank.exception.TTIOException; import org.treetank.service.xml.diff.DiffFactory.Builder; import org.treetank.service.xml.diff.DiffFactory.EDiff; import org.treetank.service.xml.diff.DiffFactory.EDiffOptimized; /** * Abstract diff class which implements common functionality. * * @author Johannes Lichtenberger, University of Konstanz * */ abstract class AbsDiff extends AbsDiffObservable { /** Determines if a diff should be fired or not. */ enum EFireDiff { /** Yes, it should be fired. */ TRUE, /** No, it shouldn't be fired. */ FALSE } /** Determines the current revision. */ enum ERevision { /** Old revision. */ OLD, /** New revision. */ NEW; } /** * Kind of hash method. * * @see HashKind */ transient HashKind mHashKind; /** * Kind of difference. * * @see EDiff */ private transient EDiff mDiff; /** Diff kind. */ private transient EDiffOptimized mDiffKind; /** {@link DepthCounter} instance. */ private transient DepthCounter mDepth; /** Key of "root" node in new revision. */ private transient long mRootKey; /** * Constructor. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if setting up transactions failes */ AbsDiff(final Builder paramBuilder) throws TTException { assert paramBuilder != null; mDiffKind = paramBuilder.mKind; synchronized (paramBuilder.mSession) { mNewRtx = new NodeReadTrx(paramBuilder.mSession.beginBucketRtx(paramBuilder.mNewRev)); mOldRtx = new NodeReadTrx(paramBuilder.mSession.beginBucketRtx(paramBuilder.mOldRev)); mHashKind = HashKind.Postorder; } mNewRtx.moveTo(paramBuilder.mKey); mOldRtx.moveTo(paramBuilder.mKey); mRootKey = paramBuilder.mKey; synchronized (paramBuilder.mObservers) { for (final IDiffObserver observer : paramBuilder.mObservers) { addObserver(observer); } } mDiff = EDiff.SAME; mDiffKind = paramBuilder.mKind; mDepth = new DepthCounter(paramBuilder.mNewDepth, paramBuilder.mOldDepth); // System.out.println("NEW REV: " + paramBuilder.mNewRev + " new rev: " // + // mNewRtx.getRevisionNumber()); } /** * Do the diff. * * @throws TTException * if setting up transactions failes */ void diffMovement() throws TTException { assert mHashKind != null; assert mNewRtx != null; assert mOldRtx != null; assert mDiff != null; assert mDiffKind != null; // Check first nodes. if (mNewRtx.getNode().getKind() != ROOT) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } // Iterate over new revision. while ((mOldRtx.getNode().getKind() != ROOT && mDiff == EDiff.DELETED) || moveCursor(mNewRtx, ERevision.NEW)) { if (mDiff != EDiff.INSERTED) { moveCursor(mOldRtx, ERevision.OLD); } if (mNewRtx.getNode().getKind() != ROOT || mOldRtx.getNode().getKind() != ROOT) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } } // Nodes deleted in old rev at the end of the tree. if (mOldRtx.getNode().getKind() != ROOT) { // First time it might be EDiff.INSERTED where the cursor doesn't // move. while (mDiff == EDiff.INSERTED || moveCursor(mOldRtx, ERevision.OLD)) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } } done(); } /** * Move cursor one node forward in pre order. * * @param paramRtx * the {@link IReadTransaction} to use * @param paramRevision * the {@link ERevision} constant * @return true, if cursor moved, false otherwise * @throws TTIOException */ boolean moveCursor(final INodeReadTrx paramRtx, final ERevision paramRevision) throws TTIOException { assert paramRtx != null; boolean moved = false; final ITreeStructData node = ((ITreeStructData)paramRtx.getNode()); if (node.hasFirstChild()) { if (node.getKind() != ROOT && mDiffKind == EDiffOptimized.HASHED && mHashKind != HashKind.None && (mDiff == EDiff.SAMEHASH || mDiff == EDiff.DELETED)) { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); if (!moved) { moved = moveToFollowingNode(paramRtx, paramRevision); } } else { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getFirstChildKey()); if (moved) { switch (paramRevision) { case NEW: mDepth.incrementNewDepth(); break; case OLD: mDepth.incrementOldDepth(); break; } } } } else if (node.hasRightSibling()) { if (paramRtx.getNode().getDataKey() == mRootKey) { paramRtx.moveTo(ROOT_NODE); } else { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); } } else { moved = moveToFollowingNode(paramRtx, paramRevision); } return moved; } /** * Move to next following node. * * @param paramRtx * the {@link IReadTransaction} to use * @param paramRevision * the {@link ERevision} constant * @return true, if cursor moved, false otherwise * @throws TTIOException */ private boolean moveToFollowingNode(final INodeReadTrx paramRtx, final ERevision paramRevision) throws TTIOException { boolean moved = false; while (!((ITreeStructData)paramRtx.getNode()).hasRightSibling() && ((ITreeStructData)paramRtx.getNode()).hasParent() && paramRtx.getNode().getDataKey() != mRootKey) { moved = paramRtx.moveTo(paramRtx.getNode().getParentKey()); if (moved) { switch (paramRevision) { case NEW: mDepth.decrementNewDepth(); break; case OLD: mDepth.decrementOldDepth(); break; } } } if (paramRtx.getNode().getDataKey() == mRootKey) { paramRtx.moveTo(ROOT_NODE); } moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); return moved; } /** * Diff of nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @param paramFireDiff * determines if a diff should be fired * @return kind of difference * @throws TTIOException */ EDiff diff(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth, final EFireDiff paramFireDiff) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; assert paramDepth != null; EDiff diff = EDiff.SAME; // Check for modifications. switch (paramNewRtx.getNode().getKind()) { case ROOT: case TEXT: case ELEMENT: if (!checkNodes(paramNewRtx, paramOldRtx)) { diff = diffAlgorithm(paramNewRtx, paramOldRtx, paramDepth); } break; default: // Do nothing. } if (paramFireDiff == EFireDiff.TRUE) { fireDiff(diff, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx.getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } return diff; } /** * Optimized diff, which skips unnecessary comparsions. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @param paramFireDiff * determines if a diff should be fired * @return kind of difference * @throws TTIOException */ EDiff optimizedDiff(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth, final EFireDiff paramFireDiff) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; assert paramDepth != null; EDiff diff = EDiff.SAMEHASH; // Check for modifications. switch (paramNewRtx.getNode().getKind()) { case ROOT: case TEXT: case ELEMENT: if (paramNewRtx.getNode().getDataKey() != paramOldRtx.getNode().getDataKey() || paramNewRtx.getNode().getHash() != paramOldRtx.getNode().getHash()) { // Check if nodes are the same (even if subtrees may vary). if (checkNodes(paramNewRtx, paramOldRtx)) { diff = EDiff.SAME; } else { diff = diffAlgorithm(paramNewRtx, paramOldRtx, paramDepth); } } break; default: // Do nothing. } if (paramFireDiff == EFireDiff.TRUE) { if (diff == EDiff.SAMEHASH) { fireDiff(EDiff.SAME, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx .getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } else { fireDiff(diff, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx.getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } } return diff; } /** * Main algorithm to compute diffs between two nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @return kind of diff * @throws TTIOException */ private EDiff diffAlgorithm(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth) throws TTIOException { EDiff diff = null; // Check if node has been deleted. if (paramDepth.getOldDepth() > paramDepth.getNewDepth()) { diff = EDiff.DELETED; } else if (checkUpdate(paramNewRtx, paramOldRtx)) { // Check if node has // been updated. diff = EDiff.UPDATED; } else { // See if one of the right sibling matches. EFoundEqualNode found = EFoundEqualNode.FALSE; final long key = paramOldRtx.getNode().getDataKey(); while (((ITreeStructData)paramOldRtx.getNode()).hasRightSibling() && paramOldRtx.moveTo(((ITreeStructData)paramOldRtx.getNode()).getRightSiblingKey()) && found == EFoundEqualNode.FALSE) { if (checkNodes(paramNewRtx, paramOldRtx)) { found = EFoundEqualNode.TRUE; } } paramOldRtx.moveTo(key); diff = found.kindOfDiff(); } assert diff != null; return diff; } /** * Check {@link QName} of nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @return true if nodes are "equal" according to their {@link QName}s, * otherwise false */ boolean checkName(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) { assert paramNewRtx != null; assert paramOldRtx != null; boolean found = false; if (paramNewRtx.getNode().getKind() == paramOldRtx.getNode().getKind()) { switch (paramNewRtx.getNode().getKind()) { case ELEMENT: if (paramNewRtx.getQNameOfCurrentNode().equals(paramOldRtx.getQNameOfCurrentNode())) { found = true; } break; case TEXT: if (paramNewRtx.getValueOfCurrentNode().equals(paramOldRtx.getValueOfCurrentNode())) { found = true; } break; default: } } return found; } /** * Check if nodes are equal excluding subtrees. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @return true if nodes are "equal", otherwise false */ abstract boolean checkNodes(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) throws TTIOException; /** * Check for an update of a node. * * @param paramNewRtx * first {@link IReadTransaction} instance * @param paramOldRtx * second {@link IReadTransaction} instance * @return kind of diff * @throws TTIOException */ boolean checkUpdate(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; boolean updated = false; final long newKey = paramNewRtx.getNode().getDataKey(); boolean movedNewRtx = paramNewRtx.moveTo(((ITreeStructData)paramNewRtx.getNode()).getRightSiblingKey()); final long oldKey = paramOldRtx.getNode().getDataKey(); boolean movedOldRtx = paramOldRtx.moveTo(((ITreeStructData)paramOldRtx.getNode()).getRightSiblingKey()); if (movedNewRtx && movedOldRtx && checkNodes(paramNewRtx, paramOldRtx)) { updated = true; } else if (!movedNewRtx && !movedOldRtx) { movedNewRtx = paramNewRtx.moveTo(paramNewRtx.getNode().getParentKey()); movedOldRtx = paramOldRtx.moveTo(paramOldRtx.getNode().getParentKey()); if (movedNewRtx && movedOldRtx && checkNodes(paramNewRtx, paramOldRtx)) { updated = true; } } paramNewRtx.moveTo(newKey); paramOldRtx.moveTo(oldKey); if (!updated) { updated = paramNewRtx.getNode().getDataKey() == paramOldRtx.getNode().getDataKey(); } return updated; } }
sebastiangraf/treetank
interfacemodules/xml/src/main/java/org/treetank/service/xml/diff/AbsDiff.java
4,783
// Check if node has been deleted.
line_comment
nl
/** * Copyright (c) 2011, University of Konstanz, Distributed Systems Group * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Konstanz nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.treetank.service.xml.diff; import static org.treetank.data.IConstants.ELEMENT; import static org.treetank.data.IConstants.ROOT; import static org.treetank.data.IConstants.ROOT_NODE; import static org.treetank.data.IConstants.TEXT; import javax.xml.namespace.QName; import org.treetank.access.NodeReadTrx; import org.treetank.access.NodeWriteTrx.HashKind; import org.treetank.api.INodeReadTrx; import org.treetank.data.interfaces.ITreeStructData; import org.treetank.exception.TTException; import org.treetank.exception.TTIOException; import org.treetank.service.xml.diff.DiffFactory.Builder; import org.treetank.service.xml.diff.DiffFactory.EDiff; import org.treetank.service.xml.diff.DiffFactory.EDiffOptimized; /** * Abstract diff class which implements common functionality. * * @author Johannes Lichtenberger, University of Konstanz * */ abstract class AbsDiff extends AbsDiffObservable { /** Determines if a diff should be fired or not. */ enum EFireDiff { /** Yes, it should be fired. */ TRUE, /** No, it shouldn't be fired. */ FALSE } /** Determines the current revision. */ enum ERevision { /** Old revision. */ OLD, /** New revision. */ NEW; } /** * Kind of hash method. * * @see HashKind */ transient HashKind mHashKind; /** * Kind of difference. * * @see EDiff */ private transient EDiff mDiff; /** Diff kind. */ private transient EDiffOptimized mDiffKind; /** {@link DepthCounter} instance. */ private transient DepthCounter mDepth; /** Key of "root" node in new revision. */ private transient long mRootKey; /** * Constructor. * * @param paramBuilder * {@link Builder} reference * @throws TTException * if setting up transactions failes */ AbsDiff(final Builder paramBuilder) throws TTException { assert paramBuilder != null; mDiffKind = paramBuilder.mKind; synchronized (paramBuilder.mSession) { mNewRtx = new NodeReadTrx(paramBuilder.mSession.beginBucketRtx(paramBuilder.mNewRev)); mOldRtx = new NodeReadTrx(paramBuilder.mSession.beginBucketRtx(paramBuilder.mOldRev)); mHashKind = HashKind.Postorder; } mNewRtx.moveTo(paramBuilder.mKey); mOldRtx.moveTo(paramBuilder.mKey); mRootKey = paramBuilder.mKey; synchronized (paramBuilder.mObservers) { for (final IDiffObserver observer : paramBuilder.mObservers) { addObserver(observer); } } mDiff = EDiff.SAME; mDiffKind = paramBuilder.mKind; mDepth = new DepthCounter(paramBuilder.mNewDepth, paramBuilder.mOldDepth); // System.out.println("NEW REV: " + paramBuilder.mNewRev + " new rev: " // + // mNewRtx.getRevisionNumber()); } /** * Do the diff. * * @throws TTException * if setting up transactions failes */ void diffMovement() throws TTException { assert mHashKind != null; assert mNewRtx != null; assert mOldRtx != null; assert mDiff != null; assert mDiffKind != null; // Check first nodes. if (mNewRtx.getNode().getKind() != ROOT) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } // Iterate over new revision. while ((mOldRtx.getNode().getKind() != ROOT && mDiff == EDiff.DELETED) || moveCursor(mNewRtx, ERevision.NEW)) { if (mDiff != EDiff.INSERTED) { moveCursor(mOldRtx, ERevision.OLD); } if (mNewRtx.getNode().getKind() != ROOT || mOldRtx.getNode().getKind() != ROOT) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } } // Nodes deleted in old rev at the end of the tree. if (mOldRtx.getNode().getKind() != ROOT) { // First time it might be EDiff.INSERTED where the cursor doesn't // move. while (mDiff == EDiff.INSERTED || moveCursor(mOldRtx, ERevision.OLD)) { if (mHashKind == HashKind.None || mDiffKind == EDiffOptimized.NO) { mDiff = diff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } else { mDiff = optimizedDiff(mNewRtx, mOldRtx, mDepth, EFireDiff.TRUE); } } } done(); } /** * Move cursor one node forward in pre order. * * @param paramRtx * the {@link IReadTransaction} to use * @param paramRevision * the {@link ERevision} constant * @return true, if cursor moved, false otherwise * @throws TTIOException */ boolean moveCursor(final INodeReadTrx paramRtx, final ERevision paramRevision) throws TTIOException { assert paramRtx != null; boolean moved = false; final ITreeStructData node = ((ITreeStructData)paramRtx.getNode()); if (node.hasFirstChild()) { if (node.getKind() != ROOT && mDiffKind == EDiffOptimized.HASHED && mHashKind != HashKind.None && (mDiff == EDiff.SAMEHASH || mDiff == EDiff.DELETED)) { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); if (!moved) { moved = moveToFollowingNode(paramRtx, paramRevision); } } else { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getFirstChildKey()); if (moved) { switch (paramRevision) { case NEW: mDepth.incrementNewDepth(); break; case OLD: mDepth.incrementOldDepth(); break; } } } } else if (node.hasRightSibling()) { if (paramRtx.getNode().getDataKey() == mRootKey) { paramRtx.moveTo(ROOT_NODE); } else { moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); } } else { moved = moveToFollowingNode(paramRtx, paramRevision); } return moved; } /** * Move to next following node. * * @param paramRtx * the {@link IReadTransaction} to use * @param paramRevision * the {@link ERevision} constant * @return true, if cursor moved, false otherwise * @throws TTIOException */ private boolean moveToFollowingNode(final INodeReadTrx paramRtx, final ERevision paramRevision) throws TTIOException { boolean moved = false; while (!((ITreeStructData)paramRtx.getNode()).hasRightSibling() && ((ITreeStructData)paramRtx.getNode()).hasParent() && paramRtx.getNode().getDataKey() != mRootKey) { moved = paramRtx.moveTo(paramRtx.getNode().getParentKey()); if (moved) { switch (paramRevision) { case NEW: mDepth.decrementNewDepth(); break; case OLD: mDepth.decrementOldDepth(); break; } } } if (paramRtx.getNode().getDataKey() == mRootKey) { paramRtx.moveTo(ROOT_NODE); } moved = paramRtx.moveTo(((ITreeStructData)paramRtx.getNode()).getRightSiblingKey()); return moved; } /** * Diff of nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @param paramFireDiff * determines if a diff should be fired * @return kind of difference * @throws TTIOException */ EDiff diff(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth, final EFireDiff paramFireDiff) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; assert paramDepth != null; EDiff diff = EDiff.SAME; // Check for modifications. switch (paramNewRtx.getNode().getKind()) { case ROOT: case TEXT: case ELEMENT: if (!checkNodes(paramNewRtx, paramOldRtx)) { diff = diffAlgorithm(paramNewRtx, paramOldRtx, paramDepth); } break; default: // Do nothing. } if (paramFireDiff == EFireDiff.TRUE) { fireDiff(diff, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx.getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } return diff; } /** * Optimized diff, which skips unnecessary comparsions. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @param paramFireDiff * determines if a diff should be fired * @return kind of difference * @throws TTIOException */ EDiff optimizedDiff(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth, final EFireDiff paramFireDiff) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; assert paramDepth != null; EDiff diff = EDiff.SAMEHASH; // Check for modifications. switch (paramNewRtx.getNode().getKind()) { case ROOT: case TEXT: case ELEMENT: if (paramNewRtx.getNode().getDataKey() != paramOldRtx.getNode().getDataKey() || paramNewRtx.getNode().getHash() != paramOldRtx.getNode().getHash()) { // Check if nodes are the same (even if subtrees may vary). if (checkNodes(paramNewRtx, paramOldRtx)) { diff = EDiff.SAME; } else { diff = diffAlgorithm(paramNewRtx, paramOldRtx, paramDepth); } } break; default: // Do nothing. } if (paramFireDiff == EFireDiff.TRUE) { if (diff == EDiff.SAMEHASH) { fireDiff(EDiff.SAME, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx .getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } else { fireDiff(diff, ((ITreeStructData)paramNewRtx.getNode()), ((ITreeStructData)paramOldRtx.getNode()), new DiffDepth(paramDepth.getNewDepth(), paramDepth.getOldDepth())); } } return diff; } /** * Main algorithm to compute diffs between two nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @param paramDepth * {@link DepthCounter} container for current depths of both * transaction cursors * @return kind of diff * @throws TTIOException */ private EDiff diffAlgorithm(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx, final DepthCounter paramDepth) throws TTIOException { EDiff diff = null; // Check if<SUF> if (paramDepth.getOldDepth() > paramDepth.getNewDepth()) { diff = EDiff.DELETED; } else if (checkUpdate(paramNewRtx, paramOldRtx)) { // Check if node has // been updated. diff = EDiff.UPDATED; } else { // See if one of the right sibling matches. EFoundEqualNode found = EFoundEqualNode.FALSE; final long key = paramOldRtx.getNode().getDataKey(); while (((ITreeStructData)paramOldRtx.getNode()).hasRightSibling() && paramOldRtx.moveTo(((ITreeStructData)paramOldRtx.getNode()).getRightSiblingKey()) && found == EFoundEqualNode.FALSE) { if (checkNodes(paramNewRtx, paramOldRtx)) { found = EFoundEqualNode.TRUE; } } paramOldRtx.moveTo(key); diff = found.kindOfDiff(); } assert diff != null; return diff; } /** * Check {@link QName} of nodes. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @return true if nodes are "equal" according to their {@link QName}s, * otherwise false */ boolean checkName(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) { assert paramNewRtx != null; assert paramOldRtx != null; boolean found = false; if (paramNewRtx.getNode().getKind() == paramOldRtx.getNode().getKind()) { switch (paramNewRtx.getNode().getKind()) { case ELEMENT: if (paramNewRtx.getQNameOfCurrentNode().equals(paramOldRtx.getQNameOfCurrentNode())) { found = true; } break; case TEXT: if (paramNewRtx.getValueOfCurrentNode().equals(paramOldRtx.getValueOfCurrentNode())) { found = true; } break; default: } } return found; } /** * Check if nodes are equal excluding subtrees. * * @param paramNewRtx * {@link IReadTransaction} on new revision * @param paramOldRtx * {@link IReadTransaction} on old revision * @return true if nodes are "equal", otherwise false */ abstract boolean checkNodes(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) throws TTIOException; /** * Check for an update of a node. * * @param paramNewRtx * first {@link IReadTransaction} instance * @param paramOldRtx * second {@link IReadTransaction} instance * @return kind of diff * @throws TTIOException */ boolean checkUpdate(final INodeReadTrx paramNewRtx, final INodeReadTrx paramOldRtx) throws TTIOException { assert paramNewRtx != null; assert paramOldRtx != null; boolean updated = false; final long newKey = paramNewRtx.getNode().getDataKey(); boolean movedNewRtx = paramNewRtx.moveTo(((ITreeStructData)paramNewRtx.getNode()).getRightSiblingKey()); final long oldKey = paramOldRtx.getNode().getDataKey(); boolean movedOldRtx = paramOldRtx.moveTo(((ITreeStructData)paramOldRtx.getNode()).getRightSiblingKey()); if (movedNewRtx && movedOldRtx && checkNodes(paramNewRtx, paramOldRtx)) { updated = true; } else if (!movedNewRtx && !movedOldRtx) { movedNewRtx = paramNewRtx.moveTo(paramNewRtx.getNode().getParentKey()); movedOldRtx = paramOldRtx.moveTo(paramOldRtx.getNode().getParentKey()); if (movedNewRtx && movedOldRtx && checkNodes(paramNewRtx, paramOldRtx)) { updated = true; } } paramNewRtx.moveTo(newKey); paramOldRtx.moveTo(oldKey); if (!updated) { updated = paramNewRtx.getNode().getDataKey() == paramOldRtx.getNode().getDataKey(); } return updated; } }
207029_20
/******************************************************************************* * Copyright (c) 2011 - 2012 Adrian Vielsack, Christof Urbaczek, Florian Rosenthal, Michael Hoff, Moritz Lüdecke, Philip Flohr. * * This file is part of Sudowars. * * Sudowars is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Sudowars is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Sudowars. If not, see <http://www.gnu.org/licenses/>. * * * * Diese Datei ist Teil von Sudowars. * * Sudowars ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Sudowars wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * Contributors: * initial API and implementation: * Adrian Vielsack * Christof Urbaczek * Florian Rosenthal * Michael Hoff * Moritz Lüdecke * Philip Flohr ******************************************************************************/ package org.sudowars.Model.Solver; import java.util.LinkedList; import org.sudowars.DebugHelper; import org.sudowars.Model.Sudoku.Field.Cell; import org.sudowars.Model.Sudoku.Field.DataCell; import org.sudowars.Model.Sudoku.Field.DataCellBuilder; import org.sudowars.Model.Sudoku.Field.Field; import org.sudowars.Model.Sudoku.Field.FieldBuilder; /** * This class defines the functionality to solve the next cell of a {@link Field}. It uses logical * combinations so it try to solve the next cell like a human would do. */ public class HumanSolver extends StrategyExecutor implements ConsecutiveSolver { private static final long serialVersionUID = -5626584974040288389L; /** * Initialises the used strategies and adds them to the list by there priority. */ @Override protected void createStrategies() { this.solveStrategies = new LinkedList<SolverStrategy>(); this.solveStrategies.add(new NakedSingleStrategy()); this.solveStrategies.add(new HiddenSingleStrategy()); this.solveStrategies.add(new LockedCandidateStrategy()); this.solveStrategies.add(new NakedNCliqueStrategy()); this.solveStrategies.add(new HiddenNCliqueStrategy()); } /** * Saves the solution in the cell * @param currentState the current solution state * @param solvedCell the solved cell * @param solution the solution of the cell * @return <code>true</code> if the cell was saved, <code>false</code> otherwise */ @Override protected boolean saveCell(SolverState currentState, int solvedCellIndex, int solution){ //the field does not allow setValue, the function return true, so the executor //can go on and break after this hit return true; } /** * Returns the {@link SolveStep} to solve the next {@link Cell}. * @param currentState The current field and notes of the solver * @return {@link SolveStep} to solve the next {@link Cell} */ public HumanSolveStep getCellToSolveNext(SolverState currentState) throws IllegalArgumentException { if (currentState == null) { throw new IllegalArgumentException("given SolverState cannot be null."); } //clear used strategies to save all strategies necessary to solve the next cells //from the current state this.usedStrategies.clear(); //solve the next cell StrategyExecutor.ExecuteResult result = this.executeStrategies(currentState, true); //checks if calling of the strategies found a cell HumanSolveStep humanSolveStep = null; SolveStep solveStep = currentState.getLastSolveStep(); if (result == StrategyExecutor.ExecuteResult.UNIQUESOLUTION && solveStep.hasSolvedCell()) { //check if the solver return a cell without a specific solution. That happens //if the solver needs to use backtracking to solve the cell but can not write //on the current field to save the calculated values. if (solveStep.getSolution() == 0) { //use backtracker to identify the solution of the cell BacktrackingSolver solver = new BacktrackingSolver(); //build field of data cells out of the given field FieldBuilder<DataCell> fb = new FieldBuilder<DataCell>(); Field<DataCell> solverField = fb.build(currentState.getField().getStructure(), new DataCellBuilder()); for (Cell cell : currentState.getField().getCells()) { solverField.getCell(cell.getIndex()).setInitial(cell.isInitial()); solverField.getCell(cell.getIndex()).setValue(cell.getValue()); } //iterate through the candidates and try to solve the field after setting the value of the cell for (Integer candidate : currentState.getNoteManager().getNotes(solveStep.getSolvedCell())) { //set candidate as cell value solverField.getCell(solveStep.getSolvedCell().getIndex()).setValue(candidate); //try to solve the field, as it is unique solvable the candidate is the //searched solution if the field can be solved if (solver.solve(solverField, currentState.getDependencyManager()) != null) { solveStep = new SolveStep(solveStep.getSolvedCell(), candidate, false); this.usedStrategies.clear(); break; } } } //generate HumanSolveStep humanSolveStep = new HumanSolveStep( solveStep.getSolvedCell(), solveStep.getSolution(), solveStep.hasChangedNotes(), this.getUsedStrategies()); } else { DebugHelper.log(DebugHelper.PackageName.Solver, "executeStrategies() results no unique solution or no solved cell: " + result); } return humanSolveStep; } }
sudowars/sudowars
Sudowars/src/org/sudowars/Model/Solver/HumanSolver.java
1,653
//generate HumanSolveStep
line_comment
nl
/******************************************************************************* * Copyright (c) 2011 - 2012 Adrian Vielsack, Christof Urbaczek, Florian Rosenthal, Michael Hoff, Moritz Lüdecke, Philip Flohr. * * This file is part of Sudowars. * * Sudowars is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Sudowars is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Sudowars. If not, see <http://www.gnu.org/licenses/>. * * * * Diese Datei ist Teil von Sudowars. * * Sudowars ist Freie Software: Sie können es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren * veröffentlichten Version, weiterverbreiten und/oder modifizieren. * * Sudowars wird in der Hoffnung, dass es nützlich sein wird, aber * OHNE JEDE GEWÄHELEISTUNG, bereitgestellt; sogar ohne die implizite * Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License für weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. * * Contributors: * initial API and implementation: * Adrian Vielsack * Christof Urbaczek * Florian Rosenthal * Michael Hoff * Moritz Lüdecke * Philip Flohr ******************************************************************************/ package org.sudowars.Model.Solver; import java.util.LinkedList; import org.sudowars.DebugHelper; import org.sudowars.Model.Sudoku.Field.Cell; import org.sudowars.Model.Sudoku.Field.DataCell; import org.sudowars.Model.Sudoku.Field.DataCellBuilder; import org.sudowars.Model.Sudoku.Field.Field; import org.sudowars.Model.Sudoku.Field.FieldBuilder; /** * This class defines the functionality to solve the next cell of a {@link Field}. It uses logical * combinations so it try to solve the next cell like a human would do. */ public class HumanSolver extends StrategyExecutor implements ConsecutiveSolver { private static final long serialVersionUID = -5626584974040288389L; /** * Initialises the used strategies and adds them to the list by there priority. */ @Override protected void createStrategies() { this.solveStrategies = new LinkedList<SolverStrategy>(); this.solveStrategies.add(new NakedSingleStrategy()); this.solveStrategies.add(new HiddenSingleStrategy()); this.solveStrategies.add(new LockedCandidateStrategy()); this.solveStrategies.add(new NakedNCliqueStrategy()); this.solveStrategies.add(new HiddenNCliqueStrategy()); } /** * Saves the solution in the cell * @param currentState the current solution state * @param solvedCell the solved cell * @param solution the solution of the cell * @return <code>true</code> if the cell was saved, <code>false</code> otherwise */ @Override protected boolean saveCell(SolverState currentState, int solvedCellIndex, int solution){ //the field does not allow setValue, the function return true, so the executor //can go on and break after this hit return true; } /** * Returns the {@link SolveStep} to solve the next {@link Cell}. * @param currentState The current field and notes of the solver * @return {@link SolveStep} to solve the next {@link Cell} */ public HumanSolveStep getCellToSolveNext(SolverState currentState) throws IllegalArgumentException { if (currentState == null) { throw new IllegalArgumentException("given SolverState cannot be null."); } //clear used strategies to save all strategies necessary to solve the next cells //from the current state this.usedStrategies.clear(); //solve the next cell StrategyExecutor.ExecuteResult result = this.executeStrategies(currentState, true); //checks if calling of the strategies found a cell HumanSolveStep humanSolveStep = null; SolveStep solveStep = currentState.getLastSolveStep(); if (result == StrategyExecutor.ExecuteResult.UNIQUESOLUTION && solveStep.hasSolvedCell()) { //check if the solver return a cell without a specific solution. That happens //if the solver needs to use backtracking to solve the cell but can not write //on the current field to save the calculated values. if (solveStep.getSolution() == 0) { //use backtracker to identify the solution of the cell BacktrackingSolver solver = new BacktrackingSolver(); //build field of data cells out of the given field FieldBuilder<DataCell> fb = new FieldBuilder<DataCell>(); Field<DataCell> solverField = fb.build(currentState.getField().getStructure(), new DataCellBuilder()); for (Cell cell : currentState.getField().getCells()) { solverField.getCell(cell.getIndex()).setInitial(cell.isInitial()); solverField.getCell(cell.getIndex()).setValue(cell.getValue()); } //iterate through the candidates and try to solve the field after setting the value of the cell for (Integer candidate : currentState.getNoteManager().getNotes(solveStep.getSolvedCell())) { //set candidate as cell value solverField.getCell(solveStep.getSolvedCell().getIndex()).setValue(candidate); //try to solve the field, as it is unique solvable the candidate is the //searched solution if the field can be solved if (solver.solve(solverField, currentState.getDependencyManager()) != null) { solveStep = new SolveStep(solveStep.getSolvedCell(), candidate, false); this.usedStrategies.clear(); break; } } } //generate HumanSolveStep<SUF> humanSolveStep = new HumanSolveStep( solveStep.getSolvedCell(), solveStep.getSolution(), solveStep.hasChangedNotes(), this.getUsedStrategies()); } else { DebugHelper.log(DebugHelper.PackageName.Solver, "executeStrategies() results no unique solution or no solved cell: " + result); } return humanSolveStep; } }
207151_0
/* De klasse GeheelGetal erft over van de abstracte klasse Getal en implementeert de interface Deelbaar */ public class GeheelGetal extends Getal implements Deelbaar { private Integer integer; public GeheelGetal(int i) { integer = i; } public GeheelGetal(Integer integer) { this.integer = integer; } public void increment(int step) { integer += step; } public void decrement(int step) { integer -= step; } @Override public Deelbaar getHelft() { return new GeheelGetal(integer / 2); } public String toString() { return integer.toString(); } }
gvdhaege/KdG
Java Programming 2/module 01 - Herhaling/oefeningen/deelbaar/src/GeheelGetal.java
185
/* De klasse GeheelGetal erft over van de abstracte klasse Getal en implementeert de interface Deelbaar */
block_comment
nl
/* De klasse GeheelGetal<SUF>*/ public class GeheelGetal extends Getal implements Deelbaar { private Integer integer; public GeheelGetal(int i) { integer = i; } public GeheelGetal(Integer integer) { this.integer = integer; } public void increment(int step) { integer += step; } public void decrement(int step) { integer -= step; } @Override public Deelbaar getHelft() { return new GeheelGetal(integer / 2); } public String toString() { return integer.toString(); } }
207160_0
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren voor hele getallen List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip voor niet-gehele getallen } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
Ja90n/CollatzDisplayer
src/main/java/com/jadonvb/Main.java
598
// Tooltip-tekst genereren voor hele getallen
line_comment
nl
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren<SUF> List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip voor niet-gehele getallen } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
207160_1
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren voor hele getallen List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip voor niet-gehele getallen } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
Ja90n/CollatzDisplayer
src/main/java/com/jadonvb/Main.java
598
// Geen tooltip voor niet-gehele getallen
line_comment
nl
package com.jadonvb; import org.knowm.xchart.*; import org.knowm.xchart.style.Styler; import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Voer een geheel getal in: "); int startingNumber = scanner.nextInt(); List<Integer> xData = new ArrayList<>(); List<Integer> yData = new ArrayList<>(); int n = startingNumber; int step = 0; while (n != 1) { xData.add(step); yData.add(n); if (n % 2 == 0) { n = n / 2; } else { n = 3 * n + 1; } step++; } xData.add(step); yData.add(1); // Tooltip-tekst genereren voor hele getallen List<String> toolTips = new ArrayList<>(); for (int i = 0; i < xData.size(); i++) { if (xData.get(i) % 1 == 0) { toolTips.add("Step: " + xData.get(i) + ", Number: " + yData.get(i)); } else { toolTips.add(""); // Geen tooltip<SUF> } } // Grafiek maken XYChart chart = new XYChartBuilder().width(800).height(600).title("Collatz Conjecture").xAxisTitle("Tijd").yAxisTitle("Getal").build(); // Data toevoegen XYSeries series = chart.addSeries("Collatz", xData, yData); // Tooltips instellen met aangepaste tooltip generator chart.getStyler().setToolTipType(Styler.ToolTipType.yLabels); chart.getStyler().setCursorEnabled(true); chart.getStyler().setToolTipsEnabled(true); chart.getStyler().setToolTipFont(new java.awt.Font("Dialog", java.awt.Font.PLAIN, 12)); chart.getStyler().setToolTipBackgroundColor(java.awt.Color.WHITE); chart.getStyler().setToolTipBorderColor(java.awt.Color.BLACK); // Laten zien new SwingWrapper<>(chart).displayChart(); } }
207189_0
package cui; import java.util.Scanner; public class DoWhileControle2 { public static void main(String[] args) { new DoWhileControle2().controleerInvoer(); } private void controleerInvoer() { Scanner input = new Scanner(System.in); int getal; do // INVOERCONTROLE { System.out.print("Geef een strikt positief en even geheel getal in: "); getal = input.nextInt(); } while (getal <= 0 || getal % 2 != 0); // einde do/while structuur <1> System.out.printf("Het ingevoerde getal = %d", getal); } }
kodarakK/hogent
OOSDI/H02_theorie/H02_theorie/src/cui/DoWhileControle2.java
196
// einde do/while structuur <1>
line_comment
nl
package cui; import java.util.Scanner; public class DoWhileControle2 { public static void main(String[] args) { new DoWhileControle2().controleerInvoer(); } private void controleerInvoer() { Scanner input = new Scanner(System.in); int getal; do // INVOERCONTROLE { System.out.print("Geef een strikt positief en even geheel getal in: "); getal = input.nextInt(); } while (getal <= 0 || getal % 2 != 0); // einde do/while<SUF> System.out.printf("Het ingevoerde getal = %d", getal); } }
207190_0
package cui; import java.util.Scanner; public class DoWhileControle1 { public static void main(String[] args) { new DoWhileControle1().controleerInvoer(); } private void controleerInvoer() { Scanner input = new Scanner(System.in); int getal; do // INVOERCONTROLE <1> { // <2> System.out.print("Geef een strikt positief geheel getal in: "); getal = input.nextInt(); } while (getal <= 0); // einde do/while structuur <3> System.out.printf("Het ingevoerde getal = %d", getal); } }
kodarakK/hogent
OOSDI/H02_theorie/H02_theorie/src/cui/DoWhileControle1.java
191
// einde do/while structuur <3>
line_comment
nl
package cui; import java.util.Scanner; public class DoWhileControle1 { public static void main(String[] args) { new DoWhileControle1().controleerInvoer(); } private void controleerInvoer() { Scanner input = new Scanner(System.in); int getal; do // INVOERCONTROLE <1> { // <2> System.out.print("Geef een strikt positief geheel getal in: "); getal = input.nextInt(); } while (getal <= 0); // einde do/while<SUF> System.out.printf("Het ingevoerde getal = %d", getal); } }
207207_4
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.04 at 09:04:24 PM CET // package nl.geonovum.stri._2012._2; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DossierStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="DossierStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="in voorbereiding"/> * &lt;enumeration value="vastgesteld"/> * &lt;enumeration value="geheel in werking"/> * &lt;enumeration value="deels in werking"/> * &lt;enumeration value="niet in werking"/> * &lt;enumeration value="geheel onherroepelijk in werking"/> * &lt;enumeration value="deels onherroepelijk in werking"/> * &lt;enumeration value="vervallen"/> * &lt;enumeration value="geconsolideerd"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "DossierStatus") @XmlEnum public enum DossierStatus { @XmlEnumValue("in voorbereiding") IN_VOORBEREIDING("in voorbereiding"), @XmlEnumValue("vastgesteld") VASTGESTELD("vastgesteld"), @XmlEnumValue("geheel in werking") GEHEEL_IN_WERKING("geheel in werking"), @XmlEnumValue("deels in werking") DEELS_IN_WERKING("deels in werking"), @XmlEnumValue("niet in werking") NIET_IN_WERKING("niet in werking"), @XmlEnumValue("geheel onherroepelijk in werking") GEHEEL_ONHERROEPELIJK_IN_WERKING("geheel onherroepelijk in werking"), @XmlEnumValue("deels onherroepelijk in werking") DEELS_ONHERROEPELIJK_IN_WERKING("deels onherroepelijk in werking"), @XmlEnumValue("vervallen") VERVALLEN("vervallen"), @XmlEnumValue("geconsolideerd") GECONSOLIDEERD("geconsolideerd"); private final String value; DossierStatus(String v) { value = v; } public String value() { return value; } public static DossierStatus fromValue(String v) { for (DossierStatus c: DossierStatus.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
bellmit/imro-harvester
stri-classes/src/main/java/nl/geonovum/stri/_2012/_2/DossierStatus.java
796
/** * <p>Java class for DossierStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="DossierStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="in voorbereiding"/> * &lt;enumeration value="vastgesteld"/> * &lt;enumeration value="geheel in werking"/> * &lt;enumeration value="deels in werking"/> * &lt;enumeration value="niet in werking"/> * &lt;enumeration value="geheel onherroepelijk in werking"/> * &lt;enumeration value="deels onherroepelijk in werking"/> * &lt;enumeration value="vervallen"/> * &lt;enumeration value="geconsolideerd"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */
block_comment
nl
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.04 at 09:04:24 PM CET // package nl.geonovum.stri._2012._2; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for<SUF>*/ @XmlType(name = "DossierStatus") @XmlEnum public enum DossierStatus { @XmlEnumValue("in voorbereiding") IN_VOORBEREIDING("in voorbereiding"), @XmlEnumValue("vastgesteld") VASTGESTELD("vastgesteld"), @XmlEnumValue("geheel in werking") GEHEEL_IN_WERKING("geheel in werking"), @XmlEnumValue("deels in werking") DEELS_IN_WERKING("deels in werking"), @XmlEnumValue("niet in werking") NIET_IN_WERKING("niet in werking"), @XmlEnumValue("geheel onherroepelijk in werking") GEHEEL_ONHERROEPELIJK_IN_WERKING("geheel onherroepelijk in werking"), @XmlEnumValue("deels onherroepelijk in werking") DEELS_ONHERROEPELIJK_IN_WERKING("deels onherroepelijk in werking"), @XmlEnumValue("vervallen") VERVALLEN("vervallen"), @XmlEnumValue("geconsolideerd") GECONSOLIDEERD("geconsolideerd"); private final String value; DossierStatus(String v) { value = v; } public String value() { return value; } public static DossierStatus fromValue(String v) { for (DossierStatus c: DossierStatus.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
207208_4
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.04 at 09:03:51 PM CET // package nl.geonovum.stri._2012._1; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DossierStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="DossierStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="in voorbereiding"/> * &lt;enumeration value="vastgesteld"/> * &lt;enumeration value="geheel in werking"/> * &lt;enumeration value="deels in werking"/> * &lt;enumeration value="niet in werking"/> * &lt;enumeration value="geheel onherroepelijk in werking"/> * &lt;enumeration value="deels onherroepelijk in werking"/> * &lt;enumeration value="vervallen"/> * &lt;enumeration value="geconsolideerd"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "DossierStatus") @XmlEnum public enum DossierStatus { @XmlEnumValue("in voorbereiding") IN_VOORBEREIDING("in voorbereiding"), @XmlEnumValue("vastgesteld") VASTGESTELD("vastgesteld"), @XmlEnumValue("geheel in werking") GEHEEL_IN_WERKING("geheel in werking"), @XmlEnumValue("deels in werking") DEELS_IN_WERKING("deels in werking"), @XmlEnumValue("niet in werking") NIET_IN_WERKING("niet in werking"), @XmlEnumValue("geheel onherroepelijk in werking") GEHEEL_ONHERROEPELIJK_IN_WERKING("geheel onherroepelijk in werking"), @XmlEnumValue("deels onherroepelijk in werking") DEELS_ONHERROEPELIJK_IN_WERKING("deels onherroepelijk in werking"), @XmlEnumValue("vervallen") VERVALLEN("vervallen"), @XmlEnumValue("geconsolideerd") GECONSOLIDEERD("geconsolideerd"); private final String value; DossierStatus(String v) { value = v; } public String value() { return value; } public static DossierStatus fromValue(String v) { for (DossierStatus c: DossierStatus.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
bellmit/imro-harvester
stri-classes/src/main/java/nl/geonovum/stri/_2012/_1/DossierStatus.java
796
/** * <p>Java class for DossierStatus. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="DossierStatus"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="in voorbereiding"/> * &lt;enumeration value="vastgesteld"/> * &lt;enumeration value="geheel in werking"/> * &lt;enumeration value="deels in werking"/> * &lt;enumeration value="niet in werking"/> * &lt;enumeration value="geheel onherroepelijk in werking"/> * &lt;enumeration value="deels onherroepelijk in werking"/> * &lt;enumeration value="vervallen"/> * &lt;enumeration value="geconsolideerd"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */
block_comment
nl
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2016.03.04 at 09:03:51 PM CET // package nl.geonovum.stri._2012._1; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for<SUF>*/ @XmlType(name = "DossierStatus") @XmlEnum public enum DossierStatus { @XmlEnumValue("in voorbereiding") IN_VOORBEREIDING("in voorbereiding"), @XmlEnumValue("vastgesteld") VASTGESTELD("vastgesteld"), @XmlEnumValue("geheel in werking") GEHEEL_IN_WERKING("geheel in werking"), @XmlEnumValue("deels in werking") DEELS_IN_WERKING("deels in werking"), @XmlEnumValue("niet in werking") NIET_IN_WERKING("niet in werking"), @XmlEnumValue("geheel onherroepelijk in werking") GEHEEL_ONHERROEPELIJK_IN_WERKING("geheel onherroepelijk in werking"), @XmlEnumValue("deels onherroepelijk in werking") DEELS_ONHERROEPELIJK_IN_WERKING("deels onherroepelijk in werking"), @XmlEnumValue("vervallen") VERVALLEN("vervallen"), @XmlEnumValue("geconsolideerd") GECONSOLIDEERD("geconsolideerd"); private final String value; DossierStatus(String v) { value = v; } public String value() { return value; } public static DossierStatus fromValue(String v) { for (DossierStatus c: DossierStatus.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
207217_5
import com.google.common.base.Preconditions; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import org.apache.commons.lang.ArrayUtils; import sun.misc.BASE64Encoder; import sun.security.pkcs11.wrapper.CK_PKCS5_PBKD2_PARAMS; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.security.*; import java.security.cert.Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.ResourceBundle; /** * Created by David on 24-6-2016. */ public class UIController implements Initializable { @FXML private PasswordField password; @FXML private TextArea message; @FXML private Button btnEncrypt; @FXML private Button btnDecrypt; private File file; public void initialize(URL location, ResourceBundle resources) { btnEncrypt.setOnMouseClicked(event -> { try { encrypt(event); } catch (Exception e) { e.printStackTrace(); } }); btnDecrypt.setOnMouseClicked(event -> { try { decrypt(event); } catch (Exception e) { e.printStackTrace(); } }); } private Cipher initCipher(byte[] salt) { // wrap key data in Key/IV specs to pass to cipher SecretKeySpec key = new SecretKeySpec(password.getText().getBytes(), "DES"); IvParameterSpec ivSpec = new IvParameterSpec(salt); // create the cipher with the algorithm you choose // see javadoc for Cipher class for more info, e.g. try { return Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } return null; } private byte[] generateSalt() { SecureRandom secureRandom = new SecureRandom(); byte[] salt = new byte[8]; secureRandom.nextBytes(salt); return salt; } private SecretKey getSecretKey(String password, byte[] salt) throws NoSuchAlgorithmException { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); SecretKey tmp = null; try { tmp = factory.generateSecret(spec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return new SecretKeySpec(tmp.getEncoded(), "AES"); } private void encrypt(MouseEvent event) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException { Preconditions.checkArgument(!password.getText().isEmpty()); Preconditions.checkArgument(!message.getText().isEmpty()); // De mess staat voor semester 4 in zijn geheel String mess = message.getText(); byte[] salt = generateSalt(); Cipher cipher = initCipher(salt); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password.getText(), salt)); byte[] encrypted = new byte[cipher.getOutputSize(mess.length())]; int enc_len = cipher.update(mess.getBytes(), 0, mess.length(), encrypted, 0); enc_len += cipher.doFinal(encrypted, enc_len); writeEncrypted(salt, encrypted, enc_len, cipher.getIV()); } private void writeEncrypted(byte[] salt, byte[] encrypted, int enc_len, byte[] iv) { File f = new File("text.enc"); try { FileOutputStream fos = new FileOutputStream(f); fos.write(salt.length); fos.write(enc_len); fos.write(iv.length); fos.write(salt); fos.write(iv); fos.write(encrypted); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void decrypt(MouseEvent event) throws ShortBufferException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, InvalidKeyException { File f = new File("text.enc"); FileInputStream fis = new FileInputStream(f); int saltLength = Math.abs(fis.read()); int enc_len = Math.abs(fis.read()); int iv_len = Math.abs(fis.read()); byte[] salt = new byte[saltLength]; byte[] iv = new byte[iv_len]; byte[] mess = new byte[(int) (f.length() - 1 - saltLength - iv_len)]; fis.read(salt, 0, saltLength); fis.read(iv, 0, iv_len); fis.read(mess); Cipher cipher = initCipher(salt); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password.getText(), salt), new IvParameterSpec(iv)); byte[] decrypted = new byte[cipher.getOutputSize(enc_len)]; cipher.update(mess, 0, enc_len, decrypted, 0); message.setText(new String(decrypted)); } }
Requinard/se42-encryption-2
src/main/java/UIController.java
1,384
// De mess staat voor semester 4 in zijn geheel
line_comment
nl
import com.google.common.base.Preconditions; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.PasswordField; import javafx.scene.control.TextArea; import javafx.scene.input.MouseEvent; import org.apache.commons.lang.ArrayUtils; import sun.misc.BASE64Encoder; import sun.security.pkcs11.wrapper.CK_PKCS5_PBKD2_PARAMS; import javax.crypto.*; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import java.io.*; import java.net.URL; import java.nio.charset.Charset; import java.security.*; import java.security.cert.Certificate; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.util.ResourceBundle; /** * Created by David on 24-6-2016. */ public class UIController implements Initializable { @FXML private PasswordField password; @FXML private TextArea message; @FXML private Button btnEncrypt; @FXML private Button btnDecrypt; private File file; public void initialize(URL location, ResourceBundle resources) { btnEncrypt.setOnMouseClicked(event -> { try { encrypt(event); } catch (Exception e) { e.printStackTrace(); } }); btnDecrypt.setOnMouseClicked(event -> { try { decrypt(event); } catch (Exception e) { e.printStackTrace(); } }); } private Cipher initCipher(byte[] salt) { // wrap key data in Key/IV specs to pass to cipher SecretKeySpec key = new SecretKeySpec(password.getText().getBytes(), "DES"); IvParameterSpec ivSpec = new IvParameterSpec(salt); // create the cipher with the algorithm you choose // see javadoc for Cipher class for more info, e.g. try { return Cipher.getInstance("AES/CBC/PKCS5Padding"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } return null; } private byte[] generateSalt() { SecureRandom secureRandom = new SecureRandom(); byte[] salt = new byte[8]; secureRandom.nextBytes(salt); return salt; } private SecretKey getSecretKey(String password, byte[] salt) throws NoSuchAlgorithmException { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); SecretKey tmp = null; try { tmp = factory.generateSecret(spec); } catch (InvalidKeySpecException e) { e.printStackTrace(); } return new SecretKeySpec(tmp.getEncoded(), "AES"); } private void encrypt(MouseEvent event) throws ShortBufferException, IllegalBlockSizeException, BadPaddingException, NoSuchAlgorithmException, InvalidKeyException { Preconditions.checkArgument(!password.getText().isEmpty()); Preconditions.checkArgument(!message.getText().isEmpty()); // De mess<SUF> String mess = message.getText(); byte[] salt = generateSalt(); Cipher cipher = initCipher(salt); cipher.init(Cipher.ENCRYPT_MODE, getSecretKey(password.getText(), salt)); byte[] encrypted = new byte[cipher.getOutputSize(mess.length())]; int enc_len = cipher.update(mess.getBytes(), 0, mess.length(), encrypted, 0); enc_len += cipher.doFinal(encrypted, enc_len); writeEncrypted(salt, encrypted, enc_len, cipher.getIV()); } private void writeEncrypted(byte[] salt, byte[] encrypted, int enc_len, byte[] iv) { File f = new File("text.enc"); try { FileOutputStream fos = new FileOutputStream(f); fos.write(salt.length); fos.write(enc_len); fos.write(iv.length); fos.write(salt); fos.write(iv); fos.write(encrypted); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private void decrypt(MouseEvent event) throws ShortBufferException, NoSuchAlgorithmException, InvalidAlgorithmParameterException, IOException, InvalidKeyException { File f = new File("text.enc"); FileInputStream fis = new FileInputStream(f); int saltLength = Math.abs(fis.read()); int enc_len = Math.abs(fis.read()); int iv_len = Math.abs(fis.read()); byte[] salt = new byte[saltLength]; byte[] iv = new byte[iv_len]; byte[] mess = new byte[(int) (f.length() - 1 - saltLength - iv_len)]; fis.read(salt, 0, saltLength); fis.read(iv, 0, iv_len); fis.read(mess); Cipher cipher = initCipher(salt); cipher.init(Cipher.DECRYPT_MODE, getSecretKey(password.getText(), salt), new IvParameterSpec(iv)); byte[] decrypted = new byte[cipher.getOutputSize(enc_len)]; cipher.update(mess, 0, enc_len, decrypted, 0); message.setText(new String(decrypted)); } }
207218_0
package nl.youngcapital.movies.model; /* zonder public of iets anders is package private oftewel indezelfde folder */ public class Movie { public static String customerName = "Netflix"; // Encapsulation private String name; private int length; private int stars; public static int movieCounter = 0; /* Java heeft 8 primitives: the element of the periodic system gehele getallen - byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8) - short => 16 bits < -32768 - 32767) - int => 32 bits geheel getal (-2miljard tot +2 miljard) - long => 64 bits geheel getal < - letters: - char 'a', 'b', 'z', 'q' - waar of niet waar ... boolean - true false - floating points -- float: 32 bits floating point number.... 1.2f, 2.3f -- double: 64 bits floating point number 1.2, 2.3 1000.3343434; // let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen. */ // new and constructor is a marriage public Movie(String name) { this.name = name; movieCounter++; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } // this is a 'method' and more specific: a 'setter' public void setLength(int length) { this.length = length; } // this is a 'method' and more specific: a 'getter' public int getStars() { return stars; } public void setStars(int stars) { if (stars > 0 && stars <= 5) { this.stars = stars; } } }
raymieloman/movies-oo
src/main/java/nl/youngcapital/movies/model/Movie.java
521
/* zonder public of iets anders is package private oftewel indezelfde folder */
block_comment
nl
package nl.youngcapital.movies.model; /* zonder public of<SUF>*/ public class Movie { public static String customerName = "Netflix"; // Encapsulation private String name; private int length; private int stars; public static int movieCounter = 0; /* Java heeft 8 primitives: the element of the periodic system gehele getallen - byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8) - short => 16 bits < -32768 - 32767) - int => 32 bits geheel getal (-2miljard tot +2 miljard) - long => 64 bits geheel getal < - letters: - char 'a', 'b', 'z', 'q' - waar of niet waar ... boolean - true false - floating points -- float: 32 bits floating point number.... 1.2f, 2.3f -- double: 64 bits floating point number 1.2, 2.3 1000.3343434; // let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen. */ // new and constructor is a marriage public Movie(String name) { this.name = name; movieCounter++; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } // this is a 'method' and more specific: a 'setter' public void setLength(int length) { this.length = length; } // this is a 'method' and more specific: a 'getter' public int getStars() { return stars; } public void setStars(int stars) { if (stars > 0 && stars <= 5) { this.stars = stars; } } }
207218_1
package nl.youngcapital.movies.model; /* zonder public of iets anders is package private oftewel indezelfde folder */ public class Movie { public static String customerName = "Netflix"; // Encapsulation private String name; private int length; private int stars; public static int movieCounter = 0; /* Java heeft 8 primitives: the element of the periodic system gehele getallen - byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8) - short => 16 bits < -32768 - 32767) - int => 32 bits geheel getal (-2miljard tot +2 miljard) - long => 64 bits geheel getal < - letters: - char 'a', 'b', 'z', 'q' - waar of niet waar ... boolean - true false - floating points -- float: 32 bits floating point number.... 1.2f, 2.3f -- double: 64 bits floating point number 1.2, 2.3 1000.3343434; // let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen. */ // new and constructor is a marriage public Movie(String name) { this.name = name; movieCounter++; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } // this is a 'method' and more specific: a 'setter' public void setLength(int length) { this.length = length; } // this is a 'method' and more specific: a 'getter' public int getStars() { return stars; } public void setStars(int stars) { if (stars > 0 && stars <= 5) { this.stars = stars; } } }
raymieloman/movies-oo
src/main/java/nl/youngcapital/movies/model/Movie.java
521
/* Java heeft 8 primitives: the element of the periodic system gehele getallen - byte => 8 bits => -128 tot(via de 0) +127 (256 mogelijkheden = 2^8) - short => 16 bits < -32768 - 32767) - int => 32 bits geheel getal (-2miljard tot +2 miljard) - long => 64 bits geheel getal < - letters: - char 'a', 'b', 'z', 'q' - waar of niet waar ... boolean - true false - floating points -- float: 32 bits floating point number.... 1.2f, 2.3f -- double: 64 bits floating point number 1.2, 2.3 1000.3343434; // let op met floats in Java want ze zijn onderhevig aan (foutieve) afrondingen. */
block_comment
nl
package nl.youngcapital.movies.model; /* zonder public of iets anders is package private oftewel indezelfde folder */ public class Movie { public static String customerName = "Netflix"; // Encapsulation private String name; private int length; private int stars; public static int movieCounter = 0; /* Java heeft 8<SUF>*/ // new and constructor is a marriage public Movie(String name) { this.name = name; movieCounter++; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getLength() { return length; } // this is a 'method' and more specific: a 'setter' public void setLength(int length) { this.length = length; } // this is a 'method' and more specific: a 'getter' public int getStars() { return stars; } public void setStars(int stars) { if (stars > 0 && stars <= 5) { this.stars = stars; } } }
207222_0
package be.intecbrussel.Les3; public class MathExample1 { public static void main(String[] args) { //Methode abs() //Heeft de absolute van een waarde terug. /ybiraet minus int result = Math.abs(-10); System.out.println(result); // 10 //Methode round() //De round() functie zal het komma getal double of //float afronden naar het dichtstbijzijnde geheel getal. // okruglaet chifry s zapuatoi float result2 =Math.round(4.6F); System.out.println(result2); //5.0 } }
9elmaz9/Java_Fundamentals
Chapter02_OOP/src/be/intecbrussel/Les3/MathExample1.java
167
//Heeft de absolute van een waarde terug. /ybiraet minus
line_comment
nl
package be.intecbrussel.Les3; public class MathExample1 { public static void main(String[] args) { //Methode abs() //Heeft de<SUF> int result = Math.abs(-10); System.out.println(result); // 10 //Methode round() //De round() functie zal het komma getal double of //float afronden naar het dichtstbijzijnde geheel getal. // okruglaet chifry s zapuatoi float result2 =Math.round(4.6F); System.out.println(result2); //5.0 } }