├── README.md ├── .gitignore ├── src ├── main │ ├── java │ │ └── org │ │ │ └── levelup │ │ │ ├── job │ │ │ └── list │ │ │ │ ├── reflection │ │ │ │ ├── annotation │ │ │ │ │ ├── Service.java │ │ │ │ │ ├── Brands.java │ │ │ │ │ ├── ServiceImpl.java │ │ │ │ │ ├── Profiling.java │ │ │ │ │ ├── ServiceFactory.java │ │ │ │ │ ├── RandomString.java │ │ │ │ │ ├── RandomStringAnnotationProcessor.java │ │ │ │ │ └── ProfilingAnnotationProcessor.java │ │ │ │ ├── Car.java │ │ │ │ └── ReflectionApp.java │ │ │ │ ├── domain │ │ │ │ ├── Position.java │ │ │ │ └── User.java │ │ │ │ ├── jdbc │ │ │ │ ├── JdbcUtils.java │ │ │ │ ├── UserService.java │ │ │ │ ├── PositionService.java │ │ │ │ ├── JdbcJobListServise.java │ │ │ │ ├── PositionJdbcServise.java │ │ │ │ └── UserJdbcServise.java │ │ │ │ └── JobListApplication.java │ │ │ ├── application │ │ │ ├── dao │ │ │ │ ├── PositionDao.java │ │ │ │ ├── UserDao.java │ │ │ │ ├── CompanyDao.java │ │ │ │ ├── CompanyLegalDetailsDao.java │ │ │ │ ├── JobListDao.java │ │ │ │ ├── PositionDaoImpl.java │ │ │ │ ├── CompanyLegalDetailsDaoImpl.java │ │ │ │ ├── AbstractDao.java │ │ │ │ ├── JobListDaoImpl.java │ │ │ │ ├── UserDaoImpl.java │ │ │ │ └── CompanyDaoImpl.java │ │ │ ├── domain │ │ │ │ ├── UserAddressEntity.java │ │ │ │ ├── JobListId.java │ │ │ │ ├── CompanyLegalDetailsEntity.java │ │ │ │ ├── PositionEntity.java │ │ │ │ ├── JobListEntity.java │ │ │ │ ├── UserEntity.java │ │ │ │ └── CompanyEntity.java │ │ │ └── JobApplication.java │ │ │ ├── theads │ │ │ ├── stop │ │ │ │ ├── ShutdownApp.java │ │ │ │ └── ThreadStop.java │ │ │ ├── counter │ │ │ │ ├── Counter.java │ │ │ │ ├── NonBlockingCounter.java │ │ │ │ ├── ReentrantLockCounter.java │ │ │ │ ├── CounterThread.java │ │ │ │ └── App.java │ │ │ ├── queue │ │ │ │ ├── ProducerConsumerApp.java │ │ │ │ ├── App.java │ │ │ │ ├── ThreadSafeQueue.java │ │ │ │ └── ReentrantThreadSafeQueue.java │ │ │ ├── pool │ │ │ │ └── ThreadPoolApp.java │ │ │ └── ThreadsExample.java │ │ │ ├── lesson │ │ │ ├── Animal.java │ │ │ ├── Car.java │ │ │ ├── ReflectionLessons.java │ │ │ ├── Person.java │ │ │ └── ClassFinder.java │ │ │ ├── hibernate │ │ │ ├── JobSessionFactoryConfiguration.java │ │ │ ├── HibernateApp.java │ │ │ └── servise │ │ │ │ └── UserService.java │ │ │ └── streams │ │ │ ├── CollectionUtils.java │ │ │ └── StreamsExampl.java │ └── resources │ │ ├── sql │ │ ├── lesson8 │ │ │ └── lessons8.sql │ │ ├── lesson7 │ │ │ └── lesson7.sql │ │ ├── lesson9 │ │ │ └── alter_tables.sql │ │ ├── lesson1 │ │ │ └── users.sql │ │ └── lesson2 │ │ │ └── job_list.sql │ │ └── hibernate.cfg.xml └── test │ └── java │ └── org │ └── levelup │ ├── job │ └── list │ │ └── jdbc │ │ ├── UserJdbcServiseTest.java │ │ └── PositionJdbcServiceTest.java │ ├── streams │ └── CollectionUtilsTest.java │ ├── application │ └── dao │ │ ├── PositionDaoImplTest.java │ │ ├── PositionDaoImlpIntegrationTest.java │ │ └── SessionFactoryStub.java │ └── comfiguration │ └── HibernateTestConfiguration.java ├── .jpb └── persistence-units.xml ├── SECURITY.md ├── pom.xml └── .github └── workflows └── codeql-analysis.yml /README.md: -------------------------------------------------------------------------------- 1 | # java2_course_1_2020 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | *.iml 3 | *.class 4 | /target/ 5 | /target/maven-status/ 6 | /target/test-classes/ 7 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/Service.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | public interface Service { 4 | 5 | void doSomthing(); 6 | } 7 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/PositionDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.levelup.application.domain.PositionEntity; 4 | 5 | public interface PositionDao { 6 | 7 | PositionEntity createPosition(String name); 8 | } 9 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/Brands.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | public enum Brands { 4 | KIA, 5 | HYUNDAI, 6 | VOLKSWAGEN, 7 | BMV, 8 | AUDI, 9 | VOLVO, 10 | LEXUS 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/ServiceImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | public class ServiceImpl implements Service { 4 | 5 | @Override 6 | @Profiling 7 | public void doSomthing() { 8 | System.out.println("do samthing..."); 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/UserDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.levelup.application.domain.UserEntity; 4 | 5 | import java.util.Collection; 6 | 7 | public interface UserDao { 8 | 9 | UserEntity createUser(String name, String lastName, String passport, Collection addresses); 10 | } 11 | -------------------------------------------------------------------------------- /.jpb/persistence-units.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /src/main/resources/sql/lesson8/lessons8.sql: -------------------------------------------------------------------------------- 1 | create table company_positions ( 2 | company_id integer not null, 3 | position_id integer not null, 4 | constraint company_positions_pkey primary key (company_id, position_id), 5 | constraint company_positions_company_id_fkey foreign key (company_id) references companies(id), 6 | constraint company_positions_position_id_fkey foreign key (position_id) references positions(id) 7 | ); -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/Profiling.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | @Retention(RetentionPolicy.RUNTIME) 9 | @Target(ElementType.METHOD) 10 | public @interface Profiling { 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/CompanyDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.levelup.application.domain.CompanyEntity; 4 | 5 | public interface CompanyDao { 6 | 7 | void create(String name, String ein, String address); 8 | 9 | CompanyEntity findById(Integer id); 10 | 11 | CompanyEntity findByEin(String ein); 12 | 13 | CompanyEntity findByName(String name); 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/stop/ShutdownApp.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.stop; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | public class ShutdownApp { 6 | 7 | @SneakyThrows 8 | public static void main(String[] args) { 9 | ThreadStop thread = new ThreadStop(); 10 | thread.start(); 11 | 12 | Thread.sleep(1000); 13 | new Thread(() -> thread.shutdown()).start(); 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/stop/ThreadStop.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.stop; 2 | 3 | public class ThreadStop extends Thread { 4 | 5 | volatile boolean shutdown; 6 | 7 | @Override 8 | public void run() { 9 | while (!shutdown) { 10 | System.out.println("I'm working..."); 11 | } 12 | } 13 | 14 | public void shutdown () { 15 | shutdown = true; 16 | } 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/domain/Position.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.domain; 2 | 3 | public class Position { 4 | private int id; 5 | private String name; 6 | 7 | public Position ( int id, String name) { 8 | this.id = id; 9 | this.name = name; 10 | } 11 | 12 | public int getId() { 13 | return id; 14 | } 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/ServiceFactory.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | public class ServiceFactory { 4 | public static Service getService() { 5 | return (Service) ProfilingAnnotationProcessor.process(new ServiceImpl()); 6 | } 7 | 8 | public static void main(String[] args) { 9 | Service service = getService(); 10 | service.doSomthing(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/CompanyLegalDetailsDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.levelup.application.domain.CompanyLegalDetailsEntity; 4 | 5 | import java.util.Collection; 6 | 7 | public interface CompanyLegalDetailsDao { 8 | 9 | void updateLegalDetailsInCompany (Integer companyId, String bankName, String bic); 10 | 11 | Collection findAllByBankName (String bankName); 12 | } 13 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/lesson/Animal.java: -------------------------------------------------------------------------------- 1 | package org.levelup.lesson; 2 | 3 | public class Animal { 4 | public int id; 5 | public String type; 6 | 7 | public Animal() { 8 | this.id = 25; 9 | this.type = "Bird"; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Animal{" + 15 | "id=" + id + 16 | ", type='" + type + '\'' + 17 | '}'; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/RandomString.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | import java.lang.annotation.ElementType; 4 | import java.lang.annotation.Retention; 5 | import java.lang.annotation.RetentionPolicy; 6 | import java.lang.annotation.Target; 7 | 8 | 9 | @Retention(RetentionPolicy.RUNTIME) 10 | @Target(ElementType.FIELD) 11 | public @interface RandomString { 12 | 13 | int maxLength() default 30; 14 | 15 | } 16 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/lesson/Car.java: -------------------------------------------------------------------------------- 1 | package org.levelup.lesson; 2 | 3 | public class Car { 4 | private int number; 5 | public String brand; 6 | 7 | public Car() { 8 | this.number = 458; 9 | this.brand = "BMV"; 10 | } 11 | 12 | @Override 13 | public String toString() { 14 | return "Car{" + 15 | "number=" + number + 16 | ", brand='" + brand + '\'' + 17 | '}'; 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/main/resources/sql/lesson7/lesson7.sql: -------------------------------------------------------------------------------- 1 | create table company_legal_details ( 2 | company_id integer primary key, 3 | bank_name varchar not null, 4 | bic varchar not null, 5 | constraint cimpany_id_fkey foreign key (company_id) references companies(id) 6 | ); 7 | 8 | create table user_addresses ( 9 | id serial primary key, 10 | user_id integer not null, 11 | address varchar not null, 12 | constraint user_addreess_user_id_fkey foreign key (user_id) references users(id) 13 | ); -------------------------------------------------------------------------------- /src/main/java/org/levelup/hibernate/JobSessionFactoryConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.levelup.hibernate; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.hibernate.cfg.Configuration; 5 | 6 | public class JobSessionFactoryConfiguration { 7 | 8 | public SessionFactory configure() { 9 | Configuration configuration = new Configuration().configure(); 10 | SessionFactory factory = configuration.buildSessionFactory(); 11 | return factory; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/JobListDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.levelup.application.domain.JobListEntity; 4 | 5 | import java.time.LocalDate; 6 | 7 | public interface JobListDao { 8 | 9 | JobListEntity createJobRecord(Integer companyId, Integer userId, Integer positionId, 10 | LocalDate startDate, LocalDate endDate); 11 | 12 | JobListEntity findJobRecord(Integer companyId, Integer userId, Integer positionId); 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/counter/Counter.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.counter; 2 | 3 | 4 | public class Counter { 5 | 6 | protected int counter; 7 | 8 | public void incrementCounter() { 9 | synchronized (this) { 10 | // synchronized (this) { 11 | // counter++; 12 | // } 13 | counter = getCounter() + 1; 14 | } 15 | } 16 | 17 | public synchronized int getCounter () { 18 | return counter; 19 | } 20 | 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/counter/NonBlockingCounter.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.counter; 2 | 3 | import java.util.concurrent.atomic.AtomicInteger; 4 | 5 | public class NonBlockingCounter extends Counter { 6 | 7 | private AtomicInteger atomicCounter = new AtomicInteger(0); 8 | 9 | @Override 10 | public void incrementCounter() { 11 | atomicCounter.incrementAndGet(); 12 | } 13 | 14 | @Override 15 | public int getCounter() { 16 | return atomicCounter.get(); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/JdbcUtils.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import java.sql.Connection; 4 | import java.sql.DriverManager; 5 | import java.sql.SQLException; 6 | 7 | public class JdbcUtils { 8 | public static Connection getConnection() throws SQLException { 9 | 10 | Connection connection = DriverManager.getConnection( 11 | "jdbc:postgresql://localhost:5432/jobs_list", 12 | "postgres", 13 | "root"); 14 | return connection; 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/UserAddressEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | 8 | @Data 9 | @Entity 10 | @NoArgsConstructor 11 | @Table(name = "user_addresses") 12 | public class UserAddressEntity { 13 | 14 | @Id 15 | @GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Integer id; 17 | private String address; 18 | 19 | //@ManyToOne 20 | // private UserEntity user; 21 | 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/JobListId.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.AllArgsConstructor; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.Column; 7 | import javax.persistence.Embeddable; 8 | import java.io.Serializable; 9 | 10 | @Embeddable 11 | @AllArgsConstructor 12 | @NoArgsConstructor 13 | public class JobListId implements Serializable { 14 | 15 | @Column(name = "company_id") 16 | private Integer companyId; 17 | @Column(name = "position_id") 18 | private Integer positionId; 19 | @Column(name = "user_id") 20 | private Integer userId; 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/streams/CollectionUtils.java: -------------------------------------------------------------------------------- 1 | package org.levelup.streams; 2 | 3 | import lombok.AccessLevel; 4 | import lombok.NoArgsConstructor; 5 | 6 | import java.util.Collection; 7 | import java.util.stream.Collectors; 8 | 9 | @NoArgsConstructor(access = AccessLevel.PRIVATE) 10 | public final class CollectionUtils { 11 | 12 | //private CollectionUtils() {} 13 | 14 | public static Collection removeLongStrings(Collection collection, int naxLength) { 15 | return collection.stream() 16 | .filter(string -> string.length() <= naxLength) 17 | .collect(Collectors.toList()); 18 | } 19 | 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/lesson/ReflectionLessons.java: -------------------------------------------------------------------------------- 1 | package org.levelup.lesson; 2 | 3 | import java.lang.reflect.Method; 4 | import java.util.Arrays; 5 | 6 | public class ReflectionLessons { 7 | 8 | public static void main(String[] args) throws ClassNotFoundException { 9 | //Class personClass = Person.class; 10 | 11 | Class personClass = Class.forName("org.levelup.lesson.Person"); 12 | 13 | Method[] methods = personClass.getMethods(); 14 | for (Method method : methods) 15 | System.out.println(method.getName() + ", " 16 | + method.getReturnType() + ", " + Arrays.toString(method.getParameterTypes())); 17 | 18 | 19 | 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | Use this section to tell people about which versions of your project are 6 | currently being supported with security updates. 7 | 8 | | Version | Supported | 9 | | ------- | ------------------ | 10 | | 5.1.x | :white_check_mark: | 11 | | 5.0.x | :x: | 12 | | 4.0.x | :white_check_mark: | 13 | | < 4.0 | :x: | 14 | 15 | ## Reporting a Vulnerability 16 | 17 | Use this section to tell people how to report a vulnerability. 18 | 19 | Tell them where to go, how often they can expect to get an update on a 20 | reported vulnerability, what to expect if the vulnerability is accepted or 21 | declined, etc. 22 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/PositionDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.application.domain.PositionEntity; 5 | 6 | public class PositionDaoImpl extends AbstractDao implements PositionDao { 7 | 8 | public PositionDaoImpl(SessionFactory factory) { 9 | super(factory); 10 | } 11 | 12 | @Override 13 | public PositionEntity createPosition(String name) { 14 | return runInTransaction(session -> { 15 | PositionEntity position = new PositionEntity(); 16 | position.setName(name); 17 | 18 | session.persist(position); 19 | return position; 20 | }); 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/counter/ReentrantLockCounter.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.counter; 2 | 3 | import java.util.concurrent.locks.ReentrantLock; 4 | 5 | public class ReentrantLockCounter extends Counter { 6 | 7 | private ReentrantLock lock = new ReentrantLock(true); 8 | 9 | @Override 10 | public void incrementCounter() { 11 | lock.lock(); 12 | try { 13 | counter++; 14 | } finally { 15 | lock.unlock(); 16 | } 17 | } 18 | 19 | @Override 20 | public int getCounter() { 21 | lock.lock(); 22 | try { 23 | return counter; 24 | } finally { 25 | lock.unlock(); 26 | } 27 | } 28 | 29 | 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/UserService.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.levelup.job.list.domain.User; 4 | 5 | import java.sql.SQLException; 6 | import java.util.Collection; 7 | 8 | public interface UserService { 9 | 10 | User createUser(String name, String lastName, String passport) throws SQLException; 11 | Collection findByPassport(String passport) throws SQLException; 12 | Collection findByNameAndLastName(String name, String lastName) throws SQLException; 13 | Collection findByLastName(String lastName) throws SQLException; 14 | void deleteUserByPassport(String passport) throws SQLException; 15 | User updateUser(String passport, String name, String lastName) throws SQLException; 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/Car.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection; 2 | 3 | import org.levelup.job.list.reflection.annotation.RandomString; 4 | 5 | public class Car { 6 | 7 | @RandomString(maxLength = 10) 8 | public String brand; 9 | private String model; 10 | 11 | public Car(String model) { 12 | this.model = model; 13 | } 14 | 15 | private Car(String brand, String model) { 16 | this.brand = brand; 17 | this.model = model; 18 | } 19 | 20 | public String getBrand() { 21 | return brand; 22 | } 23 | 24 | public String getModel() { 25 | return model; 26 | } 27 | 28 | private void changeModel(String model) { 29 | this.model = model; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/domain/User.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.domain; 2 | 3 | public class User { 4 | private int id; 5 | private String name; 6 | private String lastName; 7 | private String passport; 8 | 9 | public User(int id, String name, String lastName, String passport) { 10 | this.id = id; 11 | this.name = name; 12 | this.lastName = lastName; 13 | this.passport = passport; 14 | } 15 | 16 | public int getId() { 17 | return id; 18 | } 19 | 20 | public String getName() { 21 | return name; 22 | } 23 | 24 | public String getLastName() { 25 | return lastName; 26 | } 27 | 28 | public String getPassport() { 29 | return passport; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/PositionService.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.levelup.job.list.domain.Position; 4 | 5 | import java.sql.SQLException; 6 | import java.util.Collection; 7 | 8 | public interface PositionService { 9 | 10 | Position createPosition (String name) throws SQLException; 11 | void deletePositionById (int id) throws SQLException; 12 | void deletePositionByName(String name) throws SQLException; 13 | Collection findAllPositionWhichNameLike(String name) throws SQLException; 14 | Collection findPositionById(int id) throws SQLException; 15 | Collection findAllPositions() throws SQLException; 16 | Collection findPositionByName(String name) throws SQLException; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/CompanyLegalDetailsEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | 8 | @Data 9 | @Entity 10 | @NoArgsConstructor 11 | @Table(name = "company_legal_details") 12 | public class CompanyLegalDetailsEntity { 13 | 14 | @OneToOne(mappedBy = "legalDetails") 15 | private CompanyEntity company; 16 | 17 | @Id 18 | @Column(name ="company_id") 19 | private Integer companyId; 20 | @Column(name = "bank_name", nullable = false) 21 | private String bankName; 22 | @Column(name = "bic", nullable = false) 23 | private String BIC; 24 | 25 | public CompanyLegalDetailsEntity(Integer companyId, String bankName, String BIC) { 26 | this.companyId = companyId; 27 | this.bankName = bankName; 28 | this.BIC = BIC; 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/PositionEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Data; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | import java.util.List; 10 | 11 | @Setter 12 | @Getter 13 | @Entity 14 | @NoArgsConstructor 15 | @Table(name = "positions") 16 | public class PositionEntity { 17 | 18 | @Id 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | private Integer id; 21 | @Column(unique = true) 22 | private String name; 23 | 24 | @ManyToMany(mappedBy = "positions", fetch = FetchType.EAGER) 25 | private List companies; 26 | 27 | @Override 28 | public String toString() { 29 | return "PositionEntity{" + 30 | "id=" + id + 31 | ", name='" + name + '\'' + 32 | '}'; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/counter/CounterThread.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.counter; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | public class CounterThread implements Runnable{ 6 | 7 | private Counter counter; 8 | 9 | public CounterThread (Counter counter) { 10 | this.counter = counter; 11 | } 12 | 13 | @Override 14 | @SneakyThrows 15 | public void run() { 16 | 17 | 18 | // while (counter.getCounter() < 150 && !Thread.currentThread().isInterrupted()) { 19 | while (counter.getCounter() < 30 ) { 20 | if (Thread.interrupted() && counter.getCounter() > 15) { 21 | return; 22 | } 23 | 24 | counter.incrementCounter(); 25 | System.out.println("Counter value from runnable " + Thread.currentThread().getName() + ": " + counter.getCounter()); 26 | //Thread.sleep(20); 27 | } 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/counter/App.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.counter; 2 | 3 | public class App { 4 | 5 | public static void main(String[] args) throws InterruptedException { 6 | Counter counter = new Counter(); 7 | 8 | Thread t1 = new Thread(new CounterThread(counter)); 9 | Thread t2 = new Thread(new CounterThread(counter)); 10 | Thread t3 = new Thread(new CounterThread(counter)); 11 | 12 | long start = System.nanoTime(); 13 | 14 | t1.start(); 15 | t2.start(); 16 | t3.start(); 17 | 18 | Thread.sleep(5); 19 | t1.interrupt(); 20 | System.out.println("please , t1"); 21 | 22 | t1.join(); 23 | t2.join(); 24 | t3.join(); 25 | 26 | long end = System.nanoTime(); 27 | System.out.println(counter.getCounter()); 28 | System.out.println("Execution time: " + (end - start)); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/job/list/jdbc/UserJdbcServiseTest.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.junit.jupiter.api.Test; 4 | 5 | import java.sql.SQLException; 6 | 7 | import static org.junit.jupiter.api.Assertions.*; 8 | 9 | class UserJdbcServiseTest { 10 | 11 | @Test 12 | void createUser() throws SQLException { 13 | UserJdbcServise servise = new UserJdbcServise(); 14 | 15 | for (int i = 0; i < 10; i++) { 16 | servise.createUser("Iervattn" + i, "Ivawodretv " + i + 25, "025 0585000 458 " + i + 50); 17 | } 18 | System.out.println(); 19 | 20 | } 21 | 22 | @Test 23 | void findByPassport() { 24 | } 25 | 26 | @Test 27 | void findByNameAndLastName() { 28 | } 29 | 30 | @Test 31 | void findByLastName() { 32 | } 33 | 34 | @Test 35 | void deleteUserByPassport() { 36 | } 37 | 38 | @Test 39 | void updateUser() { 40 | } 41 | } -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/JobListEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Data; 4 | import lombok.NoArgsConstructor; 5 | 6 | import javax.persistence.*; 7 | import java.time.LocalDate; 8 | 9 | @Data 10 | @Entity 11 | @NoArgsConstructor 12 | @Table(name = "job_list") 13 | public class JobListEntity { 14 | 15 | @EmbeddedId 16 | private JobListId id; 17 | 18 | @ManyToOne 19 | @MapsId("company_id") 20 | private CompanyEntity company; 21 | @ManyToOne 22 | @MapsId("position_id") 23 | private PositionEntity position; 24 | @ManyToOne 25 | @MapsId("user_id") 26 | private UserEntity user; 27 | 28 | @Column(name = "start_date", nullable = false) 29 | private LocalDate startDate; 30 | @Column(name = "end_date") 31 | private LocalDate endDate; 32 | 33 | public JobListEntity(JobListId id, LocalDate startDate) { 34 | this.id = id; 35 | this.startDate = startDate; 36 | 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /src/main/resources/sql/lesson9/alter_tables.sql: -------------------------------------------------------------------------------- 1 | create table auth_details ( 2 | id serial primary key, -- serial -> biging default nextval('') 3 | login varchar not null unique, 4 | password varchar not null 5 | ); 6 | 7 | -- nextval('users_id_seq') -> next ID 8 | alter table users 9 | -- alter column 10 | -- drop column 11 | -- add column 12 | -- drop constraint 13 | alter column id type integer; 14 | 15 | alter table users 16 | alter column id drop default; 17 | -- drop table 18 | -- drop database 19 | drop sequence users_id_seq; 20 | 21 | insert into auth_details (id, login, password) select id, concat(id, name), last_name from users; 22 | 23 | -- max(id) users 24 | -- table_name_field_name_seq 25 | select setval('auth_details_id_seq', (select max(id) from users) + 1); 26 | 27 | alter table users add constraint users_auth_details_id_fkey foreign key (id) references auth_details(id); 28 | 29 | -- nextval 30 | -- setval 31 | -- currval 32 | select currval('auth_details_id_seq') -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/JobListApplication.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list; 2 | 3 | import org.levelup.job.list.domain.Position; 4 | import org.levelup.job.list.jdbc.JdbcJobListServise; 5 | 6 | import java.sql.SQLException; 7 | import java.util.Collection; 8 | 9 | public class JobListApplication { 10 | public static void main(String[] args) throws SQLException { 11 | JdbcJobListServise servise = new JdbcJobListServise(); 12 | 13 | for (int i = 0; i < 10; i++) { 14 | servise.createPosition("Delop5052 " + i); 15 | } 16 | System.out.println(); 17 | 18 | Collection allPositions = servise.findAll(); 19 | for (Position position : allPositions) { 20 | System.out.println(position.getId() + " " + position.getName()); 21 | } 22 | System.out.println(); 23 | 24 | Collection likePositions = servise.findPositionWithNameLike("Java%"); 25 | for (Position position : likePositions) { 26 | System.out.println(position.getId() + " " + position.getName()); 27 | } 28 | 29 | 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/job/list/jdbc/PositionJdbcServiceTest.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.junit.jupiter.api.Test; 4 | import org.levelup.job.list.domain.Position; 5 | 6 | import java.sql.SQLException; 7 | import java.util.Collection; 8 | 9 | class PositionJdbcServiceTest { 10 | 11 | @Test 12 | void createPosition() { 13 | 14 | 15 | } 16 | 17 | @Test 18 | void deletePositionById() { 19 | } 20 | 21 | @Test 22 | void deletePositionByName() { 23 | } 24 | 25 | @Test 26 | void findAllPositionWhichNameLike() throws SQLException { 27 | PositionJdbcServise pJService = new PositionJdbcServise(); 28 | 29 | Collection allLikePositions = pJService.findAllPositionWhichNameLike("%eve%"); 30 | for (Position position : allLikePositions) 31 | System.out.println(position.getId() + " " + position.getName()); 32 | 33 | } 34 | 35 | @Test 36 | void findPositionById() { 37 | } 38 | 39 | @Test 40 | void findAllPositions() { 41 | } 42 | 43 | @Test 44 | void findPositionByName() { 45 | } 46 | } -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/CompanyLegalDetailsDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.application.domain.CompanyLegalDetailsEntity; 5 | 6 | import java.util.Collection; 7 | 8 | public class CompanyLegalDetailsDaoImpl extends AbstractDao implements CompanyLegalDetailsDao { 9 | 10 | public CompanyLegalDetailsDaoImpl(SessionFactory factory) { 11 | super(factory); 12 | } 13 | 14 | @Override 15 | public void updateLegalDetailsInCompany(Integer companyId, String bankName, String bic) { 16 | runInTransaction(session -> { 17 | session.persist(new CompanyLegalDetailsEntity(companyId, bankName, bic)); 18 | }); 19 | 20 | } 21 | 22 | @Override 23 | public Collection findAllByBankName(String bankName) { 24 | return runWithoutTransaction(session -> session 25 | .createQuery("from CompanyLegalDetailsEntity where bankName = :bankName", CompanyLegalDetailsEntity.class) 26 | .setParameter("bankName", bankName) 27 | .getResultList() 28 | ); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/hibernate/HibernateApp.java: -------------------------------------------------------------------------------- 1 | package org.levelup.hibernate; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.hibernate.servise.UserService; 5 | 6 | public class HibernateApp { 7 | public static void main(String[] args) { 8 | SessionFactory factory = new JobSessionFactoryConfiguration().configure(); 9 | 10 | UserService userService = new UserService(factory); 11 | // User user = userService.createUserPersist("Oleg", "Olegov", "4568 852654"); 12 | // System.out.println(user); 13 | 14 | // Integer id = userService.createUserSave("bvz", "nbzh", "2558 669854"); 15 | // System.out.println(id); 16 | 17 | //Integer cloneId = userService.cloneUser(38, "2548 548586"); 18 | //System.out.println(cloneid); 19 | 20 | // User user = userService.updateUserNameWithMerge(38, "Kolya"); 21 | // System.out.println("original user: " + Integer.toHexString(user.hashCode())); 22 | 23 | // User user = userService.mergeNewUser("Uyt", "Ujgy", "548 548965"); 24 | // System.out.println(user); 25 | 26 | userService.updateUser("tr", "fr", "5485"); 27 | 28 | factory.close(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/queue/ProducerConsumerApp.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.queue; 2 | 3 | public class ProducerConsumerApp { 4 | public static void main(String[] args) { 5 | 6 | ThreadSafeQueue queue = new ThreadSafeQueue<>(3); 7 | 8 | Thread producer = new Thread(() -> { 9 | for (int i = 0; i < 10; i++) { 10 | queue.put(i * i); 11 | System.err.println("Producer: " + i); 12 | 13 | try { 14 | Thread.sleep(500); 15 | } 16 | catch (InterruptedException e) { 17 | e.printStackTrace(); 18 | } 19 | } 20 | }); 21 | Thread consumer = new Thread(() -> { 22 | for (int i = 0; i < 10 ; i++) { 23 | 24 | Integer task = queue.take(); 25 | System.err.println("Consumer: " + task); 26 | 27 | try { 28 | Thread.sleep(1200); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | }); 35 | 36 | consumer.start(); 37 | producer.start(); 38 | 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/UserEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Data; 4 | import lombok.Getter; 5 | import lombok.NoArgsConstructor; 6 | import lombok.Setter; 7 | 8 | import javax.persistence.*; 9 | import java.util.List; 10 | 11 | @Setter 12 | @Getter 13 | @NoArgsConstructor 14 | @Entity 15 | @Table(name= "users") 16 | public class UserEntity { 17 | 18 | @Id // primary key 19 | @GeneratedValue(strategy = GenerationType.IDENTITY) 20 | private Integer id; 21 | @Column(length = 100, nullable = false) //varchar(100) not null 22 | private String name; 23 | @Column(name = "last_name", length = 100, nullable = false) //varchar(100) not null 24 | private String lastName; 25 | @Column(length = 50, nullable = false, unique = true) //varchar(50) not null unique 26 | private String passport; 27 | 28 | @OneToMany(cascade = CascadeType.ALL) 29 | @JoinColumn(name = "user_id", nullable = false) 30 | private List addresses; 31 | 32 | @Override 33 | public String toString() { 34 | return "UserEntity{" + 35 | "id=" + id + 36 | ", name='" + name + '\'' + 37 | ", lastName='" + lastName + '\'' + 38 | ", passport='" + passport + '\'' + 39 | '}'; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/AbstractDao.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import lombok.RequiredArgsConstructor; 4 | import org.hibernate.Session; 5 | import org.hibernate.SessionFactory; 6 | import org.hibernate.Transaction; 7 | 8 | import java.util.function.Consumer; 9 | import java.util.function.Function; 10 | 11 | @RequiredArgsConstructor 12 | public abstract class AbstractDao { 13 | 14 | protected final SessionFactory factory; 15 | 16 | protected T runInTransaction (Function function) { 17 | try (Session session = factory.openSession()) { 18 | Transaction transaction =session.beginTransaction(); 19 | 20 | T resuit = function.apply(session); 21 | 22 | transaction.commit(); 23 | return resuit; 24 | } 25 | } 26 | 27 | protected void runInTransaction (Consumer consumer) { 28 | try (Session session = factory.openSession()) { 29 | Transaction transaction = session.beginTransaction(); 30 | consumer.accept(session); 31 | transaction.commit(); 32 | } 33 | } 34 | 35 | protected T runWithoutTransaction(Function function) { 36 | try (Session session = factory.openSession()) { 37 | return function.apply(session); 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/domain/CompanyEntity.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.domain; 2 | 3 | import lombok.Getter; 4 | import lombok.Setter; 5 | 6 | import javax.persistence.*; 7 | import java.util.List; 8 | 9 | @Setter 10 | @Getter 11 | @Entity 12 | @Table(name = "companies") 13 | public class CompanyEntity { 14 | 15 | @Id@GeneratedValue(strategy = GenerationType.IDENTITY) 16 | private Integer id; 17 | @Column(nullable = false) 18 | private String name; 19 | @Column(nullable = false, unique = true) 20 | private String ein; 21 | @Column(nullable = false) 22 | private String address; 23 | 24 | @OneToOne(cascade = CascadeType.ALL) 25 | @JoinColumn(name = "id") 26 | private CompanyLegalDetailsEntity legalDetails; 27 | 28 | @ManyToMany 29 | @JoinTable( 30 | name = "company_positions", 31 | joinColumns =@JoinColumn(name = "company_id"), 32 | inverseJoinColumns = @JoinColumn(name = "position_id") 33 | ) 34 | private List positions; 35 | 36 | @Override 37 | public String toString() { 38 | return "CompanyEntity{" + 39 | "id=" + id + 40 | ", name='" + name + '\'' + 41 | ", ein='" + ein + '\'' + 42 | ", address='" + address + '\'' + 43 | '}'; 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/JobListDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.application.domain.JobListEntity; 5 | import org.levelup.application.domain.JobListId; 6 | 7 | import java.time.LocalDate; 8 | 9 | public class JobListDaoImpl extends AbstractDao implements JobListDao { 10 | 11 | public JobListDaoImpl(SessionFactory factory) { 12 | super(factory); 13 | } 14 | 15 | @Override 16 | public JobListEntity createJobRecord(Integer companyId, Integer userId, Integer positionId, 17 | LocalDate startDate, LocalDate endDate) { 18 | return runInTransaction(session -> { 19 | JobListId id = new JobListId(companyId, positionId, userId); 20 | JobListEntity jobRecord = new JobListEntity(id, startDate); 21 | 22 | if (endDate != null) 23 | jobRecord.setEndDate(endDate); 24 | 25 | session.persist(jobRecord); 26 | return jobRecord; 27 | }); 28 | } 29 | 30 | @Override 31 | public JobListEntity findJobRecord(Integer companyId, Integer userId, Integer positionId) { 32 | return runWithoutTransaction(session -> 33 | session.get(JobListEntity.class, new JobListId(companyId, positionId, userId))); 34 | } 35 | 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/queue/App.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.queue; 2 | 3 | public class App { 4 | public static void main(String[] args) { 5 | 6 | ReentrantThreadSafeQueue queue = new ReentrantThreadSafeQueue<>(10); 7 | 8 | Runnable producer = () -> { 9 | for (int i = 0; i < 50 ; i++) { 10 | queue.put("String " + i + ", thread: " + Thread.currentThread().getName()); 11 | System.out.println("String " + i + ", thread: " + Thread.currentThread().getName()); 12 | 13 | try { 14 | Thread.sleep(200); 15 | } catch (InterruptedException e) { 16 | e.printStackTrace(); 17 | } 18 | 19 | } 20 | }; 21 | 22 | Runnable consumer = () -> { 23 | while (true) { 24 | String result = queue.take(); 25 | System.out.println("Consumer: " + result); 26 | 27 | try { 28 | Thread.sleep(200); 29 | } catch (InterruptedException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | }; 34 | 35 | new Thread(producer).start(); 36 | new Thread(producer).start(); 37 | new Thread(producer).start(); 38 | 39 | new Thread(consumer).start(); 40 | new Thread(consumer).start(); 41 | 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/RandomStringAnnotationProcessor.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | import java.lang.reflect.Field; 4 | import java.util.Random; 5 | 6 | public class RandomStringAnnotationProcessor { 7 | 8 | public static Object process(Object object) throws IllegalAccessException { 9 | // сканировать пакет 10 | 11 | //Нужно получить обект класс 12 | //найти поля с анатацией 13 | // сгенирировать рандомное число для установки определенной строки 14 | // поменять значение у поля на строку 15 | 16 | Class objClass = object.getClass(); 17 | Field[] fields = objClass.getDeclaredFields(); 18 | for (Field field : fields) { 19 | RandomString annotation = field.getAnnotation(RandomString.class); 20 | if (annotation != null) { 21 | int maxLength = annotation.maxLength(); 22 | Random random = new Random(); 23 | int number = random.nextInt(Brands.values().length); 24 | 25 | String generatedBrand = Brands.values()[number].name().toLowerCase(); 26 | String brand = generatedBrand.substring(0, Math.min(generatedBrand.length(), maxLength)); 27 | 28 | field.setAccessible(true); 29 | field.set(object, brand); 30 | } 31 | } 32 | return object; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/pool/ThreadPoolApp.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.pool; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Random; 8 | import java.util.concurrent.ExecutorService; 9 | import java.util.concurrent.Executors; 10 | import java.util.concurrent.Future; 11 | import java.util.concurrent.ScheduledExecutorService; 12 | 13 | public class ThreadPoolApp { 14 | 15 | @SneakyThrows 16 | public static void main(String[] args) { 17 | ExecutorService executorService = Executors.newFixedThreadPool(3); 18 | 19 | //ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2); 20 | //Executors.newSingleThreadExecutor(); 1 thread 21 | //Executors.newCachedThreadPool(); 22 | 23 | 24 | for (int i = 0; i < 100 ; i++) { 25 | executorService.submit(() -> System.out.println(Thread.currentThread().getName())); 26 | } 27 | 28 | List> futures = new ArrayList<>(); 29 | for (int i = 0; i < 10; i++) { 30 | Future future = executorService.submit(() -> { 31 | Random random = new Random(); 32 | return random.nextInt(10); 33 | }); 34 | futures.add(future); 35 | } 36 | for (Future future : futures) { 37 | System.out.println(future.get()); 38 | } 39 | 40 | executorService.shutdown(); 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/streams/StreamsExampl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.streams; 2 | 3 | import java.sql.Array; 4 | import java.util.ArrayList; 5 | import java.util.Collection; 6 | import java.util.Collections; 7 | import java.util.List; 8 | import java.util.stream.Collectors; 9 | 10 | public class StreamsExampl { 11 | 12 | public static void main(String[] args) { 13 | Collection integers = new ArrayList<>(); 14 | integers.add(5536); 15 | integers.add(75); 16 | integers.add(585); 17 | integers.add(55); 18 | integers.add(50); 19 | integers.add(15); 20 | 21 | 22 | List sortedCollection = new ArrayList<>(integers); 23 | Collections.sort(sortedCollection); 24 | 25 | List integersAsString = new ArrayList<>(integers.size()); 26 | for (Integer integer : integers) { 27 | integersAsString.add(String.valueOf(integer)); 28 | } 29 | 30 | Collection sorted = integers.stream().sorted().collect(Collectors.toList()); 31 | 32 | Collection strings = integers 33 | .stream() 34 | .filter(integer -> integer > 9 && integer < 100) 35 | //.map(integer -> String.valueOf(integer)) 36 | .map(String :: valueOf) 37 | .filter(string -> string.length() <= 3) 38 | .collect(Collectors.toList()); 39 | 40 | boolean all = strings.stream().allMatch(string -> string.length() == 2); 41 | 42 | 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/queue/ThreadSafeQueue.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.queue; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | 8 | public class ThreadSafeQueue { 9 | 10 | private final Queue queue; 11 | private final int maxSize; 12 | 13 | private final Object notFull = new Object(); 14 | private final Object notEmpty = new Object(); 15 | 16 | public ThreadSafeQueue(int maxSize) { 17 | this.maxSize = maxSize; 18 | this.queue = new LinkedList<>(); 19 | } 20 | 21 | @SneakyThrows 22 | public void put(T task) { 23 | synchronized (notFull) { 24 | while (queue.size() == maxSize) { 25 | System.err.println("Producer: wait"); 26 | notFull.wait(); 27 | System.err.println("Producer: wake up"); 28 | } 29 | } 30 | synchronized (notEmpty) { 31 | queue.add(task); 32 | notEmpty.notifyAll(); 33 | } 34 | } 35 | 36 | @SneakyThrows 37 | public T take() { 38 | synchronized (notEmpty) { 39 | while (queue.isEmpty()) { 40 | System.err.println("Consumer: wait"); 41 | notEmpty.wait(); 42 | System.err.println("Consumer: wake up"); 43 | } 44 | } 45 | synchronized (notFull) { 46 | T task = queue.remove(); 47 | notFull.notifyAll(); 48 | return task; 49 | } 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/UserDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.application.domain.UserAddressEntity; 5 | import org.levelup.application.domain.UserEntity; 6 | 7 | import java.util.Collection; 8 | import java.util.List; 9 | import java.util.stream.Collectors; 10 | 11 | public class UserDaoImpl extends AbstractDao implements UserDao { 12 | 13 | public UserDaoImpl(SessionFactory factory) { 14 | super(factory); 15 | } 16 | 17 | @Override 18 | public UserEntity createUser(String name, String lastName, String passport, Collection addresses) { 19 | return runInTransaction(session -> { 20 | UserEntity user = new UserEntity(); 21 | user.setName(name); 22 | user.setLastName(lastName); 23 | user.setPassport(passport); 24 | 25 | List addressEntities = addresses 26 | .stream() 27 | .map(address -> { 28 | UserAddressEntity addressEntity = new UserAddressEntity(); 29 | addressEntity.setAddress(address); 30 | // addressEntity.setUser(user); 31 | return addressEntity; 32 | }) 33 | .collect(Collectors.toList()); 34 | 35 | user.setAddresses(addressEntities); 36 | session.persist(user); 37 | 38 | return user; 39 | }); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/resources/hibernate.cfg.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | org.postgresql.Driver 11 | jdbc:postgresql://localhost:5432/jobs_list 12 | postgres 13 | root 14 | org.hibernate.dialect.PostgreSQL81Dialect 15 | 16 | 17 | validate 18 | true 19 | true 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/queue/ReentrantThreadSafeQueue.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads.queue; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | import java.util.LinkedList; 6 | import java.util.Queue; 7 | import java.util.concurrent.locks.Condition; 8 | import java.util.concurrent.locks.ReentrantLock; 9 | 10 | public class ReentrantThreadSafeQueue { 11 | 12 | private final int maxSize; 13 | private final Queue queue; 14 | 15 | private final ReentrantLock lock; 16 | private final Condition notEmpty; 17 | private final Condition notFull; 18 | 19 | public ReentrantThreadSafeQueue(int maxSize) { 20 | this.maxSize = maxSize; 21 | this.queue = new LinkedList<>(); 22 | this.lock = new ReentrantLock(); 23 | 24 | this.notEmpty = lock.newCondition(); 25 | this.notFull = lock.newCondition(); 26 | } 27 | 28 | @SneakyThrows 29 | public void put(T task) { 30 | lock.lock(); 31 | try { 32 | while (queue.size() == maxSize) { 33 | notFull.await(); 34 | } 35 | queue.add(task); 36 | notEmpty.signal(); 37 | } finally { 38 | lock.unlock(); 39 | } 40 | } 41 | 42 | @SneakyThrows 43 | public T take() { 44 | lock.lock(); 45 | try { 46 | while (queue.isEmpty()) { 47 | notEmpty.await(); 48 | } 49 | T task = queue.remove(); 50 | notFull.signalAll(); 51 | return task; 52 | } finally { 53 | lock.unlock(); 54 | } 55 | } 56 | 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/resources/sql/lesson1/users.sql: -------------------------------------------------------------------------------- 1 | -- users: id, login, name, password 2 | -- text - для строк, у которых длина больше 255 3 | -- primary key (первичный ключ) 4 | -- serial - bigint unsigned auto_increment 5 | -- primary key - not null unique 6 | create table if not exists users ( 7 | id serial primary key, 8 | login varchar(30) not null unique, 9 | name varchar(100) not null, 10 | password varchar(100) not null 11 | ); 12 | -- 2018-06-08T10:26:26 13 | insert into users (login, name, password) values 14 | ('admin', 'Oleg', 'admin'); 15 | 16 | insert into users (name, login, password) values 17 | ('Ivan', 'ivanroot', 'root'), 18 | ('Petr', 'petya', 'qwerty'), 19 | ('Dazdranagon', 'dazdranagon', 'dazdranagon'); 20 | 21 | update users set password = 'admin2' where login = 'admin' and id = 1; 22 | 23 | delete from users where name = 'Petr'; 24 | 25 | select * from users order by id, name desc, login; 26 | 27 | create table user_details ( 28 | -- id serial primary key, 29 | user_id integer primary key, 30 | last_name varchar(100), 31 | age integer not null, 32 | email varchar(100) not null, 33 | constraint unique_email unique (email), 34 | constraint user_id_fkey foreign key (user_id) references users(id) 35 | ); 36 | 37 | create table job_list ( 38 | id serial primary key, 39 | user_id integer not null, 40 | company_name varchar(100) not null, 41 | company_address varchar not null, 42 | position varchar not null, 43 | constraint user_id_fkey foreign key (user_id) references users(id) 44 | ); 45 | 46 | insert into user_details (user_id, last_name, age, email) values 47 | (1, 'Olegov', 43, 'oleg-admin@yandex.ru'); 48 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/streams/CollectionUtilsTest.java: -------------------------------------------------------------------------------- 1 | package org.levelup.streams; 2 | 3 | import org.junit.jupiter.api.Assertions; 4 | import org.junit.jupiter.api.Test; 5 | 6 | import java.util.ArrayList; 7 | import java.util.Arrays; 8 | import java.util.Collection; 9 | 10 | class CollectionUtilsTest { 11 | 12 | //test_when_then 13 | @Test 14 | public void testRemoveLongSrting_whenCollectionEmpty_returnEmptyCollectionCopyt() { 15 | Collection emptyCollection = new ArrayList<>(); 16 | 17 | Collection resuit = CollectionUtils.removeLongStrings(emptyCollection, 10); 18 | //resuit.add(" "); 19 | Assertions.assertTrue(resuit.isEmpty()); 20 | Assertions.assertNotSame(emptyCollection, resuit); 21 | } 22 | 23 | @Test 24 | public void testRemoveLongSrting_whenCollectionIsNull_throwExeption() { 25 | Assertions.assertThrows(NullPointerException.class, () -> CollectionUtils.removeLongStrings(null, 10)); 26 | } 27 | 28 | @Test 29 | public void testRemoveLongSrting_whenCollectionIsIsValid_returnFilteredCollection() { 30 | Collection originalCollection = new ArrayList<>(Arrays.asList("String1", "Long string")); 31 | 32 | Collection result = CollectionUtils.removeLongStrings(originalCollection, 10); 33 | //Assertions.assertNotEquals(originalCollection.size(), result.size()); 34 | Assertions.assertEquals(2, originalCollection.size()); 35 | Assertions.assertEquals(1, result.size()); 36 | 37 | boolean isAllStringLendthLessThan10 = result.stream().allMatch(string -> string.length() <= 10); 38 | Assertions.assertTrue(isAllStringLendthLessThan10); 39 | } 40 | } -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/annotation/ProfilingAnnotationProcessor.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection.annotation; 2 | 3 | import java.lang.reflect.InvocationHandler; 4 | import java.lang.reflect.Method; 5 | import java.lang.reflect.Proxy; 6 | 7 | public class ProfilingAnnotationProcessor { 8 | public static Object process(Object object) { 9 | Class objClass = object.getClass(); 10 | Method[] methods = objClass.getDeclaredMethods(); 11 | 12 | boolean hasProfilingAnnotation = false; 13 | for (Method method : methods) { 14 | Profiling annotation = method.getAnnotation(Profiling.class); 15 | if ( annotation != null) { 16 | hasProfilingAnnotation = true; 17 | break; 18 | 19 | } 20 | } 21 | 22 | if (hasProfilingAnnotation) { 23 | return Proxy.newProxyInstance( 24 | objClass.getClassLoader(), 25 | objClass.getInterfaces(), 26 | new ProfilingInvocationHandler(object) 27 | ); 28 | } 29 | return object; 30 | } 31 | static class ProfilingInvocationHandler implements InvocationHandler { 32 | private Object target; 33 | 34 | public ProfilingInvocationHandler(Object target) { 35 | this.target = target; 36 | } 37 | 38 | @Override 39 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 40 | 41 | long start = System.nanoTime(); 42 | 43 | Object result = method.invoke(target, args); 44 | System.out.println("method execution time: " + (System.nanoTime() - start)); 45 | 46 | return result; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/lesson/Person.java: -------------------------------------------------------------------------------- 1 | package org.levelup.lesson; 2 | 3 | import java.io.File; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | public class Person { 10 | public int id; 11 | public String name; 12 | public String lastName; 13 | 14 | public Person() { 15 | this.id = 1; 16 | this.name = "Jon"; 17 | this.lastName = "Swift"; 18 | } 19 | 20 | @Override 21 | public String toString() { 22 | return "Person{" + 23 | "id=" + id + 24 | ", name='" + name + '\'' + 25 | ", lastName='" + lastName + '\'' + 26 | '}'; 27 | } 28 | 29 | @Target(ElementType.METHOD) 30 | @Retention(RetentionPolicy.RUNTIME) 31 | public static @interface MethodInfo { 32 | String author() default "Neil"; 33 | int dateOfCreation() default 2019; 34 | String purpose(); 35 | } 36 | 37 | public static class Search { 38 | 39 | public static String name = "ru.levelup.lessons"; 40 | 41 | public static void search2 (String name) throws ClassNotFoundException { 42 | Class nameClass = Class.forName(name); 43 | System.out.println(nameClass.toString()); 44 | 45 | } 46 | 47 | 48 | 49 | public static void main(String[] args) throws ClassNotFoundException { 50 | 51 | search2(name); 52 | 53 | File dir = new File ("C:\\Users\\Alex\\IdeaProjects\\java2_course_1_2020\\src\\main\\java\\org\\levelup\\job\\list\\"); 54 | 55 | dir.getAbsolutePath(); 56 | 57 | 58 | } 59 | } 60 | 61 | public static class Test { 62 | @MethodInfo(purpose = "Print Hello World") 63 | public void printHelloWorid() { 64 | System.out.println("Hello World!"); 65 | } 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/JobApplication.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.levelup.application.dao.*; 5 | import org.levelup.application.domain.JobListEntity; 6 | import org.levelup.hibernate.JobSessionFactoryConfiguration; 7 | import org.levelup.application.domain.UserEntity; 8 | 9 | import java.time.LocalDate; 10 | import java.util.ArrayList; 11 | import java.util.Arrays; 12 | 13 | public class JobApplication { 14 | public static void main(String[] args) { 15 | 16 | SessionFactory factory = new JobSessionFactoryConfiguration().configure(); 17 | 18 | CompanyDao companyDao = new CompanyDaoImpl(factory); 19 | CompanyLegalDetailsDao legalDetailsDao = new CompanyLegalDetailsDaoImpl(factory); 20 | 21 | companyDao.create("Company JobList", "0897865895", "SBp"); 22 | Integer companyId = companyDao.findByEin("0897865895").getId(); 23 | 24 | UserDao userDao = new UserDaoImpl(factory); 25 | UserEntity user = userDao.createUser("User1", "Last2", "0897865 4895", new ArrayList<>(Arrays.asList( 26 | "addres 1", 27 | "addres 2", 28 | "addres 3" 29 | ))); 30 | 31 | PositionDao positionDao = new PositionDaoImpl(factory); 32 | Integer positionId = positionDao.createPosition("PO 8").getId(); 33 | 34 | JobListDao jobListDao = new JobListDaoImpl(factory); 35 | jobListDao.createJobRecord(companyId, user.getId(), positionId, LocalDate.of(2019, 12, 4), null); 36 | 37 | JobListEntity jobRecord = jobListDao.findJobRecord(companyId, user.getId(), positionId); 38 | 39 | System.out.println(jobRecord.getCompany()); 40 | System.out.println(jobRecord.getPosition()); 41 | System.out.println(jobRecord.getUser()); 42 | System.out.println(jobRecord.getStartDate()); 43 | System.out.println(jobRecord.getEndDate()); 44 | 45 | 46 | 47 | factory.close(); 48 | 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/application/dao/PositionDaoImplTest.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.Session; 4 | import org.hibernate.SessionFactory; 5 | import org.hibernate.Transaction; 6 | import org.junit.jupiter.api.*; 7 | import org.levelup.application.domain.PositionEntity; 8 | import org.mockito.*; 9 | 10 | import static org.junit.jupiter.api.Assertions.*; 11 | import static org.mockito.Mockito.*; 12 | 13 | 14 | class PositionDaoImplTest { 15 | 16 | //private PositionDaoImpl dao = new PositionDaoImpl(new SessionFactoryStub()); 17 | @Mock 18 | private SessionFactory factory; 19 | @Mock 20 | private Session session; 21 | @Mock 22 | private Transaction transaction; 23 | 24 | @InjectMocks 25 | private PositionDaoImpl dao; 26 | 27 | @BeforeAll 28 | public static void beforeAll() { 29 | System.out.println("Before all"); 30 | } 31 | 32 | @BeforeEach 33 | public void initialize() { 34 | MockitoAnnotations.initMocks(this); 35 | // factory = mock(SessionFactory.class); 36 | // session = mock(Session.class); 37 | // transaction = mock(Transaction.class); 38 | 39 | when(factory.openSession()).thenReturn(session); 40 | when(session.beginTransaction()).thenReturn(transaction); 41 | 42 | //dao = new PositionDaoImpl(factory); 43 | } 44 | 45 | @Test 46 | public void testCreatePosition_validParams_persistNewPosition() { 47 | String name = "position name"; 48 | PositionEntity entity = dao.createPosition(name); 49 | assertEquals(name, entity.getName()); 50 | 51 | verify(session).persist(ArgumentMatchers.any(PositionEntity.class)); 52 | verify(transaction, Mockito.times(1)).commit(); 53 | verify(session).close(); 54 | } 55 | 56 | @AfterEach 57 | public void removeDao() { 58 | dao = null; 59 | } 60 | 61 | @AfterAll 62 | public static void afterAll() { 63 | System.out.println("After all"); 64 | } 65 | } -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/reflection/ReflectionApp.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.reflection; 2 | 3 | import org.levelup.job.list.reflection.annotation.RandomStringAnnotationProcessor; 4 | 5 | import java.lang.reflect.Constructor; 6 | import java.lang.reflect.Field; 7 | import java.lang.reflect.InvocationTargetException; 8 | import java.lang.reflect.Method; 9 | 10 | public class ReflectionApp { 11 | public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, 12 | NoSuchMethodException, InvocationTargetException, InstantiationException { 13 | Car carObj = new Car("Rio"); 14 | 15 | Class carClass = carObj.getClass(); 16 | //Class carClass = Car.class; 17 | 18 | Field[] publicFields = carClass.getFields(); 19 | for (Field publicField : publicFields) { 20 | System.out.println(publicField.getName()); 21 | } 22 | 23 | Field modelField = carClass.getDeclaredField("model"); 24 | System.out.println("private field name: " + modelField.getName()); 25 | modelField.setAccessible(true); 26 | modelField.set(carObj, "Solaris"); 27 | System.out.println("changed field value: " + carObj.getModel()); 28 | 29 | Method changeModelMethod = carClass.getDeclaredMethod("changeModel", String.class); 30 | changeModelMethod.setAccessible(true); 31 | changeModelMethod.invoke(carObj, "Polo"); 32 | System.out.println("field value afte private method invocation: " + carObj.getModel()); 33 | 34 | Constructor carConstructor = carClass.getDeclaredConstructor(String.class, String.class); 35 | carConstructor.setAccessible(true); 36 | Car refCar = (Car) carConstructor.newInstance("Lada", "Granta"); 37 | System.out.println(refCar.getBrand() + " " + refCar.getModel()); 38 | 39 | 40 | Car car = new Car("Polo"); 41 | RandomStringAnnotationProcessor.process(car); 42 | System.out.println(car.getBrand() + " " + car.getModel()); 43 | 44 | 45 | 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/comfiguration/HibernateTestConfiguration.java: -------------------------------------------------------------------------------- 1 | package org.levelup.comfiguration; 2 | 3 | import org.hibernate.SessionFactory; 4 | import org.hibernate.boot.registry.StandardServiceRegistry; 5 | import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 6 | import org.hibernate.cfg.Configuration; 7 | import org.levelup.application.domain.*; 8 | 9 | import java.util.Properties; 10 | 11 | public class HibernateTestConfiguration { 12 | 13 | private static SessionFactory factory; 14 | 15 | static { 16 | Properties hibernateProperties = new Properties(); 17 | hibernateProperties.setProperty("hibernate.connection.driver_class", "org.h2.Driver"); 18 | hibernateProperties.setProperty("hibernate.connection.url", "jdbc:h2:mem:job_list_test;INIT=CREATE SCHEMA IF NOT EXISTS job_list_test"); 19 | hibernateProperties.setProperty("hibernate.connection.username", "sa"); 20 | hibernateProperties.setProperty("hibernate.connection.password", ""); 21 | hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop"); 22 | hibernateProperties.setProperty("hibernate.show_sql", "true"); 23 | hibernateProperties.setProperty("hibernate.format_sql", "true"); 24 | 25 | StandardServiceRegistry registry = new StandardServiceRegistryBuilder() 26 | .applySettings(hibernateProperties) 27 | .build(); 28 | 29 | factory = new Configuration() 30 | .addAnnotatedClass(UserEntity.class) 31 | .addAnnotatedClass(CompanyEntity.class) 32 | .addAnnotatedClass(CompanyLegalDetailsEntity.class) 33 | .addAnnotatedClass(UserAddressEntity.class) 34 | .addAnnotatedClass(PositionEntity.class) 35 | .addAnnotatedClass(JobListEntity.class) 36 | .buildSessionFactory(registry); 37 | } 38 | 39 | public static SessionFactory getFactory() { 40 | return factory; 41 | } 42 | 43 | public static void close() { 44 | factory.close(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/application/dao/PositionDaoImlpIntegrationTest.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.Session; 4 | import org.hibernate.SessionFactory; 5 | import org.junit.jupiter.api.Assertions; 6 | import org.junit.jupiter.api.BeforeAll; 7 | import org.junit.jupiter.api.DisplayName; 8 | import org.junit.jupiter.api.Test; 9 | import org.levelup.application.domain.PositionEntity; 10 | import org.levelup.comfiguration.HibernateTestConfiguration; 11 | 12 | import javax.persistence.PersistenceException; 13 | 14 | public class PositionDaoImlpIntegrationTest { 15 | 16 | private static SessionFactory factory; 17 | private static PositionDao positionDao; 18 | 19 | 20 | @BeforeAll 21 | public static void setupPositionDao() { 22 | factory = HibernateTestConfiguration.getFactory(); 23 | positionDao = new PositionDaoImpl(factory); 24 | } 25 | 26 | @Test 27 | @DisplayName("Create new position, then position with this name doesn't exist") 28 | public void testCreatePosition_whenPositionWithNameNotExist_thenCreateNewPosition() { 29 | String name = "Java Developer"; 30 | 31 | PositionEntity result = positionDao.createPosition(name); 32 | Assertions.assertNotNull(result.getId()); 33 | Assertions.assertEquals(name, result.getName()); 34 | 35 | Session session = factory.openSession(); 36 | PositionEntity fromDb = session.createQuery("from PositionEntity where name =:name", PositionEntity.class) 37 | .setParameter("name", name) 38 | .getSingleResult(); 39 | Assertions.assertNotNull(fromDb); 40 | session.close(); 41 | } 42 | 43 | @Test 44 | @DisplayName("Throw exception, when position wjth this name exists") 45 | public void testCreatePosition_whenPositionWithNameExists_thenThowExeption() { 46 | String name = "PositionName"; 47 | positionDao.createPosition(name); 48 | 49 | Assertions.assertThrows(PersistenceException.class, () -> positionDao.createPosition(name)); 50 | 51 | } 52 | 53 | 54 | } 55 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/theads/ThreadsExample.java: -------------------------------------------------------------------------------- 1 | package org.levelup.theads; 2 | 3 | import lombok.SneakyThrows; 4 | 5 | //@SuppressWarnings("All") 6 | public class ThreadsExample { 7 | 8 | @SneakyThrows 9 | public static void main(String[] args) { 10 | 11 | Thread codeAnalyzer = new Thread(new BackgroundTask()); 12 | codeAnalyzer.setDaemon(true); 13 | codeAnalyzer.start(); 14 | 15 | 16 | Thread helloWorldThread = new Thread(new HelloWorldRunnabl(), "Hello-world-thread"); 17 | helloWorldThread.start(); 18 | 19 | Thread counter = new CounterThead(); 20 | counter.start(); 21 | Thread counter2 = new CounterThead(); 22 | counter2.start(); 23 | 24 | System.out.println("Main thread"); 25 | String threadName = Thread.currentThread().getName(); 26 | System.out.println("Thread name: " + threadName); 27 | 28 | Thread.sleep(13_000); 29 | System.out.println("Main thread finished"); 30 | 31 | } 32 | 33 | static class CounterThead extends Thread{ 34 | 35 | @Override 36 | @SneakyThrows 37 | public void run() { 38 | String threadName = Thread.currentThread().getName(); 39 | System.out.println(threadName + ": start counter thread"); 40 | for(int i = 0; i < 10; i++) { 41 | Thread.sleep(1000); 42 | System.out.println(threadName + ": " + i); 43 | } 44 | } 45 | 46 | } 47 | 48 | static class HelloWorldRunnabl implements Runnable { 49 | 50 | @Override 51 | @SneakyThrows 52 | public void run() { 53 | Thread.sleep(4000); 54 | System.out.println("Hello from: " + Thread.currentThread().getName()); 55 | } 56 | } 57 | 58 | static class BackgroundTask implements Runnable { 59 | 60 | @Override 61 | @SneakyThrows 62 | public void run() { 63 | while (true) { 64 | Thread.sleep(500); 65 | System.out.println("Code analyzer started..."); 66 | } 67 | 68 | } 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | org.example 8 | java2_course_1_2020 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 13 | 14 | org.postgresql 15 | postgresql 16 | 42.3.8 17 | 18 | 19 | 20 | org.hibernate 21 | hibernate-core 22 | 5.4.24.Final 23 | 24 | 25 | 26 | org.projectlombok 27 | lombok 28 | 1.18.12 29 | provided 30 | 31 | 32 | 33 | org.junit.jupiter 34 | junit-jupiter-api 35 | 5.6.2 36 | test 37 | 38 | 39 | 40 | org.mockito 41 | mockito-core 42 | 3.3.3 43 | test 44 | 45 | 46 | 47 | com.h2database 48 | h2 49 | 2.1.210 50 | test 51 | 52 | 53 | 54 | 55 | 56 | 17 57 | 58 | 59 | 60 | 61 | 62 | org.apache.maven.plugins 63 | maven-compiler-plugin 64 | 65 | ${java.version} 66 | ${java.version} 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /src/main/resources/sql/lesson2/job_list.sql: -------------------------------------------------------------------------------- 1 | create table users ( 2 | id serial primary key, 3 | name varchar(100) not null, 4 | last_name varchar(100) not null, 5 | passport varchar(50) not null unique 6 | ); 7 | 8 | create table companies ( 9 | id serial primary key, 10 | name varchar(100) not null, 11 | ein varchar(40) not null unique, 12 | address text not null 13 | ); 14 | 15 | create table positions ( 16 | id serial primary key, 17 | name varchar not null unique 18 | ); 19 | 20 | create table job_list ( 21 | user_id integer not null, 22 | company_id integer not null, 23 | position_id integer not null, 24 | start_date date not null, 25 | end_date date, 26 | constraint job_list_pkey primary key (user_id, company_id, position_id), 27 | constraint job_list_user_id_fkey foreign key (user_id) references users(id), 28 | constraint job_list_company_id_fkey foreign key (company_id) references companies(id), 29 | constraint job_list_position_id_fkey foreign key (position_id) references positions(id) 30 | ); 31 | 32 | insert into users (name, last_name, passport) values 33 | ((nextval('users_id_seq'), 'Oleg', 'Olegov', '5453 469764'), 34 | ('Ivan', 'Ivanov', '5075 545665'); 35 | insert into companies (name, ein, address) values 36 | ('R&K', '5398694056', 'SPb'), 37 | ('Lll', '5603545653', 'Moscow'); 38 | insert into positions (name) values 39 | ('Developer'), 40 | ('QA'), 41 | ('DevOps'); 42 | 43 | insert into job_list (user_id, company_id, position_id, start_date, end_date) values 44 | (1, 1, 1, '2015-05-12', '2017-09-18'), 45 | (1, 2, 3, '2017-09-19', null), 46 | (2, 1, 2, '2016-03-26', '2017-05-08'), 47 | (2, 1, 1, '2017-05-09', '2018-08-29'), 48 | (2, 2, 1, '2018-08-30', null); 49 | 50 | select jl.start_date from job_list jl; 51 | 52 | select * from users u, companies c, job_list jl 53 | where u.id = 1; 54 | 55 | select distinct(c.name), u.name from users u 56 | inner join job_list jl on u.id = jl.user_id 57 | inner join companies c on c.id = jl.company_id 58 | where u.id = 2; 59 | 60 | -- comapany name - количество позиций 61 | -- aggregation functions 62 | -- count, sum, avg, min, max 63 | select count(u.name) from users u; 64 | select count(jl.end_date) from job_list jl; 65 | 66 | select c.name, count(jl.company_id) from users u 67 | inner join job_list jl on u.id = jl.user_id 68 | inner join companies c on c.id = jl.company_id 69 | where u.id = 2 70 | group by c.name 71 | having count(jl.company_id) > 1 72 | order by c.name 73 | limit 10 74 | offset 10; 75 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/JdbcJobListServise.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.levelup.job.list.domain.Position; 4 | 5 | import java.sql.*; 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | 9 | @SuppressWarnings("ALL") 10 | public class JdbcJobListServise { 11 | 12 | public Position createPosition(String name) throws SQLException { 13 | Connection connection = JdbcUtils.getConnection(); 14 | 15 | PreparedStatement statement = connection.prepareStatement("insert into positions (name) values (?)"); 16 | statement.setString(1, name); 17 | int rowChanged = statement.executeUpdate(); // insert/update/delete 18 | 19 | System.out.println("Колличество добавленных строк: " + rowChanged); 20 | 21 | Statement selectStatement = connection.createStatement(); 22 | ResultSet resultSet = selectStatement.executeQuery("select * from positions where name = '" + name + "'"); //select 23 | 24 | resultSet.next(); 25 | int id = resultSet.getInt(1); 26 | String positionName = resultSet.getString("name"); 27 | System.out.println("Должность: ID = " + id + ", name = " + positionName); 28 | 29 | return new Position(id, positionName); 30 | } 31 | 32 | public Collection findAll() throws SQLException { 33 | try (Connection connection = JdbcUtils.getConnection()) { 34 | Statement statement = connection.createStatement(); 35 | ResultSet resultSet = statement.executeQuery("select * from positions"); 36 | return extractPositions(resultSet); 37 | } 38 | } 39 | 40 | public Collection findPositionWithNameLike(String name) throws SQLException { 41 | try (Connection connection = JdbcUtils.getConnection()) { 42 | PreparedStatement statement = connection.prepareStatement("select * from positions where name like ?"); 43 | statement.setString(1, name); 44 | ResultSet resultSet = statement.executeQuery(); 45 | return extractPositions(resultSet); 46 | } 47 | } 48 | 49 | private Collection extractPositions(ResultSet resultSet) throws SQLException { 50 | Collection positions = new ArrayList<>(); 51 | while (resultSet.next()) { 52 | int id = resultSet.getInt("id"); 53 | String name = resultSet.getString("name"); 54 | positions.add(new Position(id, name)); 55 | } 56 | return positions; 57 | } 58 | 59 | public void deletePosition(String name) throws SQLException { 60 | try(Connection connection = JdbcUtils.getConnection()) { 61 | PreparedStatement statement = connection.prepareStatement("delete from positions where name = ?"); 62 | statement.setString(1, name); 63 | 64 | int rowDeleted = statement.executeUpdate(); 65 | System.out.println("Удалено позиций " + rowDeleted); 66 | } 67 | } 68 | 69 | } 70 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | # For most projects, this workflow file will not need changing; you simply need 2 | # to commit it to your repository. 3 | # 4 | # You may wish to alter this file to override the set of languages analyzed, 5 | # or to provide custom queries or build logic. 6 | # 7 | # ******** NOTE ******** 8 | # We have attempted to detect the languages in your repository. Please check 9 | # the `language` matrix defined below to confirm you have the correct set of 10 | # supported CodeQL languages. 11 | # 12 | name: "CodeQL" 13 | 14 | on: 15 | push: 16 | branches: [ master ] 17 | pull_request: 18 | # The branches below must be a subset of the branches above 19 | branches: [ master ] 20 | schedule: 21 | - cron: '29 7 * * 6' 22 | 23 | jobs: 24 | analyze: 25 | name: Analyze 26 | runs-on: ubuntu-latest 27 | permissions: 28 | actions: read 29 | contents: read 30 | security-events: write 31 | 32 | strategy: 33 | fail-fast: false 34 | matrix: 35 | language: [ 'java' ] 36 | # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] 37 | # Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support 38 | 39 | steps: 40 | - name: Checkout repository 41 | uses: actions/checkout@v3 42 | 43 | # Initializes the CodeQL tools for scanning. 44 | - name: Initialize CodeQL 45 | uses: github/codeql-action/init@v2 46 | with: 47 | languages: ${{ matrix.language }} 48 | # If you wish to specify custom queries, you can do so here or in a config file. 49 | # By default, queries listed here will override any specified in a config file. 50 | # Prefix the list here with "+" to use these queries and those in the config file. 51 | 52 | # Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs 53 | # queries: security-extended,security-and-quality 54 | 55 | 56 | # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). 57 | # If this step fails, then you should remove it and run the build manually (see below) 58 | - name: Autobuild 59 | uses: github/codeql-action/autobuild@v2 60 | 61 | # ℹ️ Command-line programs to run using the OS shell. 62 | # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun 63 | 64 | # If the Autobuild fails above, remove it and uncomment the following three lines. 65 | # modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance. 66 | 67 | # - run: | 68 | # echo "Run, Build Application using script" 69 | # ./location_of_script_within_repo/buildscript.sh 70 | 71 | - name: Perform CodeQL Analysis 72 | uses: github/codeql-action/analyze@v2 73 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/application/dao/CompanyDaoImpl.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import lombok.SneakyThrows; 4 | import org.hibernate.Session; 5 | import org.hibernate.SessionFactory; 6 | import org.levelup.application.domain.CompanyEntity; 7 | 8 | import java.lang.reflect.Method; 9 | import java.util.List; 10 | import java.util.function.Function; 11 | 12 | public class CompanyDaoImpl extends AbstractDao implements CompanyDao { 13 | 14 | public CompanyDaoImpl (SessionFactory factory) { 15 | super(factory); 16 | } 17 | 18 | @Override 19 | public void create(String name, String ein, String address) { 20 | 21 | runInTransaction(session -> { 22 | CompanyEntity entity = new CompanyEntity(); 23 | entity.setName(name); 24 | entity.setEin(ein); 25 | entity.setAddress(address); 26 | session.persist(entity); 27 | }); 28 | } 29 | 30 | @Override 31 | public CompanyEntity findById(Integer id) { 32 | return runWithoutTransaction(session -> session.get(CompanyEntity.class, id)); 33 | } 34 | 35 | @Override 36 | public CompanyEntity findByEin(String ein) { 37 | 38 | return runWithoutTransaction(session -> { 39 | return session 40 | .createQuery("from CompanyEntity where ein = :ein", CompanyEntity.class) 41 | .setParameter("ein", ein) 42 | .getSingleResult(); 43 | }); 44 | } 45 | 46 | public CompanyEntity findByName(String name) { 47 | 48 | List entities = runWithoutTransaction(session -> { 49 | return session 50 | .createQuery("from CompanyEntity where name =:name", CompanyEntity.class) 51 | .setParameter("name", name) 52 | .getResultList(); 53 | }); 54 | return entities.isEmpty() ? null : entities.get(0); 55 | } 56 | 57 | @SneakyThrows 58 | private void performDatabaseOperation(Method method, Object object, Object... args) { 59 | Session session = factory.openSession(); 60 | method.invoke(object, args); 61 | session.close(); 62 | 63 | } 64 | 65 | 66 | private TYPE perform(Function function) { 67 | Session session = factory.openSession(); 68 | TYPE result = function.apply(session); 69 | session.close(); 70 | return result; 71 | } 72 | 73 | private void performWithoutTransaction(DatabaseOperation operation) { 74 | Session session = factory.openSession(); 75 | // action, method 76 | 77 | operation.doAction(); 78 | session.close(); 79 | 80 | } 81 | 82 | 83 | interface DatabaseOperation { 84 | void doAction(); 85 | } 86 | 87 | class FindByIdOperatio implements DatabaseOperation { 88 | 89 | @Override 90 | public void doAction() { 91 | 92 | } 93 | } 94 | 95 | } 96 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/lesson/ClassFinder.java: -------------------------------------------------------------------------------- 1 | package org.levelup.lesson; 2 | 3 | import java.io.File; 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | 7 | public class ClassFinder { 8 | 9 | public static void main(String[] args) { 10 | findClassesInPackage("org.levelup.lesson"); 11 | } 12 | 13 | private static void findClassesInPackage(String packageName) { 14 | String pathToPackage = ClassFinder.class 15 | .getResource("") 16 | .toString() 17 | .substring(6) 18 | .replace("/", "\\") + packageName.replace(".", "\\"); 19 | File packageDir = new File(pathToPackage); 20 | if (!packageDir.exists()) { 21 | System.out.println("Package does not exist or is empty."); 22 | return; 23 | } 24 | findClassesInDirectory(packageDir); 25 | } 26 | 27 | private static void findClassesInDirectory(File directory) { 28 | File[] codeFiles = directory.listFiles(); 29 | if (codeFiles == null) { 30 | return; 31 | } 32 | Class classFromFile; 33 | for (File file : codeFiles) { 34 | if (file.isDirectory()) 35 | findClassesInDirectory(file); 36 | else if (file.isFile() && file.getAbsolutePath().endsWith(".class")) { 37 | String className = file.getAbsolutePath().substring( 38 | ClassFinder.class.getResource("") 39 | .toString().substring(6).replace("/", "\\").length(), 40 | file.getAbsolutePath().length() - 6 41 | ).replace("\\", "."); 42 | try { 43 | classFromFile = Class.forName(className); 44 | } catch (ClassNotFoundException e) { 45 | continue; 46 | } 47 | if (classFromFile.getDeclaredFields().length >= 1 && classFromFile.getDeclaredFields().length <= 3) { 48 | try { 49 | Object instance = classFromFile.newInstance(); 50 | Method method = classFromFile.getMethod("toString"); 51 | if (method.equals(Object.class.getMethod("toString"))) { 52 | System.out.println("toString() method is not overridden for class: " + classFromFile.getName()); 53 | } else { 54 | System.out.println("Found class " + classFromFile.getName()); 55 | System.out.println(method.invoke(instance)); 56 | } 57 | } catch (InstantiationException | IllegalAccessException e) { 58 | if (!classFromFile.isAnnotation() && !classFromFile.isEnum() && !classFromFile.isInterface()) { 59 | System.out.println("Cannot create object for class: " + classFromFile.getName()); 60 | } 61 | } catch (NoSuchMethodException e) { 62 | System.out.println("toString() method does not exist for class: " + classFromFile.getName()); 63 | } catch (InvocationTargetException e) { 64 | System.out.println("Cannot invoke toString() method for class: " + classFromFile.getName()); 65 | } 66 | } else { 67 | System.out.println("Incorrect number of properties for class: " + classFromFile.getName()); 68 | } 69 | } 70 | } 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/hibernate/servise/UserService.java: -------------------------------------------------------------------------------- 1 | package org.levelup.hibernate.servise; 2 | 3 | import org.hibernate.Session; 4 | import org.hibernate.SessionFactory; 5 | import org.hibernate.Transaction; 6 | import org.levelup.application.domain.UserEntity; 7 | 8 | public class UserService { 9 | 10 | private final SessionFactory factory; 11 | 12 | public UserService(SessionFactory factory) { 13 | this.factory = factory; 14 | } 15 | 16 | public UserEntity createUserPersist(String name, String lastName, String passport) { 17 | Session session = factory.openSession(); 18 | Transaction transaction = session.beginTransaction(); 19 | 20 | UserEntity user = new UserEntity(); // transient 21 | 22 | user.setName(name); 23 | user.setLastName(lastName); 24 | user.setPassport(passport); 25 | 26 | session.persist(user); //manager/persistent 27 | 28 | transaction.commit(); 29 | session.close(); 30 | 31 | return user; 32 | } 33 | 34 | public Integer createUserSave (String name, String lastName, String passport) { 35 | Session session = factory.openSession(); 36 | Transaction transaction = session.beginTransaction(); 37 | 38 | UserEntity user = new UserEntity(); 39 | user.setName(name); 40 | user.setLastName(lastName); 41 | user.setPassport(passport); 42 | 43 | Integer generateId = (Integer) session.save(user); 44 | //Integer generateId = user.getId(); 45 | 46 | transaction.commit(); 47 | session.close(); 48 | 49 | return generateId; 50 | } 51 | 52 | public UserEntity getById(Integer id) { 53 | Session session = factory.openSession(); 54 | UserEntity user = session.get(UserEntity.class, id); 55 | 56 | session.close(); // user - detached 57 | 58 | return user; 59 | } 60 | 61 | public Integer cloneUser(Integer id, String passport) { 62 | UserEntity user = getById(id); 63 | Session session = factory.openSession(); 64 | Transaction transaction = session.beginTransaction(); 65 | 66 | user.setPassport(passport); 67 | Integer cloneId = (Integer) session.save(user); 68 | 69 | transaction.commit(); 70 | session.close(); 71 | 72 | return cloneId; 73 | 74 | } 75 | 76 | public UserEntity updateUserNameWithMerge(Integer id, String name) { 77 | UserEntity user = getById(id); 78 | 79 | Session session = factory.openSession(); 80 | Transaction transaction = session.beginTransaction(); 81 | 82 | user.setName(name); 83 | UserEntity mergedUser = (UserEntity) session.merge(user); 84 | 85 | transaction.commit(); 86 | session.close(); 87 | 88 | System.out.println("original user: " + Integer.toHexString(user.hashCode())); 89 | 90 | return mergedUser; 91 | } 92 | 93 | public UserEntity mergeNewUser (String name, String lastName, String passport) { 94 | Session session = factory.openSession(); 95 | Transaction transaction = session.beginTransaction(); 96 | 97 | UserEntity user = new UserEntity(); 98 | user.setName(name); 99 | user.setLastName(lastName); 100 | user.setPassport(passport); 101 | 102 | UserEntity newUser = (UserEntity) session.merge(user); 103 | 104 | transaction.commit(); 105 | session.close(); 106 | 107 | return newUser; 108 | } 109 | 110 | public void updateUser (String name, String lastName, String passport) { 111 | Session session = factory.openSession(); 112 | Transaction transaction = session.beginTransaction(); 113 | 114 | UserEntity user = new UserEntity(); 115 | user.setName(name); 116 | user.setLastName(lastName); 117 | user.setPassport(passport); 118 | 119 | session.update(user); 120 | 121 | transaction.commit(); 122 | session.close(); 123 | 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/PositionJdbcServise.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.levelup.job.list.domain.Position; 4 | 5 | import java.sql.*; 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | 9 | public class PositionJdbcServise implements PositionService { 10 | 11 | @Override 12 | public Position createPosition(String name) throws SQLException { 13 | Connection connection = JdbcUtils.getConnection(); 14 | 15 | PreparedStatement statement = connection.prepareStatement("insert into positions (name) values (?)"); 16 | statement.setString(1, name); 17 | int rowChanged = statement.executeUpdate(); // insert/update/delete 18 | 19 | System.out.println("Колличество добавленных строк: " + rowChanged); 20 | 21 | Statement selectStatement = connection.createStatement(); 22 | ResultSet resultSet = selectStatement.executeQuery("select * from positions where name = '" + name + "'"); //select 23 | 24 | resultSet.next(); 25 | int id = resultSet.getInt(1); 26 | String positionName = resultSet.getString("name"); 27 | System.out.println("Должность: ID = " + id + ", name = " + positionName); 28 | 29 | return new Position(id, positionName); 30 | } 31 | 32 | @Override 33 | public void deletePositionById(int id) throws SQLException { 34 | try(Connection connection = JdbcUtils.getConnection()) { 35 | PreparedStatement statement = connection.prepareStatement("delete from positions where id = ?"); 36 | statement.setInt(1, id); 37 | int rowDeleted = statement.executeUpdate(); 38 | System.out.println("Удалено позиций: " + rowDeleted); 39 | } 40 | } 41 | 42 | @Override 43 | public void deletePositionByName(String name) throws SQLException { 44 | try (Connection connection = JdbcUtils.getConnection()) { 45 | PreparedStatement statement = connection.prepareStatement("delete from positions where name = ?"); 46 | statement.setString(1, name); 47 | int rowDeleted = statement.executeUpdate(); 48 | System.out.println("Удалено позиций: " + rowDeleted); 49 | } 50 | } 51 | 52 | @Override 53 | public Collection findAllPositionWhichNameLike(String name) throws SQLException { 54 | try (Connection connection = JdbcUtils.getConnection()) { 55 | Statement selectStatement = connection.createStatement(); 56 | ResultSet resultSet = selectStatement.executeQuery("select * from positions where name like '" + name + "'"); 57 | return extractPositions(resultSet); 58 | } 59 | } 60 | 61 | @Override 62 | public Collection findPositionById(int id) throws SQLException { 63 | try (Connection connection = JdbcUtils.getConnection()) { 64 | PreparedStatement statement = connection.prepareStatement("select * from positions where id = ?"); 65 | statement.setInt(1, id); 66 | ResultSet resultSet = statement.executeQuery(); 67 | return extractPositions(resultSet); 68 | } 69 | } 70 | 71 | @Override 72 | public Collection findAllPositions() throws SQLException { 73 | try (Connection connection = JdbcUtils.getConnection()) { 74 | PreparedStatement statement = connection.prepareStatement("select * from positions"); 75 | ResultSet resultSet = statement.executeQuery(); 76 | return extractPositions(resultSet); 77 | } 78 | } 79 | 80 | @Override 81 | public Collection findPositionByName(String name) throws SQLException { 82 | try (Connection connection = JdbcUtils.getConnection()) { 83 | PreparedStatement statement = connection.prepareStatement("select * from positions where name = ?"); 84 | statement.setString(1, name); 85 | ResultSet resultSet = statement.executeQuery(); 86 | return extractPositions(resultSet); 87 | } 88 | } 89 | 90 | private Collection extractPositions(ResultSet resultSet) throws SQLException { 91 | Collection positions = new ArrayList<>(); 92 | while (resultSet.next()) { 93 | int id = resultSet.getInt("id"); 94 | String name = resultSet.getString("name"); 95 | positions.add(new Position(id, name)); 96 | } 97 | return positions; 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /src/test/java/org/levelup/application/dao/SessionFactoryStub.java: -------------------------------------------------------------------------------- 1 | package org.levelup.application.dao; 2 | 3 | import org.hibernate.*; 4 | import org.hibernate.boot.spi.SessionFactoryOptions; 5 | import org.hibernate.engine.spi.FilterDefinition; 6 | import org.hibernate.metadata.ClassMetadata; 7 | import org.hibernate.metadata.CollectionMetadata; 8 | import org.hibernate.stat.Statistics; 9 | 10 | import javax.naming.NamingException; 11 | import javax.naming.Reference; 12 | import javax.persistence.EntityGraph; 13 | import javax.persistence.EntityManager; 14 | import javax.persistence.PersistenceUnitUtil; 15 | import javax.persistence.SynchronizationType; 16 | import javax.persistence.criteria.CriteriaBuilder; 17 | import java.sql.Connection; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.Set; 21 | 22 | public class SessionFactoryStub implements SessionFactory { 23 | @Override 24 | public SessionFactoryOptions getSessionFactoryOptions() { 25 | return null; 26 | } 27 | 28 | @Override 29 | public SessionBuilder withOptions() { 30 | return null; 31 | } 32 | 33 | @Override 34 | public Session openSession() throws HibernateException { 35 | return null; 36 | } 37 | 38 | @Override 39 | public Session getCurrentSession() throws HibernateException { 40 | return null; 41 | } 42 | 43 | @Override 44 | public StatelessSessionBuilder withStatelessOptions() { 45 | return null; 46 | } 47 | 48 | @Override 49 | public StatelessSession openStatelessSession() { 50 | return null; 51 | } 52 | 53 | @Override 54 | public StatelessSession openStatelessSession(Connection connection) { 55 | return null; 56 | } 57 | 58 | @Override 59 | public Statistics getStatistics() { 60 | return null; 61 | } 62 | 63 | @Override 64 | public void close() throws HibernateException { 65 | 66 | } 67 | 68 | @Override 69 | public Map getProperties() { 70 | return null; 71 | } 72 | 73 | @Override 74 | public boolean isClosed() { 75 | return false; 76 | } 77 | 78 | @Override 79 | public Cache getCache() { 80 | return null; 81 | } 82 | 83 | @Override 84 | public PersistenceUnitUtil getPersistenceUnitUtil() { 85 | return null; 86 | } 87 | 88 | @Override 89 | public void addNamedQuery(String s, javax.persistence.Query query) { 90 | 91 | } 92 | 93 | @Override 94 | public T unwrap(Class aClass) { 95 | return null; 96 | } 97 | 98 | @Override 99 | public void addNamedEntityGraph(String s, EntityGraph entityGraph) { 100 | 101 | } 102 | 103 | @Override 104 | public Set getDefinedFilterNames() { 105 | return null; 106 | } 107 | 108 | @Override 109 | public FilterDefinition getFilterDefinition(String s) throws HibernateException { 110 | return null; 111 | } 112 | 113 | @Override 114 | public boolean containsFetchProfileDefinition(String s) { 115 | return false; 116 | } 117 | 118 | @Override 119 | public TypeHelper getTypeHelper() { 120 | return null; 121 | } 122 | 123 | @Override 124 | public ClassMetadata getClassMetadata(Class aClass) { 125 | return null; 126 | } 127 | 128 | @Override 129 | public ClassMetadata getClassMetadata(String s) { 130 | return null; 131 | } 132 | 133 | @Override 134 | public CollectionMetadata getCollectionMetadata(String s) { 135 | return null; 136 | } 137 | 138 | @Override 139 | public Map getAllClassMetadata() { 140 | return null; 141 | } 142 | 143 | @Override 144 | public Map getAllCollectionMetadata() { 145 | return null; 146 | } 147 | 148 | @Override 149 | public Reference getReference() throws NamingException { 150 | return null; 151 | } 152 | 153 | @Override 154 | public List> findEntityGraphsByType(Class aClass) { 155 | return null; 156 | } 157 | 158 | @Override 159 | public EntityManager createEntityManager() { 160 | return null; 161 | } 162 | 163 | @Override 164 | public EntityManager createEntityManager(Map map) { 165 | return null; 166 | } 167 | 168 | @Override 169 | public EntityManager createEntityManager(SynchronizationType synchronizationType) { 170 | return null; 171 | } 172 | 173 | @Override 174 | public EntityManager createEntityManager(SynchronizationType synchronizationType, Map map) { 175 | return null; 176 | } 177 | 178 | @Override 179 | public CriteriaBuilder getCriteriaBuilder() { 180 | return null; 181 | } 182 | 183 | @Override 184 | public Metamodel getMetamodel() { 185 | return null; 186 | } 187 | 188 | @Override 189 | public boolean isOpen() { 190 | return false; 191 | } 192 | } 193 | -------------------------------------------------------------------------------- /src/main/java/org/levelup/job/list/jdbc/UserJdbcServise.java: -------------------------------------------------------------------------------- 1 | package org.levelup.job.list.jdbc; 2 | 3 | import org.levelup.job.list.domain.User; 4 | 5 | import java.sql.*; 6 | import java.util.ArrayList; 7 | import java.util.Collection; 8 | 9 | public class UserJdbcServise implements UserService { 10 | 11 | @Override 12 | public User createUser(String name, String lastName, String passport) throws SQLException { 13 | try (Connection connection= JdbcUtils.getConnection()) { 14 | PreparedStatement statement = connection.prepareStatement("insert into users (name, last_name, passport) values (?, ?, ?)"); 15 | statement.setString(1, name); 16 | statement.setString(2, lastName); 17 | statement.setString(3, passport); 18 | int rowChanged = statement.executeUpdate(); 19 | System.out.println("Колличество добавленных строк: " + rowChanged); 20 | 21 | Statement selectStatement = connection.createStatement(); 22 | ResultSet resultSet = selectStatement.executeQuery("select * from users where passport = '" + passport + "'" ); //select 23 | 24 | resultSet.next(); 25 | int id = resultSet.getInt(1); 26 | String userName = resultSet.getString("name"); 27 | String userLastName = resultSet.getString("last_name"); 28 | String userPassport = resultSet.getString("passport"); 29 | 30 | System.out.println("User: ID = " + id + 31 | ", name = " + userName + 32 | ", last name = " + userLastName + 33 | ", passport = " + passport ); 34 | 35 | return new User(id, userName, userLastName, passport); 36 | } 37 | } 38 | 39 | @Override 40 | public Collection findByPassport(String passport) throws SQLException { 41 | try(Connection connection = JdbcUtils.getConnection()) { 42 | PreparedStatement statement = connection.prepareStatement("select * from users where passport = ?"); 43 | statement.setString(1, passport); 44 | ResultSet resultSet = statement.executeQuery(); 45 | return extractUsers(resultSet); 46 | } 47 | } 48 | 49 | @Override 50 | public Collection findByNameAndLastName(String name, String lastName) throws SQLException { 51 | try(Connection connection = JdbcUtils.getConnection()) { 52 | PreparedStatement statement = connection.prepareStatement("select * from users where name = ? and last_name = ?"); 53 | statement.setString(1, name); 54 | statement.setString(2, lastName); 55 | ResultSet resultSet = statement.executeQuery(); 56 | return extractUsers(resultSet); 57 | } 58 | } 59 | 60 | @Override 61 | public Collection findByLastName(String lastName) throws SQLException { 62 | try(Connection connection = JdbcUtils.getConnection()) { 63 | PreparedStatement statement = connection.prepareStatement("select * from users where last_name = ?"); 64 | statement.setString(1, lastName); 65 | ResultSet resultSet = statement.executeQuery(); 66 | return extractUsers(resultSet); 67 | } 68 | } 69 | 70 | @Override 71 | public void deleteUserByPassport(String passport) throws SQLException { 72 | try (Connection connection = JdbcUtils.getConnection()) { 73 | PreparedStatement statement = connection.prepareStatement("delete from userss where passport = ?"); 74 | statement.setString(1, passport); 75 | int rowDeleted = statement.executeUpdate(); 76 | System.out.println("Удалено позиций: " + rowDeleted); 77 | } 78 | 79 | } 80 | 81 | @Override 82 | public User updateUser(String passport, String name, String lastName) throws SQLException { 83 | try (Connection connection= JdbcUtils.getConnection()) { 84 | PreparedStatement statement = connection.prepareStatement("update users set passport = ?, name = ?, last_name = ?"); 85 | statement.setString(1, passport); 86 | statement.setString(2, name); 87 | statement.setString(3, lastName); 88 | 89 | int rowChanged = statement.executeUpdate(); 90 | System.out.println("Колличество обновленных строк: " + rowChanged); 91 | 92 | Statement selectStatement = connection.createStatement(); 93 | ResultSet resultSet = selectStatement.executeQuery("select * from users where passport = ?" ); //select 94 | 95 | resultSet.next(); 96 | int id = resultSet.getInt(1); 97 | String userName = resultSet.getString("name"); 98 | String userLastName = resultSet.getString("last_name"); 99 | String userPassport = resultSet.getString("passport"); 100 | 101 | System.out.println("User: ID = " + id + 102 | ", name = " + userName + 103 | ", last name = " + userLastName + 104 | ", passport = " + passport ); 105 | 106 | return new User(id, userName, userLastName, passport); 107 | } 108 | } 109 | 110 | private Collection extractUsers(ResultSet resultSet) throws SQLException { 111 | Collection users = new ArrayList<>(); 112 | while (resultSet.next()) { 113 | int id = resultSet.getInt("id"); 114 | String userName = resultSet.getString("name"); 115 | String userLastName = resultSet.getString("last_name"); 116 | String userPassport = resultSet.getString("passport"); 117 | users.add(new User(id, userName, userLastName, userPassport)); 118 | } 119 | return users; 120 | } 121 | } 122 | --------------------------------------------------------------------------------