nov3630/RLRetriever
Feature Extraction
•
Updated
•
155
•
3
Error code: DatasetGenerationError Exception: CastError Message: Couldn't cast task_id: string path: string right_context: string groundtruth: string left_context: string crossfile_context: list<item: struct<path: string, text: string>> child 0, item: struct<path: string, text: string> child 0, path: string child 1, text: string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 994 to {'path': Value(dtype='string', id=None), 'content': Value(dtype='string', id=None), 'first': Value(dtype='bool', id=None)} because column names don't match Traceback: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1492, in compute_config_parquet_and_info_response fill_builder_info(builder, hf_endpoint=hf_endpoint, hf_token=hf_token, validate=validate) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 702, in fill_builder_info num_examples_and_sizes: list[tuple[int, int]] = thread_map( File "/src/services/worker/.venv/lib/python3.9/site-packages/tqdm/contrib/concurrent.py", line 69, in thread_map return _executor_map(ThreadPoolExecutor, fn, *iterables, **tqdm_kwargs) File "/src/services/worker/.venv/lib/python3.9/site-packages/tqdm/contrib/concurrent.py", line 51, in _executor_map return list(tqdm_class(ex.map(fn, *iterables, chunksize=chunksize), **kwargs)) File "/src/services/worker/.venv/lib/python3.9/site-packages/tqdm/std.py", line 1169, in __iter__ for obj in iterable: File "/usr/local/lib/python3.9/concurrent/futures/_base.py", line 609, in result_iterator yield fs.pop().result() File "/usr/local/lib/python3.9/concurrent/futures/_base.py", line 446, in result return self.__get_result() File "/usr/local/lib/python3.9/concurrent/futures/_base.py", line 391, in __get_result raise self._exception File "/usr/local/lib/python3.9/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 574, in retry_validate_get_num_examples_and_size validate(pf) File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 640, in validate raise TooBigRowGroupsError( worker.job_runners.config.parquet_and_info.TooBigRowGroupsError: Parquet file has too big row groups. First row group has 430270127 which exceeds the limit of 300000000 During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1995, in _prepare_split_single for _, table in generator: File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 797, in wrapped for item in generator(*args, **kwargs): File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/parquet/parquet.py", line 97, in _generate_tables yield f"{file_idx}_{batch_idx}", self._cast_table(pa_table) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/packaged_modules/parquet/parquet.py", line 75, in _cast_table pa_table = table_cast(pa_table, self.info.features.arrow_schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2302, in table_cast return cast_table_to_schema(table, schema) File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/table.py", line 2256, in cast_table_to_schema raise CastError( datasets.table.CastError: Couldn't cast task_id: string path: string right_context: string groundtruth: string left_context: string crossfile_context: list<item: struct<path: string, text: string>> child 0, item: struct<path: string, text: string> child 0, path: string child 1, text: string -- schema metadata -- pandas: '{"index_columns": [{"kind": "range", "name": null, "start": 0, "' + 994 to {'path': Value(dtype='string', id=None), 'content': Value(dtype='string', id=None), 'first': Value(dtype='bool', id=None)} because column names don't match The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1505, in compute_config_parquet_and_info_response parquet_operations, partial, estimated_dataset_info = stream_convert_to_parquet( File "/src/services/worker/src/worker/job_runners/config/parquet_and_info.py", line 1099, in stream_convert_to_parquet builder._prepare_split( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 1882, in _prepare_split for job_id, done, content in self._prepare_split_single( File "/src/services/worker/.venv/lib/python3.9/site-packages/datasets/builder.py", line 2038, in _prepare_split_single raise DatasetGenerationError("An error occurred while generating the dataset") from e datasets.exceptions.DatasetGenerationError: An error occurred while generating the dataset
Need help to make the dataset viewer work? Make sure to review how to configure the dataset viewer, and open a discussion for direct support.
path
string | content
string | first
bool |
---|---|---|
src/main/java/module-info.java | module de.ybroeker.blog.javafx.demo {
requires javafx.controls;
requires javafx.fxml;
exports de.ybroeker.blog.javafx.demo;
}
| true |
src/main/java/com/driver/Student.java | package com.driver;
public class Student {
private String name;
private int age;
private double averageScore;
public Student(){
}
public Student(String name, int age, double averageScore) {
this.name = name;
this.age = age;
this.averageScore = averageScore;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getAverageScore() {
return averageScore;
}
public void setAverageScore(double averageScore) {
this.averageScore = averageScore;
}
} | true |
src/main/java/com/driver/StudentService.java | package com.driver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class StudentService {
@Autowired
StudentRepository studentRepository;
//Add Student at Service Layer
public static void addStudentAtService(Student student){
StudentRepository.addStudentToDb(student);
}
//Add teacher at service layer
public static void addTeacherAtService(Teacher teacher){
StudentRepository.addTeacherToDb(teacher);
}
//Add student teacher pair at service layer
public static void addStudentTeacherPair(String student, String teacher){
StudentRepository.addStudentTeacherPairToDb(student,teacher);
}
//Get student by name at service layer
public static Student getStudentByName(String name){
Student student=StudentRepository.getStudentByNameFromDb(name);
return student;
}
//get teacher by name at service layer
public static Teacher getTeacherByName(String name){
Teacher teacher= StudentRepository.getTeacherByNameFromDb(name);
return teacher;
}
//get Students by teacher name
public static List<String> getStudentsByTeacherName(String name){
return StudentRepository.getStudentsByTeacherNameFromDb(name);
}
//get all student added at service layer
public static List<String> getAllStudentAdded(){
return StudentRepository.getAllStudentsAddedFromDb();
}
//Delete teacher and its students at service layer
public static void deleteTeacherByName(String name){
StudentRepository.deleteTeacherByNameFromDb(name);
}
//Delete All Teachers
public static void deleteAllTeahers(){
StudentRepository.deleteAllTeachersFromDb();
}
} | false |
src/main/java/com/driver/Teacher.java | package com.driver;
public class Teacher {
private String name;
private int numberOfStudents;
private int age;
public Teacher() {
}
public Teacher(String name, int numberOfStudents, int age) {
this.name = name;
this.numberOfStudents = numberOfStudents;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int numberOfStudents) {
this.numberOfStudents = numberOfStudents;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
} | false |
src/main/java/com/driver/StudentController.java | package com.driver;
import com.driver.Student;
import com.driver.StudentService;
import com.driver.Teacher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("students")
public class StudentController {
@Autowired
StudentService studentService;
//Add student
@PostMapping("/add-student")
public ResponseEntity<String> addStudent(@RequestBody Student student){
StudentService.addStudentAtService(student);
return new ResponseEntity<>("New student added successfully", HttpStatus.CREATED);
}
//Add Teacher
@PostMapping("/add-teacher")
public ResponseEntity<String> addTeacher(@RequestBody Teacher teacher){
StudentService.addTeacherAtService(teacher);
return new ResponseEntity<>("New teacher added successfully", HttpStatus.CREATED);
}
//add Student teacher pair
@PutMapping("/add-student-teacher-pair")
public ResponseEntity<String> addStudentTeacherPair(@RequestParam("student") String student, @RequestParam("teacher") String teacher){
StudentService.addStudentTeacherPair(student,teacher);
return new ResponseEntity<>("New student-teacher pair added successfully", HttpStatus.CREATED);
}
//Get student by student name
@GetMapping("/get-student-by-name/{name}")
public ResponseEntity<Student> getStudentByName(@PathVariable() String name){
Student student = StudentService.getStudentByName(name); // Assign student by calling service layer method
return new ResponseEntity<>(student, HttpStatus.CREATED);
}
//Get teacher by name
@GetMapping("/get-teacher-by-name/{name}")
public ResponseEntity<Teacher> getTeacherByName(@PathVariable String name){
Teacher teacher = StudentService.getTeacherByName(name); // Assign student by calling service layer method
return new ResponseEntity<>(teacher, HttpStatus.CREATED);
}
//get all students by teacher name
@GetMapping("/get-students-by-teacher-name/{teacher}")
public ResponseEntity<List<String>> getStudentsByTeacherName(@PathVariable String teacher){
List<String> students = StudentService.getStudentsByTeacherName(teacher); // Assign list of student by calling service layer method
return new ResponseEntity<>(students, HttpStatus.CREATED);
}
//get all students
@GetMapping("/get-all-students")
public ResponseEntity<List<String>> getAllStudents(){
List<String> students = StudentService.getAllStudentAdded(); // Assign list of student by calling service layer method
return new ResponseEntity<>(students, HttpStatus.CREATED);
}
//Delete teacher by name
@DeleteMapping("/delete-teacher-by-name")
public ResponseEntity<String> deleteTeacherByName(@RequestParam("teacher") String teacher){
StudentService.deleteTeacherByName(teacher);
return new ResponseEntity<>(teacher + " removed successfully", HttpStatus.CREATED);
}
//Delete all teachers
@DeleteMapping("/delete-all-teachers")
public ResponseEntity<String> deleteAllTeachers(){
StudentService.deleteAllTeahers();
return new ResponseEntity<>("All teachers deleted successfully", HttpStatus.CREATED);
}
} | false |
Unit07Varabyova/src/lt/lhu/unit07/main/Task05.java | package lt.lhu.unit07.main;
public class Task05 {
public static void main(String[] args) {
double a = 1;
double x1 = -2 * a;
double dX = a / 5.0;
double n = 5;
double y;
double x = x1;
for (int i = 0; i <= n; i++) {
if (x <= 0) {
y = a / 2.0 * (Math.pow(Math.E, x / a) + Math.pow(Math.E, -x / a));
} else {
y = 4.0 * Math.pow(a, 3) / (Math.pow(x, 2) + 4 * Math.pow(a, 2));
}
System.out.printf("For argument %.2f the function result is %.4f\n", x, y);
x += dX;
}
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task04.java | package lt.lhu.unit07.main;
import java.util.Random;
public class Task04 {
public static void main(String[] args) {
int n = 10;
Random rand = new Random();
int countPoints = 0;
int i = 0;
while (i < n) {
Double p1 = rand.nextDouble(-5, 5);
Double p2 = rand.nextDouble(-5, 5);
i++;
if (((p1 >= -2 && p1 <= 0) && (p2 >= 0 && p2 <= 2)) || ((p1 >= 0 && p1 <= 2) && (p2 >= -1 && p2 <= 1))) {
System.out.println("Point with coordinates: " + p1 + ", " + p2 + " is in the area");
countPoints++;
} else {
System.out.println("Point with coordinates: " + p1 + ", " + p2 + " is NOT in the area");
}
}
System.out.println("The number of points in the area is: " + countPoints);
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task07.java | package lt.lhu.unit07.main;
public class Task07 {
public static void main(String[] args) {
double z;
double result;
double x1 = 0.5;
double z1 = 0.6;
double hX = 0.2;
double zX = 0.3;
int n = 5;
int m = 5;
double x = x1;
for (int i = 0; i < n; i++) {
z = z1;
for (int j = 0; j < m; j++) {
result = Math.sqrt(Math.pow(z, 2) + Math.pow(x, 2)) * Math.log(z) + Math.abs(Math.log(z)) / Math.sqrt(Math.pow(x, 2) - Math.pow(z, 2) + 3.2);
System.out.printf("x = %.2f z = %.2f result = %.4f\n", x, z, result);
z += zX;
}
x += hX;
}
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task02.java | package lt.lhu.unit07.main;
public class Task02 {
public static void main(String[] args) {
double a = 0.5;
double b = 1.0;
int n = 10;
//used n-1 instead of n because we should divide by 9 in order to get 10 points
double h = (b - a) / (n - 1);
/*used count<=n instead of i<=b because i<=b is not accurate when we use double.
*the 10th point will be 1.00000004 instead of 1.0
*/
for (double i = a, count = 1.0; count <= n; i += h, count++) {
double result = Math.sqrt(Math.pow(Math.E, 2.2 * i)) - Math.abs(Math.sin(Math.PI * i / (i + 2.0 / 3.0)))
+ 1.7;
System.out.printf("|\t%4d\t|\t%.4f\t|\t%.6f\t|", (int) count, i, result);
System.out.println();
System.out.println("--------------------------------------------------------");
}
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task01.java | package lt.lhu.unit07.main;
public class Task01 {
public static void main(String[] args) {
double result;
double x = 0.5;
result = Math.sqrt(Math.pow(Math.E, 2.2 * x)) - Math.abs(Math.sin(Math.PI * x / (x + 2.0 / 3.0))) + 1.7;
System.out.println(result);
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task08.java | package lt.lhu.unit07.main;
public class Task08 {
public static void main(String[] args) {
double x = 0.1;
double h = 0.1;
double n = 10;
double previousY = Double.NaN;
while (x < n) {
double y = calculateFunction(x);
if (y == 0) {
System.out.println("Function zero is found with x " + x);
break;
} else {
if (previousY == Double.NaN) {
previousY = y;
} else {
if ((y > 0 && previousY < 0) || (y < 0 && previousY > 0)) {
System.out.printf("Function zero is found between %.4f and %.4f", previousY, y);
break;
} else {
previousY = y;
x += h;
}
}
}
}
if (x >= n) {
System.out.println("Function zero was not found");
}
}
public static double calculateFunction(double x) {
return Math.pow(x, 2) - Math.pow(Math.E, 2 * x) + 4;
}
}
| true |
Unit07Varabyova/src/lt/lhu/unit07/main/Task06.java | package lt.lhu.unit07.main;
public class Task06 {
public static void main(String[] args) {
double a = 3 * Math.pow(10, 3);
double b = 6 * Math.pow(10, 4);
double m = 4;
double t1 = Math.sqrt(a + b + m);
double t2 = m * Math.sqrt(a + b);
double t3 = Math.sqrt(a * b * m);
double t4 = m * Math.sqrt(a * b);
double result;
int sum = 0;
for (int k = -30; k < 60; k++) {
result = Math.pow(k, 3) - (25.0 * Math.pow(k, 2)) + (50.0 * k) + 1000;
if ((result > t1 && result < t2) || (result > t3 && result < t4)) {
System.out.println(result);
} else {
sum++;
}
}
System.out.println("Not suitable values sum: " + sum);
}
}
| true |
src/java/Entidades/Pedido.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entidades;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author a1712136
*/
@Entity
@Table(name = "pedido")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Pedido.findAll", query = "SELECT p FROM Pedido p")
, @NamedQuery(name = "Pedido.findByIdPedido", query = "SELECT p FROM Pedido p WHERE p.idPedido = :idPedido")
, @NamedQuery(name = "Pedido.findByData", query = "SELECT p FROM Pedido p WHERE p.data = :data")})
public class Pedido implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id_pedido")
private Integer idPedido;
@Basic(optional = false)
@Column(name = "data")
@Temporal(TemporalType.DATE)
private Date data;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "pedido")
private List<ItensPedido> itensPedidoList;
@JoinColumn(name = "cliente_id_cliente", referencedColumnName = "id_cliente")
@ManyToOne(optional = false)
private Cliente clienteIdCliente;
public Pedido() {
}
public Pedido(Integer idPedido) {
this.idPedido = idPedido;
}
public Pedido(Integer idPedido, Date data) {
this.idPedido = idPedido;
this.data = data;
}
public Integer getIdPedido() {
return idPedido;
}
public void setIdPedido(Integer idPedido) {
this.idPedido = idPedido;
}
public Date getData() {
return data;
}
public void setData(Date data) {
this.data = data;
}
@XmlTransient
public List<ItensPedido> getItensPedidoList() {
return itensPedidoList;
}
public void setItensPedidoList(List<ItensPedido> itensPedidoList) {
this.itensPedidoList = itensPedidoList;
}
public Cliente getClienteIdCliente() {
return clienteIdCliente;
}
public void setClienteIdCliente(Cliente clienteIdCliente) {
this.clienteIdCliente = clienteIdCliente;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idPedido != null ? idPedido.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Pedido)) {
return false;
}
Pedido other = (Pedido) object;
if ((this.idPedido == null && other.idPedido != null) || (this.idPedido != null && !this.idPedido.equals(other.idPedido))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entidades.Pedido[ idPedido=" + idPedido + " ]";
}
}
| true |
src/java/DAOs/DAOPedido.java | package DAOs;
import Entidades.Pedido;
import java.util.ArrayList;
import java.util.List;
import static DAOs.DAOGenerico.em;
import java.text.SimpleDateFormat;
public class DAOPedido extends DAOGenerico<Pedido> {
public DAOPedido() {
super(Pedido.class);
}
public int autoIdPedido() {
Integer a = (Integer) em.createQuery("SELECT MAX(e.idPedido) FROM Pedido e ").getSingleResult();
if (a != null) {
return a + 1;
} else {
return 1;
}
}
public List<Pedido> listByIdPedido(int idPedido) {
return em.createQuery("SELECT e FROM Pedido e WHERE e.idPedido = :idPedido").setParameter("idPedido", idPedido).getResultList();
}
public List<Pedido> listByData(String data) {
return em.createQuery("SELECT e FROM Pedido e WHERE e.data LIKE :data").setParameter("data", "%" + data + "%").getResultList();
}
public List<Pedido> listInOrderIdPedido() {
return em.createQuery("SELECT e FROM Pedido e ORDER BY e.idPedido").getResultList();
}
public List<Pedido> listInOrderData() {
return em.createQuery("SELECT e FROM Pedido e ORDER BY e.data").getResultList();
}
public List<String> listInOrderNomeStrings(String qualOrdem) {
List<Pedido> lf;
if (qualOrdem.equals("idPedido")) {
lf = listInOrderIdPedido();
} else {
lf = listInOrderData();
}
List<String> ls = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i < lf.size(); i++) {
ls.add(lf.get(i).getIdPedido() + ";" + sdf.format(lf.get(i).getData()) + ";" + lf.get(i).getClienteIdCliente() + ";");
}
return ls;
}
}
| false |
src/java/Entidades/Flores.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entidades;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author a1712136
*/
@Entity
@Table(name = "flores")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Flores.findAll", query = "SELECT f FROM Flores f")
, @NamedQuery(name = "Flores.findByIdFlor", query = "SELECT f FROM Flores f WHERE f.idFlor = :idFlor")
, @NamedQuery(name = "Flores.findByNomeFlor", query = "SELECT f FROM Flores f WHERE f.nomeFlor = :nomeFlor")
, @NamedQuery(name = "Flores.findByQuantidadeFlor", query = "SELECT f FROM Flores f WHERE f.quantidadeFlor = :quantidadeFlor")
, @NamedQuery(name = "Flores.findByPrecoFlor", query = "SELECT f FROM Flores f WHERE f.precoFlor = :precoFlor")})
public class Flores implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id_flor")
private Integer idFlor;
@Basic(optional = false)
@Column(name = "nome_flor")
private String nomeFlor;
@Basic(optional = false)
@Column(name = "quantidade_flor")
private int quantidadeFlor;
@Basic(optional = false)
@Column(name = "preco_flor")
private double precoFlor;
@JoinColumn(name = "tipo_id_tipo", referencedColumnName = "id_tipo")
@ManyToOne(optional = false)
private Tipo tipoIdTipo;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "flores")
private List<ItensPedido> itensPedidoList;
public Flores() {
}
public Flores(Integer idFlor) {
this.idFlor = idFlor;
}
public Flores(Integer idFlor, String nomeFlor, int quantidadeFlor, double precoFlor) {
this.idFlor = idFlor;
this.nomeFlor = nomeFlor;
this.quantidadeFlor = quantidadeFlor;
this.precoFlor = precoFlor;
}
public Integer getIdFlor() {
return idFlor;
}
public void setIdFlor(Integer idFlor) {
this.idFlor = idFlor;
}
public String getNomeFlor() {
return nomeFlor;
}
public void setNomeFlor(String nomeFlor) {
this.nomeFlor = nomeFlor;
}
public int getQuantidadeFlor() {
return quantidadeFlor;
}
public void setQuantidadeFlor(int quantidadeFlor) {
this.quantidadeFlor = quantidadeFlor;
}
public double getPrecoFlor() {
return precoFlor;
}
public void setPrecoFlor(double precoFlor) {
this.precoFlor = precoFlor;
}
public Tipo getTipoIdTipo() {
return tipoIdTipo;
}
public void setTipoIdTipo(Tipo tipoIdTipo) {
this.tipoIdTipo = tipoIdTipo;
}
@XmlTransient
public List<ItensPedido> getItensPedidoList() {
return itensPedidoList;
}
public void setItensPedidoList(List<ItensPedido> itensPedidoList) {
this.itensPedidoList = itensPedidoList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idFlor != null ? idFlor.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Flores)) {
return false;
}
Flores other = (Flores) object;
if ((this.idFlor == null && other.idFlor != null) || (this.idFlor != null && !this.idFlor.equals(other.idFlor))) {
return false;
}
return true;
}
@Override
public String toString() {
return "Entidades.Flores[ idFlor=" + idFlor + " ]";
}
}
| true |
src/java/DAOs/DAOFlores.java | package DAOs;
import Entidades.Flores;
import java.util.ArrayList;
import java.util.List;
import static DAOs.DAOGenerico.em;
import java.text.SimpleDateFormat;
public class DAOFlores extends DAOGenerico<Flores> {
public DAOFlores() {
super(Flores.class);
}
public int autoIdFlores() {
Integer a = (Integer) em.createQuery("SELECT MAX(e.idFlor) FROM Flores e ").getSingleResult();
if (a != null) {
return a + 1;
} else {
return 1;
}
}
public List<Flores> listByIdFlor(int idFlor) {
return em.createQuery("SELECT e FROM Flores e WHERE e.idFlor = :idFlor").setParameter("idFlor", idFlor).getResultList();
}
public List<Flores> listByNomeFlor(String nomeFlor) {
return em.createQuery("SELECT e FROM Flores e WHERE e.nomeFlor LIKE :nomeFlor").setParameter("nomeFlor", "%" + nomeFlor + "%").getResultList();
}
public List<Flores> listInOrderIdFlor() {
return em.createQuery("SELECT e FROM Flores e ORDER BY e.idFlor").getResultList();
}
public List<Flores> listInOrderNomeFlor() {
return em.createQuery("SELECT e FROM Flores e ORDER BY e.nomeFlor").getResultList();
}
public List<String> listInOrderNomeStrings(String qualOrdem) {
List<Flores> lf;
if (qualOrdem.equals("idFlor")) {
lf = listInOrderIdFlor();
} else {
lf = listInOrderNomeFlor();
}
List<String> ls = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i < lf.size(); i++) {
ls.add(lf.get(i).getIdFlor() + ";" + lf.get(i).getNomeFlor() + ";" + lf.get(i).getQuantidadeFlor() + ";" + lf.get(i).getPrecoFlor() + ";" + lf.get(i).getTipoIdTipo() + ";");
}
return ls;
}
}
| false |
src/java/Entidades/Tipo.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Entidades;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* @author a1712136
*/
@Entity
@Table(name = "tipo")
@XmlRootElement
@NamedQueries({
@NamedQuery(name = "Tipo.findAll", query = "SELECT t FROM Tipo t")
, @NamedQuery(name = "Tipo.findByIdTipo", query = "SELECT t FROM Tipo t WHERE t.idTipo = :idTipo")
, @NamedQuery(name = "Tipo.findByNomeTipo", query = "SELECT t FROM Tipo t WHERE t.nomeTipo = :nomeTipo")})
public class Tipo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Basic(optional = false)
@Column(name = "id_tipo")
private Integer idTipo;
@Basic(optional = false)
@Column(name = "nome_tipo")
private String nomeTipo;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "tipoIdTipo")
private List<Flores> floresList;
public Tipo() {
}
public Tipo(Integer idTipo) {
this.idTipo = idTipo;
}
public Tipo(Integer idTipo, String nomeTipo) {
this.idTipo = idTipo;
this.nomeTipo = nomeTipo;
}
public Integer getIdTipo() {
return idTipo;
}
public void setIdTipo(Integer idTipo) {
this.idTipo = idTipo;
}
public String getNomeTipo() {
return nomeTipo;
}
public void setNomeTipo(String nomeTipo) {
this.nomeTipo = nomeTipo;
}
@XmlTransient
public List<Flores> getFloresList() {
return floresList;
}
public void setFloresList(List<Flores> floresList) {
this.floresList = floresList;
}
@Override
public int hashCode() {
int hash = 0;
hash += (idTipo != null ? idTipo.hashCode() : 0);
return hash;
}
@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Tipo)) {
return false;
}
Tipo other = (Tipo) object;
if ((this.idTipo == null && other.idTipo != null) || (this.idTipo != null && !this.idTipo.equals(other.idTipo))) {
return false;
}
return true;
}
@Override
public String toString() {
return nomeTipo;
}
}
| false |
src/java/DAOs/DAOTipo.java | package DAOs;
import Entidades.Tipo;
import java.util.ArrayList;
import java.util.List;
import static DAOs.DAOGenerico.em;
import java.text.SimpleDateFormat;
public class DAOTipo extends DAOGenerico<Tipo> {
public DAOTipo() {
super(Tipo.class);
}
public int autoIdTipo() {
Integer a = (Integer) em.createQuery("SELECT MAX(e.idTipo) FROM Tipo e ").getSingleResult();
if (a != null) {
return a + 1;
} else {
return 1;
}
}
public List<Tipo> listByIdTipo(int idTipo) {
return em.createQuery("SELECT e FROM Tipo e WHERE e.idTipo = :idTipo").setParameter("idTipo", idTipo).getResultList();
}
public List<Tipo> listByNomeTipo(String nomeTipo) {
return em.createQuery("SELECT e FROM Tipo e WHERE e.nomeTipo LIKE :nomeTipo").setParameter("nomeTipo", "%" + nomeTipo + "%").getResultList();
}
public List<Tipo> listInOrderIdTipo() {
return em.createQuery("SELECT e FROM Tipo e ORDER BY e.idTipo").getResultList();
}
public List<Tipo> listInOrderNomeTipo() {
return em.createQuery("SELECT e FROM Tipo e ORDER BY e.nomeTipo").getResultList();
}
public List<String> listInOrderNomeStrings(String qualOrdem) {
List<Tipo> lf;
if (qualOrdem.equals("idTipo")) {
lf = listInOrderIdTipo();
} else {
lf = listInOrderNomeTipo();
}
List<String> ls = new ArrayList<>();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
for (int i = 0; i < lf.size(); i++) {
ls.add(lf.get(i).getIdTipo() + ";" + lf.get(i).getNomeTipo() + ";");
}
return ls;
}
}
| false |
src/java/Controles/CadastroFloresServlet.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controles;
import DAOs.DAOFlores;
import DAOs.DAOTipo;
import Entidades.Flores;
import Entidades.Tipo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Asus
*/
@WebServlet(name = "CadastroFloresServlet", urlPatterns = {"/cadFlor"})
public class CadastroFloresServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
DAOFlores daoFlores = new DAOFlores();
Flores p = new Flores();
String id = request.getParameter("id_flor");
String nome = request.getParameter("nome_flor");
String qtde = request.getParameter("quantidade_flor");
String preco = request.getParameter("preco_flor");
int tipoFlor = Integer.parseInt(request.getParameter("tipo_id_tipo"));
DAOTipo daoTipodaoTipo = new DAOTipo();
Tipo t = new Tipo();
out.print("aqui");
p.setIdFlor(Integer.valueOf(id));
p.setNomeFlor(nome);
p.setQuantidadeFlor(Integer.valueOf(qtde));
out.print("aqui");
p.setPrecoFlor(Double.valueOf(preco));
t = daoTipodaoTipo.obter(tipoFlor);
p.setTipoIdTipo(t);
out.print("aqui");
daoFlores.inserir(p);
response.sendRedirect(request.getContextPath()+"/paginas/flor.jsp");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false |
src/java/Controles/CadastroTipoServlet.java | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Controles;
import DAOs.DAOTipo;
import Entidades.Tipo;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Asus
*/
@WebServlet(name = "CadastroTipoServlet", urlPatterns = {"/cadTipo"})
public class CadastroTipoServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
DAOTipo daoTipo = new DAOTipo();
Tipo p = new Tipo();
String id = request.getParameter("id");
String nome = request.getParameter("nome");
p.setIdTipo(Integer.valueOf(id));
p.setNomeTipo(nome);
daoTipo.inserir(p);
response.sendRedirect(request.getContextPath()+"/paginas/tipo.jsp");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
| false |
src/test/java/com/franchisoft/demo/DemoFranchiSoftApplicationTests.java | package com.franchisoft.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class DemoFranchiSoftApplicationTests {
@Test
void contextLoads() {
}
}
| true |
src/main/java/com/franchisoft/dto/ClienteModel.java | package com.franchisoft.dto;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
@Entity
@Table(name="cliente")
public class ClienteModel {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "nombre")
private String nombre;
@Column(name = "apellido")
private String apellido;
@Column(name = "direccion")
private String direccion;
@Column(name = "Dni")
private String Dni;
@Column(name = "fecha")
@Temporal(TemporalType.TIMESTAMP)
private Date fecha;
public ClienteModel(Long id, String nombre, String apellido, String direccion, String dni, Date fecha) {
this.id = id;
this.nombre = nombre;
this.apellido = apellido;
this.direccion = direccion;
Dni = dni;
this.fecha = fecha;
}
public ClienteModel() {
}
public Long getId() {
return id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getApellido() {
return apellido;
}
public void setApellido(String apellido) {
this.apellido = apellido;
}
public String getDireccion() {
return direccion;
}
public void setDireccion(String direccion) {
this.direccion = direccion;
}
public String getDni() {
return Dni;
}
public void setDni(String dni) {
Dni = dni;
}
public Date getFecha() {
return fecha;
}
public void setFecha(Date fecha) {
this.fecha = fecha;
}
@Override
public String toString() {
return "ClienteModel [id=" + id + ", nombre=" + nombre + ", apellido=" + apellido + ", direccion="
+ direccion + ", Dni=" + Dni + ", fecha=" + fecha + "]";
}
}
| true |
src/main/java/com/franchisoft/dao/IClienteDAO.java | package com.franchisoft.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.franchisoft.dto.ClienteModel;
public interface IClienteDAO extends JpaRepository<ClienteModel, Long> {
}
| false |
src/main/java/com/franchisoft/services/IClienteServices.java | package com.franchisoft.services;
import java.util.List;
import com.franchisoft.dto.ClienteModel;
public interface IClienteServices {
public List<ClienteModel> listarClientes();
public ClienteModel guardarCliente(ClienteModel cliente);
public ClienteModel obtenerCliente(Long id);
public ClienteModel actualizarCliente(ClienteModel cliente);
public void eliminarCliente(Long id);
}
| false |
src/main/java/com/franchisoft/impl/ClienteServicesImpl.java | package com.franchisoft.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.franchisoft.dao.IClienteDAO;
import com.franchisoft.dto.ClienteModel;
import com.franchisoft.services.IClienteServices;
@Service
public class ClienteServicesImpl implements IClienteServices {
@Autowired
IClienteDAO iClienteDAO;
@Override
public List<ClienteModel> listarClientes() {
// TODO Auto-generated method stub
return iClienteDAO.findAll();
}
@Override
public ClienteModel guardarCliente(ClienteModel cliente) {
// TODO Auto-generated method stub
return iClienteDAO.save(cliente);
}
@Override
public ClienteModel obtenerCliente(Long id) {
// TODO Auto-generated method stub
return iClienteDAO.findById(id).get();
}
@Override
public ClienteModel actualizarCliente(ClienteModel cliente) {
// TODO Auto-generated method stub
return iClienteDAO.save(cliente);
}
@Override
public void eliminarCliente(Long id) {
// TODO Auto-generated method stub
iClienteDAO.deleteById(id);
}
}
| false |
src/main/java/com/franchisoft/controller/ClienteController.java | package com.franchisoft.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.franchisoft.dto.ClienteModel;
import com.franchisoft.impl.ClienteServicesImpl;
@RestController
@CrossOrigin(origins = "*", methods = {RequestMethod.DELETE, RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT})
@RequestMapping("/api")
public class ClienteController {
@Autowired
ClienteServicesImpl clienteServicesImpl;
@GetMapping("/clientes")
public List<ClienteModel> listarClientes(){
return clienteServicesImpl.listarClientes();
}
@PostMapping("/cliente")
public ClienteModel guardarCliente(@RequestBody ClienteModel cliente) {
return clienteServicesImpl.guardarCliente(cliente);
}
@GetMapping("/cliente/{id}")
public ClienteModel obtenerCliente(@PathVariable(name = "id") Long id) {
ClienteModel cliente = new ClienteModel();
cliente = clienteServicesImpl.obtenerCliente(id);
return cliente;
}
@PutMapping("/cliente/{id}")
public ClienteModel actualizarCliente(@PathVariable(name = "id") Long id, @RequestBody ClienteModel cliente) {
//
ClienteModel clienteSelecionado = new ClienteModel();
ClienteModel clienteActualizado = new ClienteModel();
// Ingreso los valores obtenidos desde el objeto enviado
clienteSelecionado = clienteServicesImpl.obtenerCliente(id);
clienteSelecionado.setNombre(cliente.getNombre());
clienteSelecionado.setApellido(cliente.getApellido());
clienteSelecionado.setDireccion(cliente.getDireccion());
clienteSelecionado.setDni(cliente.getDni());
clienteSelecionado.setFecha(cliente.getFecha());
// Actualizo y obtengo el cliente actualizado
clienteActualizado = clienteServicesImpl.actualizarCliente(clienteSelecionado);
return clienteActualizado;
}
@DeleteMapping("/cliente/{id}")
public void eliminarCliente(@PathVariable(name = "id") Long id) {
clienteServicesImpl.eliminarCliente(id);
}
@GetMapping("/")
public String home() {
return "Hola Mundo desde mi Servicio";
}
}
| false |
src/main/java/com/franchisoft/DemoFranchiSoftApplication.java | package com.franchisoft;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoFranchiSoftApplication {
public static void main(String[] args) {
SpringApplication.run(DemoFranchiSoftApplication.class, args);
}
}
| true |
Banco2/Banco2/src/main/java/com/banco/banco/Pessoa.java | package com.banco.banco;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.NonNull;
@Entity
public class Pessoa {
@Id
@GeneratedValue (strategy = GenerationType.AUTO)
private long idPessoa;
@NonNull private String nome;
@NonNull private String cpf;
@NonNull private Date dataNascimento;
public Pessoa(String nome, String cpf, Date date) {
this.nome = nome;
this.cpf = cpf;
this.dataNascimento = date;
}
public Pessoa(String nome, String cpf) {
this.nome = nome;
this.cpf = cpf;
}
public Pessoa() {
// TODO Auto-generated constructor stub
}
public long getIdPessoa() {
return idPessoa;
}
public void setIdPessoa(long idPessoa) {
this.idPessoa = idPessoa;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCpf() {
return cpf;
}
public void setCpf(String cpf) {
this.cpf = cpf;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
}
| true |
Banco2/Banco2/src/main/java/repository/PessoaRepository.java | package repository;
import org.springframework.data.repository.CrudRepository;
import com.banco.banco.Pessoa;
public interface PessoaRepository extends CrudRepository<Pessoa, Long>{
}
| false |
Banco2/Banco2/src/main/java/controller/PessoaController.java | package controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import com.banco.banco.Pessoa;
import repository.PessoaRepository;
@Controller
public class PessoaController {
@Autowired
PessoaRepository pessoaRepository;
@RequestMapping("/")
public String listaPessoa(Model model) {
model.addAttribute("contas", pessoaRepository.findAll());
return "list";
}
@GetMapping("/add")
public String pessoaForm(Model model) {
model.addAttribute("pessoa", new Pessoa());
return "pessoaForm";
}
@PostMapping("/process")
public String processForm(@Validated Pessoa pessoa, BindingResult result) {
if(result.hasErrors()) {
return "pessoaForm";
}
pessoaRepository.save(pessoa);
return "redirect:/";
}
}
| false |
src/main/java/com/stackroute/jdbctemplate/App.java | package com.stackroute.jdbctemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.List;
/**
* Hello world!
*
*/
public class App
{
public static void main(String args[])
{
ApplicationContext applicationContext=new AnnotationConfigApplicationContext(ConfigurationBean.class);
EmployeeService EmployeeService=applicationContext.getBean("EmployeeService", EmployeeService.class);
Employee Employee=new Employee();
// EmployeeService.createTable();
List<Employee> employeeList= EmployeeService.getAllEmployeesRowMapper();
for (Employee e:employeeList
) {
System.out.println(e.getId()+","+e.getName()+","+e.getAge()+","+e.getGender());
}
EmployeeService.insertData();
EmployeeService.updateDetails();
EmployeeService.deleteDetails();
}
}
| true |
src/main/java/com/stackroute/jdbctemplate/EmployeeService.java | package com.stackroute.jdbctemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Component
public class EmployeeService {
// Declaration
private JdbcTemplate jdbcTemplate;
private DataSource dataSource;
/*public void createTable()
{
String query="create table Employee(Id int,Name varchar(20),age int,gender char)";
jdbcTemplate.update(query);
}
*/
public void insertData()
{
String query="insert into Employee values(7,'Divya',24,'F')";
jdbcTemplate.execute(query);
}
public List<Employee> getAllEmployeesRowMapper(){
return jdbcTemplate.query("select * from Employee",new RowMapper<Employee>(){
@Override
public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {
Employee e=new Employee();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setAge(rs.getInt(3));
e.setGender(rs.getString(4));
return e;
}
});
}
public void updateDetails()
{
String query="update Employee set name='Cherry' where Id=2";
jdbcTemplate.execute(query);
}
public void deleteDetails()
{
String query="delete from Employee where Id=2";
jdbcTemplate.update(query);
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public DataSource getDataSource() {
return dataSource;
}
@Autowired
public void setDataSource(DataSource dataSource) {
jdbcTemplate=new JdbcTemplate(dataSource);
}
}
| true |
pet-clinic-web/src/main/java/guru/spring/petclinic/controllers/IndexController.java | package guru.spring.petclinic.controllers;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping({"", "/","index"})
public String Index(){
return "index";
}
}
| true |
worldgdp-jar/src/main/java/com/example/worldgdpjar/model/Country.java | package com.example.worldgdpjar.model;
import lombok.Data;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Data
public class Country {
@NotNull
@Size(max = 3, min = 3)
private String code;
@NotNull
@Size(max = 52)
private String name;
@NotNull private String continent;
@NotNull
@Size(max = 26)
private String region;
@NotNull private Double surfaceArea;
private Short indepYear;
@NotNull private Long population;
private Double lifeExpectancy;
private Double gnp;
@NotNull private String localName;
@NotNull private String governmentForm;
private String headOfState;
private City capital;
@NotNull private String code2;
}
| true |
worldgdp-jar/src/main/java/com/example/worldgdpjar/dao/CountryDAO.java | package com.example.worldgdpjar.dao;
import com.example.worldgdpjar.model.Country;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface CountryDAO {
public List<String> getContinents();
public List<String> getRegions();
public List<String> getHeadOfStates();
public List<String> getGovernmentTypes();
public List<Country> getCountries(
Integer size, Integer offset, String search, String continent, String region);
public Country getCountryDetails(String code);
public int getCountriesCount(String search, String continent, String region);
}
| false |
worldgdp-jar/src/main/java/com/example/worldgdpjar/dao/CountryService.java | package com.example.worldgdpjar.dao;
import com.example.worldgdpjar.model.Country;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class CountryService {
private final CountryDAO countryDAO;
private Map<String, String> paraParse(Map<String, Object> params) {
Map<String, String> rlt = new HashMap<>();
String search = params.containsKey("search") ? params.get("search").toString() : null;
String continent = params.containsKey("continent") ? params.get("continent").toString() : null;
String region = params.containsKey("region") ? params.get("region").toString() : null;
rlt.put("search", search);
rlt.put("continent", continent);
rlt.put("region", region);
return rlt;
}
public CountryService(CountryDAO countryDAO) {
this.countryDAO = countryDAO;
}
public List<Country> getCountries(Map<String, Object> params) {
// 得到了offset和size
int pageNo = 1;
if (params.containsKey("pageNo")) {
pageNo = Integer.parseInt(params.get("pageNo").toString());
}
Integer PAGE_SIZE = 20;
Integer offset = (pageNo - 1) * PAGE_SIZE;
Map<String, String> map = paraParse(params);
String search = map.get("search");
String continent = map.get("continent");
String region = map.get("region");
// String code = params.containsKey("code") ? params.get("code").toString() : null;
return countryDAO.getCountries(PAGE_SIZE, offset, search, continent, region);
}
public int getCountriesCount(Map<String, Object> params) {
Map<String, String> map = paraParse(params);
String search = map.get("search");
String continent = map.get("continent");
String region = map.get("region");
return countryDAO.getCountriesCount(search, continent, region);
}
}
| false |
worldgdp-jar/src/main/java/com/example/worldgdpjar/WorldgdpJarApplication.java | package com.example.worldgdpjar;
import com.example.worldgdpjar.dao.CountryService;
import com.example.worldgdpjar.model.Country;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@MapperScan("com.example.worldgdpjar.dao")
@SpringBootApplication
public class WorldgdpJarApplication {
public static void main(String[] args) {
ApplicationContext context = SpringApplication.run(WorldgdpJarApplication.class, args);
/*
CountryDAO dao = context.getBean(CountryDAO.class);
List<String> cs = dao.getContinents();
cs.sort(String.CASE_INSENSITIVE_ORDER);
cs.forEach(System.out::println);
List<String> gs = dao.getGovernmentTypes();
gs.forEach(System.out::println);
*/
CountryService service = context.getBean(CountryService.class);
Map<String, Object> params = new HashMap<>();
params.put("search", "ch");
List<Country> countryList = service.getCountries(params);
countryList.forEach(System.out::println);
// Country country = service.getCountryDetails("CHN");
// System.out.println(country);
}
}
| false |
worldgdp-jar/src/main/java/com/example/worldgdpjar/controller/ViewController.java | package com.example.worldgdpjar.controller;
import com.example.worldgdpjar.dao.CountryDAO;
import com.example.worldgdpjar.dao.CountryService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
@Controller
@RequestMapping("/")
public class ViewController {
private final CountryService countryService;
private final CountryDAO countryDAO;
public ViewController(CountryService countryService, CountryDAO countryDAO) {
this.countryService = countryService;
this.countryDAO = countryDAO;
}
@GetMapping({"/countries", "/"})
public String countries(Model model, @RequestParam Map<String, Object> params) {
model.addAttribute("continents", countryDAO.getContinents());
model.addAttribute("regions", countryDAO.getRegions());
model.addAttribute("countries", countryService.getCountries(params));
model.addAttribute("count", countryService.getCountriesCount(params));
return "countries";
}
@GetMapping("/countries/{code}")
public String countryDetail(@PathVariable String code, Model model) {
model.addAttribute("c", countryDAO.getCountryDetails(code));
return "country";
}
@GetMapping("/countries/{code}/form")
public String editCountry(@PathVariable String code, Model model) {
model.addAttribute("c", countryDAO.getCountryDetails(code));
/*
model.addAttribute("cities", cityDao.getCities(code));
model.addAttribute("continents", lookupDao.getContinents());
model.addAttribute("regions", lookupDao.getRegions());
model.addAttribute("heads", lookupDao.getHeadOfStates());
model.addAttribute("govs", lookupDao.getGovernmentTypes());
*/
return "country-form";
}
}
| false |
src/main/java/main/configuration/security/HashPasswordEncoder.java | package main.configuration.security;
import org.springframework.security.crypto.password.PasswordEncoder;
import javax.xml.bind.DatatypeConverter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashPasswordEncoder implements PasswordEncoder {
@Override
public String encode(CharSequence rawPassword) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(rawPassword.toString().getBytes());
byte[] digest = md.digest();
return DatatypeConverter.printHexBinary(digest).toUpperCase();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new IllegalArgumentException("No hash algorytm");
}
}
@Override
public boolean matches(CharSequence rawPassword, String encodedPassword) {
return encode(rawPassword).equals(encodedPassword);
}
}
| true |
src/main/java/main/server/controllers/IgnoreAdvice.java | package main.server.controllers;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface IgnoreAdvice {
/*
Around Methods or all Classes methods with this annotations
advice from Advices are not invoked
*/
}
| false |
src/main/java/main/server/controllers/data/Search.java | package main.server.controllers.data;
public class Search {
private String searchString;
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
}
| false |
src/main/java/main/server/controllers/data/User.java | package main.server.controllers.data;
public class User {
private String username;
private String password;
public User(){}
public User(String username,String password){
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String login) {
this.username = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
| false |
src/main/java/main/configuration/security/UserDetails.java | package main.configuration.security;
import main.server.controllers.data.User;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;
public class UserDetails implements org.springframework.security.core.userdetails.UserDetails {
private User user;
UserDetails(User user){
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return null;
}
@Override
public String getPassword() {
return /*"{noop}"+*/user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
| false |
src/main/java/main/server/beans/services/AuthorizationService.java | package main.server.beans.services;
import main.server.controllers.data.User;
public interface AuthorizationService {
User getUser(String username);
long registerUser(User user);
boolean isUserRegistered(String username);
}
| false |
src/main/java/main/configuration/security/LoginSuccessHandler.java | package main.configuration.security;
import main.server.beans.services.AuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
@Autowired
private PasswordEncoder encoder;
private static SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler();
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse httpServletResponse
,Authentication authentication) {
try {
Field field = handler.getClass().getDeclaredField("requestCache");
field.setAccessible(true);
String redirectPath = request.getRequestURI().substring(0,request.getRequestURI().lastIndexOf("/"));
DefaultSavedRequest savedRequest = ((DefaultSavedRequest)((RequestCache) field.get(handler))
.getRequest(request,httpServletResponse));
String redirect = savedRequest == null ? "/" : savedRequest.getRequestURI();
if(redirect.startsWith("/tai-app"))
redirect = redirect.substring(8);
String url = redirectPath + "/user/initContext?redirect=" + redirect
+ "&username=" + request.getParameter("username")
+ "&token=" + encoder.encode(request.getParameter("password"));
httpServletResponse.sendRedirect(url);
} catch (Exception e) { e.printStackTrace(); }
}
}
| false |
src/main/java/main/configuration/security/UserLoginService.java | package main.configuration.security;
import main.server.beans.services.AuthorizationService;
import main.server.controllers.data.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class UserLoginService implements UserDetailsService {
@Autowired
private AuthorizationService authorizationService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = authorizationService.getUser(username);
if(user == null)
throw new UsernameNotFoundException(username);
return new UserDetails(user);
}
}
| false |
src/main/java/main/server/controllers/data/product/CarProduct.java | package main.server.controllers.data.product;
public class CarProduct extends Product {
@Additional
private String vin;
@Additional
private int year;
@Additional
private int mileage;
public CarProduct(){}
public CarProduct(String vin,int year,int mileage){
//TODO REMOVE only for testing
super("Auto",23000,123456789);
this.vin = vin;
this.year = year;
this.mileage = mileage;
}
public String getVin() {
return vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public int getMileage() {
return mileage;
}
public void setMileage(int mileage) {
this.mileage = mileage;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
}
| false |
src/main/java/main/server/controllers/data/product/Product.java | package main.server.controllers.data.product;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
public abstract class Product {
private String name;
private int price;
private int quantity;
private boolean used;
private int contactNumber;
//Czy jest produkt na sprzedaż
private boolean active;
private static HashMap<Class<? extends Product>,List<String>> additionalFieldsMap = new HashMap<>();
private List<String> additionalFields;
Product(String name,int price,int contactNumber){
this.name = name;
this.price = price;
this.contactNumber = contactNumber;
intiAdditionalFields();
}
Product(){
intiAdditionalFields();
}
private void intiAdditionalFields() {
if(!additionalFieldsMap.containsKey(this.getClass())) {
Field[] fields = getClass().getDeclaredFields();
List<String> fieldNames = new LinkedList<>();
for(Field field : fields){
if(field.isAnnotationPresent(Additional.class)){
fieldNames.add(field.getName());
}
}
additionalFieldsMap.put(this.getClass(),fieldNames);
}
this.additionalFields = additionalFieldsMap.get(this.getClass());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public boolean isUsed() {
return used;
}
public void setUsed(boolean used) {
this.used = used;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public List<String> getAdditionalFields() {
return additionalFields;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
}
| false |
src/main/java/main/server/database/AbstractData.java | package main.server.database;
import java.io.Serializable;
public abstract class AbstractData implements Serializable {
public abstract Long getId();
public abstract void setId(Long id);
protected AbstractData(){
setId(AbstractRepository.getId());
}
}
| false |
src/main/java/main/server/database/AbstractRepository.java | package main.server.database;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.io.*;
import java.util.Collection;
import java.util.List;
public abstract class AbstractRepository<DATA> {
@Autowired
private SessionFactory sessionFactory;
private Class<DATA> data;
protected AbstractRepository(Class<DATA> data){
this.data = data;
}
protected Session getSession(){
return sessionFactory.getCurrentSession();
}
@Transactional
@SuppressWarnings("unchecked")
public DATA getItem(Long id){
Session session = sessionFactory.getCurrentSession();
DATA o = session.get(data,id);
return o;
}
@Transactional
@SuppressWarnings("unchecked")
public Collection<DATA> getAllItems(){
Session session = sessionFactory.getCurrentSession();
List<DATA> o = (List<DATA>) session.createCriteria(data).list();
return o;
}
@Transactional
public DATA createItem(DATA data){
Session session = sessionFactory.getCurrentSession();
session.persist(data);
return data;
}
@Transactional
public DATA modifyItem(DATA data){
Session session = sessionFactory.getCurrentSession();
session.update(data);
return data;
}
//TODO Becouse @GeneratedValue is not supported
private static Long id = null;
private static File file = null;
public static Long getId(){
id += 1;
try {
PrintWriter writer = new PrintWriter(file);
writer.write(String.valueOf(id));
writer.close();
}catch (Exception e){ e.printStackTrace(); }
return id;
}
@Autowired
private ApplicationContext applicationContext;
@PostConstruct
private void init(){
if(id == null) {
try {
file = new File(applicationContext.getResource("classpath:sequence").getFile().getAbsolutePath());
FileReader reader = new FileReader(file);
BufferedReader br = new BufferedReader(reader);
id = Long.parseLong(br.readLine());
} catch (Exception e) { e.printStackTrace(); }
}
}
}
| false |
src/main/java/main/configuration/mvc/BeanConfigurationManager.java | package main.configuration.mvc;
import main.configuration.security.HashPasswordEncoder;
import main.configuration.security.LoginSuccessHandler;
import main.server.database.AbstractRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import java.util.List;
@Configuration
@EnableTransactionManagement
public class BeanConfigurationManager {
@Bean
public AuthenticationSuccessHandler authenticationSuccessHandler(){
return new LoginSuccessHandler();
}
@Bean
public PasswordEncoder passwordEncoder(){
return new HashPasswordEncoder();
}
@Autowired
private List<AbstractRepository> repositoryList;
@Autowired
private ApplicationContext applicationContext;
}
| false |
src/main/java/main/server/database/dto/ProductData.java | package main.server.database.dto;
import main.server.database.AbstractData;
import javax.persistence.*;
@Entity
@Table(name = "PRODUCTS")
public class ProductData extends AbstractData {
@Id
@Column(name = "PRODUCT_ID")
private Long id;
@Column(name = "PRODUCTS_USER_ID")
@JoinColumn(name = "USER_ID")
private Long userId;
@Column(name = "PRODUCT_LINK")
private String productLink;
@Column(name = "PRODUCT_NAME")
private String name;
@Column(name = "PRODUCT_QUANTITY")
private int quantity;
public ProductData(String name,String productLink){
this.name = name;
this.productLink = productLink;
this.quantity = 1;
}
public ProductData(){
this.quantity = 1;
}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getProductLink() {
return productLink;
}
public void setProductLink(String productLink) {
this.productLink = productLink;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
@Override
public int hashCode() {
return (int) (this.name.length() + this.userId +
this.productLink.length()%this.name.length());
}
@Override
public boolean equals(Object obj) {
if(obj instanceof ProductData){
ProductData that = (ProductData) obj;
return that.userId.equals(this.userId)
&& that.productLink.equals(this.productLink)
&& that.name.equals(this.name);
}
return false;
}
}
| false |
src/main/java/main/server/controllers/data/Basket.java | package main.server.controllers.data;
import main.server.database.dto.ProductData;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
public class Basket {
private Set<ProductData> products;
public void addProduct(ProductData product){
products.remove(product);
products.add(product);
}
public List<ProductData> getProducts() {
return new LinkedList<>(products);
}
public void setProducts(Set<ProductData> products) {
this.products = products;
}
}
| false |
src/main/java/main/server/database/dto/UserData.java | package main.server.database.dto;
import main.server.database.AbstractData;
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "USERS")
public class UserData extends AbstractData {
@Id
@Column(name = "USER_ID")
private Long id;
@Column(name = "USER_NAME"/*,unique = true*/)
private String username;
@Column(name = "USER_PASSWORD")
private String password;
@Column(name = "USER_ROLE")
private int userRole;
@OneToMany(fetch = FetchType.EAGER,mappedBy = "userId")
private Set<ProductData> products;
public UserData() {}
@Override
public Long getId() {
return id;
}
@Override
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String login) {
this.username = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getUserRole() {
return userRole;
}
public void setUserRole(int userRole) {
this.userRole = userRole;
}
@Override
public String toString() {
return id + " : " + username;
}
public Set<ProductData> getProducts() {
return products;
}
public void setProducts(Set<ProductData> products) {
this.products = products;
}
} | false |
src/main/java/main/server/database/dao/ProductRepository.java | package main.server.database.dao;
import main.server.database.AbstractRepository;
import main.server.database.dto.ProductData;
import main.server.database.dto.UserData;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Set;
@Repository
public class ProductRepository extends AbstractRepository<ProductData> {
@Autowired
private UserRepository userRepository;
public ProductRepository() { super(ProductData.class);}
@Transactional
public Set<ProductData> getProducts(String username){
return userRepository.getItem(username).getProducts();
}
@Transactional
public synchronized ProductData createItem(Long userId,String name,String productLink) {
Session session = getSession();
ProductData product = (ProductData) session.createQuery("from ProductData where userId = :userId AND " +
"name = :name AND productLink = :productLink")
.setParameter("userId",userId).setParameter("name",name)
.setParameter("productLink",productLink).uniqueResult();
if(product == null){
product = new ProductData(name,productLink);
product.setUserId(userId);
super.createItem(product);
} else {
product.setQuantity(product.getQuantity() + 1);
super.modifyItem(product);
}
return product;
}
}
| false |
src/main/java/main/server/controllers/authorization/ApplicationContext.java | package main.server.controllers.authorization;
import main.server.controllers.data.Basket;
import main.server.database.dao.ProductRepository;
import main.server.database.dto.UserData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
public class ApplicationContext {
@Autowired
private ProductRepository productRepository;
private UserData user;
private Basket basket;
public ApplicationContext(){}
public UserData getUser() {
return user;
}
void initContext(UserData user){
this.user = user;
basket = new Basket();
basket.setProducts(productRepository.getProducts(user.getUsername()));
}
public Basket getBasket() {
return basket;
}
}
| false |
src/main/java/main/server/controllers/AbstractController.java | package main.server.controllers;
import main.server.controllers.authorization.ApplicationContext;
import org.springframework.beans.factory.annotation.Autowired;
public class AbstractController {
@Autowired
private ApplicationContext applicationContext;
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
public String redirect(String url){
if(url.startsWith("/tai-app"))
url = url.substring(8);
return "redirect:" + url;
}
public String forward(String url){
if(url.startsWith("/tai-app"))
url = url.substring(8);
return "forward:" + url;
}
}
| false |
src/main/java/main/server/controllers/authorization/IndexController.java | package main.server.controllers.authorization;
import main.server.controllers.AbstractController;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController extends AbstractController {
@RequestMapping("/")
public String index(){
return "index";
}
}
| false |
src/main/java/main/server/controllers/products/BasketController.java | package main.server.controllers.products;
import main.server.controllers.AbstractController;
import main.server.database.dao.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/user")
public class BasketController extends AbstractController {
@Autowired
private ProductRepository productRepository;
@RequestMapping(value = "/basket",method = RequestMethod.GET)
public String basket(Model model){
model.addAttribute("products",getApplicationContext().getBasket().getProducts());
return "basket";
}
@RequestMapping("/basket/add")
public String basketAdd(
@RequestParam("name") String name,
@RequestParam("productLink") String productLink,
@RequestParam("returnUrl") String returnUrl
){
getApplicationContext().getBasket().addProduct(productRepository.createItem(
getApplicationContext().getUser().getId(),name,productLink));
return redirect(returnUrl+"?productUrl="+productLink);
}
}
| false |
src/main/java/main/server/database/dao/UserRepository.java | package main.server.database.dao;
import main.configuration.security.HashPasswordEncoder;
import main.server.database.AbstractRepository;
import main.server.database.dto.UserData;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.PostConstruct;
@Repository
public class UserRepository extends AbstractRepository<UserData> {
private static PasswordEncoder passwordEncoder = new HashPasswordEncoder();
public UserRepository() { super(UserData.class);}
@Cacheable(value = "userCache",unless = "#result == null")
@Transactional
public UserData getItem(String username){
return (UserData) getSession().createQuery("from UserData where username = :username")
.setParameter("username",username).uniqueResult();
}
}
| false |
src/main/java/main/server/beans/services/AuthorizationServiceBean.java | package main.server.beans.services;
import main.server.controllers.data.User;
import main.server.database.dao.UserRepository;
import main.server.database.dto.UserData;
import org.springframework.beans.factory.annotation.Autowired;
public class AuthorizationServiceBean implements AuthorizationService {
@Autowired
private UserRepository userRepository;
@Override
public User getUser(String username) {
UserData data = userRepository.getItem(username);
if(data == null)
return null;
return new User(data.getUsername(),data.getPassword());
}
@Override
public long registerUser(User user) {
UserData data = new UserData();
data.setUsername(user.getUsername());
data.setPassword(user.getPassword());
userRepository.createItem(data);
return data.getId();
}
@Override
public boolean isUserRegistered(String username) {
return getUser(username) != null;
}
}
| false |
src/main/java/main/server/controllers/authorization/AuthorizationController.java | package main.server.controllers.authorization;
import main.server.beans.services.AuthorizationService;
import main.server.controllers.AbstractController;
import main.server.controllers.IgnoreAdvice;
import main.server.controllers.data.User;
import main.server.database.dao.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
@IgnoreAdvice
@Controller
public class AuthorizationController extends AbstractController {
@Autowired
private UserRepository userRepository;
@Autowired
private AuthorizationService authorizationService;
@Autowired
private PasswordEncoder passwordEncoder;
@RequestMapping(value = "/login",method = RequestMethod.GET)
public String getLogin(HttpServletRequest request, Model model){
if(request.getParameter("error") != null)
model.addAttribute("error","Bad login or bad password");
model.addAttribute("user",new User());
return "login";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String getRegister(Model model){
model.addAttribute("user",new User());
return "register";
}
@RequestMapping(value = "/register",method = RequestMethod.POST)
public String postRegister(User user){
if(authorizationService.isUserRegistered(user.getUsername()))
return "redirect:/register";
user.setPassword(passwordEncoder.encode(user.getPassword()));
authorizationService.registerUser(user);
return redirect("/login");
}
@RequestMapping(value = "/user/initContext",method = RequestMethod.GET)
private String init(
@RequestParam("token") String accessToken,
@RequestParam("username") String username,
@RequestParam("redirect") String redirect
){
String token = authorizationService.getUser(username).getPassword();
if(token.equals(accessToken)) {
getApplicationContext().initContext(userRepository.getItem(username));
return redirect(redirect);
}
throw new IllegalArgumentException("Access token is not valid");
}
}
| false |
src/main/java/main/server/logic/products/ProductConverter.java | package main.server.logic.products;
import main.server.controllers.data.product.Product;
public interface ProductConverter {
Product getProductFromSite(String url);
}
| false |
src/main/java/main/server/logic/products/websitetypes/AllegroProductConverter.java | package main.server.logic.products.websitetypes;
import main.server.controllers.data.product.CarProduct;
import main.server.controllers.data.product.Product;
import main.server.logic.products.ProductConverter;
public class AllegroProductConverter implements ProductConverter {
@Override
public Product getProductFromSite(String url) {
//TODO GET PRODUCT FROM ALLEGRO
return null;
}
}
| false |
src/main/java/main/server/logic/products/websitetypes/OLXProductConverter.java | package main.server.logic.products.websitetypes;
import main.server.controllers.data.product.CarProduct;
import main.server.controllers.data.product.Product;
import main.server.logic.products.ProductConverter;
public class OLXProductConverter implements ProductConverter {
@Override
public Product getProductFromSite(String url) {
//TODO get Product from URL
return new CarProduct("00000000",2001,300000);
}
}
| false |
src/main/java/main/server/logic/products/websitetypes/OtomotoProductConverter.java | package main.server.logic.products.websitetypes;
import main.server.controllers.data.product.Product;
import main.server.logic.products.ProductConverter;
public class OtomotoProductConverter implements ProductConverter {
@Override
public Product getProductFromSite(String url) {
//TODO get Product from URL
return null;
}
}
| false |
src/main/java/main/server/logic/products/WebsiteType.java | package main.server.logic.products;
import main.server.controllers.data.product.Product;
import main.server.logic.products.websitetypes.AllegroProductConverter;
import main.server.logic.products.websitetypes.OLXProductConverter;
import main.server.logic.products.websitetypes.OtomotoProductConverter;
public enum WebsiteType {
OLX(new OLXProductConverter()),
OTOMOTO(new OtomotoProductConverter()),
ALLEGRO(new AllegroProductConverter());
private ProductConverter converter;
WebsiteType(ProductConverter converter){
this.converter = converter;
}
public static Product getProductDetails(String url) {
for(WebsiteType type : WebsiteType.values())
if(url.contains(type.name().toLowerCase()+".pl"))
return type.getProduct(url);
throw new UnsupportedOperationException("Unsupported website URL: " + url);
}
public Product getProduct(String url) {
return converter.getProductFromSite(url);
}
}
| false |
src/main/java/main/server/beans/services/ShopWebsiteService.java | package main.server.beans.services;
import main.server.controllers.data.product.Product;
import main.server.controllers.products.ProductController;
import main.server.database.dto.ProductData;
import java.io.IOException;
import java.util.List;
public interface ShopWebsiteService {
List<ProductController.ProductResultList> getProducts(String searchCriteria) throws IOException;
Product getProductDetails(String url) throws IOException;
}
| false |
src/main/java/main/server/controllers/ControllerAdvice.java | package main.server.controllers;
import main.server.beans.services.ShopWebsiteService;
import main.server.controllers.data.Search;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Aspect
@Component
@Controller
public class ControllerAdvice {
@Pointcut("within(main.server.controllers.AbstractController+) &&" +
"!@annotation(main.server.controllers.IgnoreAdvice) &&" +
"!@within(main.server.controllers.IgnoreAdvice)")
public void advice(){}
@Around("advice()")
public String beforeAdvice(ProceedingJoinPoint pjp) throws Throwable {
return "forward:/initAdvice?view="+pjp.proceed();
}
@RequestMapping(value = "/initAdvice",method = {RequestMethod.GET,RequestMethod.POST})
public String initAdvice(
@RequestParam("view") String forwardView,
HttpServletRequest request,
HttpServletResponse response,
Model model
){
model.addAttribute("search",new Search());
return forwardView;
}
}
| false |
src/main/java/main/server/controllers/products/ProductController.java | package main.server.controllers.products;
import main.server.beans.services.ShopWebsiteService;
import main.server.controllers.AbstractController;
import main.server.controllers.data.Search;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
@Controller
public class ProductController extends AbstractController {
@Autowired
private ShopWebsiteService shopService;
@RequestMapping(value = "/product",method = RequestMethod.GET)
public String product(
@RequestParam("productUrl") String productUrl,
Model model
) throws IOException {
model.addAttribute("product",shopService.getProductDetails(productUrl));
model.addAttribute("productLink",productUrl);
return "product";
}
@RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Search search, Model model) throws IOException {
model.addAttribute("resultsList", shopService.getProducts(search.getSearchString()));
return "results";
}
public static class ProductResultList {
private String name;
private String url;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getUrl() { return url; }
public void setUrl(String url) { this.url = url; }
}
}
| false |
src/main/java/main/server/beans/services/ShopWebsiteServiceBean.java | package main.server.beans.services;
import main.server.controllers.data.product.Product;
import main.server.controllers.products.ProductController;
import main.server.database.dto.ProductData;
import main.server.logic.products.WebsiteType;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
public class ShopWebsiteServiceBean implements ShopWebsiteService {
@Override
public List<ProductController.ProductResultList> getProducts(String searchCriteria) throws IOException {
Document doc = Jsoup.connect("https://www.olx.pl/oferty/q-"+searchCriteria).get();
Elements table = doc.select("a.marginright5").select("strong");
List<ProductController.ProductResultList> resultsList = new LinkedList<>();
for(Element el : table){
ProductController.ProductResultList result = new ProductController.ProductResultList();
result.setName(el.html());
result.setUrl(el.parent().attributes().get("href"));
resultsList.add(result);
}
return resultsList;
}
@Override
public Product getProductDetails(String url) throws IOException {
return WebsiteType.getProductDetails(url);
}
}
| false |
src/main/java/main/server/beans/BeanServiceManager.java | package main.server.beans;
import main.configuration.security.UserLoginService;
import main.server.beans.services.AuthorizationServiceBean;
import main.server.beans.services.ShopWebsiteService;
import main.server.beans.services.ShopWebsiteServiceBean;
import main.server.database.dao.UserRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.security.core.userdetails.UserDetailsService;
import main.server.beans.services.AuthorizationService;
import main.server.controllers.authorization.ApplicationContext;
@Configuration
public class BeanServiceManager {
@Bean
public UserDetailsService userDetailsService(){
return new UserLoginService();
}
@Bean
public AuthorizationService authorizationService(){
return new AuthorizationServiceBean();
}
@Bean
public ShopWebsiteService shopWebsiteService(){ return new ShopWebsiteServiceBean(); }
@Bean
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public ApplicationContext applicationContext() {
return new ApplicationContext();
}
}
| false |
src/main/java/main/configuration/security/WebSecurityConfiguration.java | package main.configuration.security;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
@Configuration
@EnableWebMvcSecurity
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService service;
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private AuthenticationSuccessHandler successHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
//successHandel lets me to do stuff after /login post method which is managed by spring security
//atfer successfull loging in
.loginPage("/login").successHandler(successHandler).permitAll()
.and()
.authorizeRequests().antMatchers("/user/**").authenticated()
.and()
.authorizeRequests().anyRequest().permitAll()
.and()
.logout()
.logoutSuccessUrl("/login")
.logoutUrl("/logout");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(service).passwordEncoder(passwordEncoder);
}
}
| true |
src/main/java/com/allane/leasing/customer/Customer.java | package com.allane.leasing.customer;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.time.LocalDate;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "customers")
@Getter
@Setter
public class Customer {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
private String firstName;
private String lastName;
private LocalDate birthDate;
}
| true |
src/main/java/com/allane/leasing/customer/CustomerDto.java | package com.allane.leasing.customer;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.time.LocalDate;
@Getter
@Setter
public class CustomerDto {
private Integer id;
@NotBlank
@Size(min = 2, max = 50)
private String firstName;
@NotBlank
@Size(min = 2, max = 50)
private String lastName;
@NotNull
private LocalDate birthDate;
}
| false |
src/main/java/com/allane/leasing/customer/CustomerNotFoundException.java | package com.allane.leasing.customer;
import org.springframework.web.bind.annotation.ResponseStatus;
import static java.lang.String.format;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
@ResponseStatus(value = BAD_REQUEST)
public class CustomerNotFoundException extends RuntimeException {
public CustomerNotFoundException(Integer customerId) {
super(format("Customer with id '%s' does not exist", customerId));
}
}
| false |
src/main/java/com/allane/leasing/customer/CustomerRepository.java | package com.allane.leasing.customer;
import org.springframework.data.repository.CrudRepository;
public interface CustomerRepository extends CrudRepository<Customer, Integer> {
}
| false |
src/main/java/com/allane/leasing/vehicle/Vehicle.java | package com.allane.leasing.vehicle;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "vehicles")
@Getter
@Setter
public class Vehicle {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
private String brand;
private String model;
private Short modelYear;
private String vin;
private Integer priceInCents;
}
| false |
src/main/java/com/allane/leasing/contract/Contract.java | package com.allane.leasing.contract;
import com.allane.leasing.customer.Customer;
import com.allane.leasing.vehicle.Vehicle;
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import static javax.persistence.GenerationType.IDENTITY;
@Entity
@Table(name = "contracts")
@Getter
@Setter
public class Contract {
@Id
@GeneratedValue(strategy = IDENTITY)
private Integer id;
private Integer monthlyRateInCents;
@ManyToOne
@JoinColumn(name = "customer_id")
private Customer customer;
@OneToOne
@JoinColumn(name = "vehicle_id")
private Vehicle vehicle;
}
| false |
src/main/java/com/allane/leasing/vehicle/VehicleAlreadyLeasedException.java | package com.allane.leasing.vehicle;
import org.springframework.web.bind.annotation.ResponseStatus;
import static java.lang.String.format;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
@ResponseStatus(value = BAD_REQUEST)
public class VehicleAlreadyLeasedException extends RuntimeException {
public VehicleAlreadyLeasedException(Integer vehicleId) {
super(format("Vehicle with id '%s' is already in leasing", vehicleId));
}
}
| false |
src/main/java/com/allane/leasing/vehicle/VehicleDto.java | package com.allane.leasing.vehicle;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Getter
@Setter
public class VehicleDto {
private Integer id;
@NotBlank
private String brand;
@NotBlank
private String model;
@NotNull
private Short modelYear;
@Size(max = 17)
private String vin;
@NotNull
private Integer priceInCents;
}
| false |
src/main/java/com/allane/leasing/contract/ContractDetailsDto.java | package com.allane.leasing.contract;
import com.allane.leasing.customer.CustomerDto;
import com.allane.leasing.vehicle.VehicleDto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ContractDetailsDto {
private Integer id;
private Integer monthlyRateInCents;
private CustomerDto customer;
private VehicleDto vehicle;
}
| false |
src/main/java/com/allane/leasing/vehicle/VehicleNotFoundException.java | package com.allane.leasing.vehicle;
import org.springframework.web.bind.annotation.ResponseStatus;
import static java.lang.String.format;
import static org.springframework.http.HttpStatus.NOT_FOUND;
@ResponseStatus(value = NOT_FOUND)
public class VehicleNotFoundException extends RuntimeException {
public VehicleNotFoundException(Integer vehicleId) {
super(format("Vehicle with id '%s' does not exist", vehicleId));
}
}
| false |
src/main/java/com/allane/leasing/vehicle/VehicleRepository.java | package com.allane.leasing.vehicle;
import org.springframework.data.repository.CrudRepository;
public interface VehicleRepository extends CrudRepository<Vehicle, Integer> {
}
| false |
src/main/java/com/allane/leasing/contract/ContractService.java | package com.allane.leasing.contract;
import com.allane.leasing.customer.Customer;
import com.allane.leasing.customer.CustomerDto;
import com.allane.leasing.customer.CustomerNotFoundException;
import com.allane.leasing.customer.CustomerRepository;
import com.allane.leasing.vehicle.Vehicle;
import com.allane.leasing.vehicle.VehicleAlreadyLeasedException;
import com.allane.leasing.vehicle.VehicleDto;
import com.allane.leasing.vehicle.VehicleNotFoundException;
import com.allane.leasing.vehicle.VehicleRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class ContractService {
private ContractRepository contractRepository;
private CustomerRepository customerRepository;
private VehicleRepository vehicleRepository;
// TODO mapstruct
public ContractDetailsDto getContract(Integer id) {
var contract = contractRepository.findById(id)
.orElseThrow(() -> new ContractNotFoundException(id));
var contractDetails = new ContractDetailsDto();
contractDetails.setId(contract.getId());
contractDetails.setMonthlyRateInCents(contract.getMonthlyRateInCents());
var customer = contract.getCustomer();
var customerDto = new CustomerDto();
customerDto.setId(customer.getId());
customerDto.setFirstName(customer.getFirstName());
customerDto.setLastName(customer.getLastName());
customerDto.setBirthDate(customer.getBirthDate());
contractDetails.setCustomer(customerDto);
var vehicle = contract.getVehicle();
var vehicleDto = new VehicleDto();
vehicleDto.setId(vehicle.getId());
vehicleDto.setBrand(vehicle.getBrand());
vehicleDto.setModel(vehicle.getModel());
vehicleDto.setModelYear(vehicle.getModelYear());
vehicleDto.setVin(vehicle.getVin());
vehicleDto.setPriceInCents(vehicle.getPriceInCents());
contractDetails.setVehicle(vehicleDto);
return contractDetails;
}
public ContractDto createContract(ContractDto contractDto) {
var contract = new Contract();
contract.setMonthlyRateInCents(contractDto.getMonthlyRateInCents());
var customer = ensureCustomerExist(contractDto.getCustomerId());
contract.setCustomer(customer);
if (contractDto.getVehicleId() != null) {
var vehicle = ensureVehicleExistsAndNotLeased(contractDto.getVehicleId());
contract.setVehicle(vehicle);
}
var savedContract = contractRepository.save(contract);
contractDto.setId(savedContract.getId());
return contractDto;
}
public ContractDto updateContract(ContractDto contractDto) {
var contract = contractRepository.findById(contractDto.getId())
.orElseThrow(() -> new ContractNotFoundException(contractDto.getId()));
contract.setMonthlyRateInCents(contractDto.getMonthlyRateInCents());
if (!contractDto.getCustomerId().equals(contract.getCustomer().getId())) {
var customer = ensureCustomerExist(contractDto.getCustomerId());
contract.setCustomer(customer);
}
if (contractDto.getVehicleId() == null) {
contract.setVehicle(null);
} else if (contract.getVehicle() == null || !contract.getVehicle().getId().equals(contractDto.getVehicleId())) {
var vehicle = ensureVehicleExistsAndNotLeased(contractDto.getVehicleId());
contract.setVehicle(vehicle);
}
contractRepository.save(contract);
return contractDto;
}
private Customer ensureCustomerExist(Integer customerId) {
return customerRepository.findById(customerId)
.orElseThrow(() -> new CustomerNotFoundException(customerId));
}
private Vehicle ensureVehicleExistsAndNotLeased(Integer vehicleId) {
var vehicle = vehicleRepository.findById(vehicleId)
.orElseThrow(() -> new VehicleNotFoundException(vehicleId));
if (contractRepository.existsByVehicleId(vehicleId)) {
throw new VehicleAlreadyLeasedException(vehicleId);
}
return vehicle;
}
}
| false |
src/main/java/com/allane/leasing/contract/ContractNotFoundException.java | package com.allane.leasing.contract;
import org.springframework.web.bind.annotation.ResponseStatus;
import static java.lang.String.format;
import static org.springframework.http.HttpStatus.BAD_REQUEST;
@ResponseStatus(value = BAD_REQUEST)
public class ContractNotFoundException extends RuntimeException {
public ContractNotFoundException(Integer contractId) {
super(format("Contract with id '%s' does not exist", contractId));
}
}
| true |
src/main/java/com/allane/leasing/contract/ContractRepository.java | package com.allane.leasing.contract;
import org.springframework.data.repository.CrudRepository;
public interface ContractRepository extends CrudRepository<Contract, Integer> {
boolean existsByVehicleId(Integer vehicleId);
}
| true |
src/main/java/com/allane/leasing/contract/ContractController.java | package com.allane.leasing.contract;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/v1/contracts")
@AllArgsConstructor
public class ContractController {
private ContractService contractService;
@GetMapping("/{id}")
public ContractDetailsDto getContract(@PathVariable("id") Integer id) {
return contractService.getContract(id);
}
@PostMapping
public ContractDto createContract(@Valid @RequestBody ContractDto contractDto) {
return contractService.createContract(contractDto);
}
@PutMapping("/{id}")
public ContractDto updateContract(@PathVariable("id") Integer id, @Valid @RequestBody ContractDto contractDto) {
contractDto.setId(id);
return contractService.updateContract(contractDto);
}
}
| true |
src/main/java/com/allane/leasing/vehicle/VehicleController.java | package com.allane.leasing.vehicle;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;
@RestController
@RequestMapping("/api/v1/vehicles")
@AllArgsConstructor
public class VehicleController {
private VehicleService vehicleService;
private BrandsAndModels brandsAndModels;
@PostMapping
public VehicleDto createVehicle(@Valid @RequestBody VehicleDto vehicleDto) {
if (!brandsAndModels.areValid(vehicleDto.getBrand(), vehicleDto.getModel())) {
throw new InvalidBrandOrModelException(vehicleDto.getBrand(), vehicleDto.getModel());
}
return vehicleService.createVehicle(vehicleDto);
}
@GetMapping("/brands")
public Map<String, Set<String>> getBrandsAndModels() {
return brandsAndModels.getAll();
}
}
| true |
src/main/java/com/allane/leasing/vehicle/VehicleService.java | package com.allane.leasing.vehicle;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class VehicleService {
private VehicleRepository vehicleRepository;
public VehicleDto createVehicle(VehicleDto vehicleDto) {
var vehicle = new Vehicle();
vehicle.setBrand(vehicleDto.getBrand());
vehicle.setModel(vehicleDto.getModel());
vehicle.setModelYear(vehicleDto.getModelYear());
vehicle.setVin(vehicleDto.getVin());
vehicle.setPriceInCents(vehicleDto.getPriceInCents());
var savedVehicle = vehicleRepository.save(vehicle);
vehicleDto.setId(savedVehicle.getId());
return vehicleDto;
}
}
| true |
src/main/java/com/allane/leasing/vehicle/BrandsAndModels.java | package com.allane.leasing.vehicle;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Set;
@Component
public class BrandsAndModels {
private final static Map<String, Set<String>> MODELS_BY_BRAND = Map.of(
"Audi", Set.of("A1", "A3", "A4"),
"BMW", Set.of("X1", "X2", "X3"),
"VW", Set.of("Polo", "Golf", "Passat")
);
public Map<String, Set<String>> getAll() {
return MODELS_BY_BRAND;
}
public boolean areValid(String brand, String model) {
return MODELS_BY_BRAND.containsKey(brand) && MODELS_BY_BRAND.get(brand).contains(model);
}
}
| true |
src/main/java/com/allane/leasing/customer/CustomerController.java | package com.allane.leasing.customer;
import lombok.AllArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping("/api/v1/customers")
@AllArgsConstructor
public class CustomerController {
private CustomerRepository customerRepository;
private CustomerService customerService;
@GetMapping("/{id}")
public ResponseEntity<Customer> getCustomer(@PathVariable("id") Integer id) {
return ResponseEntity.of(customerRepository.findById(id)); // TODO
}
@PostMapping
public CustomerDto createCustomer(@Valid @RequestBody CustomerDto customer) {
return customerService.createCustomer(customer);
}
}
| true |
src/main/java/com/allane/leasing/customer/CustomerService.java | package com.allane.leasing.customer;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
@Service
@AllArgsConstructor
public class CustomerService {
private CustomerRepository customerRepository;
public CustomerDto createCustomer(CustomerDto customerDto) {
var customer = new Customer();
customer.setFirstName(customerDto.getFirstName());
customer.setLastName(customerDto.getLastName());
customer.setBirthDate(customerDto.getBirthDate());
var savedCustomer = customerRepository.save(customer);
customerDto.setId(savedCustomer.getId());
return customerDto;
}
}
| true |
src/main/java/yte/intern/project/common/email/SendEmailService.java | package yte.intern.project.common.email;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import javax.mail.internet.MimeMessage;
@Service
public class SendEmailService {
@Autowired
private JavaMailSender javaMailSender;
public void sendEmailWithImage(String to, String body, String subject, String imagePath) throws Exception {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom("eventmanagement10line@gmail.com");
mimeMessageHelper.setTo(to);
mimeMessageHelper.setText(body);
mimeMessageHelper.setSubject(subject);
mimeMessageHelper.setText(body + "<br/><br/><br/><img src='cid:qrcode'>", true);
mimeMessageHelper.addInline("qrcode", new FileSystemResource(imagePath));
System.out.println("Sending email to " + to);
javaMailSender.send(mimeMessage);
System.out.println("Mail Send...");
}
}
| true |
src/main/java/yte/intern/project/common/entity/BaseEntity.java | package yte.intern.project.common.entity;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;
import java.time.LocalDateTime;
import java.util.Objects;
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
@Getter
@Accessors(fluent = true)
public abstract class BaseEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Long version;
@CreatedDate
private LocalDateTime creationDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
@Override
public boolean equals(final Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
BaseEntity that = (BaseEntity) o;
return Objects.equals(id, that.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| false |
src/main/java/yte/intern/project/common/enums/MessageType.java | package yte.intern.project.common.enums;
public enum MessageType {
SUCCESS, ERROR, WARNING, INFO
}
| false |
src/main/java/yte/intern/project/common/dto/MessageResponse.java | package yte.intern.project.common.dto;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import yte.intern.project.common.enums.MessageType;
@Getter
@RequiredArgsConstructor
public class MessageResponse {
private final MessageType messageType;
private final String message;
}
| false |
src/main/java/yte/intern/project/common/exception/GlobalExceptionResolver.java | package yte.intern.project.common.exception;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.MethodArgumentNotValidException;
import yte.intern.project.common.dto.MessageResponse;
import yte.intern.project.common.enums.MessageType;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@ControllerAdvice
public class GlobalExceptionResolver {
@ExceptionHandler(value = { MethodArgumentNotValidException.class })
public void handleException(HttpServletRequest request, HttpServletResponse response, MethodArgumentNotValidException exception)
throws IOException {
MessageResponse messageResponse = new MessageResponse(MessageType.ERROR, exception.getBindingResult().getAllErrors().get(0).getDefaultMessage());
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
response.setStatus(HttpStatus.OK.value());
response.getWriter().write(new ObjectMapper().writeValueAsString(messageResponse));
}
}
| false |
src/main/java/yte/intern/project/common/qrcode/QrcodeGenerator.java | package yte.intern.project.common.qrcode;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import lombok.RequiredArgsConstructor;
import java.io.IOException;
import java.nio.file.Paths;
@RequiredArgsConstructor
public class QrcodeGenerator {
private final String eventName;
private final String firstName;
private final String lastName;
public void generateQrcode() throws WriterException, IOException {
String data = "Dear " + this.firstName + " " + this.lastName + ". You have registered to " + this.eventName + ".";
String imageName = this.firstName + this.lastName + this.eventName;
String path = "C:\\Users\\yavuz\\Desktop\\TUBITAK\\Project\\project\\front-end\\public\\%s.jpg".formatted(imageName);
BitMatrix matrix = new MultiFormatWriter()
.encode(data, BarcodeFormat.QR_CODE, 350, 350);
MatrixToImageWriter.writeToPath(matrix, "jpg", Paths.get(path));
}
}
| false |
src/main/java/yte/intern/project/security/service/CustomAuthenticationProvider.java | package yte.intern.project.security.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
@Service
public class CustomAuthenticationProvider implements AuthenticationProvider {
private final CustomUserDetailsService customUserDetailsService;
private final PasswordEncoder passwordEncoder;
@Autowired
public CustomAuthenticationProvider(final CustomUserDetailsService customUserDetailsService,
final PasswordEncoder passwordEncoder) {
this.customUserDetailsService = customUserDetailsService;
this.passwordEncoder = passwordEncoder;
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal();
String password = (String) authentication.getCredentials();
UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
if (!password.equals(userDetails.getPassword()) || !username.equals(userDetails.getUsername())) {
throw new BadCredentialsException("Wrong username or password");
}
return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
}
@Override
public boolean supports(Class<?> authentication) {
return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication);
}
} | false |
No dataset card yet
New: Create and edit this dataset card directly on the website!
Contribute a Dataset Card