repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
or-tools
or-tools-master/ortools/model_builder/samples/SimpleLpProgramMb.java
// Copyright 2010-2021 Google LLC // 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. // Minimal example to call the GLOP solver. // [START program] package com.google.ortools.modelbuilder.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.modelbuilder.LinearExpr; import com.google.ortools.modelbuilder.ModelBuilder; import com.google.ortools.modelbuilder.ModelSolver; import com.google.ortools.modelbuilder.SolveStatus; import com.google.ortools.modelbuilder.Variable; // [END import] /** Minimal Linear Programming example to showcase calling the solver. */ public final class SimpleLpProgramMb { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START model] // Create the linear model. ModelBuilder model = new ModelBuilder(); // [END model] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; // Create the variables x and y. Variable x = model.newNumVar(0.0, infinity, "x"); Variable y = model.newNumVar(0.0, infinity, "y"); System.out.println("Number of variables = " + model.numVariables()); // [END variables] // [START constraints] // x + 7 * y <= 17.5. model.addLessOrEqual(LinearExpr.newBuilder().add(x).addTerm(y, 7), 17.5).withName("c0"); // x <= 3.5. model.addLessOrEqual(x, 3.5).withName("c1"); System.out.println("Number of constraints = " + model.numConstraints()); // [END constraints] // [START objective] // Maximize x + 10 * y. model.maximize(LinearExpr.newBuilder().add(x).addTerm(y, 10.0)); // [END objective] // [START solve] // Solve with the GLOP LP solver. ModelSolver solver = new ModelSolver("glop"); final SolveStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == SolveStatus.OPTIMAL) { System.out.println("Solution:"); System.out.println("Objective value = " + solver.getObjectiveValue()); System.out.println("x = " + solver.getValue(x)); System.out.println("y = " + solver.getValue(y)); } else { System.err.println("The problem does not have an optimal solution!"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.getWallTime() + " seconds"); // [END advanced] } private SimpleLpProgramMb() {} } // [END program]
2,958
33.406977
92
java
or-tools
or-tools-master/ortools/model_builder/samples/SimpleMipProgramMb.java
// Copyright 2010-2021 Google LLC // 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. // Minimal example to call the MIP solver. // [START program] package com.google.ortools.modelbuilder.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.modelbuilder.LinearExpr; import com.google.ortools.modelbuilder.ModelBuilder; import com.google.ortools.modelbuilder.ModelSolver; import com.google.ortools.modelbuilder.SolveStatus; import com.google.ortools.modelbuilder.Variable; // [END import] /** Minimal Mixed Integer Programming example to showcase calling the solver. */ public final class SimpleMipProgramMb { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START model] // Create the linear model. ModelBuilder model = new ModelBuilder(); // [END model] // [START variables] double infinity = java.lang.Double.POSITIVE_INFINITY; // x and y are integer non-negative variables. Variable x = model.newIntVar(0.0, infinity, "x"); Variable y = model.newIntVar(0.0, infinity, "y"); System.out.println("Number of variables = " + model.numVariables()); // [END variables] // [START constraints] // x + 7 * y <= 17.5. model.addLessOrEqual(LinearExpr.newBuilder().add(x).addTerm(y, 7), 17.5).withName("c0"); // x <= 3.5. model.addLessOrEqual(x, 3.5).withName("c1"); System.out.println("Number of constraints = " + model.numConstraints()); // [END constraints] // [START objective] // Maximize x + 10 * y. model.maximize(LinearExpr.newBuilder().add(x).addTerm(y, 10.0)); // [END objective] // [START solve] // Solve with the SCIP MIP solver. ModelSolver solver = new ModelSolver("scip"); final SolveStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == SolveStatus.OPTIMAL) { System.out.println("Solution:"); System.out.println("Objective value = " + solver.getObjectiveValue()); System.out.println("x = " + solver.getValue(x)); System.out.println("y = " + solver.getValue(y)); } else { System.err.println("The problem does not have an optimal solution!"); } // [END print_solution] // [START advanced] System.out.println("\nAdvanced usage:"); System.out.println("Problem solved in " + solver.getWallTime() + " seconds"); // [END advanced] } private SimpleMipProgramMb() {} } // [END program]
2,980
34.070588
92
java
or-tools
or-tools-master/ortools/sat/samples/AssignmentGroupsSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] // CP-SAT example that solves an assignment problem. package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Assignment problem. */ public class AssignmentGroupsSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] int[][] costs = { {90, 76, 75, 70, 50, 74}, {35, 85, 55, 65, 48, 101}, {125, 95, 90, 105, 59, 120}, {45, 110, 95, 115, 104, 83}, {60, 105, 80, 75, 59, 62}, {45, 65, 110, 95, 47, 31}, {38, 51, 107, 41, 69, 99}, {47, 85, 57, 71, 92, 77}, {39, 63, 97, 49, 118, 56}, {47, 101, 71, 60, 88, 109}, {17, 39, 103, 64, 61, 92}, {101, 45, 83, 59, 92, 27}, }; final int numWorkers = costs.length; final int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); // [END data] // Allowed groups of workers: // [START allowed_groups] int[][] group1 = { {0, 0, 1, 1}, // Workers 2, 3 {0, 1, 0, 1}, // Workers 1, 3 {0, 1, 1, 0}, // Workers 1, 2 {1, 1, 0, 0}, // Workers 0, 1 {1, 0, 1, 0}, // Workers 0, 2 }; int[][] group2 = { {0, 0, 1, 1}, // Workers 6, 7 {0, 1, 0, 1}, // Workers 5, 7 {0, 1, 1, 0}, // Workers 5, 6 {1, 1, 0, 0}, // Workers 4, 5 {1, 0, 0, 1}, // Workers 4, 7 }; int[][] group3 = { {0, 0, 1, 1}, // Workers 10, 11 {0, 1, 0, 1}, // Workers 9, 11 {0, 1, 1, 0}, // Workers 9, 10 {1, 0, 1, 0}, // Workers 8, 10 {1, 0, 0, 1}, // Workers 8, 11 }; // [END allowed_groups] // Model // [START model] CpModel model = new CpModel(); // [END model] // Variables // [START variables] Literal[][] x = new Literal[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = model.newBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int worker : allWorkers) { List<Literal> tasks = new ArrayList<>(); for (int task : allTasks) { tasks.add(x[worker][task]); } model.addAtMostOne(tasks); } // Each task is assigned to exactly one worker. for (int task : allTasks) { List<Literal> workers = new ArrayList<>(); for (int worker : allWorkers) { workers.add(x[worker][task]); } model.addExactlyOne(workers); } // [END constraints] // [START assignments] // Create variables for each worker, indicating whether they work on some task. IntVar[] work = new IntVar[numWorkers]; for (int worker : allWorkers) { work[worker] = model.newBoolVar("work[" + worker + "]"); } for (int worker : allWorkers) { LinearExprBuilder expr = LinearExpr.newBuilder(); for (int task : allTasks) { expr.add(x[worker][task]); } model.addEquality(work[worker], expr); } // Define the allowed groups of worders model.addAllowedAssignments(new IntVar[] {work[0], work[1], work[2], work[3]}) .addTuples(group1); model.addAllowedAssignments(new IntVar[] {work[4], work[5], work[6], work[7]}) .addTuples(group2); model.addAllowedAssignments(new IntVar[] {work[8], work[9], work[10], work[11]}) .addTuples(group3); // [END assignments] // Objective // [START objective] LinearExprBuilder obj = LinearExpr.newBuilder(); for (int worker : allWorkers) { for (int task : allTasks) { obj.addTerm(x[worker][task], costs[worker][task]); } } model.minimize(obj); // [END objective] // Solve // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.println("Total cost: " + solver.objectiveValue() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { if (solver.booleanValue(x[worker][task])) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentGroupsSat() {} }
5,739
30.36612
84
java
or-tools
or-tools-master/ortools/sat/samples/AssignmentSat.java
// Copyright 2010-2021 Google LLC // 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. // CP-SAT example that solves an assignment problem. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Assignment problem. */ public class AssignmentSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data_model] int[][] costs = { {90, 80, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 95}, {45, 110, 95, 115}, {50, 100, 90, 100}, }; final int numWorkers = costs.length; final int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); // [END data_model] // Model // [START model] CpModel model = new CpModel(); // [END model] // Variables // [START variables] Literal[][] x = new Literal[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = model.newBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int worker : allWorkers) { List<Literal> tasks = new ArrayList<>(); for (int task : allTasks) { tasks.add(x[worker][task]); } model.addAtMostOne(tasks); } // Each task is assigned to exactly one worker. for (int task : allTasks) { List<Literal> workers = new ArrayList<>(); for (int worker : allWorkers) { workers.add(x[worker][task]); } model.addExactlyOne(workers); } // [END constraints] // Objective // [START objective] LinearExprBuilder obj = LinearExpr.newBuilder(); for (int worker : allWorkers) { for (int task : allTasks) { obj.addTerm(x[worker][task], costs[worker][task]); } } model.minimize(obj); // [END objective] // Solve // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.println("Total cost: " + solver.objectiveValue() + "\n"); for (int i = 0; i < numWorkers; ++i) { for (int j = 0; j < numTasks; ++j) { if (solver.booleanValue(x[i][j])) { System.out.println( "Worker " + i + " assigned to task " + j + ". Cost: " + costs[i][j]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentSat() {} }
3,758
29.314516
86
java
or-tools
or-tools-master/ortools/sat/samples/AssignmentTaskSizesSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] // CP-SAT example that solves an assignment problem. package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Assignment problem. */ public class AssignmentTaskSizesSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] int[][] costs = { {90, 76, 75, 70, 50, 74, 12, 68}, {35, 85, 55, 65, 48, 101, 70, 83}, {125, 95, 90, 105, 59, 120, 36, 73}, {45, 110, 95, 115, 104, 83, 37, 71}, {60, 105, 80, 75, 59, 62, 93, 88}, {45, 65, 110, 95, 47, 31, 81, 34}, {38, 51, 107, 41, 69, 99, 115, 48}, {47, 85, 57, 71, 92, 77, 109, 36}, {39, 63, 97, 49, 118, 56, 92, 61}, {47, 101, 71, 60, 88, 109, 52, 90}, }; final int numWorkers = costs.length; final int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); final int[] taskSizes = {10, 7, 3, 12, 15, 4, 11, 5}; // Maximum total of task sizes for any worker final int totalSizeMax = 15; // [END data] // Model // [START model] CpModel model = new CpModel(); // [END model] // Variables // [START variables] Literal[][] x = new Literal[numWorkers][numTasks]; for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = model.newBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker has a maximum capacity. for (int worker : allWorkers) { LinearExprBuilder expr = LinearExpr.newBuilder(); for (int task : allTasks) { expr.addTerm(x[worker][task], taskSizes[task]); } model.addLessOrEqual(expr, totalSizeMax); } // Each task is assigned to exactly one worker. for (int task : allTasks) { List<Literal> workers = new ArrayList<>(); for (int worker : allWorkers) { workers.add(x[worker][task]); } model.addExactlyOne(workers); } // [END constraints] // Objective // [START objective] LinearExprBuilder obj = LinearExpr.newBuilder(); for (int worker : allWorkers) { for (int task : allTasks) { obj.addTerm(x[worker][task], costs[worker][task]); } } model.minimize(obj); // [END objective] // Solve // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.println("Total cost: " + solver.objectiveValue() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { if (solver.booleanValue(x[worker][task])) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentTaskSizesSat() {} }
4,248
30.947368
80
java
or-tools
or-tools-master/ortools/sat/samples/AssignmentTeamsSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] // CP-SAT example that solves an assignment problem. package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Assignment problem. */ public class AssignmentTeamsSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Data // [START data] int[][] costs = { {90, 76, 75, 70}, {35, 85, 55, 65}, {125, 95, 90, 105}, {45, 110, 95, 115}, {60, 105, 80, 75}, {45, 65, 110, 95}, }; final int numWorkers = costs.length; final int numTasks = costs[0].length; final int[] allWorkers = IntStream.range(0, numWorkers).toArray(); final int[] allTasks = IntStream.range(0, numTasks).toArray(); final int[] team1 = {0, 2, 4}; final int[] team2 = {1, 3, 5}; // Maximum total of tasks for any team final int teamMax = 2; // [END data] // Model // [START model] CpModel model = new CpModel(); // [END model] // Variables // [START variables] Literal[][] x = new Literal[numWorkers][numTasks]; // Variables in a 1-dim array. for (int worker : allWorkers) { for (int task : allTasks) { x[worker][task] = model.newBoolVar("x[" + worker + "," + task + "]"); } } // [END variables] // Constraints // [START constraints] // Each worker is assigned to at most one task. for (int worker : allWorkers) { List<Literal> tasks = new ArrayList<>(); for (int task : allTasks) { tasks.add(x[worker][task]); } model.addAtMostOne(tasks); } // Each task is assigned to exactly one worker. for (int task : allTasks) { List<Literal> workers = new ArrayList<>(); for (int worker : allWorkers) { workers.add(x[worker][task]); } model.addExactlyOne(workers); } // Each team takes at most two tasks. LinearExprBuilder team1Tasks = LinearExpr.newBuilder(); for (int worker : team1) { for (int task : allTasks) { team1Tasks.add(x[worker][task]); } } model.addLessOrEqual(team1Tasks, teamMax); LinearExprBuilder team2Tasks = LinearExpr.newBuilder(); for (int worker : team2) { for (int task : allTasks) { team2Tasks.add(x[worker][task]); } } model.addLessOrEqual(team2Tasks, teamMax); // [END constraints] // Objective // [START objective] LinearExprBuilder obj = LinearExpr.newBuilder(); for (int worker : allWorkers) { for (int task : allTasks) { obj.addTerm(x[worker][task], costs[worker][task]); } } model.minimize(obj); // [END objective] // Solve // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // Print solution. // [START print_solution] // Check that the problem has a feasible solution. if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.println("Total cost: " + solver.objectiveValue() + "\n"); for (int worker : allWorkers) { for (int task : allTasks) { if (solver.booleanValue(x[worker][task])) { System.out.println("Worker " + worker + " assigned to task " + task + ". Cost: " + costs[worker][task]); } } } } else { System.err.println("No solution found."); } // [END print_solution] } private AssignmentTeamsSat() {} }
4,464
29.168919
80
java
or-tools
or-tools-master/ortools/sat/samples/AssumptionsSampleSat.java
// Copyright 2021 Xiang Chen // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.Literal; // [END import] /** Minimal CP-SAT example to showcase assumptions. */ public class AssumptionsSampleSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] IntVar x = model.newIntVar(0, 10, "x"); IntVar y = model.newIntVar(0, 10, "y"); IntVar z = model.newIntVar(0, 10, "z"); Literal a = model.newBoolVar("a"); Literal b = model.newBoolVar("b"); Literal c = model.newBoolVar("c"); // [END variables] // Creates the constraints. // [START constraints] model.addGreaterThan(x, y).onlyEnforceIf(a); model.addGreaterThan(y, z).onlyEnforceIf(b); model.addGreaterThan(z, x).onlyEnforceIf(c); // [END constraints] // Add assumptions model.addAssumptions(new Literal[] {a, b, c}); // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // Print solution. // [START print_solution] // Check that the problem is infeasible. if (status == CpSolverStatus.INFEASIBLE) { System.out.println(solver.sufficientAssumptionsForInfeasibility()); } // [END print_solution] } private AssumptionsSampleSat() {} } // [END program]
2,303
31
75
java
or-tools
or-tools-master/ortools/sat/samples/BinPackingProblemSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; /** Solves a bin packing problem with the CP-SAT solver. */ public class BinPackingProblemSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Data. int binCapacity = 100; int slackCapacity = 20; int numBins = 5; int[][] items = new int[][] {{20, 6}, {15, 6}, {30, 4}, {45, 3}}; int numItems = items.length; // Model. CpModel model = new CpModel(); // Main variables. IntVar[][] x = new IntVar[numItems][numBins]; for (int i = 0; i < numItems; ++i) { int numCopies = items[i][1]; for (int b = 0; b < numBins; ++b) { x[i][b] = model.newIntVar(0, numCopies, "x_" + i + "_" + b); } } // Load variables. IntVar[] load = new IntVar[numBins]; for (int b = 0; b < numBins; ++b) { load[b] = model.newIntVar(0, binCapacity, "load_" + b); } // Slack variables. Literal[] slacks = new Literal[numBins]; for (int b = 0; b < numBins; ++b) { slacks[b] = model.newBoolVar("slack_" + b); } // Links load and x. for (int b = 0; b < numBins; ++b) { LinearExprBuilder expr = LinearExpr.newBuilder(); for (int i = 0; i < numItems; ++i) { expr.addTerm(x[i][b], items[i][0]); } model.addEquality(expr, load[b]); } // Place all items. for (int i = 0; i < numItems; ++i) { LinearExprBuilder expr = LinearExpr.newBuilder(); for (int b = 0; b < numBins; ++b) { expr.add(x[i][b]); } model.addEquality(expr, items[i][1]); } // Links load and slack. int safeCapacity = binCapacity - slackCapacity; for (int b = 0; b < numBins; ++b) { // slack[b] => load[b] <= safeCapacity. model.addLessOrEqual(load[b], safeCapacity).onlyEnforceIf(slacks[b]); // not(slack[b]) => load[b] > safeCapacity. model.addGreaterOrEqual(load[b], safeCapacity + 1).onlyEnforceIf(slacks[b].not()); } // Maximize sum of slacks. model.maximize(LinearExpr.sum(slacks)); // Solves and prints out the solution. CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); System.out.println("Solve status: " + status); if (status == CpSolverStatus.OPTIMAL) { System.out.printf("Optimal objective value: %f%n", solver.objectiveValue()); for (int b = 0; b < numBins; ++b) { System.out.printf("load_%d = %d%n", b, solver.value(load[b])); for (int i = 0; i < numItems; ++i) { System.out.printf(" item_%d_%d = %d%n", i, b, solver.value(x[i][b])); } } } System.out.println("Statistics"); System.out.println(" - conflicts : " + solver.numConflicts()); System.out.println(" - branches : " + solver.numBranches()); System.out.println(" - wall time : " + solver.wallTime() + " s"); } }
3,806
33.609091
88
java
or-tools
or-tools-master/ortools/sat/samples/BoolOrSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.BoolVar; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.Literal; /** Code sample to demonstrates a simple Boolean constraint. */ public class BoolOrSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); BoolVar x = model.newBoolVar("x"); BoolVar y = model.newBoolVar("y"); model.addBoolOr(new Literal[] {x, y.not()}); } }
1,140
35.806452
75
java
or-tools
or-tools-master/ortools/sat/samples/ChannelingSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.BoolVar; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.DecisionStrategyProto; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.SatParameters; /** Link integer constraints together. */ public class ChannelingSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the CP-SAT model. CpModel model = new CpModel(); // Declare our two primary variables. IntVar[] vars = new IntVar[] {model.newIntVar(0, 10, "x"), model.newIntVar(0, 10, "y")}; // Declare our intermediate boolean variable. BoolVar b = model.newBoolVar("b"); // Implement b == (x >= 5). model.addGreaterOrEqual(vars[0], 5).onlyEnforceIf(b); model.addLessOrEqual(vars[0], 4).onlyEnforceIf(b.not()); // Create our two half-reified constraints. // First, b implies (y == 10 - x). model.addEquality(LinearExpr.sum(vars), 10).onlyEnforceIf(b); // Second, not(b) implies y == 0. model.addEquality(vars[1], 0).onlyEnforceIf(b.not()); // Search for x values in increasing order. model.addDecisionStrategy(new IntVar[] {vars[0]}, DecisionStrategyProto.VariableSelectionStrategy.CHOOSE_FIRST, DecisionStrategyProto.DomainReductionStrategy.SELECT_MIN_VALUE); // Create the solver. CpSolver solver = new CpSolver(); // Force the solver to follow the decision strategy exactly. solver.getParameters().setSearchBranching(SatParameters.SearchBranching.FIXED_SEARCH); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // Solve the problem with the printer callback. solver.solve(model, new CpSolverSolutionCallback() { public CpSolverSolutionCallback init(IntVar[] variables) { variableArray = variables; return this; } @Override public void onSolutionCallback() { for (IntVar v : variableArray) { System.out.printf("%s=%d ", v.getName(), value(v)); } System.out.println(); } private IntVar[] variableArray; }.init(new IntVar[] {vars[0], vars[1], b})); } }
3,004
36.098765
92
java
or-tools
or-tools-master/ortools/sat/samples/CpIsFunSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; // [END import] /** Cryptarithmetic puzzle. */ public final class CpIsFunSat { // [START solution_printer] static class VarArraySolutionPrinter extends CpSolverSolutionCallback { public VarArraySolutionPrinter(IntVar[] variables) { variableArray = variables; } @Override public void onSolutionCallback() { for (IntVar v : variableArray) { System.out.printf(" %s = %d", v.getName(), value(v)); } System.out.println(); solutionCount++; } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final IntVar[] variableArray; } // [END solution_printer] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // [START variables] int base = 10; IntVar c = model.newIntVar(1, base - 1, "C"); IntVar p = model.newIntVar(0, base - 1, "P"); IntVar i = model.newIntVar(1, base - 1, "I"); IntVar s = model.newIntVar(0, base - 1, "S"); IntVar f = model.newIntVar(1, base - 1, "F"); IntVar u = model.newIntVar(0, base - 1, "U"); IntVar n = model.newIntVar(0, base - 1, "N"); IntVar t = model.newIntVar(1, base - 1, "T"); IntVar r = model.newIntVar(0, base - 1, "R"); IntVar e = model.newIntVar(0, base - 1, "E"); // We need to group variables in a list to use the constraint AllDifferent. IntVar[] letters = new IntVar[] {c, p, i, s, f, u, n, t, r, e}; // [END variables] // Define constraints. // [START constraints] model.addAllDifferent(letters); // CP + IS + FUN = TRUE model.addEquality(LinearExpr.weightedSum(new IntVar[] {c, p, i, s, f, u, n, t, r, u, e}, new long[] {base, 1, base, 1, base * base, base, 1, -base * base * base, -base * base, -base, -1}), 0); // [END constraints] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); VarArraySolutionPrinter cb = new VarArraySolutionPrinter(letters); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // And solve. solver.solve(model, cb); // [END solve] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.println(" - conflicts : " + solver.numConflicts()); System.out.println(" - branches : " + solver.numBranches()); System.out.println(" - wall time : " + solver.wallTime() + " s"); System.out.println(" - solutions : " + cb.getSolutionCount()); // [END statistics] } private CpIsFunSat() {} } // [END program]
3,695
32.908257
98
java
or-tools
or-tools-master/ortools/sat/samples/CpSatExample.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import static java.util.Arrays.stream; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; // [END import] /** Minimal CP-SAT example to showcase calling the solver. */ public final class CpSatExample { public static void main(String[] args) { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] int varUpperBound = stream(new int[] {50, 45, 37}).max().getAsInt(); IntVar x = model.newIntVar(0, varUpperBound, "x"); IntVar y = model.newIntVar(0, varUpperBound, "y"); IntVar z = model.newIntVar(0, varUpperBound, "z"); // [END variables] // Create the constraints. // [START constraints] model.addLessOrEqual(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {2, 7, 3}), 50); model.addLessOrEqual(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {3, -5, 7}), 45); model.addLessOrEqual(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {5, 2, -6}), 37); // [END constraints] // [START objective] model.maximize(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {2, 2, 3})); // [END objective] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.printf("Maximum of objective function: %f%n", solver.objectiveValue()); System.out.println("x = " + solver.value(x)); System.out.println("y = " + solver.value(y)); System.out.println("z = " + solver.value(z)); } else { System.out.println("No solution found."); } // [END print_solution] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.printf(" conflicts: %d%n", solver.numConflicts()); System.out.printf(" branches : %d%n", solver.numBranches()); System.out.printf(" wall time: %f s%n", solver.wallTime()); // [END statistics] } private CpSatExample() {} } // [END program]
3,060
35.011765
100
java
or-tools
or-tools-master/ortools/sat/samples/EarlinessTardinessCostSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.DecisionStrategyProto; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.SatParameters; /** Encode the piecewise linear expression. */ public class EarlinessTardinessCostSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); long earlinessDate = 5; long earlinessCost = 8; long latenessDate = 15; long latenessCost = 12; // Create the CP-SAT model. CpModel model = new CpModel(); // Declare our primary variable. IntVar x = model.newIntVar(0, 20, "x"); // Create the expression variable and implement the piecewise linear function. // // \ / // \______/ // ed ld // long largeConstant = 1000; IntVar expr = model.newIntVar(0, largeConstant, "expr"); // Link together expr and the 3 segment. // First segment: y == earlinessCost * (earlinessDate - x). // Second segment: y = 0 // Third segment: y == latenessCost * (x - latenessDate). model.addMaxEquality(expr, new LinearExpr[] {LinearExpr.newBuilder() .addTerm(x, -earlinessCost) .add(earlinessCost * earlinessDate) .build(), LinearExpr.constant(0), LinearExpr.newBuilder() .addTerm(x, latenessCost) .add(-latenessCost * latenessDate) .build()}); // Search for x values in increasing order. model.addDecisionStrategy(new IntVar[] {x}, DecisionStrategyProto.VariableSelectionStrategy.CHOOSE_FIRST, DecisionStrategyProto.DomainReductionStrategy.SELECT_MIN_VALUE); // Create the solver. CpSolver solver = new CpSolver(); // Force the solver to follow the decision strategy exactly. solver.getParameters().setSearchBranching(SatParameters.SearchBranching.FIXED_SEARCH); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // Solve the problem with the printer callback. solver.solve(model, new CpSolverSolutionCallback() { public CpSolverSolutionCallback init(IntVar[] variables) { variableArray = variables; return this; } @Override public void onSolutionCallback() { for (IntVar v : variableArray) { System.out.printf("%s=%d ", v.getName(), value(v)); } System.out.println(); } private IntVar[] variableArray; }.init(new IntVar[] {x, expr})); } }
3,415
34.583333
90
java
or-tools
or-tools-master/ortools/sat/samples/IntervalSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.IntervalVar; import com.google.ortools.sat.LinearExpr; /** Code sample to demonstrates how to build an interval. */ public class IntervalSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); int horizon = 100; // An interval can be created from three affine expressions. IntVar startVar = model.newIntVar(0, horizon, "start"); IntVar endVar = model.newIntVar(0, horizon, "end"); IntervalVar intervalVar = model.newIntervalVar( startVar, LinearExpr.constant(10), LinearExpr.newBuilder().add(endVar).add(2), "interval"); System.out.println(intervalVar); // If the size is fixed, a simpler version uses the start expression and the size. IntervalVar fixedSizeIntervalVar = model.newFixedSizeIntervalVar(startVar, 10, "fixed_size_interval_var"); System.out.println(fixedSizeIntervalVar); // A fixed interval can be created using another method. IntervalVar fixedInterval = model.newFixedInterval(5, 10, "fixed_interval"); System.out.println(fixedInterval); } }
1,886
40.021739
99
java
or-tools
or-tools-master/ortools/sat/samples/LiteralSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.BoolVar; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.Literal; /** Code sample to demonstrate Boolean variable and literals. */ public class LiteralSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); BoolVar x = model.newBoolVar("x"); Literal notX = x.not(); System.out.println(notX); } }
1,112
34.903226
75
java
or-tools
or-tools-master/ortools/sat/samples/MinimalJobshopSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import static java.lang.Math.max; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.IntervalVar; import com.google.ortools.sat.LinearExpr; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.IntStream; // [END import] /** Minimal Jobshop problem. */ public class MinimalJobshopSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START data] class Task { int machine; int duration; Task(int machine, int duration) { this.machine = machine; this.duration = duration; } } final List<List<Task>> allJobs = Arrays.asList(Arrays.asList(new Task(0, 3), new Task(1, 2), new Task(2, 2)), // Job0 Arrays.asList(new Task(0, 2), new Task(2, 1), new Task(1, 4)), // Job1 Arrays.asList(new Task(1, 4), new Task(2, 3)) // Job2 ); int numMachines = 1; for (List<Task> job : allJobs) { for (Task task : job) { numMachines = max(numMachines, 1 + task.machine); } } final int[] allMachines = IntStream.range(0, numMachines).toArray(); // Computes horizon dynamically as the sum of all durations. int horizon = 0; for (List<Task> job : allJobs) { for (Task task : job) { horizon += task.duration; } } // [END data] // Creates the model. // [START model] CpModel model = new CpModel(); // [END model] // [START variables] class TaskType { IntVar start; IntVar end; IntervalVar interval; } Map<List<Integer>, TaskType> allTasks = new HashMap<>(); Map<Integer, List<IntervalVar>> machineToIntervals = new HashMap<>(); for (int jobID = 0; jobID < allJobs.size(); ++jobID) { List<Task> job = allJobs.get(jobID); for (int taskID = 0; taskID < job.size(); ++taskID) { Task task = job.get(taskID); String suffix = "_" + jobID + "_" + taskID; TaskType taskType = new TaskType(); taskType.start = model.newIntVar(0, horizon, "start" + suffix); taskType.end = model.newIntVar(0, horizon, "end" + suffix); taskType.interval = model.newIntervalVar( taskType.start, LinearExpr.constant(task.duration), taskType.end, "interval" + suffix); List<Integer> key = Arrays.asList(jobID, taskID); allTasks.put(key, taskType); machineToIntervals.computeIfAbsent(task.machine, (Integer k) -> new ArrayList<>()); machineToIntervals.get(task.machine).add(taskType.interval); } } // [END variables] // [START constraints] // Create and add disjunctive constraints. for (int machine : allMachines) { List<IntervalVar> list = machineToIntervals.get(machine); model.addNoOverlap(list); } // Precedences inside a job. for (int jobID = 0; jobID < allJobs.size(); ++jobID) { List<Task> job = allJobs.get(jobID); for (int taskID = 0; taskID < job.size() - 1; ++taskID) { List<Integer> prevKey = Arrays.asList(jobID, taskID); List<Integer> nextKey = Arrays.asList(jobID, taskID + 1); model.addGreaterOrEqual(allTasks.get(nextKey).start, allTasks.get(prevKey).end); } } // [END constraints] // [START objective] // Makespan objective. IntVar objVar = model.newIntVar(0, horizon, "makespan"); List<IntVar> ends = new ArrayList<>(); for (int jobID = 0; jobID < allJobs.size(); ++jobID) { List<Task> job = allJobs.get(jobID); List<Integer> key = Arrays.asList(jobID, job.size() - 1); ends.add(allTasks.get(key).end); } model.addMaxEquality(objVar, ends); model.minimize(objVar); // [END objective] // Creates a solver and solves the model. // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { class AssignedTask { int jobID; int taskID; int start; int duration; // Ctor AssignedTask(int jobID, int taskID, int start, int duration) { this.jobID = jobID; this.taskID = taskID; this.start = start; this.duration = duration; } } class SortTasks implements Comparator<AssignedTask> { @Override public int compare(AssignedTask a, AssignedTask b) { if (a.start != b.start) { return a.start - b.start; } else { return a.duration - b.duration; } } } System.out.println("Solution:"); // Create one list of assigned tasks per machine. Map<Integer, List<AssignedTask>> assignedJobs = new HashMap<>(); for (int jobID = 0; jobID < allJobs.size(); ++jobID) { List<Task> job = allJobs.get(jobID); for (int taskID = 0; taskID < job.size(); ++taskID) { Task task = job.get(taskID); List<Integer> key = Arrays.asList(jobID, taskID); AssignedTask assignedTask = new AssignedTask( jobID, taskID, (int) solver.value(allTasks.get(key).start), task.duration); assignedJobs.computeIfAbsent(task.machine, (Integer k) -> new ArrayList<>()); assignedJobs.get(task.machine).add(assignedTask); } } // Create per machine output lines. String output = ""; for (int machine : allMachines) { // Sort by starting time. Collections.sort(assignedJobs.get(machine), new SortTasks()); String solLineTasks = "Machine " + machine + ": "; String solLine = " "; for (AssignedTask assignedTask : assignedJobs.get(machine)) { String name = "job_" + assignedTask.jobID + "_task_" + assignedTask.taskID; // Add spaces to output to align columns. solLineTasks += String.format("%-15s", name); String solTmp = "[" + assignedTask.start + "," + (assignedTask.start + assignedTask.duration) + "]"; // Add spaces to output to align columns. solLine += String.format("%-15s", solTmp); } output += solLineTasks + "%n"; output += solLine + "%n"; } System.out.printf("Optimal Schedule Length: %f%n", solver.objectiveValue()); System.out.printf(output); } else { System.out.println("No solution found."); } // [END print_solution] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.printf(" conflicts: %d%n", solver.numConflicts()); System.out.printf(" branches : %d%n", solver.numBranches()); System.out.printf(" wall time: %f s%n", solver.wallTime()); // [END statistics] } private MinimalJobshopSat() {} } // [END program]
7,823
33.928571
99
java
or-tools
or-tools-master/ortools/sat/samples/MultipleKnapsackSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] // Solves a multiple knapsack problem using the CP-SAT solver. package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Sample showing how to solve a multiple knapsack problem. */ public class MultipleKnapsackSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Instantiate the data problem. // [START data] final int[] weights = {48, 30, 42, 36, 36, 48, 42, 42, 36, 24, 30, 30, 42, 36, 36}; final int[] values = {10, 30, 25, 50, 35, 30, 15, 40, 30, 35, 45, 10, 20, 30, 25}; final int numItems = weights.length; final int[] allItems = IntStream.range(0, numItems).toArray(); final int[] binCapacities = {100, 100, 100, 100, 100}; final int numBins = binCapacities.length; final int[] allBins = IntStream.range(0, numBins).toArray(); // [END data] // [START model] CpModel model = new CpModel(); // [END model] // Variables. // [START variables] Literal[][] x = new Literal[numItems][numBins]; for (int i : allItems) { for (int b : allBins) { x[i][b] = model.newBoolVar("x_" + i + "_" + b); } } // [END variables] // Constraints. // [START constraints] // Each item is assigned to at most one bin. for (int i : allItems) { List<Literal> bins = new ArrayList<>(); for (int b : allBins) { bins.add(x[i][b]); } model.addAtMostOne(bins); } // The amount packed in each bin cannot exceed its capacity. for (int b : allBins) { LinearExprBuilder load = LinearExpr.newBuilder(); for (int i : allItems) { load.addTerm(x[i][b], weights[i]); } model.addLessOrEqual(load, binCapacities[b]); } // [END constraints] // Objective. // [START objective] // Maximize total value of packed items. LinearExprBuilder obj = LinearExpr.newBuilder(); for (int i : allItems) { for (int b : allBins) { obj.addTerm(x[i][b], values[i]); } } model.maximize(obj); // [END objective] // [START solve] CpSolver solver = new CpSolver(); final CpSolverStatus status = solver.solve(model); // [END solve] // [START print_solution] // Check that the problem has an optimal solution. if (status == CpSolverStatus.OPTIMAL) { System.out.println("Total packed value: " + solver.objectiveValue()); long totalWeight = 0; for (int b : allBins) { long binWeight = 0; long binValue = 0; System.out.println("Bin " + b); for (int i : allItems) { if (solver.booleanValue(x[i][b])) { System.out.println("Item " + i + " weight: " + weights[i] + " value: " + values[i]); binWeight += weights[i]; binValue += values[i]; } } System.out.println("Packed bin weight: " + binWeight); System.out.println("Packed bin value: " + binValue); totalWeight += binWeight; } System.out.println("Total packed weight: " + totalWeight); } else { System.err.println("The problem does not have an optimal solution."); } // [END print_solution] } private MultipleKnapsackSat() {} } // [END program]
4,221
31.984375
96
java
or-tools
or-tools-master/ortools/sat/samples/NQueensSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; // [END import] /** OR-Tools solution to the N-queens problem. */ public final class NQueensSat { // [START solution_printer] static class SolutionPrinter extends CpSolverSolutionCallback { public SolutionPrinter(IntVar[] queensIn) { solutionCount = 0; queens = queensIn; } @Override public void onSolutionCallback() { System.out.println("Solution " + solutionCount); for (int i = 0; i < queens.length; ++i) { for (int j = 0; j < queens.length; ++j) { if (value(queens[j]) == i) { System.out.print("Q"); } else { System.out.print("_"); } if (j != queens.length - 1) { System.out.print(" "); } } System.out.println(); } solutionCount++; } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final IntVar[] queens; } // [END solution_printer] public static void main(String[] args) { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // [START variables] int boardSize = 8; IntVar[] queens = new IntVar[boardSize]; for (int i = 0; i < boardSize; ++i) { queens[i] = model.newIntVar(0, boardSize - 1, "x" + i); } // [END variables] // Define constraints. // [START constraints] // All rows must be different. model.addAllDifferent(queens); // All columns must be different because the indices of queens are all different. // No two queens can be on the same diagonal. LinearExpr[] diag1 = new LinearExpr[boardSize]; LinearExpr[] diag2 = new LinearExpr[boardSize]; for (int i = 0; i < boardSize; ++i) { diag1[i] = LinearExpr.newBuilder().add(queens[i]).add(i).build(); diag2[i] = LinearExpr.newBuilder().add(queens[i]).add(-i).build(); } model.addAllDifferent(diag1); model.addAllDifferent(diag2); // [END constraints] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); SolutionPrinter cb = new SolutionPrinter(queens); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // And solve. solver.solve(model, cb); // [END solve] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.println(" conflicts : " + solver.numConflicts()); System.out.println(" branches : " + solver.numBranches()); System.out.println(" wall time : " + solver.wallTime() + " s"); System.out.println(" solutions : " + cb.getSolutionCount()); // [END statistics] } private NQueensSat() {} } // [END program]
3,711
30.726496
85
java
or-tools
or-tools-master/ortools/sat/samples/NoOverlapSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.IntervalVar; import com.google.ortools.sat.LinearExpr; /** * We want to schedule 3 tasks on 3 weeks excluding weekends, making the final day as early as * possible. */ public class NoOverlapSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); // Three weeks. int horizon = 21; // Task 0, duration 2. IntVar start0 = model.newIntVar(0, horizon, "start0"); int duration0 = 2; IntervalVar task0 = model.newFixedSizeIntervalVar(start0, duration0, "task0"); // Task 1, duration 4. IntVar start1 = model.newIntVar(0, horizon, "start1"); int duration1 = 4; IntervalVar task1 = model.newFixedSizeIntervalVar(start1, duration1, "task1"); // Task 2, duration 3. IntVar start2 = model.newIntVar(0, horizon, "start2"); int duration2 = 3; IntervalVar task2 = model.newFixedSizeIntervalVar(start2, duration2, "task2"); // Weekends. IntervalVar weekend0 = model.newFixedInterval(5, 2, "weekend0"); IntervalVar weekend1 = model.newFixedInterval(12, 2, "weekend1"); IntervalVar weekend2 = model.newFixedInterval(19, 2, "weekend2"); // No Overlap constraint. This constraint enforces that no two intervals can overlap. // In this example, as we use 3 fixed intervals that span over weekends, this constraint makes // sure that all tasks are executed on weekdays. model.addNoOverlap(new IntervalVar[] {task0, task1, task2, weekend0, weekend1, weekend2}); // Makespan objective. IntVar obj = model.newIntVar(0, horizon, "makespan"); model.addMaxEquality(obj, new LinearExpr[] {LinearExpr.newBuilder().add(start0).add(duration0).build(), LinearExpr.newBuilder().add(start1).add(duration1).build(), LinearExpr.newBuilder().add(start2).add(duration2).build()}); model.minimize(obj); // Creates a solver and solves the model. CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); if (status == CpSolverStatus.OPTIMAL) { System.out.println("Optimal Schedule Length: " + solver.objectiveValue()); System.out.println("Task 0 starts at " + solver.value(start0)); System.out.println("Task 1 starts at " + solver.value(start1)); System.out.println("Task 2 starts at " + solver.value(start2)); } } }
3,235
39.45
98
java
or-tools
or-tools-master/ortools/sat/samples/NursesSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Nurses problem. */ public class NursesSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START data] final int numNurses = 4; final int numDays = 3; final int numShifts = 3; final int[] allNurses = IntStream.range(0, numNurses).toArray(); final int[] allDays = IntStream.range(0, numDays).toArray(); final int[] allShifts = IntStream.range(0, numShifts).toArray(); // [END data] // Creates the model. // [START model] CpModel model = new CpModel(); // [END model] // Creates shift variables. // shifts[(n, d, s)]: nurse 'n' works shift 's' on day 'd'. // [START variables] Literal[][][] shifts = new Literal[numNurses][numDays][numShifts]; for (int n : allNurses) { for (int d : allDays) { for (int s : allShifts) { shifts[n][d][s] = model.newBoolVar("shifts_n" + n + "d" + d + "s" + s); } } } // [END variables] // Each shift is assigned to exactly one nurse in the schedule period. // [START exactly_one_nurse] for (int d : allDays) { for (int s : allShifts) { List<Literal> nurses = new ArrayList<>(); for (int n : allNurses) { nurses.add(shifts[n][d][s]); } model.addExactlyOne(nurses); } } // [END exactly_one_nurse] // Each nurse works at most one shift per day. // [START at_most_one_shift] for (int n : allNurses) { for (int d : allDays) { List<Literal> work = new ArrayList<>(); for (int s : allShifts) { work.add(shifts[n][d][s]); } model.addAtMostOne(work); } } // [END at_most_one_shift] // [START assign_nurses_evenly] // Try to distribute the shifts evenly, so that each nurse works // minShiftsPerNurse shifts. If this is not possible, because the total // number of shifts is not divisible by the number of nurses, some nurses will // be assigned one more shift. int minShiftsPerNurse = (numShifts * numDays) / numNurses; int maxShiftsPerNurse; if ((numShifts * numDays) % numNurses == 0) { maxShiftsPerNurse = minShiftsPerNurse; } else { maxShiftsPerNurse = minShiftsPerNurse + 1; } for (int n : allNurses) { LinearExprBuilder numShiftsWorked = LinearExpr.newBuilder(); for (int d : allDays) { for (int s : allShifts) { numShiftsWorked.add(shifts[n][d][s]); } } model.addLinearConstraint(numShiftsWorked, minShiftsPerNurse, maxShiftsPerNurse); } // [END assign_nurses_evenly] // [START parameters] CpSolver solver = new CpSolver(); solver.getParameters().setLinearizationLevel(0); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // [END parameters] // Display the first five solutions. // [START solution_printer] final int solutionLimit = 5; class VarArraySolutionPrinterWithLimit extends CpSolverSolutionCallback { public VarArraySolutionPrinterWithLimit( int[] allNurses, int[] allDays, int[] allShifts, Literal[][][] shifts, int limit) { solutionCount = 0; this.allNurses = allNurses; this.allDays = allDays; this.allShifts = allShifts; this.shifts = shifts; solutionLimit = limit; } @Override public void onSolutionCallback() { System.out.printf("Solution #%d:%n", solutionCount); for (int d : allDays) { System.out.printf("Day %d%n", d); for (int n : allNurses) { boolean isWorking = false; for (int s : allShifts) { if (booleanValue(shifts[n][d][s])) { isWorking = true; System.out.printf(" Nurse %d work shift %d%n", n, s); } } if (!isWorking) { System.out.printf(" Nurse %d does not work%n", n); } } } solutionCount++; if (solutionCount >= solutionLimit) { System.out.printf("Stop search after %d solutions%n", solutionLimit); stopSearch(); } } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final int[] allNurses; private final int[] allDays; private final int[] allShifts; private final Literal[][][] shifts; private final int solutionLimit; } VarArraySolutionPrinterWithLimit cb = new VarArraySolutionPrinterWithLimit(allNurses, allDays, allShifts, shifts, solutionLimit); // [END solution_printer] // Creates a solver and solves the model. // [START solve] CpSolverStatus status = solver.solve(model, cb); System.out.println("Status: " + status); System.out.println(cb.getSolutionCount() + " solutions found."); // [END solve] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.printf(" conflicts: %d%n", solver.numConflicts()); System.out.printf(" branches : %d%n", solver.numBranches()); System.out.printf(" wall time: %f s%n", solver.wallTime()); // [END statistics] } private NursesSat() {} } // [END program]
6,416
32.421875
99
java
or-tools
or-tools-master/ortools/sat/samples/OptionalIntervalSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.IntervalVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.Literal; /** Code sample to demonstrates how to build an optional interval. */ public class OptionalIntervalSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); int horizon = 100; // An interval can be created from three affine expressions, and a literal. IntVar startVar = model.newIntVar(0, horizon, "start"); IntVar endVar = model.newIntVar(0, horizon, "end"); Literal presence = model.newBoolVar("presence"); IntervalVar intervalVar = model.newOptionalIntervalVar(startVar, LinearExpr.constant(10), LinearExpr.newBuilder().add(endVar).add(2), presence, "interval"); System.out.println(intervalVar); // If the size is fixed, a simpler version uses the start expression, the size and the literal. IntervalVar fixedSizeIntervalVar = model.newOptionalFixedSizeIntervalVar(startVar, 10, presence, "fixed_size_interval_var"); System.out.println(fixedSizeIntervalVar); // A fixed interval can be created using another method. IntervalVar fixedInterval = model.newOptionalFixedInterval(5, 10, presence, "fixed_interval"); System.out.println(fixedInterval); } }
2,076
42.270833
99
java
or-tools
or-tools-master/ortools/sat/samples/RabbitsAndPheasantsSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; /** * In a field of rabbits and pheasants, there are 20 heads and 56 legs. How many rabbits and * pheasants are there? */ public class RabbitsAndPheasantsSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Creates the model. CpModel model = new CpModel(); // Creates the variables. IntVar r = model.newIntVar(0, 100, "r"); IntVar p = model.newIntVar(0, 100, "p"); // 20 heads. model.addEquality(LinearExpr.newBuilder().add(r).add(p), 20); // 56 legs. model.addEquality(LinearExpr.newBuilder().addTerm(r, 4).addTerm(p, 2), 56); // Creates a solver and solves the model. CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); if (status == CpSolverStatus.OPTIMAL) { System.out.println(solver.value(r) + " rabbits, and " + solver.value(p) + " pheasants"); } } }
1,774
35.22449
94
java
or-tools
or-tools-master/ortools/sat/samples/RankingSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.BoolVar; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.IntervalVar; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; /** Code sample to demonstrates how to rank intervals. */ public class RankingSampleSat { /** * This code takes a list of interval variables in a noOverlap constraint, and a parallel list of * integer variables and enforces the following constraint * * <ul> * <li>rank[i] == -1 iff interval[i] is not active. * <li>rank[i] == number of active intervals that precede interval[i]. * </ul> */ static void rankTasks(CpModel model, IntVar[] starts, Literal[] presences, IntVar[] ranks) { int numTasks = starts.length; // Creates precedence variables between pairs of intervals. Literal[][] precedences = new Literal[numTasks][numTasks]; for (int i = 0; i < numTasks; ++i) { for (int j = 0; j < numTasks; ++j) { if (i == j) { precedences[i][i] = presences[i]; } else { BoolVar prec = model.newBoolVar(String.format("%d before %d", i, j)); precedences[i][j] = prec; // Ensure that task i precedes task j if prec is true. model.addLessThan(starts[i], starts[j]).onlyEnforceIf(prec); } } } // Create optional intervals. for (int i = 0; i < numTasks - 1; ++i) { for (int j = i + 1; j < numTasks; ++j) { List<Literal> list = new ArrayList<>(); list.add(precedences[i][j]); list.add(precedences[j][i]); list.add(presences[i].not()); // Makes sure that if i is not performed, all precedences are false. model.addImplication(presences[i].not(), precedences[i][j].not()); model.addImplication(presences[i].not(), precedences[j][i].not()); list.add(presences[j].not()); // Makes sure that if j is not performed, all precedences are false. model.addImplication(presences[j].not(), precedences[i][j].not()); model.addImplication(presences[j].not(), precedences[j][i].not()); // The following boolOr will enforce that for any two intervals: // i precedes j or j precedes i or at least one interval is not // performed. model.addBoolOr(list); // For efficiency, we add a redundant constraint declaring that only one of i precedes j and // j precedes i are true. This will speed up the solve because the reason of this // propagation is shorter that using interval bounds is true. model.addImplication(precedences[i][j], precedences[j][i].not()); model.addImplication(precedences[j][i], precedences[i][j].not()); } } // Links precedences and ranks. for (int i = 0; i < numTasks; ++i) { // ranks == sum(precedences) - 1; LinearExprBuilder expr = LinearExpr.newBuilder(); for (int j = 0; j < numTasks; ++j) { expr.add(precedences[j][i]); } expr.add(-1); model.addEquality(ranks[i], expr); } } public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); int horizon = 100; int numTasks = 4; IntVar[] starts = new IntVar[numTasks]; IntVar[] ends = new IntVar[numTasks]; IntervalVar[] intervals = new IntervalVar[numTasks]; Literal[] presences = new Literal[numTasks]; IntVar[] ranks = new IntVar[numTasks]; Literal trueLiteral = model.trueLiteral(); // Creates intervals, half of them are optional. for (int t = 0; t < numTasks; ++t) { starts[t] = model.newIntVar(0, horizon, "start_" + t); int duration = t + 1; ends[t] = model.newIntVar(0, horizon, "end_" + t); if (t < numTasks / 2) { intervals[t] = model.newIntervalVar( starts[t], LinearExpr.constant(duration), ends[t], "interval_" + t); presences[t] = trueLiteral; } else { presences[t] = model.newBoolVar("presence_" + t); intervals[t] = model.newOptionalIntervalVar( starts[t], LinearExpr.constant(duration), ends[t], presences[t], "o_interval_" + t); } // The rank will be -1 iff the task is not performed. ranks[t] = model.newIntVar(-1, numTasks - 1, "rank_" + t); } // Adds NoOverlap constraint. model.addNoOverlap(intervals); // Adds ranking constraint. rankTasks(model, starts, presences, ranks); // Adds a constraint on ranks (ranks[0] < ranks[1]). model.addLessThan(ranks[0], ranks[1]); // Creates makespan variable. IntVar makespan = model.newIntVar(0, horizon, "makespan"); for (int t = 0; t < numTasks; ++t) { model.addLessOrEqual(ends[t], makespan).onlyEnforceIf(presences[t]); } // The objective function is a mix of a fixed gain per task performed, and a fixed cost for each // additional day of activity. // The solver will balance both cost and gain and minimize makespan * per-day-penalty - number // of tasks performed * per-task-gain. // // On this problem, as the fixed cost is less that the duration of the last interval, the solver // will not perform the last interval. LinearExprBuilder obj = LinearExpr.newBuilder(); for (int t = 0; t < numTasks; ++t) { obj.addTerm(presences[t], -7); } obj.addTerm(makespan, 2); model.minimize(obj); // Creates a solver and solves the model. CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); if (status == CpSolverStatus.OPTIMAL) { System.out.println("Optimal cost: " + solver.objectiveValue()); System.out.println("Makespan: " + solver.value(makespan)); for (int t = 0; t < numTasks; ++t) { if (solver.booleanValue(presences[t])) { System.out.printf("Task %d starts at %d with rank %d%n", t, solver.value(starts[t]), solver.value(ranks[t])); } else { System.out.printf( "Task %d in not performed and ranked at %d%n", t, solver.value(ranks[t])); } } } else { System.out.println("Solver exited with nonoptimal status: " + status); } } }
7,098
38.882022
100
java
or-tools
or-tools-master/ortools/sat/samples/ReifiedSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.BoolVar; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.Literal; /** * Reification is the action of associating a Boolean variable to a constraint. This boolean * enforces or prohibits the constraint according to the value the Boolean variable is fixed to. * * <p>Half-reification is defined as a simple implication: If the Boolean variable is true, then the * constraint holds, instead of an complete equivalence. * * <p>The SAT solver offers half-reification. To implement full reification, two half-reified * constraints must be used. */ public class ReifiedSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); CpModel model = new CpModel(); BoolVar x = model.newBoolVar("x"); BoolVar y = model.newBoolVar("y"); BoolVar b = model.newBoolVar("b"); // Version 1: a half-reified boolean and. model.addBoolAnd(new Literal[] {x, y.not()}).onlyEnforceIf(b); // Version 2: implications. model.addImplication(b, x); model.addImplication(b, y.not()); // Version 3: boolean or. model.addBoolOr(new Literal[] {b.not(), x}); model.addBoolOr(new Literal[] {b.not(), y.not()}); } }
1,905
35.653846
100
java
or-tools
or-tools-master/ortools/sat/samples/ScheduleRequestsSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.LinearExpr; import com.google.ortools.sat.LinearExprBuilder; import com.google.ortools.sat.Literal; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; // [END import] /** Nurses problem with schedule requests. */ public class ScheduleRequestsSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // [START data] final int numNurses = 5; final int numDays = 7; final int numShifts = 3; final int[] allNurses = IntStream.range(0, numNurses).toArray(); final int[] allDays = IntStream.range(0, numDays).toArray(); final int[] allShifts = IntStream.range(0, numShifts).toArray(); final int[][][] shiftRequests = new int[][][] { { {0, 0, 1}, {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 0, 1}, }, { {0, 0, 0}, {0, 0, 0}, {0, 1, 0}, {0, 1, 0}, {1, 0, 0}, {0, 0, 0}, {0, 0, 1}, }, { {0, 1, 0}, {0, 1, 0}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, {0, 1, 0}, {0, 0, 0}, }, { {0, 0, 1}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 0}, {1, 0, 0}, {0, 0, 0}, }, { {0, 0, 0}, {0, 0, 1}, {0, 1, 0}, {0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 0}, }, }; // [END data] // Creates the model. // [START model] CpModel model = new CpModel(); // [END model] // Creates shift variables. // shifts[(n, d, s)]: nurse 'n' works shift 's' on day 'd'. // [START variables] Literal[][][] shifts = new Literal[numNurses][numDays][numShifts]; for (int n : allNurses) { for (int d : allDays) { for (int s : allShifts) { shifts[n][d][s] = model.newBoolVar("shifts_n" + n + "d" + d + "s" + s); } } } // [END variables] // Each shift is assigned to exactly one nurse in the schedule period. // [START exactly_one_nurse] for (int d : allDays) { for (int s : allShifts) { List<Literal> nurses = new ArrayList<>(); for (int n : allNurses) { nurses.add(shifts[n][d][s]); } model.addExactlyOne(nurses); } } // [END exactly_one_nurse] // Each nurse works at most one shift per day. // [START at_most_one_shift] for (int n : allNurses) { for (int d : allDays) { List<Literal> work = new ArrayList<>(); for (int s : allShifts) { work.add(shifts[n][d][s]); } model.addAtMostOne(work); } } // [END at_most_one_shift] // [START assign_nurses_evenly] // Try to distribute the shifts evenly, so that each nurse works // minShiftsPerNurse shifts. If this is not possible, because the total // number of shifts is not divisible by the number of nurses, some nurses will // be assigned one more shift. int minShiftsPerNurse = (numShifts * numDays) / numNurses; int maxShiftsPerNurse; if ((numShifts * numDays) % numNurses == 0) { maxShiftsPerNurse = minShiftsPerNurse; } else { maxShiftsPerNurse = minShiftsPerNurse + 1; } for (int n : allNurses) { LinearExprBuilder numShiftsWorked = LinearExpr.newBuilder(); for (int d : allDays) { for (int s : allShifts) { numShiftsWorked.add(shifts[n][d][s]); } } model.addLinearConstraint(numShiftsWorked, minShiftsPerNurse, maxShiftsPerNurse); } // [END assign_nurses_evenly] // [START objective] LinearExprBuilder obj = LinearExpr.newBuilder(); for (int n : allNurses) { for (int d : allDays) { for (int s : allShifts) { obj.addTerm(shifts[n][d][s], shiftRequests[n][d][s]); } } } model.maximize(obj); // [END objective] // Creates a solver and solves the model. // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.printf("Solution:%n"); for (int d : allDays) { System.out.printf("Day %d%n", d); for (int n : allNurses) { for (int s : allShifts) { if (solver.booleanValue(shifts[n][d][s])) { if (shiftRequests[n][d][s] == 1) { System.out.printf(" Nurse %d works shift %d (requested).%n", n, s); } else { System.out.printf(" Nurse %d works shift %d (not requested).%n", n, s); } } } } } System.out.printf("Number of shift requests met = %f (out of %d)%n", solver.objectiveValue(), numNurses * minShiftsPerNurse); } else { System.out.printf("No optimal solution found !"); } // [END print_solution] // Statistics. // [START statistics] System.out.println("Statistics"); System.out.printf(" conflicts: %d%n", solver.numConflicts()); System.out.printf(" branches : %d%n", solver.numBranches()); System.out.printf(" wall time: %f s%n", solver.wallTime()); // [END statistics] } private ScheduleRequestsSat() {} } // [END program]
6,425
29.454976
99
java
or-tools
or-tools-master/ortools/sat/samples/SearchForAllSolutionsSampleSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; /** Code sample that solves a model and displays all solutions. */ public class SearchForAllSolutionsSampleSat { // [START print_solution] static class VarArraySolutionPrinter extends CpSolverSolutionCallback { public VarArraySolutionPrinter(IntVar[] variables) { variableArray = variables; } @Override public void onSolutionCallback() { System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime()); for (IntVar v : variableArray) { System.out.printf(" %s = %d%n", v.getName(), value(v)); } solutionCount++; } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final IntVar[] variableArray; } // [END print_solution] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // [END variables] // Create the constraints. // [START constraints] model.addDifferent(x, y); // [END constraints] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); VarArraySolutionPrinter cb = new VarArraySolutionPrinter(new IntVar[] {x, y, z}); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // And solve. solver.solve(model, cb); // [END solve] System.out.println(cb.getSolutionCount() + " solutions found."); } } // [END program]
2,652
30.583333
85
java
or-tools
or-tools-master/ortools/sat/samples/SimpleSatProgram.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; // [START import] import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; // [END import] /** Minimal CP-SAT example to showcase calling the solver. */ public final class SimpleSatProgram { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // [END variables] // Create the constraints. // [START constraints] model.addDifferent(x, y); // [END constraints] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); CpSolverStatus status = solver.solve(model); // [END solve] // [START print_solution] if (status == CpSolverStatus.OPTIMAL || status == CpSolverStatus.FEASIBLE) { System.out.println("x = " + solver.value(x)); System.out.println("y = " + solver.value(y)); System.out.println("z = " + solver.value(z)); } else { System.out.println("No solution found."); } // [END print_solution] } private SimpleSatProgram() {} } // [END program]
2,139
30.940299
80
java
or-tools
or-tools-master/ortools/sat/samples/SolutionHintingSampleSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; /** Minimal CP-SAT example to showcase calling the solver. */ public class SolutionHintingSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // [END variables] // Create the constraints. // [START constraints] model.addDifferent(x, y); // [END constraints] // [START objective] model.maximize(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {1, 2, 3})); // [END objective] // Solution hinting: x <- 1, y <- 2 model.addHint(x, 1); model.addHint(y, 2); // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); VarArraySolutionPrinterWithObjective cb = new VarArraySolutionPrinterWithObjective(new IntVar[] {x, y, z}); solver.solve(model, cb); // [END solve] } static class VarArraySolutionPrinterWithObjective extends CpSolverSolutionCallback { public VarArraySolutionPrinterWithObjective(IntVar[] variables) { variableArray = variables; } @Override public void onSolutionCallback() { System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime()); System.out.printf(" objective value = %f%n", objectiveValue()); for (IntVar v : variableArray) { System.out.printf(" %s = %d%n", v.getName(), value(v)); } solutionCount++; } private int solutionCount; private final IntVar[] variableArray; } } // [END program]
2,721
31.404762
89
java
or-tools
or-tools-master/ortools/sat/samples/SolveAndPrintIntermediateSolutionsSampleSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.LinearExpr; /** Solves an optimization problem and displays all intermediate solutions. */ public class SolveAndPrintIntermediateSolutionsSampleSat { // [START print_solution] static class VarArraySolutionPrinterWithObjective extends CpSolverSolutionCallback { public VarArraySolutionPrinterWithObjective(IntVar[] variables) { variableArray = variables; } @Override public void onSolutionCallback() { System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime()); System.out.printf(" objective value = %f%n", objectiveValue()); for (IntVar v : variableArray) { System.out.printf(" %s = %d%n", v.getName(), value(v)); } solutionCount++; } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final IntVar[] variableArray; } // [END print_solution] public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the model. // [START model] CpModel model = new CpModel(); // [END model] // Create the variables. // [START variables] int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // [END variables] // Create the constraint. // [START constraints] model.addDifferent(x, y); // [END constraints] // Maximize a linear combination of variables. // [START objective] model.maximize(LinearExpr.weightedSum(new IntVar[] {x, y, z}, new long[] {1, 2, 3})); // [END objective] // Create a solver and solve the model. // [START solve] CpSolver solver = new CpSolver(); VarArraySolutionPrinterWithObjective cb = new VarArraySolutionPrinterWithObjective(new IntVar[] {x, y, z}); solver.solve(model, cb); // [END solve] System.out.println(cb.getSolutionCount() + " solutions found."); } } // [END program]
2,911
31.719101
89
java
or-tools
or-tools-master/ortools/sat/samples/SolveWithTimeLimitSampleSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverStatus; import com.google.ortools.sat.IntVar; /** Solves a problem with a time limit. */ public final class SolveWithTimeLimitSampleSat { public static void main(String[] args) { Loader.loadNativeLibraries(); // Create the model. CpModel model = new CpModel(); // Create the variables. int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // Create the constraint. model.addDifferent(x, y); // Create a solver and solve the model. CpSolver solver = new CpSolver(); solver.getParameters().setMaxTimeInSeconds(10.0); CpSolverStatus status = solver.solve(model); if (status == CpSolverStatus.OPTIMAL) { System.out.println("x = " + solver.value(x)); System.out.println("y = " + solver.value(y)); System.out.println("z = " + solver.value(z)); } } private SolveWithTimeLimitSampleSat() {} } // [END program]
1,807
33.113208
75
java
or-tools
or-tools-master/ortools/sat/samples/StepFunctionSampleSat.java
// Copyright 2010-2021 Google LLC // 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.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.DecisionStrategyProto; import com.google.ortools.sat.IntVar; import com.google.ortools.sat.Literal; import com.google.ortools.sat.SatParameters; import com.google.ortools.util.Domain; /** Link integer constraints together. */ public class StepFunctionSampleSat { public static void main(String[] args) throws Exception { Loader.loadNativeLibraries(); // Create the CP-SAT model. CpModel model = new CpModel(); // Declare our primary variable. IntVar x = model.newIntVar(0, 20, "x"); // Create the expression variable and implement the step function // Note it is not defined for var == 2. // // - 3 // -- -- --------- 2 // 1 // -- --- 0 // 0 ================ 20 // IntVar expr = model.newIntVar(0, 3, "expr"); // expr == 0 on [5, 6] U [8, 10] Literal b0 = model.newBoolVar("b0"); model.addLinearExpressionInDomain(x, Domain.fromValues(new long[] {5, 6, 8, 9, 10})) .onlyEnforceIf(b0); model.addEquality(expr, 0).onlyEnforceIf(b0); // expr == 2 on [0, 1] U [3, 4] U [11, 20] Literal b2 = model.newBoolVar("b2"); model .addLinearExpressionInDomain( x, Domain.fromIntervals(new long[][] {{0, 1}, {3, 4}, {11, 20}})) .onlyEnforceIf(b2); model.addEquality(expr, 2).onlyEnforceIf(b2); // expr == 3 when x = 7 Literal b3 = model.newBoolVar("b3"); model.addEquality(x, 7).onlyEnforceIf(b3); model.addEquality(expr, 3).onlyEnforceIf(b3); // At least one bi is true. (we could use a sum == 1). model.addBoolOr(new Literal[] {b0, b2, b3}); // Search for x values in increasing order. model.addDecisionStrategy(new IntVar[] {x}, DecisionStrategyProto.VariableSelectionStrategy.CHOOSE_FIRST, DecisionStrategyProto.DomainReductionStrategy.SELECT_MIN_VALUE); // Create the solver. CpSolver solver = new CpSolver(); // Force the solver to follow the decision strategy exactly. solver.getParameters().setSearchBranching(SatParameters.SearchBranching.FIXED_SEARCH); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // Solve the problem with the printer callback. solver.solve(model, new CpSolverSolutionCallback() { public CpSolverSolutionCallback init(IntVar[] variables) { variableArray = variables; return this; } @Override public void onSolutionCallback() { for (IntVar v : variableArray) { System.out.printf("%s=%d ", v.getName(), value(v)); } System.out.println(); } private IntVar[] variableArray; }.init(new IntVar[] {x, expr})); } }
3,589
34.544554
90
java
or-tools
or-tools-master/ortools/sat/samples/StopAfterNSolutionsSampleSat.java
// Copyright 2010-2021 Google LLC // 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. // [START program] package com.google.ortools.sat.samples; import com.google.ortools.Loader; import com.google.ortools.sat.CpModel; import com.google.ortools.sat.CpSolver; import com.google.ortools.sat.CpSolverSolutionCallback; import com.google.ortools.sat.IntVar; /** Code sample that solves a model and displays a small number of solutions. */ public final class StopAfterNSolutionsSampleSat { static class VarArraySolutionPrinterWithLimit extends CpSolverSolutionCallback { public VarArraySolutionPrinterWithLimit(IntVar[] variables, int limit) { variableArray = variables; solutionLimit = limit; } @Override public void onSolutionCallback() { System.out.printf("Solution #%d: time = %.02f s%n", solutionCount, wallTime()); for (IntVar v : variableArray) { System.out.printf(" %s = %d%n", v.getName(), value(v)); } solutionCount++; if (solutionCount >= solutionLimit) { System.out.printf("Stop search after %d solutions%n", solutionLimit); stopSearch(); } } public int getSolutionCount() { return solutionCount; } private int solutionCount; private final IntVar[] variableArray; private final int solutionLimit; } public static void main(String[] args) { Loader.loadNativeLibraries(); // Create the model. CpModel model = new CpModel(); // Create the variables. int numVals = 3; IntVar x = model.newIntVar(0, numVals - 1, "x"); IntVar y = model.newIntVar(0, numVals - 1, "y"); IntVar z = model.newIntVar(0, numVals - 1, "z"); // Create a solver and solve the model. CpSolver solver = new CpSolver(); VarArraySolutionPrinterWithLimit cb = new VarArraySolutionPrinterWithLimit(new IntVar[] {x, y, z}, 5); // Tell the solver to enumerate all solutions. solver.getParameters().setEnumerateAllSolutions(true); // And solve. solver.solve(model, cb); System.out.println(cb.getSolutionCount() + " solutions found."); if (cb.getSolutionCount() != 5) { throw new RuntimeException("Did not stop the search correctly."); } } private StopAfterNSolutionsSampleSat() {} } // [END program]
2,793
33.073171
85
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/BeanBuilder.java
package edu.ncsu.csc.itrust; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; /** * Takes a parameter map and creates a bean from that map of the appropriate type. * @param <T> The type to be returned from the appropriate parameter map. */ public class BeanBuilder<T> { /** * The code here is not obvious, but this method should not need rewriting unless a bug is found * * @param map - * typically a request.getParameterMap; also can be a HashMap * @param bean - * an instantiated bean to be loaded. Loaded bean is returned. * @return a loaded "bean" * @throws Exception - * Several exceptions are thrown here, so promotion seemed fitting */ // this warning is only suppressed because Map isn't parameterized (old JSP) @SuppressWarnings("rawtypes") public T build(Map map, T bean) throws Exception { // JavaBeans should not have overloaded methods, according to their API // (a stupid limitation!) // Nevertheless, we should check for it checkOverloadedMethods(bean); // Use an introspector to find all of the getXXX or setXXX, we only want // the setXXX PropertyDescriptor[] propertyDescriptors = Introspector.getBeanInfo(bean.getClass()) .getPropertyDescriptors(); for (PropertyDescriptor descriptor : propertyDescriptors) { // if object is null, either it was ignored or empty - just go with // bean's default String[] value = (String[]) map.get(descriptor.getName()); Method writeMethod = descriptor.getWriteMethod(); if (!"class".equals(descriptor.getName()) && value != null && writeMethod != null) { // descriptor's name is the name of your property; like // firstName // only take the first string try { // Skip the setters for enumerations if (writeMethod.getParameterTypes()[0].getEnumConstants() == null) writeMethod.invoke(bean, new Object[] { value[0] }); } catch (IllegalArgumentException e) { // Throw a more informative exception throw new IllegalArgumentException(e.getMessage() + " with " + writeMethod.getName() + " and " + value[0]); } } } return bean; } /** * Checks for overloaded methods * * @param bean item to check */ private void checkOverloadedMethods(T bean) { Method[] methods = bean.getClass().getDeclaredMethods(); HashMap<String, String> nameMap = new HashMap<String, String>(methods.length); for (Method method : methods) { if (nameMap.get(method.getName()) != null) throw new IllegalArgumentException(bean.getClass().getName() + " should not have any overloaded methods, like " + method.getName()); if (!("equals".equals(method.getName())||"compareTo".equals(method.getName()))) // allow an equals, compareTo override nameMap.put(method.getName(), "exists"); } } }
2,911
36.333333
121
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/CSVParser.java
package edu.ncsu.csc.itrust; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.util.*; import edu.ncsu.csc.itrust.exception.CSVFormatException; import edu.ncsu.csc.itrust.exception.ErrorList; /** * Provides a generic CSV parsing framework. * Implemented for patient file importing. */ //@SuppressWarnings("unused") public class CSVParser { /** * Holds the header fields from the top of the CSV file */ private ArrayList<String> CSVHeader=new ArrayList<String>(); /** * Holds the fields and records from the CSV file */ private ArrayList<ArrayList<String>> CSVData=new ArrayList<ArrayList<String>>(); /** * Holds a list of errors accumulated while parsing the CSV file. */ private ErrorList errors=new ErrorList(); /** * Constructor taking an InputStream * * @param csvstream csvstream * @throws CSVFormatException */ public CSVParser(InputStream csvstream) throws CSVFormatException{ Scanner CSVScanner = null; try { //First try at UTF-8 CSVScanner = new Scanner(new InputStreamReader(csvstream, "UTF-8")); } catch (UnsupportedEncodingException e) { try { //Try the default CSVScanner = new Scanner(new InputStreamReader(csvstream, Charset.defaultCharset().displayName())); } catch (UnsupportedEncodingException e1) { throw new CSVFormatException("Encoding errors!"); } } parseCSV(CSVScanner); } /** * Constructor taking an already-prepared Scanner * (For testing purposes) * * @param CSVScanner CSVScanner * @throws CSVFormatException */ public CSVParser(Scanner CSVScanner) throws CSVFormatException{ parseCSV(CSVScanner); } /** * Returns the ArrayList of Strings containing the CSV header fields * * @return ArrayList of Strings containing CSV header fields */ public ArrayList<String> getHeader(){ return CSVHeader; } /** * Returns the ArrayList of ArrayLists of Strings containing the CSV data fields * * @return ArrayList of ArrayLists Strings containing CSV data fields */ public ArrayList<ArrayList<String>> getData(){ return CSVData; } /** * Returns the ErrorList of errors accumulated while parsing CSV * * @return ErrorList of errors accumulated while parsing CSV */ public ErrorList getErrors(){ return errors; } /** * Parses the CSV file line-by-line. * * @param CSVScanner A scanner to a CSV stream. * @throws CSVFormatException */ private void parseCSV(Scanner CSVScanner) throws CSVFormatException{ String currentLine; ArrayList<String> parsedLine=null; //The number of fields (columns) in the CSV file as determined by the number of headers int numFields=0; //The current line number being processed (Used to report the line number of errors) int currentLineNumber=1; //Attempt to read the first line (the header) from the file if(CSVScanner.hasNextLine()){ currentLine=CSVScanner.nextLine(); CSVHeader=parseCSVLine(currentLine); numFields=CSVHeader.size(); //If it does not exist (or if the file isn't a text file at all), the entire process fails }else{ throw new CSVFormatException("File is not valid CSV file."); } //Read the file line-by-line and call the line parser for each line while(CSVScanner.hasNextLine()){ currentLineNumber++; currentLine=CSVScanner.nextLine(); try{ parsedLine=parseCSVLine(currentLine); //If the line doesn't have the right number of fields, it is ignored if(parsedLine.size()==numFields){ CSVData.add(parsedLine); }else{ errors.addIfNotNull("Field number mismatch on line "+currentLineNumber); } //If the line is otherwise invalid, it is also ignored }catch(CSVFormatException e){ errors.addIfNotNull(e.getMessage()+" on line "+currentLineNumber); } } } /** * Parses the passed line character-by-character * * @param line Line from the CSV file to parse * @return ArrayList of Strings, each containing the data from one field * @throws CSVFormatException */ private ArrayList<String> parseCSVLine(String line) throws CSVFormatException{ //Contains the fields from each line parsed ArrayList<String> aLine=new ArrayList<String>(); //Contains the data from the current field being read String currentField=""; //Contains the status of whether or not the parser is inside a quoted area //Used to handle commas and other special characters within the field. boolean insideQuotes=false; //Read the line character-by-character for(int i=0; i<line.length(); i++){ //Comma denotes the end of the current field unless it is quoted if(line.charAt(i)==',' && !insideQuotes){ aLine.add(currentField); currentField=""; //If the field is not ending }else{ //If the character is a ", ignore it and flip the quote status if(line.charAt(i)=='"'){ insideQuotes=!insideQuotes; //Otherwise, add the character to the string }else{ currentField=currentField+line.substring(i, i+1); } } } //If the line parser ends while still inside a quoted section, the input line was invalid if(insideQuotes){ throw new CSVFormatException("Line ended while inside quotes"); } //Grab text from last field too, since the last field does not end with a comma aLine.add(currentField); return aLine; } }
5,387
29.269663
103
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/DBUtil.java
package edu.ncsu.csc.itrust; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Provides a few database utilities * * * */ public class DBUtil { /** * Used to check if we can actually obtain a connection. * * @return */ public static boolean canObtainProductionInstance() { try { DAOFactory.getProductionInstance().getConnection().close(); return true; } catch (SQLException e) { System.out.println(e); return false; } } /** * Close the prepared statement and the connection in a proper way * * @param conn * @param ps */ public static void closeConnection(Connection conn, PreparedStatement ps) { try { if (ps != null){ ps.close(); } } catch (SQLException e) { System.err.println("Error closing connections"); } finally{ try{ if (conn != null){ conn.close(); } } catch (SQLException e) { System.err.println("Error closing connections"); } } } /** * Returns the last ID that was generated for an auto-increment column. Please note that this does NOT * cause transaction problems! last_insert_id() returns the last generated ID on a per-connection basis. * See the MySQL documentation at the following location to confirm this: * {@link http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html} * * Don't believe me? see {@link AutoIncrementTest} * * @param conn * @return last generated id * @throws SQLException * @throws DBException */ public static long getLastInsert(Connection conn) throws SQLException, DBException { ResultSet rs = conn.createStatement().executeQuery("SELECT LAST_INSERT_ID()"); rs.next(); long result = rs.getLong(1); rs.close(); return result; } }
1,939
21.55814
105
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/DateUtil.java
package edu.ncsu.csc.itrust; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; /** * Provides a few extra date utilities * * :) * */ public class DateUtil { public static final long YEAR_IN_MS = 1000L * 60L * 60L * 24L * 365L; /** * Returns a MM/dd/yyyy format of the date for the given years ago * * @param years * @return */ public static String yearsAgo(long years) { Calendar rightNow = Calendar.getInstance(); rightNow.set(Calendar.YEAR, rightNow.get(Calendar.YEAR) - (int)(years)); return new SimpleDateFormat("MM/dd/yyyy").format(rightNow.getTime()); } /** * Checks to see if a given date is within a range of months <strong>INCLUSIVELY</strong>, agnostic of * the year. <br /> * <br /> * * The range "wraps" so that if the first month is after the second month, then the definition of "is in * month range" is:<br /> * the date falls outside of secondMonth, firstMonth, but including secondMonth and firstMonth. * * Modular arithmetic is used to adjust month values into the valid range. * * @param date * @param firstMonth * @param secondMonth * @return */ public static boolean isInMonthRange(java.util.Date date, int firstMonth, int secondMonth) { Calendar cal = new GregorianCalendar(); cal.setTime(date); firstMonth %= 12; secondMonth %= 12; if (secondMonth >= firstMonth) { return ((cal.get(Calendar.MONTH) >= firstMonth) && (cal.get(Calendar.MONTH) <= secondMonth)); } return ((cal.get(Calendar.MONTH) >= firstMonth) || (cal.get(Calendar.MONTH) <= secondMonth)); } /** * Same as isInMonthRange but uses the current date as the date value. * * @see DateUtil#isInMonthRange(Date, int, int) * @param firstMonth * @param secondMonth * @return */ public static boolean currentlyInMonthRange(int firstMonth, int secondMonth) { return isInMonthRange(new Date(), firstMonth, secondMonth); } /** * Returns the date a certain number of years ago * @param years how many years ago * @return the date it was however many years ago */ public static Date getDateXyearsAgoFromNow(int years) { Calendar cal = new GregorianCalendar(); cal.add(Calendar.YEAR, -years); return cal.getTime(); } /** * Returns the date a certain number of years ago * @param years how many years ago * @return the date it was however many years ago */ public static java.sql.Date getSQLdateXyearsAgoFromNow(int years) { return new java.sql.Date(getDateXyearsAgoFromNow(years).getTime()); } /** * Returns the date a certain number of days ago * @param days how many days ago * @return the date it was however many days ago */ public static Date getDateXDaysAgoFromNow(int days) { Calendar cal = new GregorianCalendar(); cal.add(Calendar.DAY_OF_YEAR, -days); return cal.getTime(); } /** * Returns the date a certain number of days ago * @param days how many days ago * @return the date it was however many days ago */ public static java.sql.Date getSQLdateXDaysAgoFromNow(int days) { return new java.sql.Date(getDateXDaysAgoFromNow(days).getTime()); } /** * <!--Pass in INSTANTIATED sql date objects and they will be set to the specified range, ie, FROM * <current year> - yearsAgo1/monthValue1/01 TO <current year> - yearsAgo2/monthValue2/<last day of * month2>--> Pass in INSTANTIATED sql date objects and they will be set to the specified range, ie, FROM * &lt;current year&gt; - yearsAgo1/monthValue1/01 TO &lt;current year&gt; - * yearsAgo2/monthValue2/&lt;last day of month2&gt; * * @param month1 * First sql.Date object to be set * @param monthValue1 * @param yearsAgo1 * @param month2 * Second sql.Date object to be set * @param monthValue2 * @param yearsAgo2 */ public static void setSQLMonthRange(java.sql.Date month1, int monthValue1, int yearsAgo1, java.sql.Date month2, int monthValue2, int yearsAgo2) { GregorianCalendar cal = new GregorianCalendar(); cal.add(Calendar.YEAR, -yearsAgo1); cal.set(Calendar.MONTH, monthValue1); cal.set(Calendar.DAY_OF_MONTH, 1); month1.setTime(cal.getTimeInMillis()); cal.add(Calendar.YEAR, yearsAgo1); cal.add(Calendar.YEAR, -yearsAgo2); cal.set(Calendar.MONTH, monthValue2); cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH)); month2.setTime(cal.getTimeInMillis()); } }
4,440
31.181159
106
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/EmailUtil.java
package edu.ncsu.csc.itrust; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Sends email to users. Since we don't want to train spammers in 326, this just inserts into a database. If * we put this into an actual system, we would replace this class with stuff from javax.mail * * */ public class EmailUtil { private DAOFactory factory; public EmailUtil(DAOFactory factory) { this.factory = factory; } // DO NOT SEND REAL EMAILS!!!!! // Sending emails - even to a throwaway account, is a waste of bandwidth and looks very suspicious. // If you want to know how to send emails from Java, just Google it on your own time. public void sendEmail(Email email) throws DBException { factory.getFakeEmailDAO().sendEmailRecord(email); } }
863
31
108
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/HtmlEncoder.java
package edu.ncsu.csc.itrust; /** * Escapes a few key HTML characters and does some other checking * * * */ public class HtmlEncoder { /** * Escapes a few key HTML characters * @param input String to check and escape * @return */ public static String encode(String input) { if (input == null) return input; String str = input.replaceAll("<", "&lt;"); str = str.replaceAll(">", "&gt;"); str = str.replaceAll("\n", "<br />"); return str; } /** * Checks URL * * @param input URL to check * @return false if the input contains http://, true otherwise */ public static boolean URLOnSite(String input) { return !(input.contains("http://")); } }
690
19.323529
65
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/Localization.java
package edu.ncsu.csc.itrust; import java.util.Locale; /** Provides a singleton for accessing the current locale of iTrust * Could possibly load the country and language from a file. */ public class Localization { private Locale currentLocale; /** * Localization */ public Localization(){ currentLocale = new Locale("en", "US"); } /** * Returns the current locale * @return the current locale */ public Locale getCurrentLocale(){ return currentLocale; } static Localization currentInstance = null; /** * singleton method, may want to make this thread safe, as far as I know * iTrust doesn't do any multithreading though... * @return Localization instance */ public static Localization instance(){ if(currentInstance == null){ currentInstance = new Localization(); } return currentInstance; } }
847
20.2
73
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/Messages.java
package edu.ncsu.csc.itrust; import java.util.MissingResourceException; import java.util.ResourceBundle; /** */ public class Messages { private static final String BUNDLE_NAME = "edu.ncsu.csc.itrust.messages"; //$NON-NLS-1$ private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME, Localization.instance().getCurrentLocale()); /** * getString * @param key key * @return !key! */ public static String getString(String key) { try { return RESOURCE_BUNDLE.getString(key); } catch (MissingResourceException e) { return '!' + key + '!'; } } }
603
21.37037
137
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/ParameterUtil.java
package edu.ncsu.csc.itrust; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Provides a utility method that converts the "Map" from the JSP container to a type-checked hashmap */ public class ParameterUtil { /** * Provides a utility method that converts the "Map" from the JSP container to a type-checked hashmap * @param params Map to convert * @return converted Map */ public static HashMap<String, String> convertMap(Map<?, ?> params) { HashMap<String, String> myMap = new HashMap<String, String>(); for (Entry<?, ?> entry : params.entrySet()) { String[] value = ((String[]) entry.getValue()); if (value != null) myMap.put(entry.getKey().toString(), value[0]); else myMap.put(entry.getKey().toString(), null); } return myMap; } }
807
27.857143
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/RandomPassword.java
package edu.ncsu.csc.itrust; import java.util.Random; /** * Generates a random string of characters * * * */ public class RandomPassword { private static final Random rand = new Random(); /** * Returns a string of random characters * * @return a string of random characters */ public static String getRandomPassword() { StringBuffer buf = new StringBuffer(); for (int i = 0; i < 10; i++) { buf.append((char) (rand.nextInt(26) + 'a')); } return buf.toString(); } }
500
17.555556
49
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/XmlGenerator.java
package edu.ncsu.csc.itrust; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import org.w3c.dom.Document; import org.w3c.dom.Element; import java.util.ArrayList; /** * XmlGenerator is a class that takes headers and data and converts them into a xml compliant document. */ public class XmlGenerator{ /** * generateXml converts the headers and data into a xml file * * @param headers - Column names * @param Data - Data for columns * @return - Xml document */ public static Document generateXml(ArrayList<String> headers, ArrayList<ArrayList<String>> Data){ Document report; try{ //sorced from http://stackoverflow.com/questions/8865099/xml-file-generator-in-java DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); //new document report = builder.newDocument(); //head element Element head = report.createElement("PatientReport"); report.appendChild(head); //assumed has document builder and factory for (int x = 0; x < Data.size(); x++)//for each top level element { // makes format <Patient name="blah" age="xx" birthdate=""/> etc... Element patient = report.createElement("Patient"); for (int y = 0; ((y < Data.get(x).size()) && (y < headers.size())); y++) { patient.setAttribute(parse(headers.get(y)), parse(Data.get(x).get(y))); } head.appendChild(patient); } //for each first level element, loop through second level and } catch (ParserConfigurationException e){ //TODO log error return null; } return report; } /** * Parses the string for a xml compliant one * @param s - The string to be fixed * @return - The xml compliant string */ private static String parse(String s){ return s.replaceAll(" ", "_").replaceAll("#", "NUMBER").replaceAll("'", ""); } }
1,987
27.811594
103
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ActivityFeedAction.java
package edu.ncsu.csc.itrust.action; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Handles retrieving the log of record accesses for a given user Used by viewAccessLog.jsp */ public class ActivityFeedAction { private TransactionDAO transDAO; private PatientDAO patientDAO; private AuthDAO authDAO; private long loggedInMID; /** * Set up * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person retrieving the logs. */ public ActivityFeedAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.transDAO = factory.getTransactionDAO(); this.authDAO = factory.getAuthDAO(); this.patientDAO = factory.getPatientDAO(); } /** * Returns a list of TransactionBeans between the two dates passed as params * @param time time * @param n Number of "pages" of 20 log entries to retrieve. * @return list of 20*n TransactionBeans * @throws DBException * @throws FormValidationException */ public List<TransactionBean> getTransactions(Date time, int n) throws DBException, FormValidationException { List<PersonnelBean> dlhcps = patientDAO.getDeclaredHCPs(loggedInMID); //user has either 0 or 1 DLHCP's. Get one if exists so it can be filtered from results long dlhcpID = -1; if(!dlhcps.isEmpty()) dlhcpID = dlhcps.get(0).getMID(); List<TransactionBean> fullList = transDAO.getTransactionsAffecting(loggedInMID, dlhcpID, time, 20*n+1); return fullList; } /** * Returns an indicator of the number of days between the current date and the date passed * as a parameter. Returns 0 if the dates are on the same day, 1 if the date passed in is * "yesterday", 2 otherwise. * * @param d date * @return 0, 1, or 2, depending on the difference in the dates. */ public static int recent(Date d) { int oneDay = 24 * 60 * 60 * 1000; DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); Date rightNow = new Date(); if (sdf.format(rightNow).equals(sdf.format(d))) return 0; d.setTime(d.getTime() + oneDay); if (sdf.format(rightNow).equals(sdf.format(d))) return 1; return 2; } /** * Pulls Action Phrase from the associated TransactionType Enum * Forms an English sentence with actor, action, and timestamp. * @param actor actor * @param timestamp timestamp * @param code code * @return */ public String getMessageAsSentence(String actor, Timestamp timestamp, TransactionType code) { String result = actor + " "; StringBuffer buf = new StringBuffer(); for (TransactionType type : TransactionType.values()) { if (code.getCode() == type.getCode() && type.isPatientViewable()) buf.append(type.getActionPhrase()); } result += buf.toString(); SimpleDateFormat formatter = new SimpleDateFormat("h:mma."); switch(recent(new Date(timestamp.getTime()))) { case 0: result += " today"; break; case 1: result += " yesterday"; break; case 2: DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); result += " on " + sdf.format(new Date(timestamp.getTime())); break; default: break; } result += " at " + formatter.format(timestamp); return replaceNameWithYou(result); } private String replaceNameWithYou(String activity) { try{ return activity.replace(authDAO.getUserName(loggedInMID), "You"); } catch(Exception e) { return activity; } } }
4,033
28.881481
105
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddApptAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.sql.Timestamp; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.ApptBeanValidator; public class AddApptAction extends ApptAction { private ApptBeanValidator validator = new ApptBeanValidator(); private long loggedInMID; public AddApptAction(DAOFactory factory, long loggedInMID) { super(factory, loggedInMID); this.loggedInMID = loggedInMID; } public String addAppt(ApptBean appt, boolean ignoreConflicts) throws FormValidationException, SQLException, DBException { validator.validate(appt); if(appt.getDate().before(new Timestamp(System.currentTimeMillis()))) { return "The scheduled date of this Appointment ("+appt.getDate()+") has already passed."; } if(!ignoreConflicts){ if(getConflictsForAppt(appt.getHcp(), appt).size()>0){ return "Warning! This appointment conflicts with other appointments"; } } try { apptDAO.scheduleAppt(appt); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_ADD, loggedInMID, appt.getPatient(), ""); if(ignoreConflicts){ TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_CONFLICT_OVERRIDE, loggedInMID, appt.getPatient(), ""); } return "Success: " + appt.getApptType() + " for " + appt.getDate() + " added"; } catch (SQLException e) { return e.getMessage(); } } }
1,739
32.461538
134
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddApptRequestAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.beans.ApptRequestBean; import edu.ncsu.csc.itrust.model.old.beans.ApptTypeBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptRequestDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptTypeDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * * */ public class AddApptRequestAction { private ApptDAO aDAO; private ApptRequestDAO arDAO; private ApptTypeDAO atDAO; public AddApptRequestAction(DAOFactory factory) { aDAO = factory.getApptDAO(); arDAO = factory.getApptRequestDAO(); atDAO = factory.getApptTypeDAO(); } public String addApptRequest(ApptRequestBean bean) throws SQLException, DBException { return addApptRequest(bean, 0L, 0L); } public String addApptRequest(ApptRequestBean bean, long loggedInMID, long hcpid) throws SQLException, DBException { List<ApptBean> conflicts = aDAO.getAllHCPConflictsForAppt(bean.getRequestedAppt().getHcp(), bean.getRequestedAppt()); if (conflicts != null && !conflicts.isEmpty()) { return "The appointment you requested conflicts with other existing appointments."; } arDAO.addApptRequest(bean); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_REQUEST_SUBMITTED, loggedInMID, hcpid, ""); return "Your appointment request has been saved and is pending."; } public List<ApptBean> getNextAvailableAppts(int num, ApptBean bean) throws SQLException, DBException { List<ApptBean> appts = new ArrayList<ApptBean>(num); for (int i = 0; i < num; i++) { ApptBean b = new ApptBean(); b.setApptType(bean.getApptType()); b.setHcp(bean.getHcp()); b.setPatient(bean.getPatient()); b.setDate(new Timestamp(bean.getDate().getTime())); List<ApptBean> conflicts = null; do { conflicts = aDAO.getAllHCPConflictsForAppt(b.getHcp(), b); if (conflicts != null && !conflicts.isEmpty()) { ApptBean lastConflict = conflicts.get(conflicts.size() - 1); Timestamp afterConflict = endTime(lastConflict); b.setDate(afterConflict); } } while (!conflicts.isEmpty()); appts.add(b); Timestamp nextTime = endTime(b); bean.setDate(nextTime); } return appts; } private Timestamp endTime(ApptBean bean) throws SQLException, DBException { Timestamp d = new Timestamp(bean.getDate().getTime()); ApptTypeBean type = atDAO.getApptType(bean.getApptType()); d.setTime(d.getTime() + type.getDuration() * 60L * 1000); return d; } }
2,868
31.602273
120
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddDrugListAction.java
package edu.ncsu.csc.itrust.action; import java.io.IOException; import java.io.InputStream; import java.util.Scanner; import java.util.StringTokenizer; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.NDCodesDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class AddDrugListAction { private DrugStrategy strategy; private DAOFactory factory; private EventLoggingAction loggingAction; private long loggedInMID; public AddDrugListAction (DrugStrategy uploadStrategy, DAOFactory factory, EventLoggingAction loggingAction, long loggedInMID) { this.strategy = uploadStrategy; this.factory = factory; this.loggingAction = loggingAction; this.loggedInMID = loggedInMID; } /** * Loads the given file input stream into the drug database. * @param fileContent * @throws IOException */ public void loadFile(InputStream fileContent) throws IOException, DBException { strategy.loadFile(fileContent, factory, loggingAction, loggedInMID); } public interface DrugStrategy { void loadFile(InputStream fileContent, DAOFactory factory, EventLoggingAction loggingAction, long loggedInMID) throws IOException, DBException; } public static class SkipDuplicateDrugStrategy implements DrugStrategy { @Override public void loadFile(InputStream fileContent, DAOFactory factory, EventLoggingAction loggingAction, long loggedInMID) throws IOException, DBException { NDCodesDAO ndcodesDAO = factory.getNDCodesDAO(); Scanner fileScanner = new Scanner(fileContent, "UTF-8"); while(fileScanner.hasNextLine()) { String ndCodeWithDash; MedicationBean bean = new MedicationBean(); StringTokenizer tok = new StringTokenizer(fileScanner.nextLine(), "\t"); ndCodeWithDash = tok.nextToken(); String parts[] = ndCodeWithDash.split("-"); //Skip drug type field tok.nextToken(); bean.setNDCode(parts[0].concat(parts[1])); bean.setDescription(tok.nextToken()); try { ndcodesDAO.addNDCode(bean); loggingAction.logEvent(TransactionType.DRUG_CODE_ADD, loggedInMID, 0, "" + bean.getNDCode() + bean.getDescription()); } catch (ITrustException e) { //We just want to skip duplicate-entries. Let it pass. e.printStackTrace(); } } fileScanner.close(); } } public static class OverwriteDuplicateDrugStrategy implements DrugStrategy { @Override public void loadFile(InputStream fileContent, DAOFactory factory, EventLoggingAction loggingAction, long loggedInMID) throws IOException, DBException { NDCodesDAO ndcodesDAO = factory.getNDCodesDAO(); Scanner fileScanner = new Scanner(fileContent, "UTF-8"); while(fileScanner.hasNextLine()) { String ndCodeWithDash; MedicationBean bean = new MedicationBean(); StringTokenizer tok = new StringTokenizer(fileScanner.nextLine(), "\t"); ndCodeWithDash = tok.nextToken(); String parts[] = ndCodeWithDash.split("-"); //Skip drug type field tok.nextToken(); bean.setNDCode(parts[0].concat(parts[1])); bean.setDescription(tok.nextToken()); try { ndcodesDAO.addNDCode(bean); loggingAction.logEvent(TransactionType.DRUG_CODE_ADD, loggedInMID, 0, "" + bean.getNDCode() + " - " + bean.getDescription()); } catch (ITrustException e) { //Overwrite duplicate entries ndcodesDAO.updateCode(bean); loggingAction.logEvent(TransactionType.DRUG_CODE_EDIT, loggedInMID, 0, "" + bean.getNDCode() + " - " + bean.getDescription()); } } fileScanner.close(); } } }
3,769
34.233645
153
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddERespAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; /** * Used for Add Personnel page (addPersonnel.jsp). This just adds an empty HCP/UAP, creates a random password * for them. * * Very similar to {@link AddOfficeVisitAction} and {@link AddPatientAction} * * Copied from AddHCPAction */ public class AddERespAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; private long loggedInMID; /** * Sets up the defaults for the class * * @param factory factory for creating the defaults. * @param loggedInMID person currently logged in */ public AddERespAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Adds the new user. Event is logged. * * @param p bean containing the information for the new user * @return MID of the new user. * @throws FormValidationException * @throws ITrustException */ public long add(PersonnelBean p) throws FormValidationException, ITrustException { new AddPersonnelValidator().validate(p); long newMID = personnelDAO.addEmptyPersonnel(Role.ER); p.setMID(newMID); personnelDAO.editPersonnel(p); String pwd = authDAO.addUser(newMID, Role.ER, RandomPassword.getRandomPassword()); p.setPassword(pwd); TransactionLogger.getInstance().logTransaction(TransactionType.ER_CREATE, loggedInMID, p.getMID(), ""); return newMID; } }
2,059
32.770492
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddHCPAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; /** * Used for Add Personnel page (addPersonnel.jsp). This just adds an empty HCP/UAP, creates a random password * for them. * * Very similar to {@link AddOfficeVisitAction} and {@link AddPatientAction} * * */ public class AddHCPAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; private long loggedInMID; /** * Sets up the defaults for the class * * @param factory factory for creating the defaults. * @param loggedInMID person currently logged in */ public AddHCPAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Adds the new user. Event is logged. * * @param p bean containing the information for the new user * @return MID of the new user. * @throws FormValidationException * @throws ITrustException */ public long add(PersonnelBean p) throws FormValidationException, ITrustException { new AddPersonnelValidator().validate(p); long newMID = personnelDAO.addEmptyPersonnel(Role.HCP); p.setMID(newMID); personnelDAO.editPersonnel(p); String pwd = authDAO.addUser(newMID, Role.HCP, RandomPassword.getRandomPassword()); p.setPassword(pwd); TransactionLogger.getInstance().logTransaction(TransactionType.LHCP_CREATE, loggedInMID, p.getMID(), ""); return newMID; } }
2,044
33.661017
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddLTAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; /** * Used for Add Personnel page (addPersonnel.jsp). This just adds an empty LT, creates a random password * for them. * * */ public class AddLTAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; /** * Sets up the defaults for the class * * @param factory factory for creating the defaults. * @param loggedInMID person currently logged in */ public AddLTAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.authDAO = factory.getAuthDAO(); } /** * Adds the new user. Event is logged. * * @param p bean containing the information for the new user * @return MID of the new user. * @throws FormValidationException * @throws ITrustException */ public long add(PersonnelBean p) throws FormValidationException, ITrustException { new AddPersonnelValidator().validate(p); long newMID = personnelDAO.addEmptyPersonnel(Role.LT); p.setMID(newMID); personnelDAO.editPersonnel(p); String pwd = authDAO.addUser(newMID, Role.LT, RandomPassword.getRandomPassword()); p.setPassword(pwd); return newMID; } }
1,665
30.433962
104
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddPHAAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; /** * Used for Add Personnel page (addPersonnel.jsp). This just adds an empty PHA, creates a random password * for them. * * Very similar to {@link AddOfficeVisitAction} and {@link AddPatientAction} * */ public class AddPHAAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; private long loggedInMID; /** * Sets up the defaults for the class * * @param factory factory for creating the defaults. * @param loggedInMID person currently logged in */ public AddPHAAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Adds the new user. Event is logged. * * @param p bean containing the information for the new user * @return MID of the new user. * @throws FormValidationException * @throws ITrustException */ public long add(PersonnelBean p) throws FormValidationException, ITrustException { new AddPersonnelValidator().validate(p); long newMID = personnelDAO.addEmptyPersonnel(Role.PHA); p.setMID(newMID); personnelDAO.editPersonnel(p); String pwd = authDAO.addUser(newMID, Role.PHA, RandomPassword.getRandomPassword()); p.setPassword(pwd); TransactionLogger.getInstance().logTransaction(TransactionType.PHA_CREATE, loggedInMID, p.getMID(), ""); return newMID; } }
2,030
33.423729
106
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddPatientAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.AddPatientValidator; /** * Used for Add Patient page (addPatient.jsp). This just adds an empty patient, creates a random password for * that patient. * * Very similar to {@link AddOfficeVisitAction} * * */ public class AddPatientAction { private PatientDAO patientDAO; private AuthDAO authDAO; private long loggedInMID; /** * Just the factory and logged in MID * * @param factory * @param loggedInMID */ public AddPatientAction(DAOFactory factory, long loggedInMID) { this.patientDAO = factory.getPatientDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Creates a new patient, returns the new MID. Adds a new user to the table with a * specified dependency * * @param p patient to be created * @param isDependent true if the patient is to be a dependent, false otherwise * @return the new MID of the patient * @throws FormValidationException if the patient is not successfully validated * @throws ITrustException */ public long addDependentPatient(PatientBean p, long repId, long loggedInMID) throws FormValidationException, ITrustException { new AddPatientValidator().validate(p); long newMID = patientDAO.addEmptyPatient(); boolean isDependent = true; p.setMID(newMID); String pwd = authDAO.addUser(newMID, Role.PATIENT, RandomPassword.getRandomPassword()); patientDAO.addRepresentative(repId, newMID); authDAO.setDependent(newMID, isDependent); p.setPassword(pwd); patientDAO.editPatient(p, loggedInMID); TransactionLogger.getInstance().logTransaction(TransactionType.HCP_CREATED_DEPENDENT_PATIENT, loggedInMID, p.getMID(), ""); return newMID; } public long addPatient(PatientBean p, long loggedInMID) throws FormValidationException, ITrustException { new AddPatientValidator().validate(p); long newMID = patientDAO.addEmptyPatient(); p.setMID(newMID); String pwd = authDAO.addUser(newMID, Role.PATIENT, RandomPassword.getRandomPassword()); p.setPassword(pwd); patientDAO.editPatient(p, loggedInMID); TransactionLogger.getInstance().logTransaction(TransactionType.PATIENT_CREATE, loggedInMID, p.getMID(), ""); return newMID; } }
2,822
35.662338
127
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddPatientFileAction.java
package edu.ncsu.csc.itrust.action; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import edu.ncsu.csc.itrust.CSVParser; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.AddPatientFileException; import edu.ncsu.csc.itrust.exception.CSVFormatException; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.validate.AddPatientValidator; import edu.ncsu.csc.itrust.model.old.validate.PatientValidator; /** * Used for Upload Patient File page (uploadPatientFile.jsp). */ public class AddPatientFileAction { /** * Holds the accumulated list of errors from the CSVParser and this class */ private ErrorList errors; /** * Holds the CSV header from the CSVParser */ private ArrayList<String> CSVHeader; /** * Holds the CSV data from the CSVParser */ private ArrayList<ArrayList<String>> CSVData; /** * Holds the list of PatientBeans for passing back to the UI */ private ArrayList<PatientBean> patients=new ArrayList<PatientBean>(); /** * List of fields required to be in the CSV */ private String[] requiredFields={"firstName", "lastName", "email"}; /** * List of valid fields which can be included in the CSV */ private String[] validFields={"streetAddress1", "streetAddress2", "city", "state", "zip", "phone", "motherMID", "fatherMID", "creditCardType", "creditCardNumber"}; /** * Array to map the required field lists above to the uploaded CSV header list (which may be in any order) */ private Integer requiredFieldsMapping[] = new Integer[3]; /** * Array to map the valid field lists above to the uploaded CSV header list (which may be in any order) */ private Integer validFieldsMapping[] = new Integer[13]; /** * PatientDAO used to add patients to the DB */ private PatientDAO patientDAO; /** * AuthDAO to provide authorization for the patient actions */ private AuthDAO authDAO; /** * MID of the HCP performing the request */ private long loggedInMID; /** * Accepts the DAO factory and the CSV stream from the view and parses it. * * @param factory The DAO factory * @param loggedInMID The MID of the HCP * @param CSVStream The CSV stream uploaded by the user * @throws CSVFormatException */ public AddPatientFileAction(InputStream CSVStream, DAOFactory factory, long loggedInMID) throws CSVFormatException, AddPatientFileException { if(factory!=null){ this.patientDAO = factory.getPatientDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } CSVParser parser = new CSVParser(CSVStream); CSVHeader = parser.getHeader(); CSVData = parser.getData(); errors = parser.getErrors(); buildMappings(CSVHeader); try{ createPatients(); }catch(DBException e){ throw new AddPatientFileException("Database error while adding new patients!"); } } /** * Gets the patient list * * @return ArrayList<PatientBean> The patients from the parsed file */ public ArrayList<PatientBean> getPatients(){ return patients; } /** * Gets the error list * * @return ErrorList All errors encountered while parsing */ public ErrorList getErrors(){ return errors; } /** * Builds the mappings between the local arrays and the CSV file * Also checks for missing required, duplicate, and invalid fields * * @param CSVHeader * @throws AddPatientFileExceptionTest */ private void buildMappings(ArrayList<String> CSVHeader) throws AddPatientFileException{ boolean valid; for(int i=0; i<CSVHeader.size(); i++){ valid=false; for(int j=0; j<requiredFields.length; j++){ if(CSVHeader.get(i).equalsIgnoreCase(requiredFields[j])){ if(requiredFieldsMapping[j]==null){ valid=true; requiredFieldsMapping[j]=i; }else{ throw new AddPatientFileException("Duplicate field \""+CSVHeader.get(i)+"\"!"); } } } for(int j=0; j<validFields.length; j++){ if(CSVHeader.get(i).equalsIgnoreCase(validFields[j])){ if(validFieldsMapping[j]==null){ valid=true; validFieldsMapping[j]=i; }else{ throw new AddPatientFileException("Duplicate field \""+CSVHeader.get(i)+"\"!"); } } } if(valid == false){ throw new AddPatientFileException("Field \""+CSVHeader.get(i)+"\" is invalid!"); } } for(int i=0; i<requiredFieldsMapping.length; i++){ if(requiredFieldsMapping[i]==null){ throw new AddPatientFileException("Required field \""+requiredFields[i]+"\" is missing!"); } } } /** * Creates the patients and adds them to the DB * * @throws DBException * @throws AddPatientFileExceptionTest */ private void createPatients() throws DBException, AddPatientFileException{ for(int i=0; i<CSVData.size(); i++){ PatientBean temp=new PatientBean(); temp.setFirstName(CSVData.get(i).get(requiredFieldsMapping[Arrays.asList(requiredFields).indexOf("firstName")])); temp.setLastName(CSVData.get(i).get(requiredFieldsMapping[Arrays.asList(requiredFields).indexOf("lastName")])); temp.setEmail(CSVData.get(i).get(requiredFieldsMapping[Arrays.asList(requiredFields).indexOf("email")])); try{ temp.setStreetAddress1(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("streetAddress1")])); }catch(NullPointerException e) { //TODO } try{ temp.setStreetAddress2(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("streetAddress2")])); }catch(NullPointerException e) { //TODO } try{ temp.setCity(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("city")])); }catch(NullPointerException e) { //TODO } try{ temp.setState(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("state")])); }catch(NullPointerException e) { //TODO } try{ temp.setZip(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("zip")])); }catch(NullPointerException e) { //TODO } try{ temp.setPhone(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("phone")])); }catch(NullPointerException e) { //TODO } try{ temp.setMotherMID(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("motherMID")])); }catch(NullPointerException e) { //TODO } try{ temp.setFatherMID(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("fatherMID")])); }catch(NullPointerException e) { //TODO } try{ temp.setCreditCardType(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("creditCardType")])); }catch(NullPointerException e){ //TODO } try{ temp.setCreditCardNumber(CSVData.get(i).get(validFieldsMapping[Arrays.asList(validFields).indexOf("creditCardNumber")])); }catch(NullPointerException e) { //TODO } try{ new AddPatientValidator().validate(temp); new PatientValidator().validate(temp); if(patientDAO!=null){ long newMID = patientDAO.addEmptyPatient(); temp.setMID(newMID); String pwd = authDAO.addUser(newMID, Role.PATIENT, RandomPassword.getRandomPassword()); temp.setPassword(pwd); patientDAO.editPatient(temp, loggedInMID); } patients.add(temp); }catch(FormValidationException e){ for(int j=0; j<e.getErrorList().size(); j++){ System.out.println(e.getErrorList().get(j)); } errors.addIfNotNull("Input validation failed for patient \""+temp.getFirstName()+" "+temp.getLastName()+"\"!"); } } } }
7,961
31.234818
142
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddRemoteMonitoringDataAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.RemoteMonitoringDataBean; import edu.ncsu.csc.itrust.model.old.beans.TelemedicineBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.RemoteMonitoringDAO; import edu.ncsu.csc.itrust.model.old.validate.RemoteMonitoringDataBeanValidator; /** * Handles adding remote monitoring patient data to the database * */ public class AddRemoteMonitoringDataAction { private RemoteMonitoringDataBeanValidator validator = new RemoteMonitoringDataBeanValidator(); private RemoteMonitoringDAO rmDAO; private AuthDAO authDAO; private long loggedInMID; private long patientMID; /** * Constructor * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person recording the patient's data. * @param patientMID The MID of the patient */ public AddRemoteMonitoringDataAction(DAOFactory factory, long loggedInMID, long patientMID) { this.loggedInMID = loggedInMID; this.rmDAO = factory.getRemoteMonitoringDAO(); this.authDAO = factory.getAuthDAO(); this.patientMID = patientMID; } public List<TelemedicineBean> getTelemedicineBean(long patientMID) throws DBException { return rmDAO.getTelemedicineBean(patientMID); } /** * Adds a patient's telemedicine data to the database. * * @param weight * @param pedometerReading * @throws DBException */ public void addRemoteMonitoringData(RemoteMonitoringDataBean rmdBean) throws DBException, FormValidationException, ITrustException { validator.validate(rmdBean); String role; if (loggedInMID == patientMID){ role = "self-reported"; } else if (authDAO.getUserRole(loggedInMID).getUserRolesString().equals("uap")){ role = "case-manager"; } else { role = "patient representative"; } //Store in DB rmDAO.storePatientData(patientMID, rmdBean, role, loggedInMID); } /** * returns the patient name * * @return patient name * @throws DBException * @throws ITrustException */ public String getPatientName(long pid) throws ITrustException { return authDAO.getUserName(pid); } }
2,438
30.269231
95
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/AddUAPAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.RandomPassword; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.AddPersonnelValidator; /** * Used for Add Personnel page (addPersonnel.jsp). This just adds an empty HCP/UAP, creates a random password * for them. * * Very similar to {@link AddOfficeVisitAction} and {@link AddPatientAction} * * */ public class AddUAPAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; private long loggedInMID; /** * Sets up the defaults for the class * * @param factory factory for creating the defaults. * @param loggedInMID person currently logged in */ public AddUAPAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Adds the new user. Event is logged. * * @param p bean containing the information for the new user * @return MID of the new user. * @throws FormValidationException * @throws ITrustException */ public long add(PersonnelBean p) throws FormValidationException, ITrustException { new AddPersonnelValidator().validate(p); long newMID = personnelDAO.addEmptyPersonnel(Role.UAP); p.setMID(newMID); personnelDAO.editPersonnel(p); String pwd = authDAO.addUser(newMID, Role.UAP, RandomPassword.getRandomPassword()); p.setPassword(pwd); TransactionLogger.getInstance().logTransaction(TransactionType.UAP_CREATE, loggedInMID, p.getMID(), ""); return newMID; } }
2,033
33.474576
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ApptAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; /** * ApptAction */ public abstract class ApptAction { /**apptDAO*/ protected ApptDAO apptDAO; /**patientDAO*/ protected PatientDAO patientDAO; /**personnelDAO*/ protected PersonnelDAO personnelDAO; /** * ApptAction * @param factory factory * @param loggedInMID loggedMID */ public ApptAction(DAOFactory factory, long loggedInMID) { this.apptDAO = factory.getApptDAO(); this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); } /** * Driver method to get all appointment conflicts, used in jsp files * @param mid mid * @param appt appt * @return conflicts * @throws SQLException * @throws DBException */ public List<ApptBean> getConflictsForAppt(long mid, ApptBean appt) throws SQLException, DBException{ return apptDAO.getAllHCPConflictsForAppt(mid, appt); } /** * returns a list of appointments that conflict for a given patient/hcp * @param mid the MID of the user * @return list of apptBeans * @throws SQLException * @throws DBException */ public List<ApptBean> getAllConflicts(long mid) throws SQLException, DBException{ if(mid < 7000000000L) return apptDAO.getAllConflictsForPatient(mid); else return apptDAO.getAllConflictsForDoctor(mid); } /** * Gets a users's name from their MID * * @param mid the MID of the user * @return the user's name * @throws ITrustException */ public String getName(long mid) throws ITrustException { if(mid < 7000000000L) return patientDAO.getName(mid); else return personnelDAO.getName(mid); } }
2,054
25.688312
101
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ChangePasswordAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Manages resetting the password Used by resetPassword.jsp * * */ public class ChangePasswordAction { private AuthDAO authDAO; /** * Set up defaults * @param factory The DAOFactory used to create the DAOs used in this action. */ public ChangePasswordAction(DAOFactory factory) { this.authDAO = factory.getAuthDAO(); } /** * Changes the password for the given mid * * @param mid of the user to have their password reset * @param oldPass their old password * @param newPass their desired password * @param confirmPass their desired password again * @return status message * @throws FormValidationException * @throws DBException * @throws ITrustException */ public String changePassword(long mid, String oldPass, String newPass, String confirmPass) throws FormValidationException, DBException, ITrustException { String containsLetter = "[a-zA-Z0-9]*[a-zA-Z]+[a-zA-Z0-9]*"; String containsNumber = "[a-zA-Z0-9]*[0-9]+[a-zA-Z0-9]*"; String fiveAlphanumeric = "[a-zA-Z0-9]{5,20}"; //Make sure old password is valid if(!authDAO.authenticatePassword(mid, oldPass)) { TransactionLogger.getInstance().logTransaction(TransactionType.PASSWORD_CHANGE_FAILED, mid, 0L, ""); return "Invalid password change submission."; } //Make sure new passwords match if (!newPass.equals(confirmPass)) { TransactionLogger.getInstance().logTransaction(TransactionType.PASSWORD_CHANGE_FAILED, mid, 0L, ""); return "Invalid password change submission."; } //Validate password. Must contain a letter, contain a number, and be a string of 5-20 alphanumeric characters if(newPass.matches(containsLetter) && newPass.matches(containsNumber) && newPass.matches(fiveAlphanumeric)){ //Change the password authDAO.resetPassword(mid, newPass); TransactionLogger.getInstance().logTransaction(TransactionType.PASSWORD_CHANGE, mid, 0L, ""); return "Password Changed."; } else { TransactionLogger.getInstance().logTransaction(TransactionType.PASSWORD_CHANGE_FAILED, mid, 0L, ""); return "Invalid password change submission."; } } /** * Generate a new more secure hashed and randomly salted password based on the users * new desired password passed in as a String. * @param newpas String, desired new plain text password * @return private String genPassword(String newpas){ String pas = ""; SecureRandom rand = new SecureRandom(); //TODO change the capacity in the byte array to match that of the original password byte newbie[] = new byte[32]; sr. return pas; } */ //TODO: note, increasing password security will mean changing also how passwords are stored and retrieved to also include the salts for that hash //generate a new salt for each time a user account is made }
3,225
34.450549
146
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ChangeSessionTimeoutAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AccessDAO; /** * Used to change the session timeout, sessionTimeout.jsp. Note that a change to this timeout only gets * reflected on new sessions. * */ public class ChangeSessionTimeoutAction { private AccessDAO accessDAO; /** * Sets up defualts. * * @param factory */ public ChangeSessionTimeoutAction(DAOFactory factory) { this.accessDAO = factory.getAccessDAO(); } /** * Changes the session timeout, the complicated logic of this is somewhat regrettably in the DAO, * {@link AccessDAO} * * @param minuteString * Pass the number of minutes in the form of a string, greater than 0. * @throws FormValidationException * @throws DBException */ public void changeSessionTimeout(String minuteString) throws FormValidationException, DBException { try { Integer minutes = Integer.valueOf(minuteString); if (minutes < 1) throw new FormValidationException("Must be a number greater than 0"); accessDAO.setSessionTimeoutMins(minutes); } catch (NumberFormatException e) { throw new FormValidationException("That is not a number"); } } /** * Returns the current session timeout in minutes, as reflected in the database * * @return the number of minutes it would take for an inactive session to timeout * @throws DBException */ public int getSessionTimeout() throws DBException { return accessDAO.getSessionTimeoutMins(); } }
1,656
29.127273
103
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/DeclareHCPAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; /** * Used by the patient to declare HCPs as "designated", in editHCPs.jsp. * * */ public class DeclareHCPAction { private PatientDAO patientDAO; private AuthDAO authDAO; private long loggedInMID; /** * Sets up defaults * * @param factory The DAO factory to be used for generating the DAOs for this action. * @param loggedInMID * This patient */ public DeclareHCPAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.patientDAO = factory.getPatientDAO(); this.authDAO = factory.getAuthDAO(); } /** * Lists the declared HCPs for this current patient * * @return Returns a list of the declared HCPs * @throws ITrustException */ public List<PersonnelBean> getDeclaredHCPS() throws ITrustException { return patientDAO.getDeclaredHCPs(loggedInMID); } /** * Validate an HCP's MID and declare them, if possible * * @param hcpStr * The MID of an HCP to declare * @return A status message, * @throws ITrustException */ public String declareHCP(String hcpStr) throws ITrustException { try { long hcpID = Long.valueOf(hcpStr); if (authDAO.getUserRole(hcpID) != Role.HCP) throw new ITrustException("This user is not a licensed healthcare professional!"); boolean confirm = patientDAO.declareHCP(loggedInMID, hcpID); if (confirm) { return "HCP successfully declared"; } else return "HCP not declared"; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Validate an HCP's MID and undeclare them, if possible * * @param input * The MID of an HCP to undeclare * @return * @throws ITrustException */ public String undeclareHCP(String input) throws ITrustException { try { long hcpID = Long.valueOf(input); boolean confirm = patientDAO.undeclareHCP(loggedInMID, hcpID); if (confirm) { return "HCP successfully undeclared"; } else return "HCP not undeclared"; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } }
2,494
26.417582
86
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/DrugInteractionAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.DrugInteractionBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.DrugInteractionDAO; import edu.ncsu.csc.itrust.model.old.validate.DrugInteractionValidator; /** * Used by EditDrugInteraction.jsp to edit and get information about drug interactions. * */ public class DrugInteractionAction { private DrugInteractionDAO drugDAO; private DrugInteractionValidator validator; /** * Sets up defaults * * @param factory The DAO factory to be used for generating the DAOs for this action. * */ public DrugInteractionAction(DAOFactory factory) { this.drugDAO = factory.getDrugInteractionDAO(); this.validator = new DrugInteractionValidator(); } /** * Method to report an interaction * @param firstDrug * @param secondDrug * @param description * @return */ public String reportInteraction(String firstDrug, String secondDrug, String description) throws ITrustException, FormValidationException{ if (firstDrug.equals(secondDrug)){ return "Interactions can only be recorded between two different drugs"; } DrugInteractionBean drugInt = new DrugInteractionBean(); drugInt.setFirstDrug(firstDrug); drugInt.setSecondDrug(secondDrug); drugInt.setDescription(description); try { validator.validate(drugInt); if (drugDAO.reportInteraction(firstDrug, secondDrug, description)){ return "Interaction recorded successfully"; } else { return "Interaction could not be added"; } } catch (DBException e){ return e.getMessage(); } } /** * Method to delete an interaction * @param firstDrug * @param secondDrug * @return interaction */ public String deleteInteraction(String firstDrug, String secondDrug) throws ITrustException, FormValidationException{ DrugInteractionBean drugInt = new DrugInteractionBean(); drugInt.setFirstDrug(firstDrug); drugInt.setSecondDrug(secondDrug); drugInt.setDescription("blank"); try { validator.validate(drugInt); if (drugDAO.deleteInteraction(firstDrug, secondDrug)){ return "Interaction deleted successfully"; } else { return "Interaction could not be deleted"; } } catch (DBException e){ throw new ITrustException(e.getMessage()); } } /** * Method to return a list of drug interactions for a given drug * @param drugCode - The ND Code of the drug * @return drugDAO */ public List<DrugInteractionBean> getInteractions(String drugCode) throws ITrustException { try { return drugDAO.getInteractions(drugCode); } catch (DBException e){ throw new ITrustException(e.getMessage()); } } }
2,896
28.262626
138
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditApptAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.sql.Timestamp; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.ApptBeanValidator; /** * EditApptAction */ public class EditApptAction extends ApptAction { private ApptBeanValidator validator = new ApptBeanValidator(); private long loggedInMID; private long originalPatient; private long originalApptID; /** * EditApptAction * @param factory factory * @param loggedInMID loggedInMID */ public EditApptAction(DAOFactory factory, long loggedInMID) { this(factory, loggedInMID, 0L, 0L); } public void setOriginalApptID(long id) { this.originalApptID = id; } public void setOriginalPatient(long patient) { this.originalPatient = patient; } public void logViewAction() { TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_VIEW, loggedInMID, originalPatient, ""); } /** * EditApptAction * @param factory factory * @param loggedInMID loggedInMID */ public EditApptAction(DAOFactory factory, long loggedInMID, long originalPatient, long originalApptID) { super(factory, loggedInMID); this.loggedInMID = loggedInMID; this.originalPatient = originalPatient; this.originalApptID = originalApptID; } /** * Retrieves an appointment from the database, given its ID. * Returns null if there is no match, or multiple matches. * * @param apptID apptID * @return ApptBean with matching ID * @throws DBException * @throws SQLException */ public ApptBean getAppt(int apptID) throws DBException, SQLException { try { List<ApptBean> apptBeans = apptDAO.getAppt(apptID); if (apptBeans.size() == 1){ return apptBeans.get(0); } return null; } catch (DBException e) { return null; } } /** * Updates an existing appointment * * @param appt Appointment Bean containing the updated information * @param ignoreConflicts ignoreConflicts * @return Message to be displayed * @throws FormValidationException * @throws SQLException * @throws DBException */ public String editAppt(ApptBean appt, boolean ignoreConflicts) throws FormValidationException, SQLException, DBException { validator.validate(appt); if(appt.getDate().before(new Timestamp(System.currentTimeMillis()))) return "The scheduled date of this appointment ("+appt.getDate()+") has already passed."; if(!ignoreConflicts){ if(getConflictsForAppt(appt.getHcp(), appt).size()>0){ return "Warning! This appointment conflicts with other appointments"; } } try { apptDAO.editAppt(appt); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_EDIT, loggedInMID, originalPatient, ""+appt.getApptID()); if(ignoreConflicts){ TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_CONFLICT_OVERRIDE, loggedInMID, originalPatient, ""); } return "Success: Appointment changed"; } catch (DBException e) { return e.getMessage(); } } /** * Removes an existing appointment * * @param appt Appointment Bean containing the ID of the appointment to be removed. * @return Message to be displayed * @throws DBException */ public String removeAppt(ApptBean appt) throws DBException, SQLException { try { apptDAO.removeAppt(appt); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_REMOVE, loggedInMID, originalPatient, ""+originalApptID); return "Success: Appointment removed"; } catch (SQLException e) { return e.getMessage(); } } }
3,904
28.141791
135
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditApptTypeAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptTypeBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptTypeDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.ApptTypeBeanValidator; public class EditApptTypeAction { private ApptTypeDAO apptTypeDAO; private long loggedInMID; private ApptTypeBeanValidator validator = new ApptTypeBeanValidator(); public EditApptTypeAction(DAOFactory factory, long loggedInMID) { this.apptTypeDAO = factory.getApptTypeDAO(); this.loggedInMID = loggedInMID; TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_TYPE_VIEW, loggedInMID, 0L, ""); } public List<ApptTypeBean> getApptTypes() throws SQLException, DBException { return apptTypeDAO.getApptTypes(); } public String addApptType(ApptTypeBean apptType) throws SQLException, FormValidationException, DBException { validator.validate(apptType); List<ApptTypeBean> list = this.getApptTypes(); for(ApptTypeBean a : list) { if(a.getName().equals(apptType.getName())) return "Appointment Type: "+apptType.getName()+" already exists."; } try { if (apptTypeDAO.addApptType(apptType)) { TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_TYPE_ADD, loggedInMID, 0L, ""); return "Success: " + apptType.getName() + " - Duration: " + apptType.getDuration() + " added"; } else return "The database has become corrupt. Please contact the system administrator for assistance."; } catch (SQLException e) { return e.getMessage(); } } public String editApptType(ApptTypeBean apptType) throws SQLException, FormValidationException, DBException { validator.validate(apptType); List<ApptTypeBean> list = this.getApptTypes(); int flag = 0; for(ApptTypeBean a : list) { if(a.getName().equals(apptType.getName())) { flag = 1; if(a.getDuration() == apptType.getDuration()) return "Appointment Type: "+apptType.getName()+" already has a duration of "+apptType.getDuration()+" minutes."; break; } } if(flag == 0){ return "Appointment Type: "+apptType.getName()+" you are trying to update does not exist."; } try { if (apptTypeDAO.editApptType(apptType)) { TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_TYPE_EDIT, loggedInMID, 0L, ""); return "Success: " + apptType.getName() + " - Duration: " + apptType.getDuration() + " updated"; } else return "The database has become corrupt. Please contact the system administrator for assistance."; } catch (DBException e) { return e.getMessage(); } } }
2,957
35.975
117
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditMonitoringListAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.RemoteMonitoringDataBean; import edu.ncsu.csc.itrust.model.old.beans.TelemedicineBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.RemoteMonitoringDAO; /** * Handles changes (adds and removes) to the monitoring list for a certain HCP. * */ public class EditMonitoringListAction { private RemoteMonitoringDAO rmDAO; private AuthDAO authDAO; private long loggedInMID; /** * Constructor * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the HCP editing their monitoring list. */ public EditMonitoringListAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.rmDAO = factory.getRemoteMonitoringDAO(); this.authDAO = factory.getAuthDAO(); } /** * Adds a patient to the current HCP's remote monitoring list * * @param patientMID the patient * @param permissions Array indicating what data the patient is allowed to enter. Ordered by Systolic Blood Pressure, Diastolic Blood Pressure, Glucose Level, Weight, Pedometer Reading. * @return true if added successfully. False if already in list. * @throws DBException */ public boolean addToList(long patientMID, TelemedicineBean tBean) throws DBException { return rmDAO.addPatientToList(patientMID, loggedInMID, tBean); } /** * Removes a patient from the current HCP's remote monitoring list * * @param patientMID the patient * @return true if removed successfully. False if not in list. * @throws DBException */ public boolean removeFromList(long patientMID) throws DBException { return rmDAO.removePatientFromList(patientMID, loggedInMID); } /** * Returns whether a patient is in an HCP's list already * @param patientMID the patient * @return true if in DB, false otherwise * @throws DBException */ public boolean isPatientInList(long patientMID) throws DBException { List<RemoteMonitoringDataBean> dataset = rmDAO.getPatientsData(loggedInMID); for(RemoteMonitoringDataBean d: dataset) { if(d.getPatientMID() == patientMID) return true; } return false; } /** * returns the patient name * * @return patient name * @throws DBException * @throws ITrustException */ public String getPatientName(long pid) throws DBException, ITrustException { return authDAO.getUserName(pid); } }
2,657
30.270588
108
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditPatientAction.java
package edu.ncsu.csc.itrust.action; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import edu.ncsu.csc.itrust.action.base.PatientBaseAction; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.PatientValidator; import edu.ncsu.csc.itrust.EmailUtil; /** * Edits a patient Used by editPatient.jsp * * */ public class EditPatientAction extends PatientBaseAction { private PatientValidator validator = new PatientValidator(); private PatientDAO patientDAO; private PersonnelDAO personnelDAO; private AuthDAO authDAO; private long loggedInMID; private EmailUtil emailutil; /** * The super class validates the patient id * * @param factory The DAOFactory used to create the DAOs for this action. * @param loggedInMID The MID of the user who is authorizing this action. * @param pidString The MID of the patient being edited. * @throws ITrustException */ public EditPatientAction(DAOFactory factory, long loggedInMID, String pidString) throws ITrustException { super(factory, pidString); this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.authDAO = factory.getAuthDAO(); this.loggedInMID = loggedInMID; emailutil = new EmailUtil(factory); } /** * Takes the information out of the PatientBean param and updates the patient's information * * @param p * the new patient information * @throws ITrustException * @throws FormValidationException */ public void updateInformation(PatientBean p) throws ITrustException, FormValidationException { p.setMID(pid); // for security reasons validator.validate(p); patientDAO.editPatient(p, loggedInMID); emailutil.sendEmail(makeEmail()); } /** * Returns a PatientBean for the patient * * @return the PatientBean * @throws DBException */ public PatientBean getPatient() throws DBException { return patientDAO.getPatient(this.getPid()); } /** * Creates and e-mail to inform the patient that their information has been updated. * * @return the email with the notice * @throws DBException */ private Email makeEmail() throws DBException{ Email email = new Email(); List<PatientBean> reps = patientDAO.getRepresenting(pid); PatientBean pb = patientDAO.getPatient(pid); List<String> toAddrs = new ArrayList<String>(); toAddrs.add(pb.getEmail()); for (PatientBean r: reps) { toAddrs.add(r.getEmail()); } email.setFrom("no-reply@itrust.com"); email.setToList(toAddrs); // patient and personal representative email.setSubject(String.format("Patient Information Updated")); email.setBody("Dear " + pb.getFullName() + ",\n\tYour patient record information has been updated. " + "Please login to iTrust to see who has viewed your records."); TransactionLogger.getInstance().logTransaction(TransactionType.EMAIL_SEND, loggedInMID, pb.getMID(), ""); return email; } /** * The DateOfDeactivationStr of the PatientBean when not null indicates that the user has been deactivated. * @throws DBException */ public void deactivate(long loggedInMID) throws DBException{ PatientBean p=patientDAO.getPatient(this.getPid()); p.setMID(pid); p.setDateOfDeactivationStr(new SimpleDateFormat("MM/dd/yyyy").format(Calendar.getInstance().getTime())); patientDAO.editPatient(p, loggedInMID); patientDAO.removeAllRepresented(pid); patientDAO.removeAllRepresentee(pid); } /** * The DateOfDeactivationStr of the PatientBean is null when the patient is activated * @throws DBException */ public void activate() throws DBException{ PatientBean p=patientDAO.getPatient(this.getPid()); p.setMID(pid); p.setDateOfDeactivationStr(null); patientDAO.editPatient(p, loggedInMID); } public String getEmployeeName(long mid) throws DBException, ITrustException { return personnelDAO.getName(mid); } public boolean isDependent() { boolean isDependent = false; try { return authDAO.isDependent(pid); } catch (DBException e) { //If a DBException occurs print a stack trace and return false e.printStackTrace(); } return isDependent; } public boolean setDependent(boolean dependency) { TransactionLogger.getInstance().logTransaction(TransactionType.HCP_CHANGE_PATIENT_DEPENDENCY, loggedInMID, pid, ""); try { authDAO.setDependent(pid, dependency); if (dependency) patientDAO.removeAllRepresented(pid); } catch (DBException e) { //If a DBException occurs print a stack trace and return false e.printStackTrace(); return false; } return true; } }
5,237
31.534161
121
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditPersonnelAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.action.base.PersonnelBaseAction; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.PersonnelValidator; /** * Edits the designated personnel Used by admin/editPersonnel.jsp, staff/editMyDemographics.jsp, * editPersonnel.jsp * * */ public class EditPersonnelAction extends PersonnelBaseAction { private PersonnelDAO personnelDAO; private AuthDAO authDAO; private PersonnelValidator validator = new PersonnelValidator();; /** * Super class validates the patient id * * @param factory The DAOFactory used to create the DAOs for this action. * @param loggedInMID The MID of the user editing this personnel. * @param pidString The ID of the user being edited. * @throws ITrustException */ public EditPersonnelAction(DAOFactory factory, long loggedInMID, String pidString) throws ITrustException { super(factory, pidString); this.authDAO = factory.getAuthDAO(); long pidlong = Long.parseLong(pidString); Role editor = authDAO.getUserRole(loggedInMID); Role editing = authDAO.getUserRole(pidlong); if (editor == editing && pidlong != loggedInMID){ throw new ITrustException("You can only edit your own demographics!"); }else if (editor == Role.HCP && editing == Role.ADMIN || editor == Role.UAP && editing == Role.HCP || editor == Role.ADMIN && editing == Role.UAP){ throw new ITrustException("You are not authorized to edit this record!"); } this.personnelDAO = factory.getPersonnelDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.PERSONNEL_VIEW, loggedInMID , pidlong, editing.getUserRolesString()); } /** * Takes information from the personnelForm param and updates the patient * * @param personnelForm * PersonnelBean with new information * @throws ITrustException * @throws FormValidationException */ public void updateInformation(PersonnelBean personnelForm, long loggedInMID) throws ITrustException, FormValidationException { personnelForm.setMID(pid); validator.validate(personnelForm); personnelDAO.editPersonnel(personnelForm); if(personnelForm.getRole() == Role.HCP) // If pid belongs to an HCP TransactionLogger.getInstance().logTransaction(TransactionType.LHCP_EDIT, loggedInMID , personnelForm.getMID(), ""); else if(personnelForm.getRole() == Role.UAP) // If pid belongs to a UAP TransactionLogger.getInstance().logTransaction(TransactionType.UAP_EDIT, loggedInMID, personnelForm.getMID(), ""); else if(personnelForm.getRole() == Role.ER) // If pid belongs to a ER TransactionLogger.getInstance().logTransaction(TransactionType.ER_EDIT, loggedInMID, personnelForm.getMID(), ""); else if(personnelForm.getRole() == Role.PHA) // If pid belongs to a PHA TransactionLogger.getInstance().logTransaction(TransactionType.PHA_EDIT, loggedInMID, personnelForm.getMID(), ""); else if(personnelForm.getRole() == Role.LT) // If pid belongs to a LT TransactionLogger.getInstance().logTransaction(TransactionType.LT_EDIT, loggedInMID, personnelForm.getMID(), ""); } }
3,639
44.5
134
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EditRepresentativesAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.action.base.PatientBaseAction; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Edits a patient's personal representatives. Used by hcp/editRepresentatives.jsp * * */ public class EditRepresentativesAction extends PatientBaseAction { private PatientDAO patientDAO; private AuthDAO authDAO; private long loggedInMID; /** * Super class validates the patient mid * * @param factory The DAOFactory used in creating the DAOs for this action. * @param loggedInMID The MID of the patient editing his/her representatives. * @param pidString The MID of the representative in question. * @throws ITrustException */ public EditRepresentativesAction(DAOFactory factory, long loggedInMID, String pidString) throws ITrustException { super(factory, pidString); this.patientDAO = factory.getPatientDAO(); this.loggedInMID = loggedInMID; this.authDAO = factory.getAuthDAO(); } /** * Gets the name of the representative patient * @return the full name of the representative patient * @throws ITrustException if patient does not exist */ public String getRepresentativeName() throws ITrustException { String name = ""; try { name = patientDAO.getName(pid); } catch (DBException e) { //If a DBException is caught print a stack trace and return an empty string e.printStackTrace(); } return name; } /** * Return a list of patients that pid represents * * @param pid The id of the personnel we are looking up representees for. * @return a list of PatientBeans * @throws ITrustException */ public List<PatientBean> getRepresented(long pid) throws ITrustException { return patientDAO.getRepresented(pid); } /** * Makes the patient (pid) represent the input mid parameter * * @param pidString * the mid of the person who will be represented (the representee) * @return a message * @throws ITrustException */ public String addRepresentee(String pidString) throws ITrustException { try { long representee = Long.valueOf(pidString); if (authDAO.getUserRole(representee) != Role.PATIENT) throw new ITrustException("This user is not a patient!"); else if (super.pid == representee) throw new ITrustException("This user cannot represent themselves."); else if(!patientDAO.checkIfRepresenteeIsActive(representee)) throw new ITrustException(patientDAO.getPatient(representee).getFullName() + "cannot be added as a representee, they are not active."); boolean confirm = patientDAO.addRepresentative(pid, representee); if (confirm) { TransactionLogger.getInstance().logTransaction(TransactionType.HEALTH_REPRESENTATIVE_DECLARE, loggedInMID, representee, "Represented by: " + pid); return "Patient represented"; } else return "No change made"; } catch (NumberFormatException e) { return "MID not a number"; } } /** * Makes the patient (pid) no longer represent the input mid param * * @param input * the mid of the person be represented (representee) * @return a message * @throws ITrustException */ public String removeRepresentee(String input) throws ITrustException { try { long representee = Long.valueOf(input); boolean confirm = patientDAO.removeRepresentative(pid, representee); if (confirm) { TransactionLogger.getInstance().logTransaction(TransactionType.HEALTH_REPRESENTATIVE_UNDECLARE, loggedInMID, representee, "Represented by: " + pid); return "Patient represented"; } else return "No change made"; } catch (NumberFormatException e) { return "MID not a number"; } } public boolean checkIfPatientIsActive(long patientID) throws ITrustException { try { return patientDAO.checkIfPatientIsActive(patientID); } catch (DBException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } }
4,381
32.968992
152
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/EventLoggingAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Handles retrieving the log of record accesses for a given user Used by viewAccessLog.jsp * * */ public class EventLoggingAction { private TransactionDAO transDAO; /** * Set up * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person retrieving the logs. */ public EventLoggingAction(DAOFactory factory) { this.transDAO = factory.getTransactionDAO(); } /** * Log a transaction, with all of the info. The meaning of secondaryMID and addedInfo changes depending on * the transaction type. * * @param type The {@link TransactionType} enum representing the type this transaction is. * @param loggedInMID The MID of the user who is logged in. * @param secondaryMID Typically, the MID of the user who is being acted upon. * @param addedInfo A note about a subtransaction, or specifics of this transaction (for posterity). * @throws DBException */ public void logEvent(TransactionType type, long loggedInMID, long secondaryMID, String addedInfo) throws DBException { this.transDAO.logTransaction(type, loggedInMID, secondaryMID, addedInfo); } }
1,424
33.756098
107
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/FindExpertAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.CustomComparator; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Action class to find experts based on the distance from the user and type of expert. * */ public class FindExpertAction { /** * HospitalDAO to grab hospitals from */ HospitalsDAO hospitalsDAO; /** * PersonnelDAO to find experts from */ PersonnelDAO personnelDAO; /** * Constructor simply is used to initialize the DAOs * @param factory used to initialize DAOs */ public FindExpertAction(DAOFactory factory){ hospitalsDAO = new HospitalsDAO(factory); personnelDAO = new PersonnelDAO(factory); } /** * * Main method used to find the hospitals and all specified personnel within range * * @param distance The maximum distance that a hospital must be within range in order for it to return * @param specialty The specialty that the user is interested in * @param patientZip Zipcode entered by the patient * @param zipRange The range to search hospitals for. The amount of zipcode digits to match, starting with the first digit. * @return A relationship between hospitals within the defined proximity and the specified experts at the hospital. */ public HashMap<HospitalBean, List<PersonnelBean>> findHospitalsBySpecialty(String specialty, String patientZip, int zipRange){ HashMap<HospitalBean, List<PersonnelBean>> experts = null; try { //Grab all hospitals and filter them based on distance List<HospitalBean> hospitals = filterHospitals(hospitalsDAO.getAllHospitals(), patientZip, zipRange); //Find experts in hospitals experts = findExperts(hospitals, specialty); } catch (DBException e) { // } return experts; } /** * Method used to find experts of specified specialty from hospitals that are in range * @param hospitals The hospitals within the proximity of the user * @param specialty The expertise specified * @return A relationship between the hospitals within proximity and the personnel with the specified expertise within them. */ public HashMap<HospitalBean, List<PersonnelBean>> findExperts(List<HospitalBean> hospitals, String specialty){ HashMap<HospitalBean, List<PersonnelBean>> experts = new HashMap<HospitalBean, List<PersonnelBean>>(); try{ //Go through all nearby hospitals for(HospitalBean hospital : hospitals){ //Put the specified experts into a hashmap with the hospital experts.put(hospital, personnelDAO.getPersonnelFromHospital(hospital.getHospitalID(), specialty)); } } catch (DBException e){ // } return experts; } /** * Method used to find experts of specified specialty from hospitals that are in range * @param hospitals The hospitals within the proximity of the user * @param specialty The expertise specified * @return A relationship between the hospitals within proximity and the personnel with the specified expertise within them. */ public List<PersonnelBean> findExpertsForLocalHospitals(List<HospitalBean> hospitals, String specialty){ List<PersonnelBean> beans = new ArrayList<PersonnelBean>(); boolean searchForAll; searchForAll = specialty.equalsIgnoreCase("all"); if (searchForAll) { } try{ //Go through all nearby hospitals for(HospitalBean hospital : hospitals){ //Put the specified experts into a hashmap with the hospital //experts.put(hospital, personnelDAO.getPersonnelFromHospital(hospital.getHospitalID(), specialty)); List<PersonnelBean> personnelBeans = personnelDAO.getPersonnelFromHospital(hospital.getHospitalID(), specialty); for (PersonnelBean personnelBean : personnelBeans) { beans.add(personnelBean); } } } catch (DBException e){ e.printStackTrace(); } Collections.sort(beans, new CustomComparator()); return beans; } public List<HospitalBean> findHospitalsAssignedToHCP(long pid) throws DBException { return hospitalsDAO.getHospitalsAssignedToPhysician(pid); } /** * Filters hospitals down to just the hospitals in the specified range of the user * @param hospitals Hospitals to filter * @param patientZip Zipcode entered by the patient * @param zipRange The range to search hospitals for. The amount of zipcode digits to match, starting with the first digit. * @return All hospitals within the specified range of the user */ public List<HospitalBean> filterHospitals(List<HospitalBean> hospitals, String patientZip, int zipRange){ List<HospitalBean> inRange = new ArrayList<HospitalBean>(); for (int i = 0; i < hospitals.size(); i++) { try { //A hospital is in range if its zipcode matches the user entered one from the first number to the zipRangeth number if (hospitals.get(i).getHospitalZip().substring(0, zipRange).equals(patientZip.substring(0, zipRange))) inRange.add(hospitals.get(i)); } catch (NullPointerException e1) { //Examine next hospital if current has null zipcode entry } catch (IndexOutOfBoundsException e2) { //If the hospital's zip code is not at least 5 digits long, examine next hospital } } return inRange; } }
5,657
37.753425
127
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/GenerateCalendarAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptTypeDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.action.ViewMyApptsAction; import java.util.List; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Hashtable; import java.util.Calendar; /** * Action class for calendar.jsp * */ public class GenerateCalendarAction { private ViewMyApptsAction a_action; private List<ApptBean> send; private ApptTypeDAO apptTypeDAO; /** * Set up defaults * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the user who is viewing the calendar */ public GenerateCalendarAction(DAOFactory factory, long loggedInMID) { a_action = new ViewMyApptsAction(factory, loggedInMID); send = new ArrayList<ApptBean>(); apptTypeDAO = factory.getApptTypeDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.CALENDAR_VIEW, loggedInMID, 0L, ""); } /** * Return the send request for an AppointmentBean * @return the send request for an AppointmentBean */ public List<ApptBean> getSend() { return send; } /** * Check appointments appearing on the calendar for conflicts * with other appointments on the calendar. * * The array from this method is used to determine what appointments * will appear in bold on the calendar. * * @return An array of items that are in conflict with other items. * @throws SQLException * @throws DBException */ public boolean[] getConflicts() throws SQLException, DBException { boolean conflicts[] = new boolean[send.size()]; for(int i=0; i<send.size(); i++) { ApptBean ab = send.get(i); long t = ab.getDate().getTime(); long m = apptTypeDAO.getApptType(ab.getApptType()).getDuration() * 60L * 1000L; Timestamp time = new Timestamp(t+m); for(int j=i+1; j<send.size(); j++) { if(send.get(j).getDate().before(time)) { conflicts[i] = true; conflicts[j] = true; } } } return conflicts; } /** * Creates a hash table with all of the Appointments to be * displayed on the calendar for the month and year being viewed. * * @param thisMonth The month of the calendar to be rendered * @param thisYear The year of the calendar to be rendered * @return A Hashtable containing the AppointmentBeans to be rendered * @throws SQLException * @throws DBException */ public Hashtable<Integer, ArrayList<ApptBean>> getApptsTable(int thisMonth, int thisYear) throws SQLException, DBException { List<ApptBean> appts = a_action.getAllMyAppointments(); Hashtable<Integer, ArrayList<ApptBean>> atable = new Hashtable<Integer, ArrayList<ApptBean>>(); Calendar a = Calendar.getInstance(); for(ApptBean b : appts) { a.setTimeInMillis(b.getDate().getTime()); if(a.get(Calendar.MONTH) == thisMonth && a.get(Calendar.YEAR) == thisYear) { if(!atable.containsKey(a.get(Calendar.DAY_OF_MONTH))) atable.put(a.get(Calendar.DAY_OF_MONTH), new ArrayList<ApptBean>()); ArrayList<ApptBean> l = atable.get(a.get(Calendar.DAY_OF_MONTH)); l.add(b); send.add(b); atable.put(a.get(Calendar.DAY_OF_MONTH), l); } } return atable; } }
3,492
31.95283
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/GetUserNameAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; /** * Handles Getting the person's name associated with a certain mid Used by getUser.jsp * * */ public class GetUserNameAction { private DAOFactory factory; /** * Set up defaults * * @param factory The DAOFactory used for creating the DAOs for this action. */ public GetUserNameAction(DAOFactory factory) { this.factory = factory; } /** * Returns the person's name that matches the inputMID param * * @param inputMID The MID to look up. * @return the person's name * @throws DBException * @throws ITrustException */ public String getUserName(String inputMID) throws ITrustException { try { long mid = Long.valueOf(inputMID); return factory.getAuthDAO().getUserName(mid); } catch (NumberFormatException e) { throw new ITrustException("MID not in correct form"); } } }
969
23.25
86
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/GroupReportAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.AllergyBean; import edu.ncsu.csc.itrust.model.old.beans.FamilyMemberBean; import edu.ncsu.csc.itrust.model.old.beans.GroupReportBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.FamilyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.report.DemographicReportFilter.DemographicReportFilterType; import edu.ncsu.csc.itrust.report.MedicalReportFilter.MedicalReportFilterType; import edu.ncsu.csc.itrust.report.PersonnelReportFilter.PersonnelReportFilterType; import edu.ncsu.csc.itrust.report.ReportFilter; /** * * */ public class GroupReportAction { private PatientDAO pDAO; private AllergyDAO aDAO; private FamilyDAO fDAO; /** * * @param factory * @throws DBException */ public GroupReportAction(DAOFactory factory, long mid) throws DBException { pDAO = factory.getPatientDAO(); aDAO = factory.getAllergyDAO(); fDAO = factory.getFamilyDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.GROUP_REPORT_VIEW, mid, 0L , ""); } /** * * @param filters * @return */ public GroupReportBean generateReport(List<ReportFilter> filters) { List<PatientBean> patients; try { patients = getAllPatients(); } catch (DBException e) { return null; } for (ReportFilter filter : filters) { patients = filter.filter(patients); } return new GroupReportBean(patients, filters); } /** * * @param patient * @param filterType * @return */ public String getComprehensiveDemographicInfo(PatientBean patient, DemographicReportFilterType filterType) { switch (filterType) { case GENDER: return patient.getGender().toString(); case LAST_NAME: return patient.getLastName(); case FIRST_NAME: return patient.getFirstName(); case CONTACT_EMAIL: return patient.getEmail(); case STREET_ADDR: return patient.getStreetAddress1() + " " + patient.getStreetAddress2(); case CITY: return patient.getCity(); case STATE: return patient.getState(); case ZIP: return patient.getZip(); case PHONE: return patient.getPhone(); case EMER_CONTACT_NAME: return patient.getEmergencyName(); case EMER_CONTACT_PHONE: return patient.getEmergencyPhone(); case INSURE_NAME: return patient.getIcName(); case INSURE_ADDR: return patient.getIcAddress1() + " " + patient.getIcAddress2(); case INSURE_CITY: return patient.getIcCity(); case INSURE_STATE: return patient.getIcState(); case INSURE_ZIP: return patient.getIcZip(); case INSURE_PHONE: return patient.getIcPhone(); case MID: return Long.toString(patient.getMID()); case INSURE_ID: return patient.getIcID(); case PARENT_FIRST_NAME: try { List<FamilyMemberBean> parents = fDAO.getParents(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean parent : parents) { buff.append(parent.getFirstName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case PARENT_LAST_NAME: try { List<FamilyMemberBean> parents = fDAO.getParents(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean parent : parents) { buff.append(parent.getLastName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case CHILD_FIRST_NAME: try { List<FamilyMemberBean> children = fDAO.getChildren(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean child : children) { buff.append(child.getFirstName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case CHILD_LAST_NAME: try { List<FamilyMemberBean> children = fDAO.getChildren(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean child : children) { buff.append(child.getLastName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case SIBLING_FIRST_NAME: try { List<FamilyMemberBean> siblings = fDAO.getSiblings(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean sibling : siblings) { buff.append(sibling.getFirstName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case SIBLING_LAST_NAME: try { List<FamilyMemberBean> siblings = fDAO.getSiblings(patient.getMID()); StringBuffer buff = new StringBuffer(); for (FamilyMemberBean sibling : siblings) { buff.append(sibling.getLastName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } case DEACTIVATED: return patient.getDateOfDeactivationStr(); default: break; } return null; } /** * * @param patient * @param filterType * @return */ public String getComprehensiveMedicalInfo(PatientBean patient, MedicalReportFilterType filterType) { try { String out; StringBuffer buff = new StringBuffer(); switch (filterType) { case ALLERGY: List<AllergyBean> allergies = aDAO.getAllergies(patient.getMID()); for (AllergyBean allergy : allergies) { buff.append(allergy.getNDCode()); buff.append("\n"); } out = buff.toString(); return out; default: break; } } catch(Exception e) { return null; } return null; } /** * * @param patient * @param filterType * @return */ public String getComprehensivePersonnelInfo(PatientBean patient, PersonnelReportFilterType filterType) { switch (filterType) { case DLHCP: try { List<PersonnelBean> dlhcps = pDAO.getDeclaredHCPs(patient.getMID()); StringBuffer buff = new StringBuffer(); for (PersonnelBean dlhcp : dlhcps) { buff.append(dlhcp.getFullName()); buff.append("\n"); } String out = buff.toString(); return out; } catch (Exception e) { break; } default: break; } return null; } /** * * @return * @throws DBException */ private List<PatientBean> getAllPatients() throws DBException { return pDAO.getAllPatients(); } }
6,758
24.79771
109
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/GroupReportGeneratorAction.java
package edu.ncsu.csc.itrust.action; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletRequest; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.GroupReportBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.report.DemographicReportFilter; import edu.ncsu.csc.itrust.report.DemographicReportFilter.DemographicReportFilterType; import edu.ncsu.csc.itrust.report.MedicalReportFilter; import edu.ncsu.csc.itrust.report.MedicalReportFilter.MedicalReportFilterType; import edu.ncsu.csc.itrust.report.PersonnelReportFilter; import edu.ncsu.csc.itrust.report.PersonnelReportFilter.PersonnelReportFilterType; import edu.ncsu.csc.itrust.report.ReportFilter; /** * Generates group reports, producing ArrayLists containing * the headers, data, and filters. */ public class GroupReportGeneratorAction { /** * DAOFactory for database operations */ DAOFactory factory = null; /** * GroupReportAction for generating the individual records */ GroupReportAction action; /** * List of ReportFilters to be used in the report */ List<ReportFilter> filters = null; /** * List of report filter types that were used in the report */ ArrayList<String> reportFilterTypes = new ArrayList<String>(); /** * List of report filter values that were used in the report */ ArrayList<String> reportFilterValues = new ArrayList<String>(); /** * List of headers for the report */ ArrayList<String> reportHeaders = new ArrayList<String>(); /** * List of lists (each of the sub-lists is a record) in the report */ ArrayList<ArrayList<String>> reportData = new ArrayList<ArrayList<String>>(); /** * Initializes the group report generator with a list of filters * * @param filters List of filters to be used in the report * @throws DBException */ public GroupReportGeneratorAction(DAOFactory factory, List<ReportFilter> filters, long mid) throws DBException{ this.factory=factory; this.filters=filters; action = new GroupReportAction(factory, mid); } /** * Initializes the group report generator with a list of filters after parsing them * * @param filters HttpServletRequest to grab and parse parameters from * @throws DBException */ public GroupReportGeneratorAction(DAOFactory factory, HttpServletRequest request, long mid) throws DBException{ this.factory=factory; this.filters = new ArrayList<ReportFilter>(); parseFilters(request); action = new GroupReportAction(factory, mid); } /** * Gets a list of the filters used in the report. * * @return List of FilterTypes used in the report */ public ArrayList<String> getReportFilterTypes(){ return reportFilterTypes; } /** * Gets a list of the filter values used in the report. * * @return List of filter values used in the report */ public ArrayList<String> getReportFilterValues(){ return reportFilterValues; } /** * Gets a list of the report headers. * * @return List of report headers */ public ArrayList<String> getReportHeaders(){ return reportHeaders; } /** * Gets a list of lists of report records (patients) * * @return List of lists of report records */ public ArrayList<ArrayList<String>> getReportData(){ return reportData; } /** * Generates the ArrayLists for the report based on the filters passed * in the constructor. */ public void generateReport(){ //Initialize the GroupReportBean GroupReportBean report = action.generateReport(filters); //Populate the filter lists for (ReportFilter filter : filters) { reportFilterTypes.add(filter.getFilterTypeString()); reportFilterValues.add(filter.getFilterValue()); } //Populate the header list with the DemographicReportFilters for (DemographicReportFilterType type : DemographicReportFilterType.values()) { if (type != DemographicReportFilterType.LOWER_AGE_LIMIT && type != DemographicReportFilterType.UPPER_AGE_LIMIT){ reportHeaders.add(type.toString()); } } //Populate the header list with the MedicalReportFilters for (MedicalReportFilterType type : MedicalReportFilterType.values()) { if (type != MedicalReportFilterType.LOWER_OFFICE_VISIT_DATE && type != MedicalReportFilterType.UPPER_OFFICE_VISIT_DATE){ reportHeaders.add(type.toString()); } if (type == MedicalReportFilterType.LOWER_OFFICE_VISIT_DATE){ reportHeaders.add("OFFICE VISIT DATE"); } } //Populate the header list with the PersonnelReportFilters for (PersonnelReportFilterType type : PersonnelReportFilterType.values()) { reportHeaders.add(type.toString()); } //Loop through all the patients in the report for (PatientBean patient : report.getPatients()) { //Create a temporary ArrayList for the current patient's data ArrayList<String> currentPatientData = new ArrayList<String>(); //Populate the current record with Demographic data for (DemographicReportFilterType type : DemographicReportFilterType.values()) { if (type != DemographicReportFilterType.LOWER_AGE_LIMIT && type != DemographicReportFilterType.UPPER_AGE_LIMIT) { String val = action.getComprehensiveDemographicInfo(patient, type); if (val != null) { currentPatientData.add(val); } else { currentPatientData.add(""); } } } //Populate the current record with Medical data for (MedicalReportFilterType type : MedicalReportFilterType.values()) { if (type != MedicalReportFilterType.UPPER_OFFICE_VISIT_DATE) { String val = action.getComprehensiveMedicalInfo(patient, type); if (val != null) { currentPatientData.add(val); } else { currentPatientData.add(""); } } } //Populate the current record with Personnel data for (PersonnelReportFilterType type : PersonnelReportFilterType.values()) { String val = action.getComprehensivePersonnelInfo(patient, type); if (val != null) { currentPatientData.add(val); } else { currentPatientData.add(""); } } //Add the current record to the list of records reportData.add(currentPatientData); } //Remove MID from report int midIndex = reportHeaders.indexOf("MID"); reportHeaders.remove(midIndex); for(ArrayList<String> patients : reportData){ patients.remove(midIndex); } } /** * Method that parses the request parameters to create the filter list in order to run report. * * @param request with form parameters to create the filter list */ private void parseFilters(HttpServletRequest request){ boolean hasDeactivatedFilter = false; if (request.getParameter("demoparams") != null && !request.getParameter("demoparams").isEmpty()) { String demoparams = request.getParameter("demoparams"); String demoFilters[] = demoparams.split(" "); for (String filter : demoFilters) { if (request.getParameter(filter) != null && !request.getParameter(filter).isEmpty()) { DemographicReportFilterType filterType = DemographicReportFilter.filterTypeFromString(filter); if(filterType.toString().equals("DEACTIVATED")){ hasDeactivatedFilter=true; } DemographicReportFilter fil = new DemographicReportFilter(filterType, request.getParameter(filter), factory); filters.add(fil); } } } if(!hasDeactivatedFilter){ filters.add(new DemographicReportFilter(DemographicReportFilter.filterTypeFromString("DEACTIVATED"), "exclude", factory)); } if (request.getParameter("medparams") != null && !request.getParameter("medparams").isEmpty()) { String medparams = request.getParameter("medparams"); String medFilters[] = medparams.split(" "); for (String filter : medFilters) { if (request.getParameter(filter) != null && !request.getParameter(filter).isEmpty()) { MedicalReportFilterType filterType = MedicalReportFilter.filterTypeFromString(filter); if (filterType == MedicalReportFilterType.DIAGNOSIS_ICD_CODE || filterType == MedicalReportFilterType.MISSING_DIAGNOSIS_ICD_CODE || filterType == MedicalReportFilterType.ALLERGY || filterType == MedicalReportFilterType.CURRENT_PRESCRIPTIONS || filterType == MedicalReportFilterType.PASTCURRENT_PRESCRIPTIONS || filterType == MedicalReportFilterType.PROCEDURE) { String[] vals = request.getParameterValues(filter); for (String val : vals) { MedicalReportFilter fil = new MedicalReportFilter(filterType, val, factory); filters.add(fil); } } else { MedicalReportFilter fil = new MedicalReportFilter(filterType, request.getParameter(filter), factory); filters.add(fil); } } } } if (request.getParameter("persparams") != null && !request.getParameter("persparams").isEmpty()) { String persparams = request.getParameter("persparams"); String personnelFilters[] = persparams.split(" "); for (String filter : personnelFilters) { if (request.getParameter(filter) != null && !request.getParameter(filter).isEmpty()) { PersonnelReportFilterType filterType = PersonnelReportFilter.filterTypeFromString(filter); if (filterType == PersonnelReportFilterType.DLHCP) { String[] vals = request.getParameterValues(filter); for (String val : vals) { PersonnelReportFilter fil = new PersonnelReportFilter(filterType, val, factory); filters.add(fil); } } else { PersonnelReportFilter fil = new PersonnelReportFilter(filterType, request.getParameter(filter), factory); filters.add(fil); } } } } } }
9,769
33.522968
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/LoginFailureAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; /** * Please note that this is not the best mitigation for Denial of Service attacks. The better way would be to * keep track of password failure attempts per user account, NOT with easily spoofable ip addresses. The * reason this feature is implemented with ip addresses is a limitation in Tomcat authentication (actually, * it's technically JSP's fault for not specifying a form of account lockout). <br /> * <br /> * All authentication in this application is done by the container (Tomcat), which doesn't support account * lockout. So our options would be (a) to implement our own authentication (yuck!), or (2) to extend the * JDBCRealm class in the Tomcat source code and add the logic. I've looked into this and it's actually pretty * easy. The ONLY reason it's not implemented here is that the code would be buried in a jar in your Tomcat * installation - not very educational for those who want to learn about authentication in webapps. Feel free * to change this; extending this would be perfectly acceptable. * * */ public class LoginFailureAction { private AuthDAO authDAO; private String ipAddr; private boolean validCaptcha; private boolean hasAttempts; /** * Set up defaults * @param factory The DAOFactory used to create the DAOs used in this action. * @param ipAddr The IP address of the user making the login attempt. */ public LoginFailureAction(DAOFactory factory, String ipAddr) { this.authDAO = factory.getAuthDAO(); this.ipAddr = ipAddr; validCaptcha = false; hasAttempts = false; } /** * Calls authDAO to record the login failure in the database * * @return How many login failure attempts or a DBException message */ public String recordLoginFailure() { try { authDAO.recordLoginFailure(ipAddr); int loginFailures = authDAO.getLoginFailures(ipAddr); hasAttempts = true; return "Login failed, attempt " + loginFailures; } catch (DBException e) { return e.getMessage(); } } /** * Checks to see if the current user can login (#failures<3) * * @return true if the user is valid to login */ public boolean isValidForLogin() { try { return authDAO.getLoginFailures(ipAddr) < 3 || validCaptcha; } catch (DBException e) { return false; } } public boolean needsCaptcha() { try { return authDAO.getLoginFailures(ipAddr) >= 3; } catch (DBException e) { System.err.println("Denying access due to DBException"); return false; } } /** * resetFailure * @throws DBException * @throws SQLException */ public void resetFailures() throws DBException, SQLException{ if(hasAttempts) { authDAO.resetLoginFailuresToZero(ipAddr); hasAttempts = false; } } /** * setCaptcha * @param val val */ public void setCaptcha(boolean val) { validCaptcha = val; } /** * getFailureCount * @return 0 */ public int getFailureCount() { int loginFailures = 0; try { loginFailures = authDAO.getLoginFailures(ipAddr); if (loginFailures > 0) { hasAttempts = true; } return loginFailures; } catch (DBException e) { return 0; } } }
3,334
27.262712
110
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ManageHospitalAssignmentsAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Manages the assignment of HCPs to hospitals Used by hospitalAssignments.jsp * * */ public class ManageHospitalAssignmentsAction { private PersonnelDAO personnelDAO; private HospitalsDAO hospitalsDAO; private long loggedInMID; /** * Set up defaults * * @param factory * The DAOFactory used to create the DAOs used in this action. * @param loggedInMID * The MID of the user managing hospitals. */ public ManageHospitalAssignmentsAction(DAOFactory factory, long loggedInMID) { this.personnelDAO = factory.getPersonnelDAO(); this.hospitalsDAO = factory.getHospitalsDAO(); this.loggedInMID = loggedInMID; } /** * Returns a list of hospitals to which the given mid is not currently assigned * * @param midString * @return list of HospitalBeans * @throws ITrustException */ public List<HospitalBean> getAvailableHospitals(String midString) throws ITrustException { try { long mid = Long.valueOf(midString); List<HospitalBean> allHospitals = hospitalsDAO.getAllHospitals(); List<HospitalBean> ourHospitals = personnelDAO.getHospitals(mid); while (!ourHospitals.isEmpty()) { allHospitals.remove(ourHospitals.remove(0)); } return allHospitals; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Returns a list of hospitals to which the given mid is currently assigned * * @param midString * @return list of HosptialBeans * @throws ITrustException */ public List<HospitalBean> getAssignedHospitals(String midString) throws ITrustException { try { long mid = Long.valueOf(midString); return personnelDAO.getHospitals(mid); } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Assigns the mid to the hospital * * @param midString * The MID of the person assigned to the hospital as a String. * @param hospitalID * The ID of the hospital. * @return message indicating the status of the assignment * @throws ITrustException */ public String assignHCPToHospital(String midString, String hospitalID) throws ITrustException { try { long hcpID = Long.valueOf(midString); boolean confirm = hospitalsDAO.assignHospital(hcpID, hospitalID); if (confirm) { TransactionLogger.getInstance().logTransaction(TransactionType.LHCP_ASSIGN_HOSPITAL, loggedInMID, hcpID, ""); return "HCP successfully assigned."; } else return "Assignment did not occur"; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Removes HCPs assignment to the designated hospital * * @param midString * the HCP's mid * @param hospitalID * the hospital id to be removed * @return Status message * @throws ITrustException */ public String removeHCPAssignmentToHospital(String midString, String hospitalID) throws ITrustException { try { long hcpID = Long.valueOf(midString); boolean confirm = hospitalsDAO.removeHospitalAssignment(hcpID, hospitalID); if (confirm) { TransactionLogger.getInstance().logTransaction(TransactionType.LHCP_REMOVE_HOSPITAL, loggedInMID, hcpID, ""); return "HCP successfully unassigned"; } else return "HCP not unassigned"; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Removes all hospital assignments for the given hcp mid * * @param midString * HCP's mid * @return status message * @throws ITrustException */ public int removeAllAssignmentsFromHCP(String midString) throws ITrustException { try { long hcpID = Long.valueOf(midString); int numAssignments = hospitalsDAO.removeAllHospitalAssignmentsFrom(hcpID); return numAssignments; } catch (NumberFormatException e) { throw new ITrustException("HCP's MID not a number"); } } /** * Checks if the hcpID param is a HCP * * @param hcpID * the String to be checked * @return the mid as a long if the hcpID is a HCP's mid * @throws ITrustException */ public long checkHCPID(String hcpID) throws ITrustException { try { long pid = Long.valueOf(hcpID); if (personnelDAO.checkPersonnelExists(pid)) return pid; else throw new ITrustException("HCP does not exist"); } catch (NumberFormatException e) { throw new ITrustException("HCP ID is not a number: " + e.getMessage()); } } /** * Checks if the HCP is a LT if it is then check to see if a hospital is assigned to them * * @param hcpID * the String to be checked * @return true If the LT has an assigned hospital, false if not * @throws ITrustException */ public boolean checkLTHospital(String hcpID) throws ITrustException{ try{ long pid = Long.valueOf(hcpID); if(personnelDAO.getPersonnel(pid).getRole().toString().equals("LT")){ if(hospitalsDAO.checkLTHasHospital(pid)){ return true; } return false; } } catch (NumberFormatException e) { throw new ITrustException("LT ID is not a number: " + e.getMessage()); } return false; } }
5,627
29.586957
116
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/PatientRoomAssignmentAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.WardRoomBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.WardDAO; public class PatientRoomAssignmentAction { /** * DAOFactory to use with the WardDAO */ WardDAO wardDAO = null; public PatientRoomAssignmentAction(DAOFactory factory){ wardDAO = new WardDAO(factory); } public void assignPatientToRoom(WardRoomBean wardRoom, long patientMID) throws DBException{ wardRoom.setOccupiedBy(patientMID); wardDAO.updateWardRoomOccupant(wardRoom); } public void assignPatientToRoom(WardRoomBean wardRoom, PatientBean patient) throws DBException{ assignPatientToRoom(wardRoom, patient.getMID()); } public void removePatientFromRoom(WardRoomBean wardRoom, String reason) throws DBException{ long mid = wardRoom.getOccupiedBy(); wardDAO.checkOutPatientReason(mid, reason); wardRoom.setOccupiedBy(null); wardDAO.updateWardRoomOccupant(wardRoom); } }
1,117
30.942857
96
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/PayBillAction.java
package edu.ncsu.csc.itrust.action; import java.sql.Timestamp; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.validator.CreditCardValidator; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.BillingBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.BillingDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; /** * This class aids payBill.jsp in paying a bill for a user. This mostly will * interact with the BillingDAO and verify user input. */ public class PayBillAction { /**billingDAO just access the database when I need to.*/ private BillingDAO billingDAO; /**myBill is the bill that we are paying.*/ private BillingBean myBill; private PatientDAO patientRetriever; /**The length of a credit card number*/ public static final int CC_NUMBER_LEN = 16; /** * PayBillAction is the constructor and it just sets the instance variables. * @param factory The object that makes the BillingDAO. * @param bID The ID of the bill we are paying. */ public PayBillAction(DAOFactory factory, long bID){ this.billingDAO = factory.getBillingDAO(); this.patientRetriever = factory.getPatientDAO(); try { this.myBill = billingDAO.getBillId(bID); } catch (DBException e) { e.printStackTrace(); } } /** * getBill returns the billing bean to make jsp stuff easy. * @return the bill we a handling. */ public BillingBean getBill(){ return this.myBill; } /** * getPatient gets the patient of the office visit. * @return The name of the patient. */ public String getPatient(){ String result = null; try { result = patientRetriever.getName(myBill.getPatient()); } catch (ITrustException e) { e.printStackTrace(); } return result; } /** * Pay bill with CreditCard validates input, and pays the bill if it can. * @param ccNum The Credit Card number. * @param ccHolder The Credit Card holder. * @param ccType The Credit Card type. * @param billAddress The bill address. * @param cvv The cvv. * @throws Exception It just throws an exception that contains the error message. */ public String payBillWithCC(String ccNum, String ccHolder, String ccType, String billAddress, String cvv) throws Exception{ Pattern checkCvv = Pattern.compile("[0-9]{3,4}"); if(ccType == null || ccType.equals("null")) return ("The field for Credit Card Type must be filled."); if(ccType.length() > 20) return ("The field for the Credit Card Type must be 20 or shorter."); myBill.setCcType(ccType); if(ccNum == null || ccNum.equals("null")) return ("The field for Credit Card Number must be filled."); int type = CreditCardValidator.NONE; if(ccType.equals("MasterCard")){ type = CreditCardValidator.MASTERCARD; } else if(ccType.equals("Visa")){ type = CreditCardValidator.VISA; } else if(ccType.equals("AmericanExpress")){ type = CreditCardValidator.AMEX; } else if(ccType.equals("Discover")){ type= CreditCardValidator.DISCOVER; } CreditCardValidator c = new CreditCardValidator(type); if(ccNum.length() > CC_NUMBER_LEN || !c.isValid(ccNum)) return ("Invalid Credit Card number."); myBill.setCcNumber(ccNum); if(ccHolder == null || ccHolder.equals("null")) return ("The field for Credit Card Holder must be filled."); if(ccHolder.length() > 30) return ("The Credit Card Holder must be 30 characters or shorter."); myBill.setCcHolderName(ccHolder); if(billAddress == null || billAddress.equals("null")) return ("The field for Billing Address must be filled."); if(billAddress.length() > 120) return ("The fields for Billing Address must be 120 characters or shorter."); myBill.setBillingAddress(billAddress); if(cvv == null || cvv.equals("null")) return ("The field for CVV must be filled."); Matcher verify = checkCvv.matcher(cvv); if(!verify.matches()) return ("Invalid CVV code."); myBill.setCvv(cvv); myBill.setStatus("Submitted"); myBill.setInsurance(false); billingDAO.editBill(myBill); return null; } /** * Pay bill with insurance just pays the bill with insurance information. * @param insHolder The holder of the insurance. * @param insProvider The provider of the insurance. * @param insID The insurance policy id. * @param insAdd1 The insurance address. * @param insAdd2 The insurance address. * @param insCity The insurance city. * @param insState The insurance state. * @param insZip The insurance zip code. * @param insPhone The insurance phone number. * @throws Exception The exception contains the error message. */ public String payBillWithIns(String insHolder, String insProvider, String insID, String insAdd1, String insAdd2, String insCity, String insState, String insZip, String insPhone) throws Exception{ Pattern checkID = Pattern.compile("[0-9a-zA-Z]+"); Pattern checkPhone = Pattern.compile("[0-9]{3}-[0-9]{3}-[0-9]{4}"); if(insHolder == null || insHolder.equals("null")) return ("The field for Insurance Holder must be filled."); myBill.setInsHolderName(insHolder); if(insProvider == null || insProvider.equals("null")) return ("The field for Insurance Provider must be filled."); if(insProvider.length() > 20) return ("The Insurance Provider must be 20 characters or shorter."); myBill.setInsProviderName(insProvider); if(insID == null || insID.equals("null")) return ("The field for Insurance Policy ID must be filled."); Matcher verify = checkID.matcher(insID); if(!verify.matches()) return ("Insurance IDs must consist of alphanumeric characters."); myBill.setInsID(insID); if(insAdd1 == null || insAdd1.equals("null")) return ("The field for Insurance Address 1 must be filled."); if(insAdd1.length() > 20) return ("The field for Insurnace Address 1 must be 20 characters or shorter."); myBill.setInsAddress1(insAdd1); if(insAdd2 == null || insAdd2.equals("null")) return ("The field for Insurance Address 2 must be filled."); if(insAdd2.length() > 20) return ("The field for Insurnace Address 2 must 20 characters or shorter."); myBill.setInsAddress2(insAdd2); if(insCity == null || insCity.equals("null")) return ("The field for Insurance City must be filled."); if(insCity.length() > 20) return ("The field for Insurance City must be 20 characters or shorter."); myBill.setInsCity(insCity); if(insState == null || insState.equals("null")) return ("The field for Insurance State must be filled."); if(insState.length() > 2) return ("The field for Insurance State must be 2 characters."); myBill.setInsState(insState); if(insZip == null || insZip.equals("null")) return ("The field for Insurance Zip must be filled."); myBill.setInsZip(insZip); if(insPhone == null || insPhone.equals("null")) return ("The field for Insurance Phone must be filled."); verify = checkPhone.matcher(insPhone); if(!verify.matches()) return ("Insurance Phone Number must match the form \"XXX-XXX-XXXX\""); myBill.setInsPhone(insPhone); myBill.setStatus("Pending"); myBill.setSubTime(new Timestamp(new Date().getTime())); myBill.setSubmissions(myBill.getSubmissions() + 1); myBill.setInsurance(true); billingDAO.editBill(myBill); return null; } }
7,448
33.971831
82
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/RequestRecordsReleaseAction.java
package edu.ncsu.csc.itrust.action; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.RecordsReleaseBean; import edu.ncsu.csc.itrust.model.old.beans.forms.RecordsReleaseForm; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.RecordsReleaseDAO; import edu.ncsu.csc.itrust.model.old.validate.RecordsReleaseFormValidator; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; public class RequestRecordsReleaseAction { /** Error message for if there is a database exception*/ public static final String DB_ERROR = "Error: There was an error in the database"; /** Error message for if there is no digital signature on a request form*/ public static final String SIGNATURE_ERROR = "Error: Digital signature does not match name on record"; /** Success message for if the request form is successfully submitted */ public static final String SUCCESS_MESSAGE = "Request successfully sent"; /** RecordsReleaseDAO object for working with record releases in the database*/ private RecordsReleaseDAO rrDAO; /** PatientDAO for working with patient objects in the database*/ private PatientDAO patDAO; /** HospitalsDAO for getting hospital objects from the database*/ private HospitalsDAO hosDAO; /** RecordsReleaseFormValidator to validate records release forms*/ private RecordsReleaseFormValidator validator = new RecordsReleaseFormValidator(); /** Long for storing the patient's mid */ private long pid; /** * Constructor for RequestRecordsReleaseAction. Gets and initializes all necessary DAOs for * working with requesting a patient's records. */ public RequestRecordsReleaseAction(DAOFactory factory, long pid) { rrDAO = new RecordsReleaseDAO(factory); patDAO = factory.getPatientDAO(); hosDAO = factory.getHospitalsDAO(); this.pid = pid; } /** * * @return */ public String getPatientName() { String name = ""; try { name = patDAO.getName(pid); } catch (DBException e1) { e1.printStackTrace(); } catch (ITrustException e2) { e2.printStackTrace(); } return name; } public String getHospitalName(String hospitalID) { String name = ""; try { HospitalBean hospital = hosDAO.getHospital(hospitalID); if (hospital != null) name = hospital.getHospitalName(); } catch (DBException e1) { e1.printStackTrace(); } return name; } /** * * @return */ public String addRecordsRelease(RecordsReleaseForm form) { RecordsReleaseBean release; try { //Validate the form validator.validate(form); //Check that there is a digital signature if (!form.getDigitalSignature()) return SIGNATURE_ERROR; //Transfer the form to a RecordsReleaseBean object release = transferForm(form); //Add the bean to the dao rrDAO.addRecordsRelease(release); } catch (FormValidationException e1) { String errorMsg = ""; //Check that there is a digital signature if (!form.getDigitalSignature()) errorMsg = ", " + SIGNATURE_ERROR.substring(SIGNATURE_ERROR.indexOf(' ') + 1); //If a form validation exception is thrown, indicate the release could not be added return e1.getMessage() + errorMsg; } catch (DBException e2) { //If a DBException is thrown, indicate the release could not be added return DB_ERROR; } //Indicate that the release request was successfully added return SUCCESS_MESSAGE; } public List<RecordsReleaseBean> getAllPatientReleaseRequests() { List<RecordsReleaseBean> releases = new ArrayList<RecordsReleaseBean>(); try { releases = rrDAO.getAllRecordsReleasesByPid(pid); } catch (DBException e) { e.printStackTrace(); } return releases; } public List<HospitalBean> getAllPatientHospitals() { List<HospitalBean> hospitals = new ArrayList<HospitalBean>(); try { //Get all hospitals where the patient has visited hospitals = hosDAO.getAllHospitals(); } catch (DBException e) { //If a DBException is thrown, print a stack trace and return an empty list e.printStackTrace(); } return hospitals; } private RecordsReleaseBean transferForm(RecordsReleaseForm form) { RecordsReleaseBean release = new RecordsReleaseBean(); //Set the date to the current time release.setDateRequested(new Timestamp(Calendar.getInstance().getTimeInMillis())); //Set the pid release.setPid(pid); //Set the hospital id release.setReleaseHospitalID(form.getReleaseHospitalID()); //Set the recipient hospital name and address release.setRecHospitalName(form.getRecipientHospitalName()); release.setRecHospitalAddress(form.getRecipientHospitalAddress()); //Set the receiving doctor's name release.setDocFirstName(form.getRecipientFirstName()); release.setDocLastName(form.getRecipientLastName()); //Set the receiving doctor's phone and email release.setDocEmail(form.getRecipientEmail()); release.setDocPhone(form.getRecipientPhone()); //Set the justification comment release.setJustification(form.getRequestJustification()); //Set the status of the request to pending release.setStatus(0); return release; } /** * Returns a list of PatientBeans of all patients the currently logged in patient represents * * @return a list of PatientBeans of all patients the currently logged in patient represents */ public List<PatientBean> getRepresented() { List<PatientBean> represented = new ArrayList<PatientBean>(); try { represented = patDAO.getRepresented(pid); } catch (DBException e) { //If a DBException occurs print a stack trace and return an empty list e.printStackTrace(); } return represented; } /** * Returns a list of PatientBeans of all patients the currently logged in patient represents and are a dependent * * @return a list of PatientBeans of all patients the currently logged in patient represents and are a dependent */ public List<PatientBean> getDependents() { List<PatientBean> dependents = new ArrayList<PatientBean>(); try { dependents = patDAO.getDependents(pid); } catch (DBException e) { //If a DBException occurs print a stack trace and return an empty list e.printStackTrace(); } return dependents; } }
6,626
31.970149
113
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ResetPasswordAction.java
package edu.ncsu.csc.itrust.action; import java.util.Arrays; import edu.ncsu.csc.itrust.EmailUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ErrorList; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.Role; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.ValidationFormat; /** * Manages resetting the password Used by resetPassword.jsp */ public class ResetPasswordAction { /**MAX_RESET_ATTEMPTS*/ public static final int MAX_RESET_ATTEMPTS = 3; private AuthDAO authDAO; private PatientDAO patientDAO; private DAOFactory factory; /** * Set up defaults * @param factory The DAOFactory used to create the DAOs used in this action. */ public ResetPasswordAction(DAOFactory factory) { this.authDAO = factory.getAuthDAO(); this.patientDAO = factory.getPatientDAO(); this.factory = factory; } /** * Checks to see if a user exists with the given mid * * @param midString The user's MID to check for. * @return 0 if the user does not exist, else the mid of the user as a long */ public long checkMID(String midString) { try { long mid = Long.valueOf(midString); if (!authDAO.checkUserExists(mid)) return 0; return mid; } catch (NumberFormatException e) { return 0L; } catch (DBException e) { return 0L; } } /** * Checks to see if the number of reset password attempts has been exceeded for the given ipAddress * * @param ipAddress The IPv4 or IPv6 IP address as a String. * @return true if the the number of reset attempts is greater than or equal to MAX_RESET_ATTEMPTS * @throws DBException */ public boolean isMaxedOut(String ipAddress) throws DBException { return authDAO.getResetPasswordFailures(ipAddress) >= MAX_RESET_ATTEMPTS; } /** * Checks if the given mid matches the given role * * @param mid * the mid to be checked * @param role * the role to be checked * @return true if the mid and role match * @throws ITrustException */ public String checkRole(long mid, String role) throws ITrustException { try { if (("patient".equals(role) && patientDAO.getRole(mid, role).equals("patient")) || ("hcp".equals(role) && patientDAO.getRole(mid, role).equals("hcp")) || ("uap".equals(role) && patientDAO.getRole(mid, role).equals("uap")) || ("pha".equals(role) && patientDAO.getRole(mid, role).equals("pha")) || ("er".equals(role) && patientDAO.getRole(mid, role).equals("er")) || ("lt".equals(role) && patientDAO.getRole(mid, role).equals("lt"))) return role; else return null; } catch (DBException e) { //TODO } catch (ITrustException e) { throw e; } return null; } /** * Checks if the answer param is null * * @param answer the user's security answer * @return answer if not null, else return null */ public String checkAnswerNull(String answer) { if (answer == null || "".equals(answer)) return null; else return answer; } /** * Returns the security question for the mid param * * @param mid MID of the user * @return the security question or "" if DBException thrown * @throws ITrustException */ public String getSecurityQuestion(long mid) throws ITrustException { try { if (null == authDAO.getSecurityQuestion(mid) || authDAO.getSecurityQuestion(mid).equals("")) throw new ITrustException("No security question or answer for this user has been set."); else return authDAO.getSecurityQuestion(mid); } catch (DBException e) { return ""; } } /** * Resets the password for the given mid * * @param mid of the user to have their password reset * @param role what role the user has in iTrust * @param answer answers to their security question * @param password their password * @param confirmPassword their password again * @param ipAddr the ip address the request is coming from * @return status message * @throws FormValidationException * @throws ITrustException */ public String resetPassword(long mid, String role, String answer, String password, String confirmPassword, String ipAddr) throws FormValidationException, ITrustException { Role r = authDAO.getUserRole(mid); try { Role.parse(role); } catch (IllegalArgumentException e) { return "Invalid role"; } if (r.equals(Role.ADMIN)) return "This role cannot be changed here"; if (!r.equals(Role.parse(role))) return "Role mismatch"; if (authDAO.getResetPasswordFailures(ipAddr) >= MAX_RESET_ATTEMPTS) { return "Too many retries"; } try { validatePassword(password, confirmPassword); if (answer.equals(authDAO.getSecurityAnswer(mid))) { authDAO.resetPassword(mid, password); new EmailUtil(factory).sendEmail(makeEmailApp(mid, role)); TransactionLogger.getInstance().logTransaction(TransactionType.EMAIL_SEND, mid, mid, ""); TransactionLogger.getInstance().logTransaction(TransactionType.PASSWORD_RESET, new Long(mid), null, ""); return "Password changed"; } else { authDAO.recordResetPasswordFailure(ipAddr); return "Answer did not match"; } } catch (DBException e) { return "Error in validation of security answer"; } } /** * Creates and sends an e-mail about the change * * @param mid the user who's password was changed * @param role what role they have in iTrust * @return the e-mial that is sent * @throws DBException */ private Email makeEmailApp(long mid, String role) throws DBException{ if(Role.parse(role) == Role.PATIENT){ PatientBean p = new PatientDAO(factory).getPatient(mid); Email email = new Email(); email.setFrom("no-reply@itrust.com"); email.setToList(Arrays.asList(p.getEmail())); email.setSubject("Your password has been changed in iTrust"); email.setBody(String.format("Dear %s, %n You have chosen to change your iTrust password for user %s", p.getFullName(), mid)); return email; } else{ //UAP or HCP - admin taken out in "resetPassword" PersonnelBean p = new PersonnelDAO(factory).getPersonnel(mid); Email email = new Email(); email.setFrom("no-reply@itrust.com"); email.setToList(Arrays.asList(p.getEmail())); email.setSubject("Your password has been changed in iTrust"); email.setBody(String.format("Dear %s, %n You have chosen to change your iTrust password for user %s", p.getFullName(), mid)); return email; } } /** * Checks to make sure the password is correctly entered twice. * * @param password the password * @param confirmPassword the password again for confirmation * @throws FormValidationException */ private void validatePassword(String password, String confirmPassword) throws FormValidationException { ErrorList errorList = new ErrorList(); if (password == null || "".equals(password)) { errorList.addIfNotNull("Password cannot be empty"); } else { if (!password.equals(confirmPassword)) errorList.addIfNotNull("Passwords don't match"); if (!ValidationFormat.PASSWORD.getRegex().matcher(password).matches()) { errorList.addIfNotNull("Password must be in the following format: " + ValidationFormat.PASSWORD.getDescription()); } } if (errorList.hasErrors()) throw new FormValidationException(errorList); } }
7,870
31.524793
128
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ReviewsAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.ReviewsBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ReviewsDAO; /** * This class forms the action for the HCP Reviewing system, each category * rated on a scale from 1 (lowest) to 5 (highest), and providing an overall rating * for the HCP. */ public class ReviewsAction { private ReviewsDAO dao; private PersonnelDAO personnelDAO; private long loggedInMID; public ReviewsAction(DAOFactory factory, long mid){ this.dao = factory.getReviewsDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = mid; } /** * Add a review based on the input params for input of a bean. * @return true if added and false otherwise */ public boolean addReview(ReviewsBean b) throws DBException{ return dao.addReview(b); } /** * Method that returns physician based on a mid. * @param mid of physician * @return * @throws DBException */ public PersonnelBean getPhysician(long mid) throws DBException { return personnelDAO.getPersonnel(mid); } /** * Get all reviews for a given HCP (ie pid input param), * return as a Java ArrayList * @param pid HCP under review's ID * @return java.utils.ArrayList of all reviews for the HCP * @throws DBException */ public List<ReviewsBean> getReviews(long pid) throws DBException{ return dao.getReviews(pid); } /** * Checks whether a patient can post a review for a physician. * @param pid * @return * @throws DBException */ public boolean isAbleToRate(long pid) throws DBException { return dao.isRateable(loggedInMID, pid); } /** * Get total average rating for a given HCP. * @param pid Long ID of the HCP under review * @return average int "rating" for the information * @throws DBException */ public double getAverageRating(long pid) throws DBException{ return dao.getTotalAverageRating(pid); } }
2,262
27.2875
84
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/SearchUsersAction.java
package edu.ncsu.csc.itrust.action; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; /** * SearchUsersAction */ @SuppressWarnings("unused") public class SearchUsersAction { private PatientDAO patientDAO; private PersonnelDAO personnelDAO; /** * Set up defaults * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the user who is performing the search. */ public SearchUsersAction(DAOFactory factory, long loggedInMID) { this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); } /** * Searches for all personnel with the first name and last name specified in the parameter list. * @param firstName The first name to be searched. * @param lastName The last name to be searched. * @return A java.util.List of PersonnelBeans for the users who matched. */ public List<PersonnelBean> searchForPersonnelWithName(String firstName, String lastName) { try { if("".equals(firstName)) firstName = "%"; if("".equals(lastName)) lastName = "%"; return personnelDAO.searchForPersonnelWithName(firstName, lastName); } catch (DBException e) { return null; } } /** * Search for all experts with first name and last name given in parameters. * @param query query * @return A java.util.List of PersonnelBeans */ public List<PersonnelBean> fuzzySearchForExperts(String query) { String[] subqueries=null; List<PersonnelBean> result = new ArrayList<PersonnelBean>(); if(query!=null && query.length()>0 && !query.startsWith("_")){ subqueries = query.split(" "); int i=0; for(String q : subqueries){ try { List<PersonnelBean> first = personnelDAO.fuzzySearchForExpertsWithName(q, ""); List<PersonnelBean> last = personnelDAO.fuzzySearchForExpertsWithName("", q); for(int j=0; j < last.size(); j++){ if(!result.contains(last.get(j))){ result.add(0, last.get(j)); } } for(int j=0; j < first.size(); j++){ if(!result.contains(first.get(j))){ result.add(0, first.get(j)); } } i++; } catch (DBException e1) { e1.printStackTrace(); } } } return result; } /** * Search for all patients with first name and last name given in parameters. * @param firstName The first name of the patient being searched. * @param lastName The last name of the patient being searched. * @return A java.util.List of PatientBeans */ public List<PatientBean> searchForPatientsWithName(String firstName, String lastName) { try { if("".equals(firstName)) firstName = "%"; if("".equals(lastName)) lastName = "%"; return patientDAO.searchForPatientsWithName(firstName, lastName); } catch (DBException e) { return null; } } /** * Search for all patients with first name and last name given in parameters. * @param query query * @return A java.util.List of PatientBeans */ public List<PatientBean> fuzzySearchForPatients(String query) { return fuzzySearchForPatients(query, false); } /** * Search for all patients with first name and last name given in parameters. * @param query query * @param allowDeactivated allowDeactivated * @return A java.util.List of PatientBeans */ @SuppressWarnings("unchecked") public List<PatientBean> fuzzySearchForPatients(String query, boolean allowDeactivated) { String[] subqueries=null; Set<PatientBean> patientsSet = new TreeSet<PatientBean>(); if(query!=null && query.length()>0 && !query.startsWith("_")){ subqueries = query.split(" "); Set<PatientBean>[] patients = new Set[subqueries.length]; int i=0; for(String q : subqueries){ try { patients[i] = new TreeSet<PatientBean>(); List<PatientBean> first = patientDAO.fuzzySearchForPatientsWithName(q, ""); List<PatientBean> last = patientDAO.fuzzySearchForPatientsWithName("", q); patients[i].addAll(first); patients[i].addAll(last); try{ long mid = Long.valueOf(q); //If the patient exists with the mid, then add the patient to the patient list List<PatientBean> searchMID = patientDAO.fuzzySearchForPatientsWithMID(mid); patients[i].addAll(searchMID); //old way of doing it when they only were returning one person //now that we are returning everybody with that as a substring in their MID, not necessary //yet want to keep it in case we revert sometime }catch(NumberFormatException e) { //TODO } i++; } catch (DBException e1) { e1.printStackTrace(); } } if (i > 0) { patientsSet.addAll(patients[0]); } for(Set<PatientBean> results : patients){ try{ patientsSet.retainAll(results); }catch(NullPointerException e) { //TODO } } } ArrayList<PatientBean> results=new ArrayList<PatientBean>(patientsSet); if(allowDeactivated == false) { for(int i=results.size()-1; i>=0; i--){ if(!results.get(i).getDateOfDeactivationStr().equals("")){ results.remove(i); } } } Collections.reverse(results); return results; } /** * getDeactivated is a special case used for when we want to see all deactivated patients. * @return The List of deactivated patients. */ public List<PatientBean> getDeactivated(){ List<PatientBean> result = new ArrayList<PatientBean>(); try { result = patientDAO.getAllPatients(); for(int i = result.size() - 1; i >= 0; i--){ if(result.get(i).getDateOfDeactivationStr().equals("")){ result.remove(i); } } } catch (DBException e) { //TODO } return result; } }
6,097
27.900474
97
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/SendMessageAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.EmailUtil; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.MessageBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.MessageDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.EMailValidator; import edu.ncsu.csc.itrust.model.old.validate.MessageValidator; /** * Class for SendMessage.jsp. */ public class SendMessageAction { private long loggedInMID; private EmailUtil emailer; private PatientDAO patientDAO; private PersonnelDAO personnelDAO; private MessageDAO messageDAO; private EMailValidator emailVal; private MessageValidator messVal; /** * Sets up defaults * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the user sending the message. */ public SendMessageAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.emailer = new EmailUtil(factory); this.messageDAO = factory.getMessageDAO(); this.emailVal = new EMailValidator(); this.messVal = new MessageValidator(); } /** * Sends a message * * @param mBean message to be sent * @throws ITrustException * @throws SQLException */ public void sendMessage(MessageBean mBean) throws ITrustException, SQLException, FormValidationException { messVal.validate(mBean); emailVal.validate(mBean); messageDAO.addMessage(mBean); Email email = new Email(); String senderName; String fromEmail; email.setFrom("noreply@itrust.com"); List<String> toList = new ArrayList<String>(); if (8999999999L < mBean.getFrom() && 8999999999L < mBean.getTo()){ //when from and to are LHCPs PersonnelBean sender = personnelDAO.getPersonnel(loggedInMID); PersonnelBean receiver = personnelDAO.getPersonnel(mBean.getTo()); toList.add(receiver.getEmail()); senderName = sender.getFullName(); fromEmail = sender.getEmail(); email.setBody(String.format("You have received a new message from %s in iTrust. To view it, go to \"http://localhost:8080/iTrust/auth/hcp/messageInbox.jsp\" and log in to iTrust using your username and password.", senderName)); }else{ if (6999999999L < mBean.getFrom()) { PersonnelBean sender = personnelDAO.getPersonnel(loggedInMID); if (6999999999L < mBean.getTo()) { //when from is any personnel and to is any personnel PersonnelBean receiver = personnelDAO.getPersonnel(mBean.getTo()); toList.add(receiver.getEmail()); senderName = sender.getFullName(); email.setBody(String.format("You have received a new message from %s in iTrust. To view it, go to \"http://localhost:8080/iTrust/auth/hcp/messageInbox.jsp\" and log in to iTrust using your username and password.", senderName)); } else { //when from is any personnel and to is patient PatientBean receiver = patientDAO.getPatient(mBean.getTo()); toList.add(receiver.getEmail()); senderName = sender.getFullName(); email.setBody(String.format("You have received a new message from %s in iTrust. To view it, go to \"http://localhost:8080/iTrust/auth/patient/messageInbox.jsp\" and log in to iTrust using your username and password.", senderName)); } fromEmail = sender.getEmail(); } else { PatientBean sender = patientDAO.getPatient(loggedInMID); if (6999999999L < mBean.getTo()) { //when from is patient and to is any personnel PersonnelBean receiver = personnelDAO.getPersonnel(mBean.getTo()); toList.add(receiver.getEmail()); senderName = sender.getFullName(); email.setBody(String.format("You have received a new message from %s in iTrust. To view it, go to \"http://localhost:8080/iTrust/auth/hcp/messageInbox.jsp\" and log in to iTrust using your username and password.", senderName)); } else { //when from is patient and to is patient PatientBean receiver = patientDAO.getPatient(mBean.getTo()); toList.add(receiver.getEmail()); senderName = sender.getFullName(); email.setBody(String.format("You have received a new message from %s in iTrust. To view it, go to \"http://localhost:8080/iTrust/auth/patient/messageInbox.jsp\" and log in to iTrust using your username and password.", senderName)); } fromEmail = sender.getEmail(); } } email.setToList(toList); email.setFrom(fromEmail); email.setSubject(String.format("A new message from %s", senderName)); emailer.sendEmail(email); TransactionLogger.getInstance().logTransaction(TransactionType.EMAIL_SEND, loggedInMID, mBean.getTo(), ""); TransactionLogger.getInstance().logTransaction(TransactionType.MESSAGE_SEND, loggedInMID, mBean.getTo(), ""); } /** * Returns the patient's name * * @param mid MId of the patient * @return the name of the patient * @throws ITrustException */ public String getPatientName(long mid) throws ITrustException { return patientDAO.getName(mid); } /** * Returns the personnel's name * * @param mid MId of the personnel * @return the name of the personnel * @throws ITrustException */ public String getPersonnelName(long mid) throws ITrustException { return personnelDAO.getName(mid); } /** * Returns a list of the patients that the logged in HCP represents * * @return list of the patients that the logged in HCP represents * @throws ITrustException */ public List<PatientBean> getMyRepresentees() throws ITrustException { List<PatientBean> representees = new ArrayList<PatientBean>(); try { representees = patientDAO.getRepresented(loggedInMID); } catch (DBException e) { //TODO } return representees; } /** * Returns the designated HCPs for the logged in patient. * * @return designated HCPs for the logged in patient. * @throws ITrustException */ public List<PersonnelBean> getMyDLHCPs() throws ITrustException { return getDLHCPsFor(loggedInMID); } /** * Returns the designated HCPs for the given patient. * @param pid pid * @return designated HCPs for the given patient. * @throws ITrustException */ public List<PersonnelBean> getDLHCPsFor(long pid) throws ITrustException { List<PersonnelBean> dlhcps = new ArrayList<PersonnelBean>(); try { dlhcps = patientDAO.getDeclaredHCPs(pid); } catch (DBException e) { //TODO } return dlhcps; } /** * getDLHCPByMID * @param mid mid * @return personnel * @throws ITrustException */ public PersonnelBean getDLHCPByMID(long mid) throws ITrustException { return personnelDAO.getPersonnel(mid); } }
7,320
34.887255
236
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/SetSecurityQuestionAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.SecurityQA; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.validate.SecurityQAValidator; /** * Handles setting and retrieving the security questions/answers for users Used by * patient/editMyDemographics.jsp, staff/editMyDemographics.jsp, staff/editPersonnell.jsp * * */ public class SetSecurityQuestionAction { private AuthDAO authDAO; private long loggedInMID; /** * Sets up defaults * * @param factory The DAOFactory used to create the DAOs used in this action. * @param rLoggedInMID The MID of the user who is setting their security question. * @throws ITrustException */ public SetSecurityQuestionAction(DAOFactory factory, long rLoggedInMID) throws ITrustException { this.authDAO = factory.getAuthDAO(); loggedInMID = checkMID(rLoggedInMID); } /** * Updates information in the database from the information held in the SecurityQA bean passed as a param * * @param a * SecurityQuestionBean that holds new information * @throws Exception */ public void updateInformation(SecurityQA a) throws Exception { SecurityQAValidator sqav = new SecurityQAValidator(); sqav.validate(a); authDAO.setSecurityQuestionAnswer(a.getQuestion(), a.getAnswer(), loggedInMID); } /** * Returns a SecurityQA bean holding the security info for the currently logged in user * * @return SecurityQA for loggedInMid * @throws ITrustException */ public SecurityQA retrieveInformation() throws ITrustException { SecurityQA toRet = new SecurityQA(); toRet.setAnswer(authDAO.getSecurityAnswer(loggedInMID)); toRet.setQuestion(authDAO.getSecurityQuestion(loggedInMID)); return toRet; } /** * Checks to make sure the MID exists in iTrust * * @param mid MID to check * @return returns the MID if the user is valid, otherwise, throws an exception * @throws ITrustException */ private long checkMID(long mid) throws ITrustException { if (!authDAO.checkUserExists(mid)) throw new ITrustException("MID " + mid + " is not a user!"); return mid; } }
2,260
30.402778
106
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/UpdateHospitalListAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; import edu.ncsu.csc.itrust.model.old.validate.HospitalBeanValidator; /** * Handles updating the list of hospitals Used by hospitalListing.jsp * * */ public class UpdateHospitalListAction { private HospitalsDAO hospDAO; private long performerID; /** * Set up * * @param factory The DAOFactory used to create the DAOs used in this action. * @param performerID The MID of the person updating the hospitals. */ public UpdateHospitalListAction(DAOFactory factory, long performerID) { this.hospDAO = factory.getHospitalsDAO(); this.performerID = performerID; } public void logViewHospitalListing() { TransactionLogger.getInstance().logTransaction(TransactionType.HOSPITAL_LISTING_VIEW, performerID, null, ""); } /** * Adds a hospital using the HospitalBean passed as a parameter * * @param hosp the new hospital listing * @return Status message * @throws FormValidationException */ public String addHospital(HospitalBean hosp) throws FormValidationException { new HospitalBeanValidator().validate(hosp); try { if (hospDAO.addHospital(hosp)) { TransactionLogger.getInstance().logTransaction(TransactionType.HOSPITAL_LISTING_ADD, performerID, null, hosp.getHospitalID()); return "Success: " + hosp.getHospitalID() + " - " + hosp.getHospitalName() + " added"; } else { return "The database has become corrupt. Please contact the system administrator for assistance."; } } catch (DBException e) { return e.getMessage(); } catch (ITrustException e) { return e.getMessage(); } } /** * Updates a hospital (based on the hospital id) using new information from the HospitalBean passed as a * parameter * * @param hosp the new hospital information with the same hospital id * @return Status message * @throws FormValidationException */ public String updateInformation(HospitalBean hosp) throws FormValidationException { new HospitalBeanValidator().validate(hosp); try { int rows = 0; if (0 == (rows = updateHospital(hosp))) { return "Error: Hospital not found."; } else { TransactionLogger.getInstance().logTransaction(TransactionType.HOSPITAL_LISTING_EDIT, performerID, null, "" + hosp.getHospitalID()); return "Success: " + rows + " row(s) updated"; } } catch (DBException e) { return e.getMessage(); } } /** * Updates hospital * * @param hosp new information * @return id for the updated hospital * @throws DBException */ private int updateHospital(HospitalBean hosp) throws DBException { return hospDAO.updateHospital(hosp); } }
3,076
30.721649
136
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/UpdateNDCodeListAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.MedicationBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.NDCodesDAO; import edu.ncsu.csc.itrust.model.old.validate.MedicationBeanValidator; /** * Handles updating the ND Code (Prescription) List Used by editNDCodes.jsp * * The National Drug Code (NDC) is a universal product identifier used in the * United States for drugs intended for human use. * * @see http://www.fda.gov/Drugs/InformationOnDrugs/ucm142438.htm */ public class UpdateNDCodeListAction { private NDCodesDAO ndDAO; private MedicationBeanValidator validator = new MedicationBeanValidator(); /** * Set up defaults. * * @param factory The DAOFactory used to create the DAOs used in this action. * @param performerID The MID of the user updating the ND lists. */ public UpdateNDCodeListAction(DAOFactory factory, long performerID) { ndDAO = factory.getNDCodesDAO(); } /** * Adds a new ND Code (prescription) to the list * * @param med * The new ND Code to be added * @return Status message * @throws FormValidationException */ public String addNDCode(MedicationBean med) throws FormValidationException { validator.validate(med); try { if (ndDAO.addNDCode(med)) { return "Success: " + med.getNDCode() + " - " + med.getDescription() + " added"; } else return "The database has become corrupt. Please contact the system administrator for assistance."; } catch (DBException e) { return e.getMessage(); } catch (ITrustException e) { return e.getMessage(); } } /** * Updates the ND Code with new information from the MedicationBean * * @param med * the MedicationBean that holds new information but the same code * @return status message * @throws FormValidationException */ public String updateInformation(MedicationBean med) throws FormValidationException { validator.validate(med); try { int rows = updateCode(med); if (0 == rows) { return "Error: Code not found."; } else { return "Success: " + rows + " row(s) updated"; } } catch (DBException e) { return e.getMessage(); } } /** * Medication information should already be validated * * @param med * @return * @throws DBException */ private int updateCode(MedicationBean med) throws DBException { return ndDAO.updateCode(med); } /** * Removes a ND Code (prescription) from the list * * @param med The ND Code to be removed * * @return Status message * @throws DBException */ public String removeNDCode(MedicationBean med) throws DBException { try { if (ndDAO.getNDCode(med.getNDCode()) == null) { return "Drug does not exist or already has been removed from the database."; } } catch (DBException e) { return e.getMessage(); } try { if (ndDAO.removeNDCode(med)) { return "Success: " + med.getNDCode() + " - " + med.getDescription() + " removed"; } else return "The database has become corrupt. Please contact the system administrator for assistance."; } catch (DBException e) { return e.getMessage(); } catch (ITrustException e) { return e.getMessage(); } } }
3,434
27.38843
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/UpdateReasonCodeListAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.OverrideReasonBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.DrugReactionOverrideCodesDAO; import edu.ncsu.csc.itrust.model.old.validate.OverrideReasonBeanValidator; /** * Handles updating the Reason Codes List Used by editReasonCodes.jsp * * The National Drug Code (NDC) is a universal product identifier used in the * United States for drugs intended for human use. * * @see http://archinte.ama-assn.org/cgi/content/full/163/21/2625/TABLEIOI20692T4 */ public class UpdateReasonCodeListAction { private DrugReactionOverrideCodesDAO orcDAO; private OverrideReasonBeanValidator validator = new OverrideReasonBeanValidator(); /** * Set up defaults. * * @param factory The DAOFactory used to create the DAOs used in this action. * @param performerID The MID of the user updating the ND lists. */ public UpdateReasonCodeListAction(DAOFactory factory, long performerID) { orcDAO = factory.getORCodesDAO(); } /** * Adds a new ND Code (prescription) to the list * * @param orc * The new ND Code to be added * @return Status message * @throws FormValidationException */ public String addORCode(OverrideReasonBean orc) throws FormValidationException { validator.validate(orc); try { if (orcDAO.addORCode(orc)) { return "Success: " + orc.getORCode() + " - " + orc.getDescription() + " added"; } else return "The database has become corrupt. Please contact the system administrator for assistance."; } catch (DBException e) { return e.getMessage(); } catch (ITrustException e) { return e.getMessage(); } } /** * Updates the ND Code with new information from the OverrideReasonBean * * @param orc * the OverrideReasonBean that holds new information but the same code * @return status message * @throws FormValidationException */ public String updateInformation(OverrideReasonBean orc) throws FormValidationException { validator.validate(orc); try { int rows = updateCode(orc); if (0 == rows) { return "Error: Code not found."; } else { return "Success: " + rows + " row(s) updated"; } } catch (DBException e) { return e.getMessage(); } } /** * Override Reason information should already be validated * * @param orc * @return * @throws DBException */ private int updateCode(OverrideReasonBean orc) throws DBException { return orcDAO.updateCode(orc); } }
2,724
28.945055
102
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/VerifyClaimAction.java
package edu.ncsu.csc.itrust.action; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.model.old.beans.BillingBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.BillingDAO; /** * VerifyClaimAction handles the interaction between a user and the * DAOs. */ public class VerifyClaimAction { /**The DAO to access the billing table*/ private BillingDAO billAccess; /**The bill that we are verifying*/ private BillingBean bill; /** * VerifyClaimAction simply initializes the instance variables. * @param factory The DAO factory * @param bID The ID of the bill. */ public VerifyClaimAction(DAOFactory factory, long bID){ billAccess = factory.getBillingDAO(); try { bill = billAccess.getBillId(bID); } catch (DBException e) { e.printStackTrace(); } } /** * getBill returns the bill we are handling. * @return The billing bean. */ public BillingBean getBill(){ return this.bill; } /** * denyClaim handles the user choosing to deny the claim. */ public void denyClaim(){ bill.setStatus("Denied"); try { this.billAccess.editBill(bill); } catch (DBException e) { e.printStackTrace(); } } /** * approveClaim handles the user choosing to approve the claim. */ public void approveClaim(){ bill.setStatus("Approved"); try { this.billAccess.editBill(bill); } catch (DBException e) { e.printStackTrace(); } } }
1,470
21.984375
67
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewApptRequestsAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.sql.Timestamp; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.beans.ApptRequestBean; import edu.ncsu.csc.itrust.model.old.beans.MessageBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ApptRequestDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * ViewApptRequestsAction */ public class ViewApptRequestsAction { private ApptRequestDAO arDAO; private ApptDAO aDAO; private long hcpid; private SendMessageAction msgAction; private PersonnelDAO pnDAO; /** * ViewApptRequestsAction * @param hcpid hcpid * @param factory factory */ public ViewApptRequestsAction(long hcpid, DAOFactory factory) { arDAO = factory.getApptRequestDAO(); aDAO = factory.getApptDAO(); pnDAO = factory.getPersonnelDAO(); this.hcpid = hcpid; msgAction = new SendMessageAction(factory, hcpid); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_REQUEST_VIEW, hcpid, 0L, ""); } /** * getApptRequests * @return reqs * @throws SQLException * @throws DBException */ public List<ApptRequestBean> getApptRequests() throws SQLException, DBException { List<ApptRequestBean> reqs = arDAO.getApptRequestsFor(hcpid); return reqs; } /** * getNumRequests * @param reqs reqs * @return int * * Returns the number of times in the appointment request list */ public int getNumRequests(List<ApptRequestBean> reqs){ int numOfPendingAppointments = 0; for(int i = 0; i < reqs.size(); i++){ if(reqs.get(i).isPending() == true){ numOfPendingAppointments++; } } return numOfPendingAppointments; } /** * acceptApptRequest * @param reqID reqID * @return message * @throws SQLException * @throws DBException */ public String acceptApptRequest(int reqID) throws SQLException, DBException { return acceptApptRequest(reqID, 0L, 0L); } public String acceptApptRequest(int reqID, long loggedInMID, long patientMID) throws SQLException, DBException { ApptRequestBean req = arDAO.getApptRequest(reqID); if (req.isPending() && !req.isAccepted()) { req.setPending(false); req.setAccepted(true); arDAO.updateApptRequest(req); aDAO.scheduleAppt(req.getRequestedAppt()); try { MessageBean msg = constructMessage(req.getRequestedAppt(), req.isAccepted()); msgAction.sendMessage(msg); } catch (Exception e) { //TODO } TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_REQUEST_APPROVED, loggedInMID, patientMID, ""); return "The appointment request you selected has been accepted and scheduled."; } else { return "The appointment request you selected has already been acted upon."; } } /** * rejectApptRequest * @param reqID reqID * @return message * @throws SQLException * @throws DBException */ public String rejectApptRequest(int reqID) throws SQLException, DBException { return rejectApptRequest(reqID, 0L, 0L); } public String rejectApptRequest(int reqID, long loggedInMID, long patientMID) throws SQLException, DBException { ApptRequestBean req = arDAO.getApptRequest(reqID); if (req.isPending() && !req.isAccepted()) { req.setPending(false); req.setAccepted(false); arDAO.updateApptRequest(req); try { MessageBean msg = constructMessage(req.getRequestedAppt(), req.isAccepted()); msgAction.sendMessage(msg); } catch (Exception e) { //TODO } TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_REQUEST_REJECTED, loggedInMID, patientMID, ""); return "The appointment request you selected has been rejected."; } else { return "The appointment request you selected has already been acted upon."; } } /** * constructMessage * @param appt appt * @param accepted accepted * @return msg * @throws ITrustException * @throws SQLException * @throws FormValidationException */ private MessageBean constructMessage(ApptBean appt, boolean accepted) throws ITrustException, SQLException, FormValidationException { MessageBean msg = new MessageBean(); msg.setFrom(appt.getHcp()); msg.setTo(appt.getPatient()); msg.setSubject("Your appointment request"); msg.setSentDate(new Timestamp(System.currentTimeMillis())); String body = "Your appointment request with " + pnDAO.getName(appt.getHcp()) + " on " + appt.getDate() + " has been "; if (accepted) body += "accepted."; else body += "rejected."; msg.setBody(body); return msg; } }
4,956
30.373418
134
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewClaimsAction.java
package edu.ncsu.csc.itrust.action; import java.text.SimpleDateFormat; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.BillingBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.BillingDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; /** * ViewClaimsAction handles interaction between user input and the billing DAO. */ public class ViewClaimsAction { /**billingAccess provides access to the Billing table*/ private BillingDAO billingAccess; /**patientRetriever provides access to the patients table*/ private PatientDAO patientRetriever; /** * ViewClaimsAction simply initializes the DAOs. * @param fact The dao factory that will create the DAOs */ public ViewClaimsAction(DAOFactory fact){ billingAccess = fact.getBillingDAO(); patientRetriever = fact.getPatientDAO(); } /** * getClaims returns a list of all the insurance claims. * @return A list of all the insurance claims. */ public List<BillingBean> getClaims(){ List<BillingBean> result = null; try { result = billingAccess.getInsuranceBills(); } catch (DBException e) { e.printStackTrace(); } return result; } /** * getSubmitter returns the person who submitted the claim. * @param b The bill we are curious about. * @return The name of the submitter. */ public String getSubmitter(BillingBean b){ String result = null; try { result = patientRetriever.getName(b.getPatient()); } catch (ITrustException e) { e.printStackTrace(); } return result; } /** * getDate returns the date the bill was submitted. * @param b The bill we are talking * @return */ public String getDate(BillingBean b){ return new SimpleDateFormat("MM/dd/YYYY").format(b.getSubTime()); } }
1,907
26.257143
80
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewHelperAction.java
package edu.ncsu.csc.itrust.action; /** * Edits the designated personnel Used by admin/editPersonnel.jsp, staff/editMyDemographics.jsp, * editPersonnel.jsp */ public class ViewHelperAction { /** * calculateColor * @param primaryColor primaryColor * @param secondaryColor secondaryColor * @param ratio ratio * @return string */ public static String calculateColor(String primaryColor, String secondaryColor, double ratio) { double primeRed = Integer.parseInt(primaryColor.substring(0, 2), 16); double primeGreen = Integer.parseInt(primaryColor.substring(2, 4), 16); double primeBlue = Integer.parseInt(primaryColor.substring(4, 6), 16); double secondRed = Integer.parseInt(secondaryColor.substring(0, 2), 16); double secondGreen = Integer.parseInt(secondaryColor.substring(2, 4), 16); double secondBlue = Integer.parseInt(secondaryColor.substring(4, 6), 16); int newRed = (int) (secondRed*ratio + primeRed*(1-ratio)); int newGreen = (int) (secondGreen*ratio + primeGreen*(1-ratio)); int newBlue = (int) (secondBlue*ratio + primeBlue*(1-ratio)); return String.format("%06X", (newRed << 16) + (newGreen << 8) + newBlue); } }
1,172
35.65625
96
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyAccessLogAction.java
package edu.ncsu.csc.itrust.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.TransactionBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.TransactionDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Handles retrieving the log of record accesses for a given user Used by viewAccessLog.jsp * * */ public class ViewMyAccessLogAction { private TransactionDAO transDAO; private PatientDAO patientDAO; private long loggedInMID; /** * Set up * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person retrieving the logs. */ public ViewMyAccessLogAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.transDAO = factory.getTransactionDAO(); this.patientDAO = factory.getPatientDAO(); } /** * Returns a list of TransactionBeans between the two dates passed as params * * @param lowerDate * the first date * @param upperDate * the second date * @return list of TransactionBeans * @throws DBException * @throws FormValidationException */ public List<TransactionBean> getAccesses(String lowerDate, String upperDate, String logMID, boolean getByRole) throws ITrustException, DBException, FormValidationException { List<TransactionBean> accesses; //stores the log entries List<PersonnelBean> dlhcps; //get the medical dependents for a signed in user. If the selected user is not the //signed in user or one of the dependents, then the user doesn't have access to the log List<PatientBean> patientRelatives = getRepresented(loggedInMID); long mid = loggedInMID; try { mid = Long.parseLong(logMID); } catch (Exception e) { //TODO } dlhcps = patientDAO.getDeclaredHCPs(mid); boolean midInScope = false; for (PatientBean pb : patientRelatives) { if (pb.getMID() == mid) midInScope = true; } if (mid != loggedInMID && !midInScope) { //the selected user in the form is out of scope and can't be shown to the user throw new FormValidationException("Log to View."); } //user has either 0 or 1 DLHCP's. Get one if exists so it can be filtered from results long dlhcpID = -1; if(!dlhcps.isEmpty()) dlhcpID = dlhcps.get(0).getMID(); if (lowerDate == null || upperDate == null) return transDAO.getAllRecordAccesses(mid, dlhcpID, getByRole); try { /*the way the Date class works, is if you enter more months, or days than is allowed, it will simply mod it, and add it all together. To make sure it matches MM/dd/yyyy, I am going to use a Regular Expression */ //month can have 1 or 2 digits, same with day, and year must have 4 Pattern p = Pattern.compile("[0-9]{1,2}?/[0-9]{1,2}?/[0-9]{4}?"); Matcher m = p.matcher(upperDate); Matcher n = p.matcher(lowerDate); //if it fails to match either of them, throw the form validation exception if (!m.matches() || !n.matches()) { throw new FormValidationException("Enter dates in MM/dd/yyyy"); } Date lower = new SimpleDateFormat("MM/dd/yyyy").parse(lowerDate); Date upper = new SimpleDateFormat("MM/dd/yyyy").parse(upperDate); if (lower.after(upper)) throw new FormValidationException("Start date must be before end date!"); accesses = transDAO.getRecordAccesses(mid, dlhcpID, lower, upper, getByRole); } catch (ParseException e) { throw new FormValidationException("Enter dates in MM/dd/yyyy"); } return accesses; } /** * Returns the date of the first Transaction in the list passed as a param if the list is not empty * otherwise, returns today's date * * @param accesses A java.util.List of TransactionBeans for the accesses. * @return A String representing the date of the first transaction. */ public String getDefaultStart(List<TransactionBean> accesses) { String startDate = ""; if (accesses.size() > 0) { startDate = new SimpleDateFormat("MM/dd/yyyy").format(new Date(accesses.get(accesses.size() - 1) .getTimeLogged().getTime())); } else { startDate = new SimpleDateFormat("MM/dd/yyyy").format(new Date()); } return startDate; } /** * Returns the date of the last Transaction in the list passed as a param if the list is not empty * otherwise, returns today's date * * @param accesses A java.util.List of TransactionBeans storing the access. * @return A String representation of the date of the last transaction. */ public String getDefaultEnd(List<TransactionBean> accesses) { String endDate = ""; if (accesses.size() > 0) { endDate = new SimpleDateFormat("MM/dd/yyyy").format(new Date(accesses.get(0).getTimeLogged() .getTime())); } else { endDate = new SimpleDateFormat("MM/dd/yyyy").format(new Date()); } return endDate; } /** * Return a list of patients that pid represents * * @param pid The id of the personnel we are looking up representees for. * @return a list of PatientBeans * @throws ITrustException */ public List<PatientBean> getRepresented(long pid) throws ITrustException { return patientDAO.getRepresented(pid); } public void logViewAccessLog(Long mid) { TransactionLogger.getInstance().logTransaction(TransactionType.ACCESS_LOG_VIEW, mid, null, ""); } }
5,886
34.463855
148
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyApptsAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.ApptBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; public class ViewMyApptsAction extends ApptAction { private long loggedInMID; public ViewMyApptsAction(DAOFactory factory, long loggedInMID) { super(factory, loggedInMID); this.loggedInMID = loggedInMID; TransactionLogger.getInstance().logTransaction(TransactionType.UPCOMING_APPOINTMENTS_VIEW, loggedInMID, 0L, ""); TransactionLogger.getInstance().logTransaction(TransactionType.APPOINTMENT_ALL_VIEW, loggedInMID, 0L, ""); } public void setLoggedInMID(long mid) { this.loggedInMID = mid; } public List<ApptBean> getMyAppointments() throws SQLException, DBException { return apptDAO.getApptsFor(loggedInMID); } public List<ApptBean> getAllMyAppointments() throws SQLException, DBException { return apptDAO.getAllApptsFor(loggedInMID); } /** * Gets a user's appointments * * @param mid the MID of the user * @return a list of the user's appointments * @throws SQLException * @throws DBException */ public List<ApptBean> getAppointments(long MID) throws SQLException, DBException { return apptDAO.getApptsFor(MID); } }
1,432
30.152174
114
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyBillingAction.java
/** * */ package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.BillingBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.BillingDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** This class is responsible for retrieving bills for a patient */ public class ViewMyBillingAction { private BillingDAO billingDAO; private long loggedInMID; /** * @param factory The DAOFactory used to create the DAOs used in this action * @param loggedInMID MID of the patient who is viewing their bills */ public ViewMyBillingAction(DAOFactory factory, long loggedInMID) { this.billingDAO = factory.getBillingDAO(); this.loggedInMID = loggedInMID; } /** * Gets all the unpaid bills for a logged in patient * * @return a list of all unpaid bills * @throws SQLException * @throws DBException */ public List<BillingBean> getMyUnpaidBills() throws SQLException, DBException { return billingDAO.getUnpaidBills(loggedInMID); } /** * Gets all the bills for a logged in patient. * * @return a list of all bills * @throws SQLException * @throws DBException */ public List<BillingBean> getAllMyBills() throws SQLException, DBException { TransactionLogger.getInstance().logTransaction(TransactionType.PATIENT_BILLS_VIEW_ALL, loggedInMID, 0L, ""); return billingDAO.getBills(loggedInMID); } }
1,587
27.872727
113
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyMessagesAction.java
package edu.ncsu.csc.itrust.action; import java.sql.SQLException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.MessageBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.MessageDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Action class for ViewMyMessages.jsp */ public class ViewMyMessagesAction { private long loggedInMID; private PatientDAO patientDAO; private PersonnelDAO personnelDAO; private MessageDAO messageDAO; /** * Set up defaults * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the user who is viewing their messages. * @throws SQLException * @throws DBException */ public ViewMyMessagesAction(DAOFactory factory, long loggedInMID) throws DBException, SQLException { this.loggedInMID = loggedInMID; this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.messageDAO = factory.getMessageDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.MESSAGE_VIEW, loggedInMID, 0L, ""); TransactionLogger.getInstance().logTransaction(TransactionType.NOTIFICATIONS_VIEW, loggedInMID, 0l, ""); } /** * Gets all the messages for the logged in user * * @return a list of all the user's messages * @throws SQLException * @throws DBException */ public List<MessageBean> getAllMyMessages() throws SQLException, DBException { TransactionLogger.getInstance().logTransaction(TransactionType.INBOX_VIEW, loggedInMID, 0L, ""); return messageDAO.getMessagesForMID(loggedInMID); } /** * Gets all the messages for the logged in user and sorts by ascending time * * @return a list of all the user's messages * @throws SQLException * @throws DBException */ public List<MessageBean> getAllMyMessagesTimeAscending() throws SQLException, DBException { return messageDAO.getMessagesTimeAscending(loggedInMID); } /** * Gets all the messages for the logged in user and sorts names in ascending order * * @return a list of all the user's messages * @throws SQLException * @throws DBException */ public List<MessageBean> getAllMyMessagesNameAscending() throws SQLException, DBException { return messageDAO.getMessagesNameAscending(loggedInMID); } /** * Gets all the messages for the logged in user and sorts name in descending order * * @return a list of all the user's messages * @throws SQLException * @throws DBException */ public List<MessageBean> getAllMyMessagesNameDescending() throws SQLException, DBException { return messageDAO.getMessagesNameDescending(loggedInMID); } /** * Gets all the sent messages for the logged in user * * @return a list of all the user's sent messages * @throws SQLException */ public List<MessageBean> getAllMySentMessages() throws DBException, SQLException { TransactionLogger.getInstance().logTransaction(TransactionType.OUTBOX_VIEW, loggedInMID, 0l, ""); return messageDAO.getMessagesFrom(loggedInMID); } /** * Gets all the messages for the logged in user and sorts by ascending time * * @return a list of all the user's messages * @throws SQLException */ public List<MessageBean> getAllMySentMessagesTimeAscending() throws DBException, SQLException { return messageDAO.getMessagesFromTimeAscending(loggedInMID); } /** * Gets all the messages for the logged in user and sorts names in ascending order * * @return a list of all the user's messages * @throws SQLException */ public List<MessageBean> getAllMySentMessagesNameAscending() throws DBException, SQLException { return messageDAO.getMessagesFromNameAscending(loggedInMID); } /** * Gets all the messages for the logged in user and sorts name in descending order * * @return a list of all the user's messages * @throws SQLException */ public List<MessageBean> getAllMySentMessagesNameDescending() throws DBException, SQLException { return messageDAO.getMessagesFromNameDescending(loggedInMID); } /** * Gets a list of messages for a user based on their filter criteria. * * @param messages List of all of a user's MessageBeans * @param filter String containing a user's filter criteria. * @return a List of MessageBeans that meet the criteria of the filter. * @throws ITrustException * @throws ParseException */ public List<MessageBean> filterMessages(List<MessageBean> messages, String filter) throws ITrustException, ParseException { List<MessageBean> filtered = new ArrayList<MessageBean>(); String[] f = filter.split(",", -1); for(MessageBean m : messages) { /** * Check the sender filter field. * Exclude if this MessageBean does not match the * requested sender, if one is specified. */ if(!f[0].equals("")) { if(!this.getName(m.getFrom()).equalsIgnoreCase(f[0])) continue; } /** * Check the subject filter field. * Exclude if this MessageBean does not match the * requested subject, if one is specified. */ if(!f[1].equals("")) { if(!m.getSubject().equalsIgnoreCase(f[1])) continue; } /** * Check the body of the message for certain words. * Exclude if this MessageBean if it does not contain * those words in the message body. */ if(!f[2].equals("")) { if(!m.getSubject().toLowerCase().contains(f[2].toLowerCase()) && !m.getBody().toLowerCase().contains(f[2].toLowerCase())) continue; } /** * Check the body of the message for certain words. * Exclude if this MessageBean if it does contain * those words in the message body. */ if(!f[3].equals("")) { if(m.getSubject().toLowerCase().contains(f[3].toLowerCase()) || m.getBody().toLowerCase().contains(f[3].toLowerCase())) continue; } /** * Check the start date filter field. * Exclude if this MessageBean was not sent after * this date. */ if(!f[4].equals("")) { DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Date s = format.parse(f[4]); if(s.after(m.getSentDate())) continue; } /** * Check the end date filter field. * Exclude if this MessageBean was not sent before * this date. */ if(!f[5].equals("")) { DateFormat format = new SimpleDateFormat("MM/dd/yyyy"); Date s = format.parse(f[5]); Calendar c = Calendar.getInstance(); c.setTime(s); c.add(Calendar.DAY_OF_MONTH, 1); s = c.getTime(); if(s.before(m.getSentDate())) continue; } /** * If the message has not been eliminated by any * of the filter fields, add it to the new list * of messages. */ filtered.add(m); } return filtered; } /** * Gets a patient's name from their MID * * @param mid the MID of the patient * @return the patient's name * @throws ITrustException */ public String getName(long mid) throws ITrustException { if(mid < 7000000000L) return patientDAO.getName(mid); else return personnelDAO.getName(mid); } /** * Gets a personnel's name from their MID * * @param mid the MID of the personnel * @return the personnel's name * @throws ITrustException */ public String getPersonnelName(long mid) throws ITrustException { return personnelDAO.getName(mid); } /** * Set the state of the MessageBean to read, after * it is read by a user. * @param mBean MessageBean to be read */ public void setRead(MessageBean mBean) { try { messageDAO.updateRead(mBean); } catch (DBException e) { //TODO } } /** * Get the number of unread messages that the current user has. * * @return The number of unread messages. * @throws SQLException * @throws DBException */ public int getUnreadCount() throws SQLException, DBException { List<MessageBean> messages = getAllMyMessages(); int count = 0; for (MessageBean mb: messages) { if (mb.getRead() == 0) { count++; } } return count; } /** * getCCdMessages * @param refID refID * @return messageDAO * @throws DBException * @throws SQLException */ public List<MessageBean> getCCdMessages(long refID) throws DBException, SQLException{ return messageDAO.getCCdMessages(refID); } }
8,768
28.525253
125
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyRecordsAction.java
package edu.ncsu.csc.itrust.action; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.AllergyBean; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.FamilyMemberBean; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.ReportRequestBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AllergyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.FakeEmailDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.FamilyDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ReportRequestDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Handles patients viewing their own records Used by viewMyRecords.jsp * * */ public class ViewMyRecordsAction { /** The number of months in a year */ public static final int MONTHS_IN_YEAR = 12; private PatientDAO patientDAO; private PersonnelDAO personnelDAO; private AllergyDAO allergyDAO; private FamilyDAO familyDAO; private FakeEmailDAO emailDAO; private ReportRequestDAO reportRequestDAO; private long loggedInMID; /** * Set up * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person viewing the records. */ public ViewMyRecordsAction(DAOFactory factory, long loggedInMID) { this.patientDAO = factory.getPatientDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.allergyDAO = factory.getAllergyDAO(); this.familyDAO = factory.getFamilyDAO(); this.emailDAO = factory.getFakeEmailDAO(); this.reportRequestDAO = factory.getReportRequestDAO(); this.loggedInMID = loggedInMID; } /** * Takes the patient's representee as a param and returns it as a long if the patient represents the input * param * * @param input * the patient's representee mid * @return representee's mid as a long * @throws ITrustException */ public long representPatient(String input) throws ITrustException { try { long reppeeMID = Long.valueOf(input); if (patientDAO.represents(loggedInMID, reppeeMID)) { loggedInMID = reppeeMID; return reppeeMID; } else throw new ITrustException("You do not represent patient " + reppeeMID); } catch (NumberFormatException e) { throw new ITrustException("MID is not a number"); } } /** * Returns a PatientBean for the currently logged in patient * * @return PatientBean for the currently logged in patient * @throws ITrustException */ public PatientBean getPatient() throws ITrustException { return patientDAO.getPatient(loggedInMID); } /** * Returns a PatientBean for the specified MID * @param mid id of the requested bean * @return PatientBean for the specified MID * @throws ITrustException */ public PatientBean getPatient(long mid) throws ITrustException { return patientDAO.getPatient(mid); } /** * Returns a PersonnelBean for the requested MID * @param mid id of the requested bean * @return a PersonnelBean for the requested MID * @throws ITrustException */ public PersonnelBean getPersonnel(long mid) throws ITrustException { return personnelDAO.getPersonnel(mid); } /** * Returns a PatientBean for the currently logged in patient * * @return PatientBean for the currently logged in patient * @throws ITrustException */ public List<Email> getEmailHistory() throws ITrustException { TransactionLogger.getInstance().logTransaction(TransactionType.EMAIL_HISTORY_VIEW, loggedInMID, (long)0, ""); return emailDAO.getEmailsByPerson(getPatient().getEmail()); } /** * Returns a list of AllergyBeans for the currently logged in patient * * @return a list of AllergyBeans for the currently logged in patient * @throws ITrustException */ public List<AllergyBean> getAllergies() throws ITrustException { return allergyDAO.getAllergies(loggedInMID); } /** * Returns a list of Parents, Siblings, and Children of the currently logged in patient * * @return list of FamilyMemberBeans */ public List<FamilyMemberBean> getFamily() throws ITrustException { List<FamilyMemberBean> fam = new ArrayList<FamilyMemberBean>(); List<FamilyMemberBean> parents = null; try { parents = familyDAO.getParents(loggedInMID); fam.addAll(parents); fam.addAll(familyDAO.getSiblings(loggedInMID)); fam.addAll(familyDAO.getChildren(loggedInMID)); } catch (DBException e) { throw new ITrustException(e.getMessage()); } if(parents != null) { List<FamilyMemberBean> grandparents = new ArrayList<FamilyMemberBean>(); for(FamilyMemberBean parent : parents) { try { grandparents.addAll(familyDAO.getParents(parent.getMid())); } catch (DBException e) { throw new ITrustException(e.getMessage()); } } fam.addAll(grandparents); for(FamilyMemberBean gp : grandparents) { gp.setRelation("Grandparent"); } } return fam; } /** * Returns a list of Parents, Siblings, and Grand Parents of the currently logged in patient * * @return list of FamilyMemberBeans */ public List<FamilyMemberBean> getFamilyHistory() throws ITrustException { List<FamilyMemberBean> fam = new ArrayList<FamilyMemberBean>(); List<FamilyMemberBean> parents = null; try { parents = familyDAO.getParents(loggedInMID); fam.addAll(parents); fam.addAll(familyDAO.getSiblings(loggedInMID)); } catch (DBException e) { throw new ITrustException(e.getMessage()); } if(parents != null) { List<FamilyMemberBean> grandparents = new ArrayList<FamilyMemberBean>(); for(FamilyMemberBean parent : parents) { try { grandparents.addAll(familyDAO.getParents(parent.getMid())); } catch (DBException e) { throw new ITrustException(e.getMessage()); } } fam.addAll(grandparents); for(FamilyMemberBean gp : grandparents) { gp.setRelation("Grandparent"); } } return fam; } /** * Returns a list of PatientBeans of all patients the currently logged in patient represents * * @return a list of PatientBeans of all patients the currently logged in patient represents * @throws ITrustException */ public List<PatientBean> getRepresented() throws ITrustException { return patientDAO.getRepresented(loggedInMID); } /** * Returns a list of PatientBeans of all patients the currently logged in patient represents * * @return a list of PatientBeans of all patients the currently logged in patient represents * @throws ITrustException */ public List<PatientBean> getRepresenting() throws ITrustException { return patientDAO.getRepresenting(loggedInMID); } /** * Returns all the report requests for the logged in patient * @return the report requests for the logged in patient * @throws ITrustException */ public List<ReportRequestBean> getReportRequests() throws ITrustException { return reportRequestDAO.getAllReportRequestsForPatient(loggedInMID); } /** * Get patient's (logged in user's) age in months by taking the date of viewing the patient's records * and comparing it with the patient's date of birth. * * @param viewDate The date of the patient's records are being viewed * @return the patient's age in months * @throws DBException */ public int getPatientAgeInMonths(Calendar viewDate) throws DBException { //Create int for patient's age in months int ageInMonths = 0; //Get the patient's birthdate Calendar birthDate = Calendar.getInstance(); PatientBean patient = patientDAO.getPatient(loggedInMID); birthDate.setTime(patient.getDateOfBirth()); //Split the patient's birthdate into day, month, and year int birthDay = birthDate.get(Calendar.DAY_OF_MONTH); int birthMonth = birthDate.get(Calendar.MONTH) + 1; int birthYear = birthDate.get(Calendar.YEAR); //Split the office visit date into day month and year int visitDay = viewDate.get(Calendar.DAY_OF_MONTH); int visitMonth = viewDate.get(Calendar.MONTH) + 1; int visitYear = viewDate.get(Calendar.YEAR); //Calculate the year, month, and day differences int yearDiff = visitYear - birthYear; int monthDiff = visitMonth - birthMonth; int dayDiff = visitDay - birthDay; //Get the patient's age in months by multiplying the year difference by 12 //and adding the month difference ageInMonths = yearDiff * MONTHS_IN_YEAR + monthDiff; //If the day difference is negative, subtract a month from the age if (dayDiff < 0) { ageInMonths -= 1; } //Return the age in months return ageInMonths; } public void logViewMedicalRecords(Long mid, Long secondary) { TransactionLogger.getInstance().logTransaction(TransactionType.MEDICAL_RECORD_VIEW, mid, secondary, ""); } }
9,132
31.386525
111
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyRemoteMonitoringListAction.java
package edu.ncsu.csc.itrust.action; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.FormValidationException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.RemoteMonitoringDataBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.AuthDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.RemoteMonitoringDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Handles retrieving the patient data for a certain HCP as used by viewTelemedicineData.jsp */ public class ViewMyRemoteMonitoringListAction { private RemoteMonitoringDAO rmDAO; private AuthDAO authDAO; private long loggedInMID; /** * Constructor * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the HCP retrieving the patient data. */ public ViewMyRemoteMonitoringListAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.rmDAO = factory.getRemoteMonitoringDAO(); this.authDAO = factory.getAuthDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.PATIENT_LIST_VIEW, loggedInMID, (long)0, "Viewed monitored patients"); } /** * Returns a list of RemoteMonitoringDataBeans for the logged in HCP * * @return list of TransactionBeans * @throws DBException * @throws FormValidationException */ public List<RemoteMonitoringDataBean> getPatientsData() throws DBException { return rmDAO.getPatientsData(loggedInMID); } /** * Returns a list of RemoteMonitoringDataBeans for the logged in HCP * @param patientMID patientMID * @param startDate startDate * @param endDate endDate * @return list of TransactionBeans * @throws DBException * @throws FormValidationException */ public List<RemoteMonitoringDataBean> getPatientDataByDate(long patientMID, String startDate, String endDate) throws DBException, FormValidationException { Date lower; Date upper; try { lower = new SimpleDateFormat("MM/dd/yyyy").parse(startDate); upper = new SimpleDateFormat("MM/dd/yyyy").parse(endDate); if (lower.after(upper)) throw new FormValidationException("Start date must be before end date!"); } catch (ParseException e) { throw new FormValidationException("Enter dates in MM/dd/yyyy"); } return rmDAO.getPatientDataByDate(patientMID, lower, upper); } /** * Returns a list of RemoteMonitoringDataBeans for the logged in HCP based on a certain data type * @param patientMID patientMID * @param dataType dataType * @return list of TransactionBeans * @throws DBException * @throws FormValidationException */ public List<RemoteMonitoringDataBean> getPatientDataByType(long patientMID, String dataType) throws DBException, FormValidationException { String types[] = {"weight", "systolicBloodPressure", "diastolicBloodPressure", "glucoseLevel", "pedometerReading"}; boolean valid = false; for (String dType : types) { if (dType.equals(dataType)) { valid = true; break; } } if (!valid) { throw new FormValidationException("Input must be a valid telemedicine data type!"); } TransactionLogger.getInstance().logTransaction(TransactionType.PATIENT_LIST_VIEW, loggedInMID, (long)0, "Viewed monitored patients"); return rmDAO.getPatientDataByType(patientMID, dataType); } /** * getPatientDataWithoutLogging * @return rmDAO * @throws DBException */ public List<RemoteMonitoringDataBean> getPatientDataWithoutLogging() throws DBException { return rmDAO.getPatientsData(loggedInMID); } /** * returns the patient name * @param pid pid * @return patient name * @throws ITrustException */ public String getPatientName(long pid) throws ITrustException { return authDAO.getUserName(pid); } /** * Useful to figure out who is monitoring a given patient * * @return list of HCPs monitoring this patient * @throws ITrustException */ public List<PersonnelBean> getMonitoringHCPs() throws ITrustException { return rmDAO.getMonitoringHCPs(loggedInMID); } }
4,371
31.626866
156
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewMyReportRequestsAction.java
package edu.ncsu.csc.itrust.action; import java.util.Calendar; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.ReportRequestBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ReportRequestDAO; /** * Action class for ViewMyReports.jsp. Allows the user to see all their reports */ public class ViewMyReportRequestsAction { private long loggedInMID; private ReportRequestDAO reportRequestDAO; private PersonnelDAO personnelDAO; /** * Set up * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person viewing their report requests. */ public ViewMyReportRequestsAction(DAOFactory factory, long loggedInMID) { this.loggedInMID = loggedInMID; this.reportRequestDAO = factory.getReportRequestDAO(); this.personnelDAO = factory.getPersonnelDAO(); } /** * Returns all the reports for the currently logged in HCP * * @return list of all reports for the logged in HCP * @throws ITrustException */ public List<ReportRequestBean> getAllReportRequestsForRequester() throws ITrustException { return reportRequestDAO.getAllReportRequestsForRequester(loggedInMID); } /** * Adds a report request to the list * * @param patientMID ID of the patient that the report request is for * @return id * @throws ITrustException */ public long addReportRequest(long patientMID) throws ITrustException { long id = reportRequestDAO .addReportRequest(loggedInMID, patientMID, Calendar.getInstance().getTime()); return id; } /** * Returns the requested report * * @param ID id of the requested report * @return the requested report * @throws ITrustException */ public ReportRequestBean getReportRequest(int ID) throws ITrustException { return reportRequestDAO.getReportRequest(ID); } /** * Sets the viewed status of the report. If the report is "viewed" the HCP must request a new one to see it again. * * @param ID id of the report * @throws ITrustException */ public void setViewed(int ID) throws ITrustException { reportRequestDAO.setViewed(ID, Calendar.getInstance().getTime()); } /** * Gets the status of the request * * @param id id of the request * @return the request's status * @throws ITrustException */ public String getLongStatus(long id) throws ITrustException { StringBuilder s = new StringBuilder(); ReportRequestBean r = reportRequestDAO.getReportRequest(id); if (r.getStatus().equals(ReportRequestBean.Requested)) { PersonnelBean p = personnelDAO.getPersonnel(r.getRequesterMID()); s.append(String.format("Request was requested on %s by %s", r.getRequestedDateString(), p .getFullName())); } if (r.getStatus().equals(ReportRequestBean.Viewed)) { PersonnelBean p = personnelDAO.getPersonnel(r.getRequesterMID()); String fullName = "Unknown"; if(p != null){ fullName = p.getFullName(); s.append(String.format("Request was requested on %s by %s, ", r.getRequestedDateString(), p .getFullName())); } s.append(""); // removed "<br />" because it caused unit test to fail and seems to have no // purpose s.append(String.format("and viewed on %s by %s", r.getViewedDateString(), fullName)); } return s.toString(); } }
3,493
29.649123
115
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewPatientAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.Messages; import edu.ncsu.csc.itrust.action.base.PatientBaseAction; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * ViewPatientAction is just a class to help the edit demographics page get all the users that should * be displayed on the page. */ public class ViewPatientAction extends PatientBaseAction { /**patientDAO is the patientDAO that retrieves the users from the database*/ private PatientDAO patientDAO; /**loggedInMID is the patient that is logged in.*/ private long loggedInMID; /**Viewer is the patient bean for the person that is logged in*/ private PatientBean viewer; /** * ViewPateintAction is the constructor for this action class. It simply initializes the * instance variables. * @param factory The facory used to get the patientDAO. * @param loggedInMID The MID of the logged in user. * @param pidString The user ID patient we are viewing. * @throws ITrustException When there is a bad user. */ public ViewPatientAction(DAOFactory factory, long loggedInMID, String pidString) throws ITrustException { super(factory, pidString); this.patientDAO = factory.getPatientDAO(); this.loggedInMID = loggedInMID; this.viewer = patientDAO.getPatient(loggedInMID); TransactionLogger.getInstance().logTransaction(TransactionType.ACTIVITY_FEED_VIEW, loggedInMID, 0L , ""); } /** * getViewablePateints returns a list of patient beans that should be viewed by this * patient. * @return The list of this users dependents and this user. * @throws ITrustException When there is a bad user. */ public List<PatientBean> getViewablePatients() throws ITrustException{ List<PatientBean> result; try { result = patientDAO.getDependents(loggedInMID); //see if this viewer has updated his information at all, and then add him to the list this.viewer = patientDAO.getPatient(this.viewer.getMID()); result.add(0, viewer); } catch (DBException e) { throw new ITrustException("Invalid User"); } return result; } /** * Retrieves a PatientBean for the mid passed in as a String * * @param input * the mid for which the PatientBean will be returned * @return PatientBean * @throws ITrustException */ public PatientBean getPatient(String input) throws ITrustException { try { long mid = Long.valueOf(input); PatientBean patient = patientDAO.getPatient(mid); if (patient != null) { return patient; } else throw new ITrustException(Messages.getString("ViewPatientAction.1")); //not sure if this message exists } catch (NumberFormatException e) { throw new ITrustException(Messages.getString("ViewPatientAction.2")); //not sure if this message exists } } public void logViewDemographics(Long mid, Long secondaryMID) { TransactionLogger.getInstance().logTransaction(TransactionType.DEMOGRAPHICS_VIEW, mid, secondaryMID, ""); } public void logEditDemographics(Long mid, Long secondaryMID) { TransactionLogger.getInstance().logTransaction(TransactionType.DEMOGRAPHICS_EDIT, mid, secondaryMID, ""); } }
3,475
35.589474
107
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewPersonnelAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.model.old.beans.Email; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.FakeEmailDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.Messages; /** * Handles retrieving personnel beans for a given personnel Used by viewPersonnel.jsp * * */ public class ViewPersonnelAction { private PersonnelDAO personnelDAO; private FakeEmailDAO emailDAO; private long loggedInMID; /** * Set up defaults * * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person retrieving personnel beans. */ public ViewPersonnelAction(DAOFactory factory, long loggedInMID) { this.emailDAO = factory.getFakeEmailDAO(); this.personnelDAO = factory.getPersonnelDAO(); this.loggedInMID = loggedInMID; } /** * Retrieves a PersonnelBean for the mid passed as a param * * @param input * the mid for which the PersonnelBean will be returned * @return PersonnelBean * @throws ITrustException */ public PersonnelBean getPersonnel(String input) throws ITrustException { try { long mid = Long.valueOf(input); PersonnelBean personnel = personnelDAO.getPersonnel(mid); if (personnel != null) { return personnel; } else throw new ITrustException(Messages.getString("ViewPersonnelAction.1")); //$NON-NLS-1$ } catch (NumberFormatException e) { throw new ITrustException(Messages.getString("ViewPersonnelAction.2")); //$NON-NLS-1$ } } /** * Returns a PatientBean for the currently logged in personnel * * @return The PatientBean * @throws ITrustException */ public List<Email> getEmailHistory() throws ITrustException { return emailDAO.getEmailsByPerson(personnelDAO.getPersonnel(loggedInMID).getEmail()); } }
2,030
28.867647
89
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ViewReportAction.java
package edu.ncsu.csc.itrust.action; import java.util.List; import edu.ncsu.csc.itrust.exception.ITrustException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.PatientBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.PatientDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.PersonnelDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * * Action class for ViewReport.jsp * */ public class ViewReportAction { private PatientDAO patientDAO; private PersonnelDAO personnelDAO; public ViewReportAction(DAOFactory factory, long loggedInMID, long patientMID) { patientDAO = factory.getPatientDAO(); personnelDAO = factory.getPersonnelDAO(); TransactionLogger.getInstance().logTransaction(TransactionType.COMPREHENSIVE_REPORT_VIEW, loggedInMID, patientMID, ""); } /** * Set up defaults * @param factory The DAOFactory used to create the DAOs used in this action. * @param loggedInMID The MID of the person viewing the report. */ public ViewReportAction(DAOFactory factory, long loggedInMID) { this(factory, loggedInMID, 0L); } /** * Get declared HCPs list for the given patient * @param pid the patient of interest * @return list of declared HCPs * @throws ITrustException */ public List<PersonnelBean> getDeclaredHCPs(long pid) throws ITrustException { return patientDAO.getDeclaredHCPs(pid); } /** * Returns a PersonnelBean when given an MID * @param mid HCP of interest * @return PersonnelBean of the given HCP * @throws ITrustException */ public PersonnelBean getPersonnel(long mid) throws ITrustException { return personnelDAO.getPersonnel(mid); } /** * Returns a PaitentBean when given an MID * @param mid patient of interest * @return PatientBean of the given HCP * @throws ITrustException */ public PatientBean getPatient(long mid) throws ITrustException { return patientDAO.getPatient(mid); } }
2,064
29.367647
121
java
iTrust
iTrust-master/iTrust/src/main/edu/ncsu/csc/itrust/action/ZipCodeAction.java
package edu.ncsu.csc.itrust.action; import java.util.ArrayList; import java.util.List; import edu.ncsu.csc.itrust.exception.DBException; import edu.ncsu.csc.itrust.logger.TransactionLogger; import edu.ncsu.csc.itrust.model.old.beans.HospitalBean; import edu.ncsu.csc.itrust.model.old.beans.PersonnelBean; import edu.ncsu.csc.itrust.model.old.beans.ZipCodeBean; import edu.ncsu.csc.itrust.model.old.dao.DAOFactory; import edu.ncsu.csc.itrust.model.old.dao.mysql.HospitalsDAO; import edu.ncsu.csc.itrust.model.old.dao.mysql.ZipCodeDAO; import edu.ncsu.csc.itrust.model.old.enums.TransactionType; /** * Action class which handles zip code related functionality; */ public class ZipCodeAction { // private DAOFactory factory; // private long loggedInMID; private ZipCodeDAO zipCodeDAO; // private PersonnelDAO personnelDAO; private HospitalsDAO hospitalDAO; private FindExpertAction expertAction; /** * Constructor for ZipCodeAction * @param factory * @param loggedInMID */ public ZipCodeAction(DAOFactory factory, long loggedInMID) { this.zipCodeDAO = factory.getZipCodeDAO(); this.hospitalDAO = factory.getHospitalsDAO(); this.expertAction = new FindExpertAction(factory); } /** * Calculates the distance between two ZipCodes * @param zipCode1 * @param zipCode2 * @return * @throws DBException */ public int calcDistance(String zipCode1, String zipCode2) throws DBException { ZipCodeBean bean1 = zipCodeDAO.getZipCode(zipCode1); ZipCodeBean bean2 = zipCodeDAO.getZipCode(zipCode2); if(bean1 == null || bean2 == null) { return Integer.MAX_VALUE; } double latA = Double.valueOf(bean1.getLatitude()); double longA = Double.valueOf(bean1.getLongitude()); double latB = Double.valueOf(bean2.getLatitude()); double longB = Double.valueOf(bean2.getLongitude()); double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB))); return (int) ((Math.toDegrees(Math.acos(theDistance))) * 69.09); } /** * Returns all of the hospitals within the mileage range specified. * @param specialty * @param zipCode * @param mileRange * @return * @throws DBException */ private List<HospitalBean> getHosptialsWithinCertainMileage(String specialty, String zipCode, String mileRange) throws DBException { List<HospitalBean> hospitalBeans = hospitalDAO.getAllHospitals(); List<HospitalBean> hospitalsWithinRange = new ArrayList<HospitalBean>(); int miles; for (HospitalBean hospitalBean : hospitalBeans) { if(mileRange.equals("All")) miles = Integer.MAX_VALUE; else miles = Integer.parseInt(mileRange); if(calcDistance(zipCode, hospitalBean.getHospitalZip()) <= miles) { hospitalsWithinRange.add(hospitalBean); } } return hospitalsWithinRange; } private List<PersonnelBean> getExpertsForHospitals(String specialty, List<HospitalBean> hospitalBeans) { return expertAction.findExpertsForLocalHospitals(hospitalBeans, specialty); } /** * Gets all the experts within a certain range and with a certain specialty. * @param specialty * @param zipCode * @param mileRange * @return * @throws DBException */ public List<PersonnelBean> getExperts(String specialty, String zipCode, String mileRange, Long loggedInMID) throws DBException { TransactionLogger.getInstance().logTransaction(TransactionType.FIND_EXPERT, loggedInMID, null , "Zip Code Used for Search"); List<HospitalBean> hosptials = getHosptialsWithinCertainMileage(specialty, zipCode, mileRange); return getExpertsForHospitals(specialty, hosptials); } public void logError(Long loggedInMID){ TransactionLogger.getInstance().logTransaction(TransactionType.FIND_EXPERT_ZIP_ERROR, loggedInMID, null , "Zip Code Used for Search"); } }
3,948
30.592
136
java