file_id
int64 1
180k
| content
stringlengths 13
357k
| repo
stringlengths 6
109
| path
stringlengths 6
1.15k
|
---|---|---|---|
180,277 | package java26.zad1.zad1.WypozyczalniaWodna;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Wypozyczalnia {
public Map<String, SprzetInfo> sprzetWypozyczony = new HashMap<>();
void wypozyczenie(String numerBurtwy, Sprzet rodzajSprzetu) {
SprzetInfo si = new SprzetInfo(numerBurtwy, rodzajSprzetu, LocalDateTime.now());
sprzetWypozyczony.put(numerBurtwy, si);
System.out.println("Rozpoczęto wypożyczanie "+ rodzajSprzetu);
}
SprzetInfo znajdzSprzet(String numerBurtowy) throws NieMaTakiegoSprzetuException {
if (sprzetWypozyczony.containsKey(numerBurtowy)){
System.out.println("Sprzęt "+sprzetWypozyczony.get(numerBurtowy)+"jest wypożyczony ");
return sprzetWypozyczony.get(numerBurtowy);
}throw new NieMaTakiegoSprzetuException();
}
Double zakonczenieWypozyczenia(String numerBurtowy) throws NieMaTakiegoSprzetuException {
//jeśli nie ma
if (!sprzetWypozyczony.containsKey(numerBurtowy)){
throw new NieMaTakiegoSprzetuException();
}
//jeśli jednak jest..
SprzetInfo sprzetInfo = sprzetWypozyczony.get(numerBurtowy);
Duration czasWypozyczenia = Duration.between(sprzetInfo.getGodzWypozyczenia(), LocalDateTime.now() );
double naleznosc =0.0;
switch (sprzetInfo.getSprzet()){
case BOAT:
naleznosc = czasWypozyczenia.getSeconds()*1;
System.out.println(naleznosc);
break;
case JACHT:
naleznosc=czasWypozyczenia.getSeconds()*2;
System.out.println(naleznosc);
break;
case KAJAK:
naleznosc = czasWypozyczenia.getSeconds()*0.5;
System.out.println(naleznosc);
break;
}
sprzetWypozyczony.remove(numerBurtowy);
System.out.println("Sprzęt: "+sprzetInfo+"został oddany. Czas wypożycznia: "+czasWypozyczenia);
return naleznosc;
}
public static void main(String[] args) throws NieMaTakiegoSprzetuException {
Wypozyczalnia wypozyczalnia = new Wypozyczalnia();
wypozyczalnia.wypozyczenie("123", Sprzet.BOAT);
wypozyczalnia.znajdzSprzet("123");
wypozyczalnia.zakonczenieWypozyczenia("123");
}
}
| MattWroclaw/collections_exc2 | src/main/java/java26/zad1/zad1/WypozyczalniaWodna/Wypozyczalnia.java |
180,278 | package gui;
import logic.Database;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Budzet extends JFrame{
private JComboBox rodzajCombo;
private JButton powrotButton;
private JPanel panel1;
private JScrollPane tabelaScrollPane;
private JLabel text;
private JPanel panel2;
public Budzet() {
setContentPane(panel2);
setTitle("Budżet");
setSize(600, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
Database base = new Database();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
tabelaScrollPane.setViewportView(textArea);
rodzajCombo.addItem("");
rodzajCombo.addItem("Treningi");
rodzajCombo.addItem("Ćwiczenia");
rodzajCombo.addItem("Trenerzy");
rodzajCombo.addItem("Fizjoterapeuci");
rodzajCombo.addItem("Sale");
rodzajCombo.addItem("Sprzęt");
powrotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new StronaStartowa();
dispose();
}
});
rodzajCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Connection connection = base.connect();
String wypis =new String("");
switch (rodzajCombo.getSelectedItem().toString()){
case("Treningi"):
wypis="Tygodniowe wydatki na treningi\n";
try{
PreparedStatement TreningKoszt = connection.prepareStatement("Select SUM(koszt_sali) as koszt_sali,SUM(koszt_sprzetu) as koszt_sprzetu, SUM(zarobki_za_trening) as koszt_trenerow from widok_treningu");
ResultSet TreningKosztRs = TreningKoszt.executeQuery();
TreningKosztRs.next();
wypis+="Tygodniowe wydatki na sprzęt: "+ TreningKosztRs.getString("koszt_sprzetu") +"\nTygodniowe wydatki na sale: " + TreningKosztRs.getString("koszt_sali")+"\nTygodniowe wydatki na pensje trenerów: "+ TreningKosztRs.getString("koszt_trenerow")+"\n";
}catch (SQLException ex){
throw new RuntimeException(ex);
}
try{
PreparedStatement lacznyKoszt = connection.prepareStatement("SELECT * from widok_wydatki_tygodniowe_treningi");
ResultSet lacznyKosztRs = lacznyKoszt.executeQuery();
wypis+= "=================\nŁączne wydatki na treningi:\n";
while(lacznyKosztRs.next()){
wypis+= lacznyKosztRs.getString("koszt_tygodniowy_treningow") +"\n";
}
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
case("Ćwiczenia"):
wypis="Tygodniowe wydatki na ćwiczenia fizjoterapeutyczne\n";
try{
PreparedStatement kosztCwiczen = connection.prepareStatement("SELECT SUM(zarobki_za_trening) as zarobki_za_trening from widok_cwiczenia_fizjoterapeuta");
ResultSet kosztCwiczenRs = kosztCwiczen.executeQuery();
kosztCwiczenRs.next();
wypis += kosztCwiczenRs.getString("zarobki_za_trening");
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
case("Trenerzy"):
wypis = "Tygodniowe wydatki na Trenerów\n";
try{
PreparedStatement wydatkiNaTrenerow = connection.prepareStatement("select * from widok_wydatki_tygodniowe_trenerzy");
ResultSet wydatkiNaTrenerowRs = wydatkiNaTrenerow.executeQuery();
while(wydatkiNaTrenerowRs.next()){
wypis+= wydatkiNaTrenerowRs.getString("trener_imie_nazwisko")+" (treningów: "+ wydatkiNaTrenerowRs.getString("liczba_treningow") + "), tygodniowe zarobki: "+ wydatkiNaTrenerowRs.getString("koszt_tygodniowy")+"\n";
}
}catch (SQLException ex){
throw new RuntimeException(ex);
}
try{
PreparedStatement laczneZarobki = connection.prepareStatement("SELECT SUM(zarobki_za_trening) as koszt_trenerow from widok_treningu");
ResultSet laczneZarobkiRs = laczneZarobki.executeQuery();
laczneZarobkiRs.next();
wypis+= "=================\nŁączne zarobki trenerów: "+ laczneZarobkiRs.getString("koszt_trenerow");
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
case ("Sale"):
wypis = "Tygodniowe wydatki na Sale\n";
try{
PreparedStatement wydatkiNaSale = connection.prepareStatement("select * from widok_wydatki_tygodniowe_sala");
ResultSet wydatkiNaSaleRs = wydatkiNaSale.executeQuery();
while(wydatkiNaSaleRs.next()){
wypis+= wydatkiNaSaleRs.getString("nazwa_sali")+" (wynajęć: "+ wydatkiNaSaleRs.getString("liczba_wynajec") + "), koszt tygodniowy: "+ wydatkiNaSaleRs.getString("koszt_tygodniowy")+"\n";
}
}catch (SQLException ex){
throw new RuntimeException(ex);
}
try{
PreparedStatement lacznyKosztSali = connection.prepareStatement("SELECT SUM(koszt_sali) as koszt_sali from widok_treningu");
ResultSet lacznyKosztSaliRs = lacznyKosztSali.executeQuery();
lacznyKosztSaliRs.next();
wypis+= "=================\nŁączne wydatki na sale: "+ lacznyKosztSaliRs.getString("koszt_sali");
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
case ("Sprzęt"):
wypis = "Tygodniowe wydatki na Sprzet\n";
try{
PreparedStatement wydatkiNaSprzet = connection.prepareStatement("select * from widok_wydatki_tygodniowe_sprzet");
ResultSet wydatkiNaSprzetRs = wydatkiNaSprzet.executeQuery();
while(wydatkiNaSprzetRs.next()){
wypis+= wydatkiNaSprzetRs.getString("nazwa_sprzetu")+" (wynajęć: "+ wydatkiNaSprzetRs.getString("liczba_wypozyczen") + "), koszt tygodniowy: "+ wydatkiNaSprzetRs.getString("koszt_tygodniowy")+"\n";
}
}catch (SQLException ex){
throw new RuntimeException(ex);
}
try{
PreparedStatement lacznyKosztSprzetu = connection.prepareStatement("SELECT SUM(koszt_sprzetu) as koszt_sprzetu from widok_treningu");
ResultSet lacznyKosztSprzetuRs = lacznyKosztSprzetu.executeQuery();
lacznyKosztSprzetuRs.next();
wypis+= "=================\nŁączne wydatki na sprzęt: "+ lacznyKosztSprzetuRs.getString("koszt_sprzetu");
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
case("Fizjoterapeuci"):
wypis = "Tygodniowe wydatki na fizjoterapeutów\n";
try{
PreparedStatement wydatkiNaFizjoterapeutow = connection.prepareStatement("select * from widok_wydatki_tygodniowe_fizjoterapeuta");
ResultSet wydatkiNaFizjoterapeutowRs = wydatkiNaFizjoterapeutow.executeQuery();
while(wydatkiNaFizjoterapeutowRs.next()){
wypis+= wydatkiNaFizjoterapeutowRs.getString("fizjoterapeuta_imie_nazwisko")+" (zajęć: "+ wydatkiNaFizjoterapeutowRs.getString("liczba_zajec_fizjoterapeutycznych") + "), tygodniowe zarobki: "+ wydatkiNaFizjoterapeutowRs.getString("koszt_tygodniowy")+"\n";
}
}catch (SQLException ex){
throw new RuntimeException(ex);
}
try{
PreparedStatement laczneZarobkiFizjo = connection.prepareStatement("SELECT SUM(zarobki_za_trening) as koszt_fizjoterapeutow from widok_cwiczenia_fizjoterapeuta");
ResultSet laczneZarobkiFizjoRs = laczneZarobkiFizjo.executeQuery();
laczneZarobkiFizjoRs.next();
wypis+= "=================\nŁączne zarobki fizjoterapeutów: "+ laczneZarobkiFizjoRs.getString("koszt_fizjoterapeutow");
}catch (SQLException ex){
throw new RuntimeException(ex);
}
textArea.setText(wypis);
break;
default:
break;
}
base.closeConnection(connection);
}
});
}
}
| ZEN4est/Projects-from-studies | Java + SQL/Java+SQL Project/Projekt/src/main/java/gui/Budzet.java |
180,283 | package pl.polsl.pl.java.serial.terminal.main;
import java.nio.charset.StandardCharsets;
import java.util.Timer;
import java.util.TimerTask;
import jssc.SerialPort;
import jssc.SerialPortException;
import jssc.SerialPortList;
import pl.polsl.pl.java.serial.terminal.model.CustomSerialPortEventListener;
import pl.polsl.pl.java.serial.terminal.view.MainWindow;
/**
* The most important class in the app, controls all logic.
* Share connection parametrs for the GUI, handle sending request,
* setting up serial connection and testing it.
*
* @author Michał Lytek
*/
public class Controler {
/** Instance of GUI class */
private MainWindow view;
/** Instance of serial port */
private SerialPort serialPort;
/** Ping start time */
private long start_time;
/** Ping duration time */
private int pingResult;
/* All variables stores connection parameters */
private String terminatorToShow,
terminatorToInsert;
private int baudRate,
signBits,
stopBits,
parity,
flowControlMask;
private String signFormat;
private String serialPortName;
/**
* Creates the controler, initates the GUI and ping test fields.
*/
public Controler() {
this.view = new MainWindow(this);
// prevent field be a nullpointer
this.start_time = System.nanoTime();
this.pingResult = -1;
}
/**
* Setting up a serial port connection parameters
* - just store received values in configuration fields.
*
* @param portName the system name of selected serial port
* @param portSpeed the port baudrate
* @param signBits the number of bits for each sign - 7 or 8
* @param parityControl the parity control setting - index of combobox
* @param stopBits the bumber of stop bits - 1 or 2
* @param flowControl the flow control setting - index of combobox
* @param terminator the terminator setting or apporopiate terminator
*/
public void setupSerialPort(String portName, int portSpeed, int signBits, int parityControl, int stopBits, int flowControl, String terminator) {
this.serialPortName = portName;
this.baudRate = portSpeed;
this.signBits = signBits;
this.stopBits = stopBits;
this.terminatorToShow = terminator;
// parse sign setting to text representation
this.signFormat = Integer.toString(signBits);
switch (parityControl) {
case 0:
this.parity = SerialPort.PARITY_NONE;
this.signFormat += "N";
break;
case 1:
this.parity = SerialPort.PARITY_EVEN;
this.signFormat += "E";
break;
case 2:
this.parity = SerialPort.PARITY_ODD;
this.signFormat += "O";
break;
default:
this.parity = SerialPort.PARITY_NONE;
}
this.signFormat += Integer.toString(stopBits);
// parse flow control settings to the serial port mask
switch (flowControl) {
case 0:
this.flowControlMask = SerialPort.FLOWCONTROL_NONE;
break;
case 1:
this.flowControlMask = SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT;
break;
case 2:
this.flowControlMask = SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT;
break;
default:
this.flowControlMask = SerialPort.FLOWCONTROL_NONE;
}
// parse terminator settings to appropriate format
switch (terminator) {
case "Brak":
this.terminatorToInsert = "";
break;
case "CR":
this.terminatorToInsert = "\r";
break;
case "LF":
this.terminatorToInsert = "\n";
break;
case "CR-LF":
this.terminatorToInsert = "\r\n";
break;
default:
this.terminatorToInsert = terminator;
break;
}
view.showConnectionParameters();
}
/**
* Perform connection to the port using earlier defined parameters.
*
* @return true if connected succesfuly, false if error occured
*/
public boolean connectToPort() {
try {
this.serialPort = new SerialPort(this.serialPortName);
this.serialPort.openPort();
this.serialPort.setParams(this.baudRate, this.signBits, this.stopBits, this.parity);
this.serialPort.setFlowControlMode(this.flowControlMask);
this.serialPort.addEventListener(new CustomSerialPortEventListener(serialPort, terminatorToInsert, this));
} catch (SerialPortException ex) {
System.err.println(ex);
return false;
}
return true;
}
/**
* Disconnect from an earlier connected port.
*
* @return true if disconected, false if error occured
*/
public boolean disconnectFromPort() {
try {
this.serialPort.closePort();
} catch (SerialPortException ex) {
System.err.println(ex);
return false;
}
return true;
}
/**
* Perform ping test of serial connection.
* Send ENQ sign, set start time and wait 5s timeout for receive ACK.
*/
public void testConnection() {
try {
// this.sendText("*PING");
serialPort.writeByte((byte) 5); //ENQ
this.start_time = System.nanoTime();
this.pingResult = -1;
Timer timeoutTimer = new Timer();
timeoutTimer.schedule(new TimerTask() {
@Override
public void run() {
if (Controler.this.pingResult == -1) {
view.showConnectionTestResults(false, 0);
}
}
}, 5000);
} catch (SerialPortException ex) {
System.err.println(ex);
}
}
/**
* Handle receiving ping response request.
* Calculate time difference and send it to GUI.
*/
public void receivedPingResponse() {
long end_time = System.nanoTime();
Double difference = (end_time - start_time)/1e6;
this.pingResult = difference.intValue();
view.showConnectionTestResults(true, pingResult);
}
/**
* Split received text to lines and send each one by serial interface,
* adding terminator to the end of all command.
*
* @param text string to send through serial connection
*
* @return true if was sended ok, false if an error occured
*/
public boolean sendText(String text) {
String[] commandLines = text.split(System.getProperty("line.separator"));
for (String command : commandLines) {
String textToSend = command + terminatorToInsert;
try {
byte[] sendedChars = textToSend.getBytes(StandardCharsets.US_ASCII);
serialPort.writeBytes(sendedChars);
} catch (SerialPortException ex) {
System.err.println(ex);
return false;
}
}
return true;
}
/**
* Wraps model request - call GUI method to show text in the field.
*
* @param chars string to be showed in single line
*/
public void receivedNewChars(String chars) {
view.insertReceivedText(chars, false);
}
/**
* Wraps model request - call GUI method to show text in the field.
*
* @param line string to be showed in new line
*/
public void receivedNewLine(String line) {
view.insertReceivedText(line, true);
}
/*
Getters to serial port informations.
*/
/**
* List all avaiables serial port names in system.
* @return the array of serial port names
*/
public String[] getAvaiablePortsNames() {
return SerialPortList.getPortNames();
}
/**
* Getter to the connected port system name.
* @return the port name
*/
public String getConnectedPortName() {
return this.serialPortName;
}
/**
* Convert setted up port speed (baudrate) to string representation.
* @return the connected port speed
*/
public String getConnectedPortSpeed() {
return Integer.toString(this.baudRate);
}
/**
* Getter to the sign format setting.
* @return the sign format setting
*/
public String getConnectedPortSignFormat() {
return this.signFormat;
}
/**
* Convert setted up flow control mask to string representation.
* @return the current flow control setting
*/
public String getConnectedPortFlowControl() {
switch (this.flowControlMask) {
case SerialPort.FLOWCONTROL_NONE:
return "brak";
case SerialPort.FLOWCONTROL_RTSCTS_IN | SerialPort.FLOWCONTROL_RTSCTS_OUT:
return "sprzętowa";
case SerialPort.FLOWCONTROL_XONXOFF_IN | SerialPort.FLOWCONTROL_XONXOFF_OUT:
return "programowa";
default:
return "";
}
}
/**
* Getter to the setted up terminator string.
* @return the terminator string
*/
public String getConnectedPortTerminator() {
return this.terminatorToShow;
}
}
| MichalLytek/Java-Serial-Terminal | src/pl/polsl/pl/java/serial/terminal/main/Controler.java |
180,286 | package kungfu.Views;
import java.util.*;
import kungfu.Controller;
import kungfu.Classes.*;
import javax.swing.table.AbstractTableModel;
import org.hibernate.Session;
public class RentalMemberTable extends AbstractTableModel{
private List<Rental> memRentals = new ArrayList<>();
public RentalMemberTable(Member m) {
this.memRentals =m.getMemberRentals();
}
@Override
public int getColumnCount() {
return 6;
}
@Override
public int getRowCount() {
return memRentals.size();
}
@Override
public String getColumnName(int colNr) {
if(colNr == 0) return "Nazwa sprzętu";
if(colNr ==1) return "Nr seryjny";
if(colNr ==2 ) return "Min. stopień wyp.";
if(colNr ==3 ) return "Właściciel";
if(colNr ==4) return "Data wypożyczenia";
if(colNr==5) return "Data zwrotu";
return "";
}
@Override
public Object getValueAt(int rowNr, int colNr) {
Rental rental = memRentals.get(rowNr);
if(colNr == 0) return rental.getEqSportive().getName();
if(colNr == 1) return rental.getEqSportive().getSerialNumber().toString();
if(colNr == 2) return rental.getEqSportive().getMinGrade().toString();
if(colNr == 3) return rental.getEqSportive().getSchool().toString();
if(colNr == 4) return rental.getRentDay().toString();
if(colNr == 5) {
if(rental.getReturnDay() != null) return rental.getReturnDay().toString();
else return "Wciąż w wypożyczeniu";
}
return null;
}
public List<Rental> getRentals(){
return this.memRentals;
}
}
| magdazelena/KungFuSchoolApp | src/kungfu/Views/RentalMemberTable.java |
180,292 | package pl.medos.cmmsApi.service.impl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import pl.medos.cmmsApi.exception.HardwareNotFoundException;
import pl.medos.cmmsApi.model.Hardware;
import pl.medos.cmmsApi.repository.HardwareRepository;
import pl.medos.cmmsApi.repository.entity.HardwareEntity;
import pl.medos.cmmsApi.service.HardwareService;
import pl.medos.cmmsApi.service.mapper.HardwareMapper;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.logging.Logger;
@Service
@Slf4j
public class HardwareServiceImpl implements HardwareService {
private final HardwareRepository hardwareRepository;
private final HardwareMapper hardwareMapper;
public HardwareServiceImpl(HardwareRepository hardwareRepository, HardwareMapper hardwareMapper) {
this.hardwareRepository = hardwareRepository;
this.hardwareMapper = hardwareMapper;
}
public List<Hardware> listAll() {
log.debug("listAll()");
List<HardwareEntity> hardwareEntities = hardwareRepository.findAll();
List<Hardware> hardwares = hardwareMapper.litsEntityToModels(hardwareEntities);
log.debug("listAll(...)");
return hardwares;
}
public Page<Hardware> pagesHardware(int pageNo, int size, String sortField, String sortDirection) {
log.debug("pagesHardware()");
Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.DESC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
Pageable pageable = PageRequest.of(pageNo - 1, size, sort);
Page<HardwareEntity> hardwareEntities = hardwareRepository.findAll(pageable);
Page<Hardware> hardwares = hardwareMapper.pageEntityToModels(hardwareEntities);
log.debug("pagesHardware(...)");
return hardwares;
}
@Override
public List<Hardware> findAllSorted(String direction, String field) {
log.debug("findAllSorted()");
Sort sort = direction.equalsIgnoreCase(Sort.Direction.DESC.name()) ? Sort.by(field).ascending() : Sort.by(field).descending();
List<HardwareEntity> hardwareEntities = hardwareRepository.findAll(sort);
List<Hardware> hardwares = hardwareMapper.litsEntityToModels(hardwareEntities);
log.debug("findAllSorted(...)");
return hardwares;
}
@Override
public Hardware create(Hardware hardware) {
log.debug("createHardware() " + hardware.getId());
String inventoryNo = hardware.getInventoryNo().toUpperCase();
hardware.setInventoryNo(inventoryNo);
HardwareEntity hardwareEntity = hardwareMapper.mapModelToEntity(hardware);
HardwareEntity saveHardwareEntity = hardwareRepository.save(hardwareEntity);
Hardware savedHardware = hardwareMapper.mapEntityToModel(saveHardwareEntity);
log.debug("createHardware(...)" + savedHardware);
return savedHardware;
}
@Override
public Hardware read(Long id) throws HardwareNotFoundException {
log.debug("readHardware(" + id + ")");
Optional<HardwareEntity> optionalHardwareEntity = hardwareRepository.findById(id);
HardwareEntity hardwareEntity = optionalHardwareEntity.orElseThrow(
() -> new HardwareNotFoundException("Nie odnaleziono sprzętu o podanym id.")
);
Hardware hardware = hardwareMapper.mapEntityToModel(hardwareEntity);
log.debug("readHardware(...) " + hardware);
return hardware;
}
@Override
public Hardware update(Hardware hardware) throws HardwareNotFoundException {
log.debug("mapUpdateHardware()" + hardware.getId());
HardwareEntity hardwareEntity = hardwareMapper.mapModelToEntity(hardware);
hardwareEntity.setId(hardware.getId());
HardwareEntity saveHardwareEntity = hardwareRepository.save(hardwareEntity);
Hardware savedHardware = hardwareMapper.mapEntityToModel(saveHardwareEntity);
log.debug("mapUpdateHardware(...)" + savedHardware);
return savedHardware;
}
@Override
public void delete(Long id) {
log.debug("deleteHardware(" + id + ")");
hardwareRepository.deleteById(id);
log.debug("deleteHardware(...)");
}
@Override
public void deleteAll() {
log.debug("deleteAllHardware()");
hardwareRepository.deleteAll();
log.debug("deleteAllHardware(...)");
}
@Override
public List<Hardware> findByIpAddress(String ipAddres) {
log.debug("findByIpAddress");
Optional<List<HardwareEntity>> byIpAddress = hardwareRepository.findByIpAddress(ipAddres);
if (byIpAddress.isPresent()) {
List<HardwareEntity> hardwareEntities = byIpAddress.get();
return hardwareMapper.litsEntityToModels(hardwareEntities);
} else {
return new ArrayList<>();
}
}
@Override
public Page<Hardware> findHardwarePageByQuery(int pageNo, int pageSize, String sortField, String sortDir, String query) {
log.debug("findHardwarePageByQuery()");
Sort sort = sortDir.equalsIgnoreCase(Sort.Direction.DESC.name()) ? Sort.by(sortField).ascending() : Sort.by(sortField).descending();
Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
Page<HardwareEntity> hardwareEntityPage = hardwareRepository.findByQueryPagable(query, pageable);
Page<Hardware> hardware = hardwareMapper.pageEntityToModels(hardwareEntityPage);
log.debug("findHardwarePageByQuery(...)");
return hardware;
}
}
| WoelkeK/cmmsAPI | src/main/java/pl/medos/cmmsApi/service/impl/HardwareServiceImpl.java |
180,296 | package com.example.datagenerator.jpa.generator.generators;
import com.example.datagenerator.jpa.entity.AdditionalRooms;
import com.example.datagenerator.jpa.entity.AdditionalRoomType;
import com.example.datagenerator.jpa.generator.GeneratorHelper;
import com.example.datagenerator.jpa.repository.AdditionalRoomsRepository;
import com.example.datagenerator.jpa.repository.AdditionalRoomTypeRepository;
import com.example.datagenerator.jpa.repository.UserRepository;
import com.github.javafaker.Faker;
import java.util.List;
public class AdditionalRoomsGenerator extends GeneratorHelper {
private final AdditionalRoomsRepository additionalRoomsRepository;
private final List<AdditionalRoomType> additionalRoomTypes;
private final List<String> descriptions = List.of(
"Kuchnia wyposażona w sztućce, kubki i talerze oraz czajnik",
"Sala kominkowa do spotkań i relaksu",
"Sala fitness z nowoczesnym sprzętem do ćwiczeń",
"Sala konferencyjna z miejscami siedzącymi dla 50 osób",
"Sala gier z bilardem, ping-pongiem i grami planszowymi",
"Pracownia komputerowa z dostępem do internetu",
"Biblioteka z bogatym zbiorem książek i czasopism",
"Pralnia samoobsługowa z pralkami i suszarkami",
"Pomieszczenie do przechowywania rowerów",
"Kawiarnia z kawą i przekąskami dla mieszkańców"
);
public AdditionalRoomsGenerator(Faker faker, UserRepository userRepository, AdditionalRoomsRepository additionalRoomsRepository, AdditionalRoomTypeRepository additionalRoomTypeRepository) {
super(faker, userRepository);
this.additionalRoomsRepository = additionalRoomsRepository;
additionalRoomTypes = additionalRoomTypeRepository.findAll();
}
public void generateAdditionalRooms(int numberOfAdditionalRooms) {
if(additionalRoomTypes.isEmpty()) {
return;
}
for (int i = 0; i < numberOfAdditionalRooms; i++) {
AdditionalRooms additionalRooms = AdditionalRooms.builder()
.roomNumber(faker.number().numberBetween(1, 110))
.description(descriptions.get(faker.number().numberBetween(0, descriptions.size())))
.additionalRoomType(getRandomAdditionalRoomType())
.build();
additionalRoomsRepository.save(additionalRooms);
}
}
private AdditionalRoomType getRandomAdditionalRoomType() {
return additionalRoomTypes.get(faker.number().numberBetween(0, additionalRoomTypes.size()));
}
}
| Gawron97/dataGenerator | src/main/java/com/example/datagenerator/jpa/generator/generators/AdditionalRoomsGenerator.java |
180,297 | package com.example.aplikacjatreningowa;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.net.Uri;
import android.os.Bundle;
import android.Manifest;
import android.provider.Settings;
import android.widget.SearchView;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.karumi.dexter.Dexter;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionDeniedResponse;
import com.karumi.dexter.listener.PermissionGrantedResponse;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.single.PermissionListener;
import java.io.IOException;
import java.util.List;
public class Mapa extends AppCompatActivity implements OnMapReadyCallback {
boolean isPermissionGranted; // zmienna typu bool, która będzie sprawdzać czy uzyskano dostęp
GoogleMap mGoogleMap; // obiekt klasy GoogleMap
SearchView searchview; // obiekt klasy SearchView
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
// implementacja funkcji sprawdzającej dostęp
checkMyPermission();
// funkcja if sprawdza czy uzyskano dostęp
if(isPermissionGranted)
{
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
supportMapFragment.getMapAsync(this);
}
// implementacja paska wyszukiwania
searchview = findViewById(R.id.map_search_view);
searchview.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
String location = searchview.getQuery().toString();
List<Address> addressList = null;
// jeśli nie podano lokalizacji to geokodowanie oblicza aktualną lokalizację
if (location != null || location.equals(""))
{
Geocoder geocoder = new Geocoder(Mapa.this);
try {
addressList = geocoder.getFromLocationName(location, 1);
} catch (IOException e)
{
e.printStackTrace();
}
//pobieranie współrzędnych geograficznych
Address address = addressList.get(0);
LatLng latLng = new LatLng(address.getLatitude(), address.getLongitude());
// ustawienie znacznika lokalizacji
mGoogleMap.addMarker(new MarkerOptions().position(latLng).title(location));
// poruszanie kamerą
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 10));
}
return false;
}
// wywołanie zwrotne dotyczące zmian w tekście zapytania
@Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
}
// sprawdzenie dostępu
private void checkMyPermission()
{
Dexter.withContext(this).withPermission(Manifest.permission.ACCESS_FINE_LOCATION).withListener(new PermissionListener()
{
//fragment klasy wywołuje się gdy otrzyma dostęp
@Override
public void onPermissionGranted(PermissionGrantedResponse permissionGrantedResponse)
{
Toast.makeText(Mapa.this, "Uzyskano dostęp", Toast.LENGTH_SHORT).show();
isPermissionGranted = true;
}
//fragment klasy wywołuje się gdy nie otrzyma dostępu
@Override
public void onPermissionDenied(PermissionDeniedResponse permissionDeniedResponse)
{
Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(),"");
intent.setData(uri);
startActivity(intent);
}
//fragment klasy pokazuje interfejs użytkownika z uzasadnieniem
@Override
public void onPermissionRationaleShouldBeShown(PermissionRequest permissionRequest, PermissionToken permissionToken)
{
permissionToken.continuePermissionRequest();
}
}).check();
}
@SuppressLint("MissingPermission")
// fragment klasy onMapReady wykrywający lokalizację sprzętu
@Override
public void onMapReady(GoogleMap googleMap)
{
mGoogleMap = googleMap;
mGoogleMap.setMyLocationEnabled(true);
}
} | Rolfer150/reposprojekt | app/src/main/java/com/example/aplikacjatreningowa/Mapa.java |
180,300 | package org.polsl.backend.controller;
import org.polsl.backend.dto.ApiBasicResponse;
import org.polsl.backend.dto.PaginatedResult;
import org.polsl.backend.dto.hardware.HardwareDTO;
import org.polsl.backend.dto.hardware.HardwareListOutputDTO;
import org.polsl.backend.entity.Hardware;
import org.polsl.backend.service.HardwareService;
import org.polsl.backend.service.export.ExportService;
import org.polsl.backend.specification.HardwareSpecification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
import static org.polsl.backend.service.filtering.SearchService.getSpecification;
/**
* Kontroler odpowiedzialny za zarządzanie hardware'm.
*/
@RestController
@RequestMapping("api/hardware")
public class HardwareController {
private final HardwareService hardwareService;
private final ExportService exportService;
@Autowired
public HardwareController(HardwareService hardwareService, ExportService exportService) {
this.hardwareService = hardwareService;
this.exportService = exportService;
}
/**
* Endpoint obsługujący uzyskiwanie listy wszystkich nieusuniętych hardware'ów
*
* @param searchQuery kryteria wyszukiwania
* @param searchType typ wyszukiwania
* @param withHistory informacja o tym, czy należy wyświetlić również usunięte rekordy
* @return lista hardware'ów
*/
@GetMapping
public ResponseEntity<?> getHardwareList(
@RequestParam(value = "search", required = false) String searchQuery,
@RequestParam(value = "search-type", required = false) String searchType,
@RequestParam(name = "with-history", required = false, defaultValue = "false") boolean withHistory
) {
Specification<Hardware> specification = getSpecification(searchQuery, searchType, HardwareSpecification.class);
return ResponseEntity.ok(hardwareService.getHardwareList(specification, withHistory));
}
/**
* Endpoint obsługujący uzyskiwanie hardware'u o danym id.
*
* @param id ID wybranego sprzętu
* @return hardware o danym id
*/
@GetMapping("/{id}")
public ResponseEntity<?> getHardware(@PathVariable(value = "id") Long id) {
return ResponseEntity.ok(hardwareService.getOneHardware(id));
}
/**
* Endpoint obsługujący uzyskiwanie historii przynależności hardware'u o danym id.
*
* @param id ID wybranego sprzętu
* @return historia przynależności hardware'u o danym id
*/
@GetMapping("/{id}/affiliations-history")
public ResponseEntity<?> getHardwareAffiliationsHistoryList(@PathVariable(value = "id") Long id) {
return ResponseEntity.ok(hardwareService.getHardwareAffiliationsHistory(id));
}
/**
* Endpoint obsługujący uzyskiwanie historii powiązań hardware'u o danym id z zestawami komputerowymi.
*
* @param id ID wybranego sprzętu
* @return historia powiązań hardware'u o danym id z zestawami komputerowymi
*/
@GetMapping("/{id}/computer-sets-history")
public ResponseEntity<?> getHardwareComputerSetsHistoryList(@PathVariable(value = "id") Long id) {
return ResponseEntity.ok(hardwareService.getHardwareComputerSetsHistory(id));
}
/**
* Endpoint obsługujący uzyskiwanie pliku pdf z listą sprzętu.
*
* @return plik pdf z listą rekordów
*/
@GetMapping("/export")
public ResponseEntity<?> printListToPdf() {
PaginatedResult<HardwareListOutputDTO> data = hardwareService.getHardwareList(null, false);
InputStreamResource inputStreamResource = exportService.export("Sprzęty", data.getItems());
return ResponseEntity.ok()
.contentType(MediaType.APPLICATION_PDF)
.body(inputStreamResource);
}
/**
* Endpoint obsługujący dodawanie nowego sprzętu.
*
* @param request stuktura {@link HardwareDTO} zawierająca dane nowego sprzętu
* @return informacja o poprawnym utworzeniu sprzętu
*/
@PostMapping
public ResponseEntity<?> createHardware(@Valid @RequestBody HardwareDTO request) {
hardwareService.createHardware(request);
return ResponseEntity.ok(new ApiBasicResponse(true, "Utworzono sprzęt"));
}
/**
* Endpoint obsługujący edycję parametrów przynależności.
*
* @param request stuktura {@link HardwareDTO} zawierająca nowe dane sprzętu
* @return informacja o poprawnym zaktualizowaniu parametrów sprzętu
*/
@PutMapping("/{id}")
public ResponseEntity<?> editAffiliation(
@PathVariable(value = "id") Long id,
@Valid @RequestBody HardwareDTO request
) {
hardwareService.editHardware(id, request);
return ResponseEntity.ok(new ApiBasicResponse(true, "Zaktualizowano parametry sprzętu"));
}
/**
* Endpoint obsługujący usuwanie sprzętu.
*
* @param id ID wybranego sprzętu
* @return informacja o poprawnym usunięciu sprzętu
*/
@DeleteMapping("/{id}")
public ResponseEntity<?> deleteHardware(@PathVariable(value = "id") Long id) {
hardwareService.deleteHardware(id);
return ResponseEntity.ok(new ApiBasicResponse(true, "Usunięto sprzęt"));
}
}
| Samograje/co-gdzie-kiedy | backend/src/main/java/org/polsl/backend/controller/HardwareController.java |
180,301 | package com.example.aplikacjatreningowa;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.json.JSONObject;
import cz.msebera.android.httpclient.Header;
public class Pogoda extends AppCompatActivity {
// kod api aplikacji
final String APP_ID = "e2c5964a00a2516538af244af5f37723";
// kod api pogody ze strony openweathermap
final String WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather";
final long MIN_TIME = 5000;
final float MIN_DISTANCE = 1000;
final int REQUEST_CODE = 101;
String Location_Provider = LocationManager.GPS_PROVIDER;
TextView NameofCity, weatherState, Temperature;
ImageView mweatherIcon;
RelativeLayout mCityFinder;
LocationManager mLocationManager;
LocationListener mLocationListner;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pogoda);
weatherState = findViewById(R.id.weatherCondition);
Temperature = findViewById(R.id.temperature);
mweatherIcon = findViewById(R.id.weatherIcon);
mCityFinder = findViewById(R.id.cityFinder);
NameofCity = findViewById(R.id.cityName);
mCityFinder.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Pogoda.this, cityFinder.class);
startActivity(intent);
}
});
}
@Override
protected void onResume() {
super.onResume();
Intent mIntent=getIntent();
String city= mIntent.getStringExtra("City");
if(city!=null)
{
getWeatherForNewCity(city);
}
else
{
getWeatherForCurrentLocation();
}
}
// wprowadzanie nazwy miejscowosci
private void getWeatherForNewCity(String city)
{
RequestParams params=new RequestParams();
params.put("q",city);
params.put("appid",APP_ID);
letsdoSomeNetworking(params);
}
// funkcja wywołuje aktualne inforamcje na podstawie aktualnych współrzędnych
private void getWeatherForCurrentLocation() {
// implementacja obiektu mLocationManager, który pobiera współrzędne geograficzne sprzętu
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListner = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
// implementacja stringów, przechowujących informacje na temat współrzędnych
String Latitude = String.valueOf(location.getLatitude());
String Longitude = String.valueOf(location.getLongitude());
// wywołanie parametrów - szerokości geograficznej i długości geograficznej
RequestParams params =new RequestParams();
params.put("lat" ,Latitude);
params.put("lon",Longitude);
params.put("appid",APP_ID);
letsdoSomeNetworking(params);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
//not able to get location
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.ACCESS_FINE_LOCATION},REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(Location_Provider, MIN_TIME, MIN_DISTANCE, mLocationListner);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==REQUEST_CODE)
{
if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(Pogoda.this,"Locationget Succesffully",Toast.LENGTH_SHORT).show();
getWeatherForCurrentLocation();
}
}
}
private void letsdoSomeNetworking(RequestParams params)
{
AsyncHttpClient client = new AsyncHttpClient();
client.get(WEATHER_URL,params,new JsonHttpResponseHandler()
{
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(Pogoda.this,"Data Get Success",Toast.LENGTH_SHORT).show();
weatherData weatherD=weatherData.fromJson(response);
updateUI(weatherD);
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
}
});
}
private void updateUI(weatherData weather){
Temperature.setText(weather.getmTemperature());
NameofCity.setText(weather.getMcity());
weatherState.setText(weather.getmWeatherType());
int resourceID=getResources().getIdentifier(weather.getMicon(),"drawable",getPackageName());
mweatherIcon.setImageResource(resourceID);
}
@Override
protected void onPause() {
super.onPause();
if(mLocationManager!=null)
{
mLocationManager.removeUpdates(mLocationListner);
}
}
} | Rolfer150/reposprojekt | app/src/main/java/com/example/aplikacjatreningowa/Pogoda.java |
180,302 | package pl.edu.wat.mspw_frontend.inputcontrollers;
import javafx.beans.property.BooleanProperty;
import javafx.beans.property.SimpleBooleanProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import pl.edu.wat.mspw_backend.service.*;
import pl.edu.wat.mspw_frontend.enums.TableViews;
import pl.edu.wat.mspw_frontend.enums.Views;
import pl.edu.wat.mspw_frontend.interfaces.ControlGenerator;
import pl.edu.wat.mspw_frontend.interfaces.Item;
import pl.edu.wat.mspw_frontend.model.StanAmoSpwDto;
import pl.edu.wat.mspw_frontend.readcontrollers.TableStanAmoSpwController;
import pl.edu.wat.mspw_frontend.util.Toast;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static pl.edu.wat.mspw_frontend.interfaces.ChoiceList.amoList;
import static pl.edu.wat.mspw_frontend.interfaces.ChoiceList.spwList;
import static pl.edu.wat.mspw_frontend.util.Toast.showToast;
public class InputStanAmoSpwController {
private StanAmoSpwService stanAmoSpwService = new StanAmoSpwService();
private SprzetWojService sprzetWojService = new SprzetWojService();
private AmoService amoService = new AmoService();
private TableStanAmoSpwController tableController;
@FXML
private AnchorPane tableContainer; // Container dla TableMpsView
@FXML
private GridPane inputGridPane;
@FXML
private Button addButton;
@FXML
private Button deleteButton;
@FXML
private Label labelTitle;
private Map<String, Control> dynamicControls = new HashMap<>();
private BooleanProperty anyControlEmpty = new SimpleBooleanProperty(false);
private ControlGenerator controller = new ControlGenerator();
public void initialize() {
InputControllerStatic.setupTitle(labelTitle,"Wprowadzanie ilości amunicji dla sprzętu wojskowego");
setupDynamicControls();
loadTableView(TableViews.TABLE_STAN_AMO_SPW.getValue());
InputControllerStatic.setupDynamicControlsListeners(
dynamicControls,
addButton,
anyControlEmpty
);
InputControllerStatic.setupButtonProperties(addButton,deleteButton,anyControlEmpty,tableController);
InputControllerStatic.updateAnyControlEmpty(anyControlEmpty,dynamicControls);
InputControllerStatic.updateButtonStyle(addButton);
}
private void loadTableView(String path) {
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource(path));
Node view = loader.load();
tableController = loader.getController();
AnchorPane.setTopAnchor(view, 0.0);
AnchorPane.setBottomAnchor(view, 0.0);
AnchorPane.setLeftAnchor(view, 0.0);
AnchorPane.setRightAnchor(view, 0.0);
tableContainer.getChildren().setAll(view);
} catch (IOException e) {
e.printStackTrace();
}
}
private void setupDynamicControls() {
InputControllerStatic.generateDynamicControl("AMO_FK", "AMO_FK", dynamicControls, 0, ChoiceBox.class, amoList,controller,inputGridPane);
controller.generateButton(inputGridPane, "AMO_FK", "#", Views.INPUTAMOVIEW.getValue(), 2, 0);
InputControllerStatic.generateDynamicControl("SPW_FK", "SPW_FK", dynamicControls, 1, ChoiceBox.class, spwList,controller,inputGridPane);
controller.generateButton(inputGridPane, "SPW_FK", "#", Views.INPUTSPWVIEW.getValue(), 2, 1);
InputControllerStatic.generateDynamicControl("STAN_NORMATYW", "STAN NORMATYWNY", dynamicControls, 2, TextField.class, null,controller,inputGridPane);
}
@FXML
private void addButtonAction(){
Stage stage = (Stage) addButton.getScene().getWindow();
Integer liczba = InputControllerStatic.getIntegerControlValue(stage,inputGridPane,"STAN_NORMATYWTextField",controller);
Integer amo= InputControllerStatic.getIntegerControlValue(stage,inputGridPane,"AMO_FKChoiceBox",controller);
Integer spw= InputControllerStatic.getIntegerControlValue(stage,inputGridPane,"SPW_FKChoiceBox",controller);
try {
if (!InputControllerStatic.isAnyControlEmpty(dynamicControls)) {
stanAmoSpwService.create(
StanAmoSpwDto.builder()
.stanNormatyw(liczba)
.spwFk(spw)
.amoFk(amo)
.build()
);
}
showToast(stage, "Dodano Rekord!", Toast.ToastType.SUCCESS);
} catch (Exception e) {
showToast(stage, "Wystąpił błąd - sprawdź poprawność danych!", Toast.ToastType.ERROR);
}
if (tableController != null) {
tableController.populateTable();
}
InputControllerStatic.clearDynamicControls(dynamicControls);
}
@FXML
private void deleteButtonAction() {
StanAmoSpwDto selectedAmoSpw = tableController.getTableView().getSelectionModel().getSelectedItem();
Stage stage = (Stage) deleteButton.getScene().getWindow();
if (selectedAmoSpw != null) {
try{
stanAmoSpwService.delete(Long.valueOf(selectedAmoSpw.getId()));
showToast(stage, "Rekord usunięto!", Toast.ToastType.SUCCESS);
}catch (Exception ex){
showToast(stage, "Wystąpił błąd!", Toast.ToastType.ERROR);
}
} else {
showToast(stage, "Wybierz rekord aby usunąć!", Toast.ToastType.INFO);
}
// Odświeżenie tabeli
if (tableController != null) {
tableController.populateTable();
}
}
}
| Studenci-WAT/BMS-Chaber | src/main/java/pl/edu/wat/mspw_frontend/inputcontrollers/InputStanAmoSpwController.java |
180,307 | package model;
import utils.ObjectPlus;
import java.time.LocalDate;
public abstract class Device extends ObjectPlus {
private static int nextDeviceID = 0;
private int deviceId;
private LocalDate devicePurchaseDate;
private String deviceBrand;
private String deviceModel;
private long deviceSerialNumber;
private int deviceAmortizationTime;
private boolean deviceInUse;
private PurchaseOrder devicePurchaseOrder;
/**
* The constructor. Klasa abstrakcyjna - sprzęt
*
* @param devicePurchaseDate Data zakupu sprzętu
* @param deviceBrand Marka
* @param deviceModel Model
* @param deviceSerialNumber Numer seryjny
* @param deviceAmortizationTime Czas amortyzacji
* @param deviceInUse Czy sprzęt jest w użyciu
*/
public Device(LocalDate devicePurchaseDate,
String deviceBrand,
String deviceModel,
long deviceSerialNumber,
int deviceAmortizationTime,
boolean deviceInUse) {
super();
this.deviceId = nextDeviceID++;
this.devicePurchaseDate = devicePurchaseDate;
this.deviceBrand = deviceBrand;
this.deviceModel = deviceModel;
this.deviceSerialNumber = deviceSerialNumber;
this.deviceAmortizationTime = deviceAmortizationTime;
this.deviceInUse = deviceInUse;
}
/**
* Dodawanie zamówienia do obiekru Sprzęt
*
* @param newPO nowe zamówienie
*/
public void addPurchaseOrder(PurchaseOrder newPO) {
if (devicePurchaseOrder == null) {
devicePurchaseOrder = newPO;
newPO.addDevice(this);
}
}
/**
* Usuwanie zamówienia z obiektu sprzet
*/
public void removePurchaseOrder(PurchaseOrder oldPO) {
if (devicePurchaseOrder != null) {
devicePurchaseOrder = null;
oldPO.removeDevice(this);
}
}
public int getDeviceId() {
return deviceId;
}
public LocalDate getDevicePurchaseDate() {
return devicePurchaseDate;
}
public String getDeviceBrand() {
return deviceBrand;
}
public String getDeviceModel() {
return deviceModel;
}
public long getDeviceSerialNumber() {
return deviceSerialNumber;
}
public int getDeviceAmortizationTime() {
return deviceAmortizationTime;
}
public boolean isDeviceInUse() {
return deviceInUse;
}
public void setDeviceId(int deviceId) {
this.deviceId = deviceId;
}
public void setDevicePurchaseDate(LocalDate devicePurchaseDate) {
this.devicePurchaseDate = devicePurchaseDate;
}
public void setDeviceBrand(String deviceBrand) {
this.deviceBrand = deviceBrand;
}
public void setDeviceModel(String deviceModel) {
this.deviceModel = deviceModel;
}
public void setDeviceSerialNumber(long deviceSerialNumber) {
this.deviceSerialNumber = deviceSerialNumber;
}
public void setDeviceAmortizationTime(int deviceAmortizationTime) {
this.deviceAmortizationTime = deviceAmortizationTime;
}
public void setDeviceInUse(boolean deviceInUse) {
this.deviceInUse = deviceInUse;
}
public void setDevicePurchaseOrder(PurchaseOrder devicePurchaseOrder) {
this.devicePurchaseOrder = devicePurchaseOrder;
}
public static void setNextDeviceID(int nextDeviceID) {
Device.nextDeviceID = nextDeviceID;
}
public void retireDevice() {
deviceInUse = false;
}
public void enableDevice() {
deviceInUse = true;
}
}
| Barteck197/PJ-MAS_end_project | src/main/java/model/Device.java |
180,308 | package main.manager;
import main.modules.Asset;
import main.modules.Company;
import main.utils.Printer;
import java.util.Scanner;
public class AssetsManager extends ManagerUtils{
private final Printer printer;
private Company company;
private Scanner scanner;
public AssetsManager() {
this.printer = super.getPrinter();
this.scanner = super.getScanner();
this.company = super.getCompany();
}
public void showAllAssets() {
if (company.getAssets().isEmpty()) {
printer.print("Firma nie posiada majątku trwałego");
return;
}
for (int i = 0; i < company.getAssets().size(); i++) {
printer.print("Nazwa sprzętu: " + company.getAssets().get(i).getAssetName() + ", typ sprzetu: " +
company.getAssets().get(i).getAssetType() + ", wartość sprzętu: " + company.getAssets().get(i).getAssetValue() +
", stopa amortyzacji: " + company.getAssets().get(i).getDepreciationRate() + "%");
}
}
public void removeAssetModule() {
int assetIndex;
printer.print("Podaj indeks sprzętu do usunięcia");
assetIndex = scanner.nextInt();
if (canCompanyDeleteAsset()) {
printer.print("Nie możesz usunąć sprzętu o danym indeksie");
} else {
deleteAsset(assetIndex);
printer.print("Sprzęt o indeksie: " + assetIndex + " został usunięty");
}
}
public void addNewAssetModule() {
printer.print("Podaj nazwę sprzętu");
String assetName = scanner.next();
printer.print("Podaj typ sprzętu");
String assetType = scanner.next();
printer.print("Podaj wartość sprzętu");
int assetValue = scanner.nextInt();
printer.print("Podaj stopę amortyzacji");
int depreciationRate = depreciationRateValidator();
Asset asset = new Asset(assetName, assetType, assetValue, depreciationRate);
addAsset(asset);
}
private int depreciationRateValidator() {
int depreciationRateToCheck = scanner.nextInt();
while (depreciationRateToCheck <= 0) {
printer.print("Wartość amortyzacji nie może być mniejsza lub równa 0.");
depreciationRateToCheck = scanner.nextInt();
}
return depreciationRateToCheck;
}
private void addAsset(Asset assets) {
company.getAssets().add(assets);
}
private boolean canCompanyDeleteAsset() {
company.getAssets().size();
return true;
}
private void deleteAsset(int assetIndex) {
company.addCash(company.getAssets().get(assetIndex).getAssetValue());
company.getAssets().remove(assetIndex);
}
}
| aniawzs/SimpleCompanyManager1 | src/main/manager/AssetsManager.java |
180,311 | package model;
import utils.ObjectPlus;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
public class PurchaseOrder extends ObjectPlus {
private static int nextPurchaseOrderID = 0;
private int purchaseOrderNumber;
private LocalDate orderPlaceDate;
private int quantity;
private List<Device> orderDevices = new ArrayList<>();
private List<Software> orderSoftware = new ArrayList<>();
/**
* Konstruktor klasy: Zamówienie sprzętu
*
* @param orderPlaceDate Data złożenia zamówienia
* @param quantity Ilość
* @param deviceToOrder Sprzęt do zamówienia
*/
public PurchaseOrder(LocalDate orderPlaceDate, int quantity, Device deviceToOrder) {
super();
this.orderPlaceDate = orderPlaceDate;
this.quantity = quantity;
this.purchaseOrderNumber = nextPurchaseOrderID++;
orderDevices.add(deviceToOrder);
}
/**
* Konstruktor klasy: zamówienie oprogramowania
*
* @param orderPlaceDate data złożenia zamówienia
* @param quantity ilość
* @param softwareToOrder oprogramowanie do zamówienia
*/
public PurchaseOrder(LocalDate orderPlaceDate, int quantity, Software softwareToOrder) {
this.orderPlaceDate = orderPlaceDate;
this.quantity = quantity;
this.purchaseOrderNumber = nextPurchaseOrderID++;
orderSoftware.add(softwareToOrder);
}
public void addDevice(Device newDevice) {
if (!orderDevices.contains(newDevice)) {
orderDevices.add(newDevice);
newDevice.addPurchaseOrder(this);
}
}
public void removeDevice(Device oldDevice) {
orderDevices.remove(oldDevice);
oldDevice.removePurchaseOrder(this);
}
public void addSoftware(Software newSoftware) {
if (!orderSoftware.contains(newSoftware)) {
orderSoftware.add(newSoftware);
newSoftware.addPurchaseOrder(this);
}
}
public void removeSoftware(Software oldSoftware) {
orderSoftware.remove(oldSoftware);
oldSoftware.removePurchaseOrder(this);
}
}
| Barteck197/PJ-MAS_end_project | src/main/java/model/PurchaseOrder.java |
180,316 | package pl.lodz.p.edu.rest.model;
import jakarta.persistence.*;
import jakarta.transaction.Transactional;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import pl.lodz.p.edu.rest.model.DTO.RentDTO;
import pl.lodz.p.edu.rest.model.users.Client;
import java.time.LocalDateTime;
@Access(AccessType.FIELD)
@Entity
@Table(name = "rent")
@Transactional
@Valid
public class Rent extends AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
@SequenceGenerator(initialValue = 0, name = "rent_sequence_generator")
@Column(name = "rent_id")
private long id;
@NotNull
@JoinColumn(name = "equipment_id")
@ManyToOne(fetch = FetchType.EAGER,
cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Equipment equipment;
@NotNull
@JoinColumn(name = "client_id")
@ManyToOne(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private Client client;
@NotNull
@Column(name = "begin_time")
private LocalDateTime beginTime;
@Column(name = "end_time")
private LocalDateTime endTime;
public Rent(LocalDateTime beginTime, LocalDateTime endTime,
Equipment equipment, Client client) {
this.beginTime = beginTime;
this.endTime = endTime;
this.equipment = equipment;
this.client = client;
}
protected Rent() {
}
public Rent(RentDTO rentDTO, Equipment equipment, Client client) {
this.beginTime = LocalDateTime.parse(rentDTO.getBeginTime());
if (rentDTO.getEndTime() != null) {
this.endTime = LocalDateTime.parse(rentDTO.getEndTime());
} else {
this.endTime = null;
}
this.equipment = equipment;
this.client = client;
}
public Rent(long id, LocalDateTime beginTime, LocalDateTime endTime,
Equipment equipment, Client client) {
this(beginTime, endTime, equipment, client);
this.id = id;
}
public String toString() {
String sb = "Rent{" + "id=" + id +
"Klient=" + getClient().toString() +
"Sprzęt=" + getEquipment().toString() +
"Czas wypożyczenia=" +
"Początek=" + beginTime +
" do " +
"Koniec=" + endTime +
'}';
return sb;
}
public void merge(RentDTO rentDTO, Equipment equipment, Client client) {
this.beginTime = LocalDateTime.parse(rentDTO.getBeginTime());
if (rentDTO.getEndTime() != null) {
this.endTime = LocalDateTime.parse(rentDTO.getEndTime());
} else {
this.endTime = null;
}
this.equipment = equipment;
this.client = client;
}
public LocalDateTime getBeginTime() {
return beginTime;
}
public void setBeginTime(LocalDateTime beginTime) {
this.beginTime = beginTime;
}
public LocalDateTime getEndTime() {
return endTime;
}
public void setEndTime(LocalDateTime endTime) {
this.endTime = endTime;
}
public Equipment getEquipment() {
return equipment;
}
public void setEquipment(Equipment equipment) {
this.equipment = equipment;
}
public Client getClient() {
return client;
}
public void setClient(Client client) {
this.client = client;
}
}
| Firedog01/Pasenbazen | src/main/java/pl/lodz/p/edu/rest/model/Rent.java |
180,317 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.exception;
import org.apache.commons.lang3.StringUtils;
import pl.polsl.skirentalservice.core.AbstractAppException;
import pl.polsl.skirentalservice.core.servlet.WebServletRequest;
import pl.polsl.skirentalservice.util.UserRole;
public class AlreadyExistException {
public static class PeselAlreadyExistException extends AbstractAppException {
public PeselAlreadyExistException(String pesel, UserRole role) {
super(StringUtils.capitalize(role.getName()) + " z numerem PESEL <strong>" + pesel +
"</strong> istnieje już w systemie.");
}
}
public static class PhoneNumberAlreadyExistException extends AbstractAppException {
public PhoneNumberAlreadyExistException(String phoneNumber, UserRole role) {
super(StringUtils.capitalize(role.getName()) + " z numerem telefonu <strong>" + phoneNumber +
"</strong> istnieje już w systemie.");
}
}
public static class EmailAddressAlreadyExistException extends AbstractAppException {
public EmailAddressAlreadyExistException(String emailAddress, UserRole role) {
super(StringUtils.capitalize(role.getName()) + " z adresem email <strong>" + emailAddress +
"</strong> istnieje już w systemie.");
}
}
public static class EquipmentTypeAlreadyExistException extends AbstractAppException {
public EquipmentTypeAlreadyExistException() {
super("Wybrany typ sprzętu narciarskiego do dodania istnieje już w systemie. Spróbuj dodać inny sprzęt, " +
"bądź wybierz z listy dostępnych.");
}
}
public static class EquipmentBrandAlreadyExistException extends AbstractAppException {
public EquipmentBrandAlreadyExistException() {
super("Wybrana marka sprzętu narciarskiego do dodania istnieje już w systemie. Spróbuj dodać inną markę, " +
"bądź wybierz z listy dostępnych.");
}
}
public static class EquipmentColorAlreadyExistException extends AbstractAppException {
public EquipmentColorAlreadyExistException() {
super("Wybrany kolor sprzętu narciarskiego do dodania istnieje już w systemie. Spróbuj dodać inny kolor, " +
"bądź wybierz z listy dostępnych.");
}
}
public static class EquipmentAlreadyExistException extends AbstractAppException {
public EquipmentAlreadyExistException() {
super("Wybrany model sprzętu istnieje już w systemie Jeśli chcesz dodać więcej elementów, zwiększ ich ilość " +
"w wypożyczalni.");
}
}
public static class EquipmentTypeHasConnectionsException extends AbstractAppException {
public EquipmentTypeHasConnectionsException() {
super("Wybrany typ sprzętu narciarskiego nie jest możliwy do usunięcia, ponieważ powiązane są z nim sprzęty. " +
"Jeśli chcesz usunąć typ, musisz usunąć wszystkie powiązane z nim sprzęty.");
}
}
public static class EquipmentBrandHasConnectionsException extends AbstractAppException {
public EquipmentBrandHasConnectionsException() {
super("Wybrana marka sprzętu narciarskiego nie jest możliwa do usunięcia, ponieważ powiązane są z nią sprzęty. " +
"Jeśli chcesz usunąć markę, musisz usunąć wszystkie powiązane z nią sprzęty.");
}
}
public static class EquipmentColorHasConnectionsException extends AbstractAppException {
public EquipmentColorHasConnectionsException() {
super("Wybrany kolor sprzętu narciarskiego nie jest możliwy do usunięcia, ponieważ powiązane są z nim sprzęty. " +
"Jeśli chcesz usunąć kolor, musisz usunąć wszystkie powiązane z nim sprzęty.");
}
}
public static class EquipmentInCartAlreadyExistException extends AbstractAppException {
public EquipmentInCartAlreadyExistException() {
super("Dodawany sprzęt istnieje już w zestawieniu nowego wypożyczenia. Aby zwiększyć ilość, edytuj pozycję.");
}
}
public static class TooMuchEquipmentsException extends AbstractAppException {
public TooMuchEquipmentsException() {
super("Podano więcej sztuk sprzętu, aniżeli jest dostępnych na stanie.");
}
}
public static class CustomerHasOpenedRentsException extends AbstractAppException {
public CustomerHasOpenedRentsException() {
super("Nie jest możliwe usunięcie użytkownika, który posiada w danej chwili przynamniej jedno wypożyczenie " +
"ze statusem innym niż <strong>Zwrócone</strong>.");
}
}
public static class EmployerHasOpenedRentsException extends AbstractAppException {
public EmployerHasOpenedRentsException() {
super("Nie jest możliwe usunięcie pracownika, który zarządza w danej chwili przynamniej jednym wypożyczeniem " +
"ze statusem innym niż <strong>Zwrócone</strong>.");
}
}
public static class EquipmenHasOpenedRentsException extends AbstractAppException {
public EquipmenHasOpenedRentsException() {
super("Nie jest możliwe usunięcie sprzętu narciarskiego, który obecny jest w danej chwili w przynajmniej " +
"jednym wypożyczeniu ze statusem innym niż <strong>Zwrócone</strong>.");
}
}
public static class ReturnDocumentAlreadyExistException extends AbstractAppException {
public ReturnDocumentAlreadyExistException(WebServletRequest req, String returnIdentifier, Long returnId) {
super("Wybrane wypożyczenie posiada już wygenerowany dokument zwrotu. Możesz go znaleźć, klikając w " +
"<a class='alert-link' href='" + req.getContextPath() + "/seller/return-details?id=" + returnId +
"'>ten link</a> lub wyszukujac po numerze zwrotu: <strong>" + returnIdentifier + "</strong>.");
}
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/exception/AlreadyExistException.java |
180,320 | package com.studionagranapp.guicontrollers.userdashboard.owner;
import com.studionagranapp.guicontrollers.userdashboard.ModifySessionController;
import com.studionagranapp.helpers.configurators.tableconfigurators.ClientsTableConfigurator;
import com.studionagranapp.helpers.configurators.tableconfigurators.EngineersTableConfigurator;
import com.studionagranapp.helpers.configurators.tableconfigurators.EquipmentTableConfigurator;
import com.studionagranapp.helpers.configurators.tableconfigurators.SessionsTableConfigurator;
import com.studionagranapp.helpers.contentloaders.SceneCreator;
import com.studionagranapp.helpers.databaseconnection.DatabaseManager;
import com.studionagranapp.helpers.databaseconnection.DatabaseResponse;
import com.studionagranapp.helpers.errorhandling.AlertManager;
import com.studionagranapp.helpers.models.Equipment;
import com.studionagranapp.helpers.models.Session;
import com.studionagranapp.helpers.models.User;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;
import java.net.URL;
import java.sql.Date;
import java.util.Optional;
import java.util.ResourceBundle;
public class OwnersDashboardController implements Initializable {
@FXML
private Label userInfo;
@FXML
private Button logoutButton;
@FXML
TableView<Session> sessionsTable;
@FXML
TableColumn<Session, String> seshNameColumn;
@FXML
TableColumn<Session, String> seshClientColumn;
@FXML
TableColumn<Session, String> seshBandColumn;
@FXML
TableColumn<Session, String> seshEngineerColumn;
@FXML
TableColumn<Session, Date> seshBeginColumn;
@FXML
TableColumn<Session, Date> seshEndColumn;
@FXML
TableColumn<Session, Integer> seshDurationColumn;
@FXML
TableView<User> clientsTable;
@FXML
TableColumn<User, String> clientFullNameColumn;
@FXML
TableColumn<User, String> clientEmailColumn;
@FXML
TableColumn<User, String> clientPhoneColumn;
@FXML
TableView<User> engineersTable;
@FXML
TableColumn<User, String> engineerFullNameColumn;
@FXML
TableColumn<User, String> engineerEmailColumn;
@FXML
TableColumn<User, String> engineerPhoneColumn;
@FXML
TableView<Equipment> equipmentTable;
@FXML
TableColumn<Equipment, String> eqNameColumn;
@FXML
TableColumn<Equipment, String> eqTypeColumn;
@FXML
TableColumn<Equipment, Integer> eqQuantityColumn;
private final ObservableList<Session> sessionsObservableList = FXCollections.observableArrayList();
private final ObservableList<User> clientsObservableList = FXCollections.observableArrayList();
private final ObservableList<User> engineersObservableList = FXCollections.observableArrayList();
private final ObservableList<Equipment> equipmentObservableList = FXCollections.observableArrayList();
private final DatabaseManager databaseManager;
private final SessionsTableConfigurator sessionsTableConfigurator;
private final ClientsTableConfigurator clientsTableConfigurator;
private final EngineersTableConfigurator engineersTableConfigurator;
private final EquipmentTableConfigurator equipmentTableConfigurator;
private final AlertManager alertManager;
public OwnersDashboardController() {
databaseManager = DatabaseManager.getInstance();
sessionsTableConfigurator = new SessionsTableConfigurator();
clientsTableConfigurator = new ClientsTableConfigurator();
engineersTableConfigurator = new EngineersTableConfigurator();
equipmentTableConfigurator = new EquipmentTableConfigurator();
alertManager = new AlertManager();
}
public void setUserInfo(String userInfo) {
this.userInfo.setText(userInfo);
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
sessionsTableConfigurator.provideFullConfiguration(sessionsObservableList, sessionsTable);
clientsTableConfigurator.provideConfiguration(clientsObservableList, clientsTable);
engineersTableConfigurator.provideConfiguration(engineersObservableList, engineersTable);
equipmentTableConfigurator.provideFullConfiguration(equipmentObservableList, equipmentTable);
initSessionsData();
initClientsData();
initEngineersData();
initEquipmentData();
}
@FXML
private void refresh() {
sessionsTableConfigurator.provideFullConfiguration(sessionsObservableList, sessionsTable);
clientsTableConfigurator.provideConfiguration(clientsObservableList, clientsTable);
engineersTableConfigurator.provideConfiguration(engineersObservableList, engineersTable);
equipmentTableConfigurator.provideFullConfiguration(equipmentObservableList, equipmentTable);
initSessionsData();
initClientsData();
initEngineersData();
initEquipmentData();
}
@FXML
private void logout() {
Stage stage = (Stage) logoutButton.getScene().getWindow();
stage.close();
SceneCreator.createScene("gui/login-panel.fxml", 800, 600);
}
@FXML
public void modifySession() {
try {
Session session = sessionsTable.getSelectionModel().getSelectedItem();
Integer sessionID = session.getId();
ModifySessionController modifySessionController = (ModifySessionController)
SceneCreator.createScene("gui/modify-session-window.fxml", 240, 150);
assert modifySessionController != null;
modifySessionController.setAlertManager(alertManager);
modifySessionController.setSessionID(sessionID);
} catch (Exception e) {
alertManager.throwError("Nie wybrano żadnej sesji z listy!");
}
}
@FXML
public void cancelSession() {
try {
Session session = sessionsTable.getSelectionModel().getSelectedItem();
if (session == null)
throw new Exception();
boolean confirmation = alertManager
.throwConfirmation("Czy na pewno chcesz odwołać wybraną sesję?");
if (!confirmation)
return;
DatabaseResponse result = databaseManager.delete(session);
if (result == DatabaseResponse.ERROR)
alertManager.throwError("Wystąpił błąd podczas usuwania sesji");
else if (result == DatabaseResponse.SUCCESS) {
alertManager.throwInformation("Pomyslnie odwołano sesję!");
refresh();
}
} catch (Exception e) {
alertManager.throwError("Nie wybrano żadnej sesji z listy!");
}
}
@FXML
public void addEngineer() {
NewEngineerDashboardController newEngineerDashboardController = (NewEngineerDashboardController)
SceneCreator.createScene("gui/new-engineer-dashboard.fxml", 600, 460);
assert newEngineerDashboardController != null;
}
@FXML
public void deleteEngineer() {
try {
User engineer = engineersTable.getSelectionModel().getSelectedItem();
if (engineer == null)
throw new Exception();
boolean confirmation = alertManager
.throwConfirmation("Czy na pewno chcesz usunąć wybranego realizatora?");
if (!confirmation)
return;
DatabaseResponse result = databaseManager.delete(engineer);
if (result == DatabaseResponse.ERROR)
alertManager.throwError("Wystąpił błąd podczas usuwania danych z bazy");
else if (result == DatabaseResponse.SUCCESS) {
alertManager.throwInformation("Realizator usunięty pomyslnie!");
refresh();
}
} catch (Exception e) {
alertManager.throwError("Nie wybrano żadnego realizatora z listy!");
}
}
@FXML
public void addEquipment() {
Dialog<ButtonType> addEquipmentDialog = new Dialog<>();
addEquipmentDialog.setTitle("Dodawanie sprzętu");
addEquipmentDialog.setHeaderText("Dodaj nowy sprzęt");
ButtonType loginButtonType = new ButtonType("Dodaj", ButtonBar.ButtonData.OK_DONE);
ButtonType cancelButtonType = new ButtonType("Powrót", ButtonBar.ButtonData.CANCEL_CLOSE);
addEquipmentDialog.getDialogPane().getButtonTypes().addAll(loginButtonType, cancelButtonType);
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 150, 10, 10));
TextField equipmentName = new TextField();
equipmentName.setPromptText("Nazwa sprzętu");
TextField equipmentType = new TextField();
equipmentType.setPromptText("Rodzaj sprzętu");
TextField equipmentQuantity = new TextField();
equipmentQuantity.setPromptText("Ilosć");
ChoiceBox<String> backlineChoiceBox = new ChoiceBox<>();
backlineChoiceBox.getItems().add("Tak");
backlineChoiceBox.getItems().add("Nie");
grid.add(new Label("Nazwa sprzętu:"), 0, 0);
grid.add(equipmentName, 1, 0);
grid.add(new Label("Rodzaj sprzętu:"), 0, 1);
grid.add(equipmentType, 1, 1);
grid.add(new Label("Ilosć:"), 0, 2);
grid.add(equipmentQuantity, 1, 2);
grid.add(new Label("Backline:"), 0, 3);
grid.add(backlineChoiceBox, 1, 3);
addEquipmentDialog.getDialogPane().setContent(grid);
Platform.runLater(equipmentName::requestFocus);
Optional<ButtonType> result = addEquipmentDialog.showAndWait();
if (result.isPresent() && !equipmentName.getText().isBlank() && !equipmentType.getText().isBlank() &&
!equipmentQuantity.getText().isBlank() &&
!(backlineChoiceBox.getSelectionModel().getSelectedItem() == null)) {
DatabaseResponse newEquipmentResult = databaseManager
.insertEquipment(equipmentName.getText(),
equipmentType.getText(),
equipmentQuantity.getText(),
backlineChoiceBox.getSelectionModel().getSelectedItem());
if (newEquipmentResult == DatabaseResponse.SUCCESS) {
alertManager.throwInformation("Sprzęt dodany pomyslnie!");
refresh();
} else
alertManager.throwError("Błąd zapisu danych do bazy!");
} else if (result.isPresent() && result.get() == cancelButtonType)
return;
else {
alertManager.throwError("Sprawdź wprowadzone dane!");
addEquipment();
}
}
@FXML
public void deleteEquipment() {
try {
Equipment equipment = equipmentTable.getSelectionModel().getSelectedItem();
if (equipment == null)
throw new Exception();
boolean confirmation = alertManager
.throwConfirmation("Czy na pewno chcesz usunąć wybrany sprzęt?");
if (!confirmation)
return;
DatabaseResponse result = databaseManager.delete(equipment);
if (result == DatabaseResponse.ERROR)
alertManager.throwError("Wystąpił błąd podczas usuwania danych z bazy");
else if (result == DatabaseResponse.SUCCESS) {
alertManager.throwInformation("Sprzęt usunięty pomyslnie!");
refresh();
}
} catch (Exception e) {
alertManager.throwError("Nie wybrano żadnego sprzętu z listy!");
}
}
@FXML
public void modifyEqQuantity() {
try {
Equipment equipment = equipmentTable.getSelectionModel().getSelectedItem();
Integer equipmentID = equipment.getId();
ModifyQuantityController modifyQuantityController = (ModifyQuantityController)
SceneCreator.createScene("gui/modify-quantity-window.fxml", 200, 100);
assert modifyQuantityController != null;
modifyQuantityController.setAlertManager(alertManager);
modifyQuantityController.setEquipmentID(equipmentID);
} catch (Exception e) {
alertManager.throwError("Nie wybrano żadnego przedmiotu z listy!");
}
}
private void initSessionsData() {
seshNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
seshClientColumn.setCellValueFactory(new PropertyValueFactory<>("clientName"));
seshBandColumn.setCellValueFactory(new PropertyValueFactory<>("bandName"));
seshEngineerColumn.setCellValueFactory(new PropertyValueFactory<>("engineerName"));
seshBeginColumn.setCellValueFactory(new PropertyValueFactory<>("startDate"));
seshEndColumn.setCellValueFactory(new PropertyValueFactory<>("endDate"));
seshDurationColumn.setCellValueFactory(new PropertyValueFactory<>("duration"));
sessionsTable.setItems(sessionsObservableList);
FilteredList<Session> filteredData = new FilteredList<>(sessionsObservableList, b -> true);
SortedList<Session> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(sessionsTable.comparatorProperty());
sessionsTable.setItems(sortedData);
}
private void initClientsData() {
clientFullNameColumn.setCellValueFactory(new PropertyValueFactory<>("fullName"));
clientEmailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));
clientPhoneColumn.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
clientsTable.setItems(clientsObservableList);
FilteredList<User> filteredData = new FilteredList<>(clientsObservableList, b -> true);
SortedList<User> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(clientsTable.comparatorProperty());
clientsTable.setItems(sortedData);
}
private void initEngineersData() {
engineerFullNameColumn.setCellValueFactory(new PropertyValueFactory<>("fullName"));
engineerEmailColumn.setCellValueFactory(new PropertyValueFactory<>("email"));
engineerPhoneColumn.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
engineersTable.setItems(engineersObservableList);
FilteredList<User> filteredData = new FilteredList<>(engineersObservableList, b -> true);
SortedList<User> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(engineersTable.comparatorProperty());
engineersTable.setItems(sortedData);
}
private void initEquipmentData() {
eqNameColumn.setCellValueFactory(new PropertyValueFactory<>("name"));
eqTypeColumn.setCellValueFactory(new PropertyValueFactory<>("type"));
eqQuantityColumn.setCellValueFactory(new PropertyValueFactory<>("quantity"));
equipmentTable.setItems(equipmentObservableList);
FilteredList<Equipment> filteredData = new FilteredList<>(equipmentObservableList, b -> true);
SortedList<Equipment> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(equipmentTable.comparatorProperty());
equipmentTable.setItems(sortedData);
}
}
| Matias3004/BD2-StudioNagran-App-V2 | src/main/java/com/studionagranapp/guicontrollers/userdashboard/owner/OwnersDashboardController.java |
180,321 | package server;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ProductionEmployee extends Employee{
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/system";
private static final String USER = "root";
private static final String PASSWORD = "";
private Connection connection;
public ProductionEmployee(int id, String name, String lastName, String role, String zone, String login, String password) {
super(id, name, lastName, role, zone, login, password);
}
public ProductionEmployee(int id, String name, String lastName, String role, String zone, String login, String password, Task task) {
super(id, name, lastName, role, zone, login, password, task);
}
public Task getMyTask(Employee employee)
{
Task task = null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
System.out.println("Pomyślnie połączono z bazą danych");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
String query = "SELECT \n" +
" task.taskID,\n" +
" MAX(task.name) as taskName,\n" +
" MAX(task.priority) as taskPriority,\n" +
" MAX(task.description) as taskDescription,\n" +
" MAX(taskCategory.name) as nameCategory,\n" +
" MAX(task.norm) as taskNorm,\n" +
" MAX(taskStatus.stepName) as status,\n" +
" MAX(product.name) as productName,\n" +
" MAX(task.quantity) as taskQuantity,\n" +
" MAX(zone.name) as zoneName,\n" +
" MAX(equipment.name) as equipmentName,\n" +
" GROUP_CONCAT( DISTINCT component.name) as componentName \n" +
"FROM \n" +
" task\n" +
"JOIN \n" +
" taskStatus ON taskStatus.taskID = task.taskID\n" +
"JOIN \n" +
" taskCategory ON taskCategory.taskCategoryID = task.taskCategory\n" +
"JOIN \n" +
" product ON product.productID = task.productID\n" +
"JOIN \n" +
" zone ON zone.zoneID = task.zoneID\n" +
"JOIN \n" +
" taskEquipment ON taskEquipment.taskID = task.taskID\n" +
"JOIN \n" +
" equipment ON equipment.equipmentID = taskEquipment.equipmentID\n" +
"JOIN \n" +
" taskComponent ON taskComponent.taskID = task.taskID\n" +
"JOIN \n" +
" component ON component.componentID = taskComponent.componentID\n" +
"WHERE \n" +
" taskStatus.employeeID = ?\n" +
" AND taskStatus.stepName = 'in progress' \n" +
" AND taskStatus.endStep = '0000-00-00 00-00-00'\n" +
"GROUP BY \n" +
" task.taskID;\n";
try{
int employeeID = employee.getId();
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1,employeeID);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()){
int taskID = resultSet.getInt("taskID");
String taskName = resultSet.getString("taskName");
String priority = resultSet.getString("taskPriority");
String description = resultSet.getString("taskDescription");
String category = resultSet.getString("nameCategory");
int norm = resultSet.getInt("taskNorm");
int quantityOK = 0;
int quantityNOK = 0;
String status = resultSet.getString("status");
String product = resultSet.getString("productName");
int quantity = resultSet.getInt("taskQuantity");
String zone = resultSet.getString("zoneName");
String equipment = resultSet.getString("equipmentName");
String component = resultSet.getString("componentName");
task = new Task(taskID,taskName,priority,description,category,norm,quantityOK,quantityNOK,status,product,quantity,zone,equipment,component);
}
}catch (SQLException e){
e.printStackTrace();
}
return task;
}
public List<Task> getListOfTask(int employeeID) {
List<Task> tasks = new ArrayList<>();
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
System.out.println("Pomyślnie połączono z bazą danych");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
String query = "SELECT t.taskID, t.name, t.priority, t.description, p.name AS 'product', t.quantity, t.norm,\n" +
" ts.stepName AS 'status',\n" +
" GROUP_CONCAT(DISTINCT eq.name) AS 'equipment', GROUP_CONCAT(DISTINCT c.name) AS 'component'\n" +
"FROM task t\n" +
" JOIN product p ON p.productID = t.productID\n" +
" JOIN taskstatus ts ON ts.taskID = t.taskID\n" +
" JOIN taskequipment te ON te.taskID = t.taskID\n" +
" JOIN equipment eq ON eq.equipmentID = te.equipmentID\n" +
" JOIN taskcomponent tc ON tc.taskID = t.taskID\n" +
" JOIN component c ON c.componentID = tc.componentID\n" +
"WHERE\n" +
" -- zadanie jest dostępne:\n" +
" ts.endStep = '0000-00-00 00:00:00' AND ts.stepName = 'available'\n" +
" -- uprawnienie na zadanie:\n" +
" AND t.taskCategory IN (SELECT DISTINCT taskcategoryid FROM taskcategorylicense WHERE licenseID IN\n" +
" (SELECT licenseId FROM employeelicense WHERE employeeId = ? AND expirationDate >= CURRENT_DATE))\n" +
" -- uprawnienie na sprzęt:\n" +
" AND eq.equipmentCategoryID IN (SELECT equipmentcategoryId FROM equipmentcategorylicense WHERE licenseID IN\n" +
" (SELECT licenseId FROM employeelicense WHERE employeeId = ? AND expirationDate >= CURRENT_DATE))\n" +
" -- componenty są dostępne:\n" +
" AND (\n" +
" SELECT COUNT(*) = SUM(CASE WHEN tc.quantity <= c.quantity THEN 1 ELSE 0 END)\n" +
" FROM taskcomponent tc\n" +
" JOIN component c ON tc.componentid = c.componentid\n" +
" WHERE tc.taskid = t.taskid\n" +
" ) > 0\n" +
"\n" +
" -- sprzęt jest dostępny:\n" +
" AND (\n" +
" SELECT COUNT(*) = SUM(CASE WHEN e.status = 'available' THEN 1 ELSE 0 END)\n" +
" FROM equipment e\n" +
" JOIN taskequipment te ON e.equipmentID = te.equipmentID\n" +
" WHERE te.taskId = t.taskid\n" +
" ) > 0\n" +
"\n" +
"GROUP BY t.taskID;\n";
try {
PreparedStatement preparedStatement = connection.prepareStatement(query);
preparedStatement.setInt(1, employeeID);
preparedStatement.setInt(2,employeeID);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
int taskID = resultSet.getInt("taskID");
String name = resultSet.getString("name");
String priority = resultSet.getString("priority");
String description = resultSet.getString("description");
String productName = resultSet.getString("product");
int quantity = resultSet.getInt("quantity");
int norm = resultSet.getInt("norm");
String status = resultSet.getString("status");
String equipment = resultSet.getString("equipment");
String component = resultSet.getString("component");
tasks.add(new Task(taskID, name, priority, description, productName, quantity, norm, status, equipment, component));
}
} catch (SQLException e) {
e.printStackTrace();
}
return tasks;
}
}
| SylwiaJa/Pojekt-System-do-zarzadzania-zasobami | projekt2023_24/src/server/ProductionEmployee.java |
180,322 | package pl.coderslab.domain.restaurant;
import org.springframework.stereotype.Service;
import pl.coderslab.domain.equipment.Equipment;
import pl.coderslab.domain.equipment.JpaEquipmentService;
import pl.coderslab.domain.repair_service.JpaRepairService;
import pl.coderslab.domain.repair_service.RepairService;
import java.util.List;
import java.util.Optional;
@Service
public class JpaRestaurantService implements RestaurantService{
private final RestaurantRepository restaurantRepository;
private final JpaEquipmentService jpaEquipmentService;
private final JpaRepairService jpaRepairService;
public JpaRestaurantService(RestaurantRepository restaurantRepository, JpaEquipmentService jpaEquipmentService, JpaRepairService jpaRepairService) {
this.restaurantRepository = restaurantRepository;
this.jpaEquipmentService = jpaEquipmentService;
this.jpaRepairService = jpaRepairService;
}
@Override
public List<Restaurant> getAll() {
return restaurantRepository.findAll();
}
@Override
public Optional<Restaurant> get(Long id) {
return restaurantRepository.findById(id);
}
@Override
public void create(Restaurant restaurant) {
List<Equipment> equipmentList = jpaEquipmentService.getAll();
for (Equipment e : equipmentList) {
restaurant.addEquipment(e);
}
List<RepairService> repairServiceList = jpaRepairService.getAll();
for(RepairService rs : repairServiceList) {
restaurant.addRepairService(rs);
}
restaurantRepository.save(restaurant);
}
@Override
public void delete(Long id) {
restaurantRepository.deleteById(id);
}
public void addEquipmentToRestaurant(Long equipmentId, Long restaurantID) {
Optional<Equipment> equipmentOptional = jpaEquipmentService.get(equipmentId);
Optional<Restaurant> restaurantOptional = restaurantRepository.findById(restaurantID);
if(restaurantOptional.isPresent() && equipmentOptional.isPresent()) {
Restaurant restaurant = restaurantOptional.get();
Equipment equipment = equipmentOptional.get();
restaurant.addEquipment(equipment);
restaurantRepository.save(restaurant);
} else {
throw new RuntimeException("Sprzęt z ID: " + equipmentId + " nie znaleziony");
}
}
public void deleteEquipmentFromRestaurant(Long equipmentId, Long restaurantID) {
Optional<Equipment> equipmentOptional = jpaEquipmentService.get(equipmentId);
Optional<Restaurant> restaurantOptional = restaurantRepository.findById(restaurantID);
if(restaurantOptional.isPresent() && equipmentOptional.isPresent()) {
Restaurant restaurant = restaurantOptional.get();
Equipment equipment = equipmentOptional.get();
restaurant.removeEquipment(equipment);
restaurantRepository.save(restaurant);
} else {
throw new RuntimeException("Sprzęt z ID: " + equipmentId + " nie znaleziony");
}
}
public void addRepairServiceToRestaurant(Long repairServiceId, Long restaurantId) {
Optional<RepairService> repairServiceOptional = jpaRepairService.get(repairServiceId);
Optional<Restaurant> restaurantOptional = restaurantRepository.findById(restaurantId);
if(repairServiceOptional.isPresent() && restaurantOptional.isPresent()) {
Restaurant restaurant = restaurantOptional.get();
RepairService repairService = repairServiceOptional.get();
restaurant.addRepairService(repairService);
restaurantRepository.save(restaurant);
} else {
throw new RuntimeException("Repair service z ID" + repairServiceId + " nie znaleziony");
}
}
public void deleteRepairServiceFromRestaurant(Long repairServiceId, Long restaurantId) {
Optional<RepairService> repairServiceOptional = jpaRepairService.get(repairServiceId);
Optional<Restaurant> restaurantOptional = restaurantRepository.findById(restaurantId);
if(repairServiceOptional.isPresent() && restaurantOptional.isPresent()) {
Restaurant restaurant = restaurantOptional.get();
RepairService repairService = repairServiceOptional.get();
restaurant.removeRepairService(repairService);
restaurantRepository.save(restaurant);
} else {
throw new RuntimeException("Repair service z ID" + repairServiceId + " nie znaleziony");
}
}
}
| EduardSynohub/Final_project | management_for_services/src/main/java/pl/coderslab/domain/restaurant/JpaRestaurantService.java |
180,323 | package com.example.trzewa.bandrider;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
public class ShowCategoriesActivity extends ActionBarActivity {
private static final String TAG = "DialogDemo";
private Context mContext;
final String[] choiceList =
{"Instrumenty", "Sprzęt" , "Akcesoria" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_show_categories);
showDialogButtonClick();
}
private int selected = 0;
private int buffKey = 0; // add buffer value
private void showDialogButtonClick() {
Log.i(TAG, "show Dialog ButtonClick");
AlertDialog.Builder builder =
new AlertDialog.Builder(mContext);
builder.setTitle("Wybierz kategorię");
builder.setSingleChoiceItems(
choiceList,
selected,
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,
int which) {
//set to buffKey instead of selected
//(when cancel not save to selected)
buffKey = which;
}
})
.setCancelable(false)
.setPositiveButton("Ok",
new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog,
int which) {
Log.d(TAG,"Which value="+which);
Log.d(TAG,"Selected value="+buffKey);
//set buff to selected
selected = buffKey;
Intent intent = new Intent(ShowCategoriesActivity.this, PlanRiderActivity.class);
intent.putExtra(Constans.CATEGORY_SELECTED, selected);
startActivity(intent);
// listView.setVisibility(View.VISIBLE);
}
}
)
.setNegativeButton("Anuluj",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
}
}
);
AlertDialog alert = builder.create();
alert.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_show_categories, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| trzewa/BandRider | app/src/main/java/com/example/trzewa/bandrider/ShowCategoriesActivity.java |
180,324 | package com.example.trzewa.bandrider;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.parse.FindCallback;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class PlanRiderActivity extends ListActivity {
private AlertDialog alertDialog;
private static final String TAG = "DialogDemo";
private Context mContext;
final String[] choiceList =
{"Instrumenty", "Sprzęt" , "Akcesoria" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Context context = getApplicationContext();
mContext = this;
final ArrayList<HashMap<String, String>> instrumentItems = new ArrayList<>();
final ArrayList<HashMap<String, String>> stuffItems = new ArrayList<>();
Intent intent = getIntent();
int selected = intent.getIntExtra(Constans.CATEGORY_SELECTED, 0);
boolean networkstate = Utilities.getConnectivityStatus(context);
if (networkstate) {
Toast.makeText(getApplicationContext(), "nawiazano połączenie", Toast.LENGTH_LONG).show();
switch(choiceList[selected]) {
case "Instrumenty":
Toast.makeText( mContext,"Select aaaa "+choiceList[selected],Toast.LENGTH_SHORT).show();
ParseQuery<ParseObject> queryInstruments = ParseQuery.getQuery("Instrument");
queryInstruments.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> instrumentList, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + instrumentList.size() + "instrumentów");
if(instrumentList.size() > 0)
{
for(int i=0;i<instrumentList.size();i++)
{
HashMap<String, String> map = new HashMap<>();
ParseObject ob = instrumentList.get(i);
map.put("nazwa_inst", ob.getString("name"));
map.put("kategoria_inst", ob.getString("category"));
map.put("wlasciciel_inst", ob.getString("owner"));
map.put("status_inst", ob.getString("Switchstatus"));
if((!ob.getString("Switchstatus").isEmpty()) && ob.getString("Switchstatus").equals("dostępny"))
{
instrumentItems.add(map);
Toast.makeText( mContext,map.get("nazwa_inst"),Toast.LENGTH_SHORT).show();
}
}
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
setContentView(R.layout.activity_plan_rider);
ListAdapter adapter = new SimpleAdapter(this, instrumentItems,
R.layout.item,
new String[]{"nazwa_inst", "wlasciciel_inst"}, new int[]{
R.id.nazwa, R.id.wlasciciel});
setListAdapter(adapter);
ListView w = getListView();
w.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CharSequence colors[] = new CharSequence[]{"wypożycz", "zobacz info"};
AlertDialog.Builder builder = new AlertDialog.Builder(PlanRiderActivity.this);
builder.setTitle("Co chcesz zrobić?");
builder.setItems(colors, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// obsługa kliknięcia
}
});
builder.show();
}
});
break;
case "Sprzęt":
Toast.makeText( mContext,"Select aaaa "+choiceList[selected],Toast.LENGTH_SHORT).show();
ParseQuery<ParseObject> queryStuff = ParseQuery.getQuery("Stuff");
queryStuff.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> stuffList, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + stuffList.size() );
if(stuffList.size() > 0)
{
for(int i=0;i<stuffList.size();i++)
{
HashMap<String, String> map = new HashMap<>();
ParseObject ob = stuffList.get(i);
map.put("nazwa_sprzet", ob.getString("name"));
map.put("kategoria_sprzet", ob.getString("category"));
map.put("wlasciciel_sprzet", ob.getString("owner"));
stuffItems.add(map);
Toast.makeText( mContext,map.get("nazwa_sprzet"),Toast.LENGTH_SHORT).show();
}
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
setContentView(R.layout.listviewstuff);
ListAdapter adapter_stuff = new SimpleAdapter(this, stuffItems,
R.layout.item,
new String[]{"nazwa_sprzet", "wlasciciel_sprzet"}, new int[]{
R.id.nazwa, R.id.wlasciciel});
setListAdapter(adapter_stuff);
break;
case "Akcesoria":
setContentView(R.layout.listviewaccesories);
Toast.makeText( mContext,"Select aaaa "+choiceList[selected],Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText( mContext,"brak danych - nieznana kategoria",Toast.LENGTH_SHORT).show();
startActivity(new Intent(PlanRiderActivity.this, ShowCategoriesActivity.class));
finish();
}
} else {
alertDialog = new AlertDialog.Builder(PlanRiderActivity.this)
.setTitle("Brak Internetu")
.setMessage("brak połączenia z siecią Internet")
.setNegativeButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
finish();
}
})
.create();
alertDialog.show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_plan_rider, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| trzewa/BandRider | app/src/main/java/com/example/trzewa/bandrider/PlanRiderActivity.java |
180,325 | package org.polsl.backend.service;
import org.polsl.backend.dto.PaginatedResult;
import org.polsl.backend.dto.computerset.ComputerSetDTO;
import org.polsl.backend.dto.computerset.ComputerSetListOutputDTO;
import org.polsl.backend.dto.history.HistoryDTO;
import org.polsl.backend.entity.Affiliation;
import org.polsl.backend.entity.AffiliationComputerSet;
import org.polsl.backend.entity.ComputerSet;
import org.polsl.backend.entity.ComputerSetHardware;
import org.polsl.backend.entity.ComputerSetSoftware;
import org.polsl.backend.entity.Hardware;
import org.polsl.backend.entity.Software;
import org.polsl.backend.exception.BadRequestException;
import org.polsl.backend.exception.NotFoundException;
import org.polsl.backend.repository.AffiliationComputerSetRepository;
import org.polsl.backend.repository.AffiliationRepository;
import org.polsl.backend.repository.ComputerSetHardwareRepository;
import org.polsl.backend.repository.ComputerSetRepository;
import org.polsl.backend.repository.ComputerSetSoftwareRepository;
import org.polsl.backend.repository.HardwareRepository;
import org.polsl.backend.repository.SoftwareRepository;
import org.polsl.backend.type.InventoryNumberEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Logika biznesowa zestawów komputerowych.
*/
@Service
public class ComputerSetService {
private final ComputerSetRepository computerSetRepository;
private final AffiliationComputerSetRepository affiliationComputerSetRepository;
private final ComputerSetHardwareRepository computerSetHardwareRepository;
private final ComputerSetSoftwareRepository computerSetSoftwareRepository;
private final AffiliationRepository affiliationRepository;
private final HardwareRepository hardwareRepository;
private final SoftwareRepository softwareRepository;
@Autowired
public ComputerSetService(ComputerSetRepository computerSetRepository,
AffiliationComputerSetRepository affiliationComputerSetRepository,
ComputerSetHardwareRepository computerSetHardwareRepository,
ComputerSetSoftwareRepository computerSetSoftwareRepository,
AffiliationRepository affiliationRepository,
HardwareRepository hardwareRepository,
SoftwareRepository softwareRepository) {
this.computerSetRepository = computerSetRepository;
this.affiliationComputerSetRepository = affiliationComputerSetRepository;
this.computerSetHardwareRepository = computerSetHardwareRepository;
this.computerSetSoftwareRepository = computerSetSoftwareRepository;
this.affiliationRepository = affiliationRepository;
this.hardwareRepository = hardwareRepository;
this.softwareRepository = softwareRepository;
}
public PaginatedResult<ComputerSetListOutputDTO> getAllComputerSets(Specification<ComputerSet> specification,
boolean withDeleted) {
final Specification<ComputerSet> resultSpecification = withDeleted
? specification
: ((Specification<ComputerSet>) (root, query, criteriaBuilder) -> criteriaBuilder.isNull(root.get("validTo")))
.and(specification);
Iterable<ComputerSet> computerSets = computerSetRepository.findAll(resultSpecification);
List<ComputerSetListOutputDTO> dtos = new ArrayList<>();
for (ComputerSet computerSet : computerSets) {
ComputerSetListOutputDTO dto = new ComputerSetListOutputDTO();
dto.setId(computerSet.getId());
dto.setDeleted(computerSet.getValidTo() != null);
dto.setName(computerSet.getName());
dto.setComputerSetInventoryNumber(computerSet.getInventoryNumber());
dto.setAffiliationName(getValidAffiliationName(computerSet));
dto.setHardwareInventoryNumbers(getValidHardwareInventoryNumbers(computerSet));
dto.setSoftwareInventoryNumbers(getValidSoftwareInventoryNumbers(computerSet));
dtos.add(dto);
}
PaginatedResult<ComputerSetListOutputDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
@Transactional
public void createComputerSet(ComputerSetDTO request) {
ComputerSet computerSet = new ComputerSet();
/* INVENTORY NUMBER */
if (request.getInventoryNumber() != null)
throw new BadRequestException("Zakaz ręcznego wprowadzania numeru inwentarzowego.");
String newInvNumb = InventoryNumberGenerator
.generateInventoryNumber(InventoryNumberEnum.COMPUTER_SET, computerSetRepository.count());
computerSet.setInventoryNumber(newInvNumb);
computerSet.setName(request.getName());
computerSetRepository.save(computerSet);
Affiliation affiliation = affiliationRepository.findByIdAndIsDeletedIsFalse(request.getAffiliationId())
.orElseThrow(() -> new NotFoundException("przynależność", "id", request.getAffiliationId()));
AffiliationComputerSet affiliationComputerSet = new AffiliationComputerSet(affiliation, computerSet);
affiliationComputerSetRepository.save(affiliationComputerSet);
if (request.getHardwareIds() != null) {
request.getHardwareIds().forEach(hardwareId -> {
Hardware hardware = hardwareRepository.findByIdAndValidToIsNull(hardwareId)
.orElseThrow(() -> new NotFoundException("sprzęt", "id", hardwareId));
ComputerSetHardware computerSetHardware = new ComputerSetHardware(computerSet, hardware);
computerSetHardwareRepository.save(computerSetHardware);
});
}
if (request.getSoftwareIds() != null) {
request.getSoftwareIds().forEach(softwareId -> {
Software software = softwareRepository.findByIdAndValidToIsNull(softwareId)
.orElseThrow(() -> new NotFoundException("oprogramowanie", "id", softwareId));
ComputerSetSoftware computerSetSoftware = new ComputerSetSoftware(computerSet, software);
computerSetSoftwareRepository.save(computerSetSoftware);
});
}
}
@Transactional
public void editComputerSet(Long id, ComputerSetDTO request) throws NotFoundException {
ComputerSet computerSet = computerSetRepository.findByIdAndValidToIsNull(id)
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", id));
computerSet.setName(request.getName());
computerSetRepository.save(computerSet);
Long requestAffiliationId = request.getAffiliationId();
Set<Long> requestHardwareIds = request.getHardwareIds();
Set<Long> requestSoftwareIds = request.getSoftwareIds();
Long currentAffiliationId = getCurrentAffiliationId(computerSet);
Set<Long> currentHardwareIds = getCurrentHardwareIds(computerSet);
Set<Long> currentSoftwareIds = getCurrentSoftwareIds(computerSet);
//----------------------------------------INVENTORY NB----------------------------------------
if (request.getInventoryNumber() != null) {
throw new BadRequestException("Zakaz ręcznego wprowadzania numeru inwentarzowego.");
}
//----------------------------------------AFFILIATION----------------------------------------
if (currentAffiliationId != requestAffiliationId) {
//NOWE POŁĄCZENIE
Affiliation newAffiliation = affiliationRepository.findByIdAndIsDeletedIsFalse(requestAffiliationId)
.orElseThrow(() -> new NotFoundException("afiliacja", "id", requestAffiliationId));
AffiliationComputerSet newAffiliationComputerSet = new AffiliationComputerSet(newAffiliation, computerSet);
affiliationComputerSetRepository.save(newAffiliationComputerSet);
//STARE POŁĄCZENIE
AffiliationComputerSet oldAffiliationComputerSet = affiliationComputerSetRepository
.findByAffiliationIdAndComputerSetIdAndValidToIsNull(currentAffiliationId, computerSet.getId());
oldAffiliationComputerSet.setValidTo(LocalDateTime.now());
}
//----------------------------------------HARDWARE----------------------------------------
//NOWE POŁĄCZENIE
requestHardwareIds.forEach(requestHardwareId -> {
if (!currentHardwareIds.contains(requestHardwareId)) {
Hardware newHardware = hardwareRepository.findByIdAndValidToIsNull(requestHardwareId)
.orElseThrow(() -> new NotFoundException("sprzęt", "id", requestHardwareId));
ComputerSetHardware newComputerSetHardware = new ComputerSetHardware(computerSet, newHardware);
computerSetHardwareRepository.save(newComputerSetHardware);
}
});
//STARE POŁĄCZENIE
currentHardwareIds.forEach(currentHardwareId -> {
if (!requestHardwareIds.contains(currentHardwareId)) {
ComputerSetHardware oldComputerSetHardware = computerSetHardwareRepository
.findByComputerSetIdAndHardwareIdAndValidToIsNull(computerSet.getId(), currentHardwareId);
oldComputerSetHardware.setValidTo(LocalDateTime.now());
}
});
//----------------------------------------SOFTWARE----------------------------------------
//NOWE POŁĄCZENIE
requestSoftwareIds.forEach(requestSoftwareId -> {
if (!currentSoftwareIds.contains(requestSoftwareId)) {
Software newSoftware = softwareRepository.findByIdAndValidToIsNull(requestSoftwareId)
.orElseThrow(() -> new NotFoundException("oprogramowanie", "id", requestSoftwareId));
ComputerSetSoftware newComputerSetSoftware = new ComputerSetSoftware(computerSet, newSoftware);
computerSetSoftwareRepository.save(newComputerSetSoftware);
}
});
//STARE POŁĄCZENIE
currentSoftwareIds.forEach(currentSoftwareId -> {
if (!requestSoftwareIds.contains(currentSoftwareId)) {
ComputerSetSoftware oldComputerSetSoftware = computerSetSoftwareRepository
.findByComputerSetIdAndSoftwareIdAndValidToIsNull(computerSet.getId(), currentSoftwareId);
oldComputerSetSoftware.setValidTo(LocalDateTime.now());
}
});
}
public void deleteComputerSet(Long id) throws NotFoundException {
ComputerSet computerSet = computerSetRepository.findByIdAndValidToIsNull(id)
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", id));
computerSet.setValidTo(LocalDateTime.now());
computerSetRepository.save(computerSet);
affiliationComputerSetRepository.findAllByComputerSetIdAndValidToIsNull(computerSet.getId()).forEach(relation -> {
relation.setValidTo(LocalDateTime.now());
affiliationComputerSetRepository.save(relation);
});
computerSetHardwareRepository.findAllByComputerSetIdAndValidToIsNull(computerSet.getId()).forEach(relation -> {
relation.setValidTo(LocalDateTime.now());
computerSetHardwareRepository.save(relation);
});
computerSetSoftwareRepository.findAllByComputerSetIdAndValidToIsNull(computerSet.getId()).forEach(relation -> {
relation.setValidTo(LocalDateTime.now());
computerSetSoftwareRepository.save(relation);
});
}
public ComputerSetDTO getOneComputerSet(Long id) {
ComputerSetDTO dto = new ComputerSetDTO();
Set<Long> hardwareIds = new HashSet<>();
Set<Long> softwareIds = new HashSet<>();
ComputerSet computerSet = computerSetRepository.findByIdAndValidToIsNull(id)
.orElseThrow(() -> new NotFoundException("zestaw", "id", id));
dto.setName(computerSet.getName());
dto.setInventoryNumber(computerSet.getInventoryNumber());
AffiliationComputerSet ac = affiliationComputerSetRepository.findByComputerSetIdAndValidToIsNull(id);
dto.setAffiliationId(ac.getAffiliation().getId());
Set<ComputerSetHardware> chs = computerSetHardwareRepository.findAllByComputerSetIdAndValidToIsNull(id);
if (chs != null) {
chs.forEach(ch -> {
hardwareIds.add(ch.getHardware().getId());
});
}
dto.setHardwareIds(hardwareIds);
Set<ComputerSetSoftware> css = computerSetSoftwareRepository.findAllByComputerSetIdAndValidToIsNull(id);
if (css != null) {
css.forEach(cs -> {
softwareIds.add(cs.getSoftware().getId());
});
}
dto.setSoftwareIds(softwareIds);
return dto;
}
public PaginatedResult<HistoryDTO> getComputerSetSoftwareHistory(Long computerSetId) {
List<HistoryDTO> dtos = new ArrayList<>();
ComputerSet cs = computerSetRepository.findById(computerSetId)
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", computerSetId));
Set<ComputerSetSoftware> computerSetSoftwareSet = cs.getComputerSetSoftwareSet();
computerSetSoftwareSet.forEach(computerSetSoftware -> {
HistoryDTO dto = new HistoryDTO();
dto.setInventoryNumber(computerSetSoftware.getSoftware().getInventoryNumber());
dto.setName(computerSetSoftware.getSoftware().getName());
dto.setValidFrom(computerSetSoftware.getValidFrom());
dto.setValidTo(computerSetSoftware.getValidTo());
dtos.add(dto);
});
PaginatedResult<HistoryDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
public PaginatedResult<HistoryDTO> getComputerSetHardwareHistory(Long computerSetId) {
List<HistoryDTO> dtos = new ArrayList<>();
ComputerSet cs = computerSetRepository.findById(computerSetId)
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", computerSetId));
Set<ComputerSetHardware> computerSetHardwareSet = cs.getComputerSetHardwareSet();
computerSetHardwareSet.forEach(computerSetHardware -> {
HistoryDTO dto = new HistoryDTO();
dto.setInventoryNumber(computerSetHardware.getHardware().getInventoryNumber());
dto.setName(computerSetHardware.getHardware().getName());
dto.setValidFrom(computerSetHardware.getValidFrom());
dto.setValidTo(computerSetHardware.getValidTo());
dtos.add(dto);
});
PaginatedResult<HistoryDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
public PaginatedResult<HistoryDTO> getComputerSetAffiliationsHistory(Long computerSetId) {
List<HistoryDTO> dtos = new ArrayList<>();
ComputerSet cs = computerSetRepository.findById(computerSetId)
.orElseThrow(() -> new NotFoundException("zestaw komputerowy", "id", computerSetId));
Set<AffiliationComputerSet> affiliationComputerSetSet = cs.getAffiliationComputerSetSet();
affiliationComputerSetSet.forEach(affiliationComputerSet -> {
HistoryDTO dto = new HistoryDTO();
dto.setName(AffiliationService.generateName(affiliationComputerSet.getAffiliation()));
dto.setValidFrom(affiliationComputerSet.getValidFrom());
dto.setValidTo(affiliationComputerSet.getValidTo());
dtos.add(dto);
});
PaginatedResult<HistoryDTO> response = new PaginatedResult<>();
response.setItems(dtos);
response.setTotalElements((long) dtos.size());
return response;
}
//region metodyPomocnicze
public Long getCurrentAffiliationId(ComputerSet cs) {
for (AffiliationComputerSet affiliationComputerSet : cs.getAffiliationComputerSetSet()) {
if (affiliationComputerSet.getValidTo() == null) {
return (affiliationComputerSet.getAffiliation()).getId();
}
}
return null;
}
public Set<Long> getCurrentHardwareIds(ComputerSet cs) {
Set<Long> ids = new HashSet<>();
cs.getComputerSetHardwareSet().forEach(computerSetHardware -> {
if (computerSetHardware.getValidTo() == null) {
ids.add(computerSetHardware.getHardware().getId());
}
});
return ids;
}
public Set<Long> getCurrentSoftwareIds(ComputerSet cs) {
Set<Long> ids = new HashSet<>();
cs.getComputerSetSoftwareSet().forEach(computerSetSoftware -> {
if (computerSetSoftware.getValidTo() == null) {
ids.add(computerSetSoftware.getSoftware().getId());
}
});
return ids;
}
public String getValidAffiliationName(ComputerSet cs) {
for (AffiliationComputerSet affiliationComputerSet : cs.getAffiliationComputerSetSet()) {
if (affiliationComputerSet.getValidTo() == null) {
return AffiliationService.generateName(affiliationComputerSet.getAffiliation());
}
}
return null;
}
public Set<String> getValidHardwareInventoryNumbers(ComputerSet cs) {
Set<String> inventoryNumbers = new HashSet<>();
cs.getComputerSetHardwareSet().forEach(computerSetHardware -> {
if (computerSetHardware.getValidTo() == null) {
inventoryNumbers.add(computerSetHardware.getHardware().getInventoryNumber());
}
});
return inventoryNumbers;
}
public Set<String> getValidSoftwareInventoryNumbers(ComputerSet cs) {
Set<String> inventoryNumbers = new HashSet<>();
cs.getComputerSetSoftwareSet().forEach(computerSetSoftware -> {
if (computerSetSoftware.getValidTo() == null) {
inventoryNumbers.add(computerSetSoftware.getSoftware().getInventoryNumber());
}
});
return inventoryNumbers;
}
//endregion
}
| Samograje/co-gdzie-kiedy | backend/src/main/java/org/polsl/backend/service/ComputerSetService.java |
180,327 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.filter.parameter;
import jakarta.inject.Inject;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import org.apache.commons.lang3.StringUtils;
import pl.polsl.skirentalservice.core.servlet.AbstractWebFilter;
import pl.polsl.skirentalservice.core.servlet.WebServletRequest;
import pl.polsl.skirentalservice.dto.AlertTupleDto;
import pl.polsl.skirentalservice.service.EquipmentService;
import pl.polsl.skirentalservice.util.SessionAlert;
import java.io.IOException;
@WebFilter(urlPatterns = {
"/owner/edit-equipment/*",
"/owner/delete-equipment/*",
"/owner/equipment-details/*",
"/seller/equipment-details/*",
"/seller/add-equipment-to-cart/*",
"/seller/delete-equipment-from-cart/*",
"/seller/edit-equipment-from-cart/*",
}, initParams = @WebInitParam(name = "mood", value = "awake"))
public class EquipmentIdNotExistFilter extends AbstractWebFilter {
private final EquipmentService equipmentService;
@Inject
public EquipmentIdNotExistFilter(EquipmentService equipmentService) {
this.equipmentService = equipmentService;
}
@Override
protected void doWebFilter(WebServletRequest req, FilterChain chain) throws IOException, ServletException {
final String equipmentId = req.getParameter("id");
final AlertTupleDto alert = new AlertTupleDto(true);
alert.setMessage("Szukany sprzęt narciarski nie istnieje.");
if (!StringUtils.isNumeric(equipmentId) || !equipmentService.checkIfEquipmentExist(Long.parseLong(equipmentId))) {
req.setSessionAttribute(SessionAlert.COMMON_EQUIPMENTS_PAGE_ALERT, alert);
req.sendRedirect("/" + req.getLoggedUserRole() + "/equipments");
return;
}
req.addAttribute("equipmentId", Long.parseLong(equipmentId));
continueRequest(req, chain);
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/filter/parameter/EquipmentIdNotExistFilter.java |
180,328 | package com.example.trzewa.bandrider;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.parse.ParseObject;
public class SummaryStuffActivity extends ActionBarActivity {
private AlertDialog alertDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary_stuff);
TextView Stuff_name = (TextView)findViewById(R.id.textView6);
TextView Stuff_owner = (TextView)findViewById(R.id.textView8);
TextView Stuff_category = (TextView)findViewById(R.id.textView9);
TextView Stuff_status = (TextView)findViewById(R.id.textView11);
Button SaveButton = (Button) findViewById(R.id.button2);
Button ReturnButton = (Button) findViewById(R.id.button);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
final String stuff_name = settings.getString(Constans.STUFF_NAME, "");
final String stuff_owner = settings.getString(Constans.STUFF_OWNER, "");
final String stuff_category = settings.getString(Constans.STUFF_CATEGORY, "");
final String stuff_status = settings.getString(Constans.STUFF_SWITCH_STATUS, "");
Stuff_name.setText("Nazwa: " + stuff_name);
Stuff_owner.setText("Właściciel: " + stuff_owner);
Stuff_category.setText("Kategoria :" + stuff_category);
Stuff_status.setText("Dostępność :" + stuff_status);
SaveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog = new AlertDialog.Builder(SummaryStuffActivity.this)
.setTitle("NIezapisane zmiany")
.setMessage("Istnieją niezapisane zmiany")
.setPositiveButton("Zapisz", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ParseObject Stuff = new ParseObject("Stuff");
Stuff.put(Constans.STUFF_NAME, stuff_name);
Stuff.put(Constans.STUFF_OWNER, stuff_owner);
Stuff.put(Constans.STUFF_CATEGORY, stuff_category);
Stuff.put(Constans.STUFF_SWITCH_STATUS, stuff_status);
Stuff.saveInBackground();
Intent Intent = new Intent(getApplicationContext(), ChoiceActivity.class);
Intent.putExtra("dane", "Sprzęt Zapisany");
startActivity(Intent);
}
})
.setNeutralButton("Cofnij", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("Anuluj", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.cancel();
}
})
.create();
alertDialog.show();
}
});
ReturnButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_summary_stuff, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| trzewa/BandRider | app/src/main/java/com/example/trzewa/bandrider/SummaryStuffActivity.java |
180,329 | package org.application.bwp.rentalskiequcrud.gui.manager;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import org.application.bwp.rentalskiequcrud.database.DatabaseService;
import org.application.bwp.rentalskiequcrud.database.DatabaseServiceImp;
import org.application.bwp.rentalskiequcrud.entity.Customer;
import org.application.bwp.rentalskiequcrud.entity.Reservation;
import org.application.bwp.rentalskiequcrud.entity.SkiEqu;
import org.application.bwp.rentalskiequcrud.entity.enums.Payment;
import org.application.bwp.rentalskiequcrud.entity.enums.Status;
import java.net.URL;
import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.ResourceBundle;
public class ManagerMainPageController implements Initializable {
// Buttons
@FXML
private Button addCustomerButton;
@FXML
private Button dropBbButton;
@FXML
private Button equAddButton;
@FXML
private Button equRefreshListButton;
@FXML
private Button equRemoveItemButton;
@FXML
private Button equUpdateButton;
@FXML
private Button initDbButton;
@FXML
private Button loadSaveDbButton;
@FXML
private Button refreshCustomersListButton;
@FXML
private Button removeCustomerButton;
@FXML
private Button saveDbButton;
@FXML
private Button updateCustomerDataButton;
@FXML
private Button refreshReservationListButton;
@FXML
private Button reservationRemoveButton;
@FXML
private Button reservationUpdateButton;
@FXML
private Button reservationAddButton;
// TableColumns
//Customer
@FXML
private TableColumn<Customer, Integer> customerIdTable;
@FXML
private TableColumn<Customer, String> customerNameTable;
//SkiEqu
@FXML
private TableColumn<SkiEqu, Integer> equIdTable;
@FXML
private TableColumn<SkiEqu, String> equRodzajTable;
@FXML
private TableColumn<SkiEqu, Status> equStatusTable;
@FXML
private TableColumn<SkiEqu, Integer> skiEquDimTable;
//Reservation
@FXML
private TableColumn<Reservation, Integer> reservationIdTable;
@FXML
private TableColumn<Reservation, Integer> reservationCustomerIdTable;
@FXML
private TableColumn<Reservation, Integer> resevationEquIdTable;
@FXML
private TableColumn<Reservation, LocalDate> reservationDateStartTable;
@FXML
private TableColumn<Reservation, LocalDate> reservationDateEndTable;
@FXML
private TableColumn<Reservation, String> resevationStatusTable;
@FXML
private TableColumn<Reservation, String> reservationPaymetStatusTable;
// TextFields
@FXML
private TextField customerSearchBar;
@FXML
private TextField equAddRodzajTextField;
@FXML
private TextField equRodzajTextField;
@FXML
private TextField equSearchBar;
@FXML
private TextField loginAddCustomerTextFiled;
@FXML
private TextField loginCustomerTextField;
@FXML
private TextField equDimUpdateTextFiled;
@FXML
private TextField equDimAddTextFiled;
@FXML
private TextField reservationSearchBar;
@FXML
private TextField reservarionAddCustomerIDTextField;
@FXML
private TextField reservationAddSkiEquIDTextField;
// PasswordFields
@FXML
private PasswordField passwordAddCustomerTextField;
@FXML
private PasswordField passwordCustomerTextField;
// ComboBoxes
@FXML
private ComboBox<String> statusAddEquComboBox;
@FXML
private ComboBox<String> statusComboBox;
@FXML
private ComboBox<String> statusUpdateComboBox;
@FXML
private ComboBox<String> reservationStatusSearchComboBox;
@FXML
private ComboBox<String> reservationPaymentSearchComboBox;
@FXML
private ComboBox<String> reservationStatusUpdateComboBox;
@FXML
private ComboBox<String> reservationPaymentUpdateComboBox;
@FXML
private ComboBox<String> reservationStatusAddComboBox;
@FXML
private ComboBox<String> reservationPaymentAddComboBox;
// Tabs
@FXML
private Tab customersTab;
@FXML
private Tab magazineTab;
@FXML
private Tab reservationTab;
// TableViews
@FXML
private TableView<Customer> customersTable;
@FXML
private TableView<SkiEqu> magazineTable;
@FXML
private TableView<Reservation> reservationTable;
// ImageView
@FXML
private ImageView logoImageView;
//DatePickers
@FXML
private DatePicker reservationDateStartSearch;
@FXML
private DatePicker reservationDateEndSearch;
@FXML
private DatePicker reservationDateStartUpdate;
@FXML
private DatePicker reservationDateEndUpdate;
@FXML
private DatePicker reservationDateStartAdd;
@FXML
private DatePicker reservationDateEndAdd;
private final DatabaseService databaseService = DatabaseServiceImp.getInstance();
private final ObservableList<Customer> customerObservableList = FXCollections.observableArrayList();
private final ObservableList<SkiEqu> skiEquObservableList = FXCollections.observableArrayList();
private final ObservableList<Reservation> reservationObservableList = FXCollections.observableArrayList();
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
//main page initialization
init();
loadLogo();
//db initialization
initDb();
loadSaveDb();
saveDb();
dropDb();
//customers tab
loadDataToTableCustomers();
removeCustomer();
updateCustomerData();
addCustomer();
//ski equ tab
prepareSkiComboBox(statusComboBox);
prepareSkiComboBox(statusAddEquComboBox);
prepareSkiComboBox(statusUpdateComboBox);
loadDataToTableSki();
addSkiEqu();
removeSkiEqu();
updateSkiEqu();
//reservation tab
preparePaymentComboBox(reservationPaymentSearchComboBox);
prepareReservationStatusComboBox(reservationStatusSearchComboBox);
preparePaymentComboBox(reservationPaymentUpdateComboBox);
prepareReservationStatusComboBox(reservationStatusUpdateComboBox);
preparePaymentComboBox(reservationPaymentAddComboBox);
prepareReservationStatusComboBox(reservationStatusAddComboBox);
loadDataToTableReservation();
reservationRemove();
updateReservation();
addReservation();
}
//main page and db initialization
//-------------------------------------------------------------------------------------------------------------
private void init() {
if (databaseService.checkIfDatabaseExist()) {
magazineTab.setDisable(false);
reservationTab.setDisable(false);
customersTab.setDisable(false);
initDbButton.setDisable(true);
magazineTab.setDisable(false);
reservationTab.setDisable(false);
customersTab.setDisable(false);
prepareCustomerData();
prepareSkiData();
prepareReservationData();
return;
}
magazineTab.setDisable(true);
reservationTab.setDisable(true);
customersTab.setDisable(true);
}
private void initDb() {
initDbButton.setOnAction(event -> {
databaseService.createDatabase();
initDbButton.setDisable(true);
databaseService.createSkiTable();
databaseService.createCustomerTable();
databaseService.createReservationTable();
magazineTab.setDisable(false);
reservationTab.setDisable(false);
customersTab.setDisable(false);
});
}
private void loadSaveDb() {
loadSaveDbButton.setOnAction(event -> {
databaseService.insertSkiData();
databaseService.insertCustomerData();
databaseService.insertReservationData();
prepareCustomerData();
prepareSkiData();
prepareReservationData();
});
}
private void saveDb() {
saveDbButton.setOnAction(event -> {
databaseService.saveSkiDataToFile();
databaseService.saveCustomerDataToFile();
databaseService.saveReservationDataToFile();
});
}
private void dropDb() {
dropBbButton.setOnAction(event -> {
databaseService.dropDatabase();
initDbButton.setDisable(false);
init();
});
}
private void loadLogo() {
try{
logoImageView.setImage(new Image(Objects.requireNonNull(getClass().getResource("/org/application/bwp/rentalskiequcrud/images/skiImage.jpg")).toString()));
} catch (NullPointerException e) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błąd ładowania pliku");
alert.setContentText("Sprawdź pliki aplikacji " + e.getMessage());
alert.showAndWait();
}
}
//customers tab
//-------------------------------------------------------------------------------------------------------------
private void loadDataToTableCustomers() {
refreshCustomersListButton.setOnAction(event -> prepareCustomerData());
}
private void prepareCustomerData() {
if (!customerObservableList.isEmpty()) customerObservableList.clear();
List<Customer> customers = databaseService.selectAllCustomer();
customerObservableList.addAll(customers);
customerIdTable.setCellValueFactory(new PropertyValueFactory<>("id"));
customerNameTable.setCellValueFactory(new PropertyValueFactory<>("nazwa"));
FilteredList<Customer> filteredData = new FilteredList<>(customerObservableList, p -> true);
customerSearchBar.textProperty().addListener((observable, oldValue, newValue) -> customerUpdateFilter(filteredData));
SortedList<Customer> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(customersTable.comparatorProperty());
customersTable.setItems(sortedData);
}
private void customerUpdateFilter(FilteredList<Customer> filteredData) {
String filter = customerSearchBar.getText();
filteredData.setPredicate(customer -> {
if (customer == null) {
return false;
}
return isMatchesSearchCustomer(customer, filter);
});
}
private boolean isMatchesSearchCustomer(Customer customer, String searchText) {
boolean matchesSearch = true;
if (searchText != null && !searchText.isBlank()) {
boolean paramNameMatches = customer.getNazwa().toLowerCase().contains(searchText.toLowerCase());
boolean paramIdMatches = Integer.toString(customer.getId()).contains(searchText);
matchesSearch = paramNameMatches || paramIdMatches;
}
return matchesSearch;
}
private void removeCustomer() {
removeCustomerButton.setOnAction(event -> {
Customer customer = customersTable.getSelectionModel().getSelectedItem();
if (customer != null) {
databaseService.deleteCustomer(customer.getId());
customerObservableList.remove(customer);
}
});
}
private void updateCustomerData() {
updateCustomerDataButton.setOnAction(event -> {
Customer customer = customersTable.getSelectionModel().getSelectedItem();
if (customer != null) {
String login = (loginCustomerTextField == null || loginCustomerTextField.getText().isBlank()) ? customer.getNazwa() : loginCustomerTextField.getText();
String password = (passwordCustomerTextField == null || passwordCustomerTextField.getText().isBlank()) ? customer.getPassword() : passwordCustomerTextField.getText();
Customer updatedCustomer = new Customer()
.setId(customer.getId())
.setNazwa(login)
.setPassword(password)
.build();
if (databaseService.updateCustomer(updatedCustomer)) {
prepareCustomerData();
loginCustomerTextField.clear();
passwordCustomerTextField.clear();
}
}
});
}
private void addCustomer() {
addCustomerButton.setOnAction(event -> {
String login = loginAddCustomerTextFiled.getText();
String password = passwordAddCustomerTextField.getText();
if (login == null || password == null || login.isBlank() || password.isBlank()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Puste pole");
alert.setContentText("Wypełnij wszystkie pola");
alert.showAndWait();
return;
}
Customer customer = new Customer()
.setNazwa(login)
.setPassword(password)
.build();
if (databaseService.insertCustomer(customer)) {
prepareCustomerData();
loginAddCustomerTextFiled.clear();
passwordAddCustomerTextField.clear();
}
});
}
//ski equ tab
//-------------------------------------------------------------------------------------------------------------
private void loadDataToTableSki() {
equRefreshListButton.setOnAction(event -> prepareSkiData());
}
private void prepareSkiComboBox(ComboBox<String> comboBox) {
comboBox.getItems().add("Select status");
comboBox.getItems().add(Status.DOSTEPNE.toString());
comboBox.getItems().add(Status.NIEDOSTEPNE.toString());
}
private void prepareSkiData() {
databaseService.updateSkiEquStatusBasedOnReservation();
if (!skiEquObservableList.isEmpty()) skiEquObservableList.clear();
List<SkiEqu> skiEqus = databaseService.selectAllSki();
skiEquObservableList.addAll(skiEqus);
equIdTable.setCellValueFactory(new PropertyValueFactory<>("id"));
equRodzajTable.setCellValueFactory(new PropertyValueFactory<>("rodzaj"));
equStatusTable.setCellValueFactory(new PropertyValueFactory<>("status"));
skiEquDimTable.setCellValueFactory(new PropertyValueFactory<>("dlugosc"));
FilteredList<SkiEqu> filteredData = new FilteredList<>(skiEquObservableList, p -> true);
equSearchBar.textProperty().addListener((observable, oldValue, newValue) -> skiUpdateFilter(filteredData));
statusComboBox.valueProperty().addListener((observable, oldValue, newValue) -> skiUpdateFilter(filteredData));
SortedList<SkiEqu> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(magazineTable.comparatorProperty());
magazineTable.setItems(sortedData);
}
private void skiUpdateFilter(FilteredList<SkiEqu> filteredData) {
String filter = equSearchBar.getText();
String statusFilter = statusComboBox.getValue();
filteredData.setPredicate(ski -> {
if (ski == null) {
return false;
}
return isMatchesSearchSki(ski, filter) && isMatchesStatusSki(ski, statusFilter);
});
}
private boolean isMatchesSearchSki(SkiEqu skiEqu, String filter) {
boolean matchesSearch = true;
if (filter != null && !filter.isBlank()) {
boolean paramRodzajMatches = skiEqu.getRodzaj().toLowerCase().contains(filter.toLowerCase());
boolean paramIdMatches = Integer.toString(skiEqu.getId()).contains(filter);
boolean paramDlugoscMatches = Integer.toString(skiEqu.getDlugosc()).contains(filter);
matchesSearch = paramRodzajMatches || paramIdMatches || paramDlugoscMatches;
}
return matchesSearch;
}
private boolean isMatchesStatusSki(SkiEqu skiEqu, String statusFilter) {
return statusFilter == null || statusFilter.isBlank() || statusFilter.equals("Select status") || skiEqu.getStatus().toString().equals(statusFilter);
}
private void addSkiEqu() {
equAddButton.setOnAction(event -> {
String rodzaj = equAddRodzajTextField.getText();
String status = statusAddEquComboBox.getValue();
String dlugosc = equDimAddTextFiled.getText();
if (rodzaj == null || rodzaj.isBlank()
|| status == null || status.isBlank()
|| status.equals("Select status")
|| dlugosc == null || dlugosc.isBlank()) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Puste pole");
alert.setContentText("Wypełnij wszystkie pola");
alert.showAndWait();
return;
}
try {
int dlugoscInt = Integer.parseInt(dlugosc);
SkiEqu skiEqu = new SkiEqu()
.setRodzaj(rodzaj)
.setStatus(Status.valueOf(status))
.setDlugosc(dlugoscInt)
.build();
if (!databaseService.insertSki(skiEqu)) return;
prepareSkiData();
equAddRodzajTextField.clear();
statusAddEquComboBox.setValue("Select status");
equDimAddTextFiled.clear();
} catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna wartość");
alert.setContentText("Wprowadź poprawną wartość długości");
alert.showAndWait();
}
});
}
private void removeSkiEqu() {
equRemoveItemButton.setOnAction(event -> {
SkiEqu skiEqu = magazineTable.getSelectionModel().getSelectedItem();
if (skiEqu != null) {
databaseService.deleteSki(skiEqu.getId());
skiEquObservableList.remove(skiEqu);
}
});
}
private void updateSkiEqu() {
equUpdateButton.setOnAction(event -> {
SkiEqu skiEqu = magazineTable.getSelectionModel().getSelectedItem();
if (skiEqu != null) {
String rodzaj = equRodzajTextField.getText().isBlank() ? skiEqu.getRodzaj() : equRodzajTextField.getText();
Status status = (statusUpdateComboBox.getValue() == null || statusUpdateComboBox.getValue().equals("Select status")) ? skiEqu.getStatus() : Status.valueOf(statusUpdateComboBox.getValue());
int dlugoscInt;
try {
dlugoscInt = equDimUpdateTextFiled.getText().isBlank() ? skiEqu.getDlugosc() : Integer.parseInt(equDimUpdateTextFiled.getText());
} catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna wartość");
alert.setContentText("Wprowadź poprawną wartość");
alert.showAndWait();
return;
}
SkiEqu updatedSkiEqu = new SkiEqu()
.setId(skiEqu.getId())
.setRodzaj(rodzaj)
.setStatus(status)
.setDlugosc(dlugoscInt)
.build();
if (databaseService.updateSki(updatedSkiEqu)) {
prepareSkiData();
equRodzajTextField.clear();
equDimUpdateTextFiled.clear();
statusUpdateComboBox.setValue("Select status");
}
}
});
}
//reservation tab
//-------------------------------------------------------------------------------------------------------------
private void loadDataToTableReservation() {
refreshReservationListButton.setOnAction(event -> prepareReservationData());
}
private void preparePaymentComboBox(ComboBox<String> comboBox) {
comboBox.getItems().add("Select status");
comboBox.getItems().add(Payment.OPLACONA.toString());
comboBox.getItems().add(Payment.NIEOPLACONA.toString());
}
private void prepareReservationStatusComboBox(ComboBox<String> comboBox) {
comboBox.getItems().add("Select status");
comboBox.getItems().add(Status.ZAKONCZONA.toString());
comboBox.getItems().add(Status.WYCOFANA.toString());
comboBox.getItems().add(Status.ROZPOCZETA.toString());
comboBox.getItems().add(Status.ZALOZONA.toString());
}
private void prepareReservationData() {
databaseService.updateSkiEquStatusBasedOnReservation();
if (!reservationObservableList.isEmpty()) reservationObservableList.clear();
List<Reservation> reservations = databaseService.selectAllReservation();
reservationObservableList.addAll(reservations);
reservationIdTable.setCellValueFactory(new PropertyValueFactory<>("id"));
reservationCustomerIdTable.setCellValueFactory(new PropertyValueFactory<>("id_klient"));
resevationEquIdTable.setCellValueFactory(new PropertyValueFactory<>("id_narty"));
reservationDateStartTable.setCellValueFactory(new PropertyValueFactory<>("data_poczatkowa"));
reservationDateEndTable.setCellValueFactory(new PropertyValueFactory<>("data_koncowa"));
resevationStatusTable.setCellValueFactory(new PropertyValueFactory<>("status"));
reservationPaymetStatusTable.setCellValueFactory(new PropertyValueFactory<>("platnosc"));
FilteredList<Reservation> filteredData = new FilteredList<>(reservationObservableList, p -> true);
reservationSearchBar.textProperty().addListener((observable, oldValue, newValue) -> reservationUpdateFilter(filteredData));
reservationStatusSearchComboBox.valueProperty().addListener((observable, oldValue, newValue) -> reservationUpdateFilter(filteredData));
reservationPaymentSearchComboBox.valueProperty().addListener((observable, oldValue, newValue) -> reservationUpdateFilter(filteredData));
reservationDateStartSearch.valueProperty().addListener((observable, oldValue, newValue) -> reservationUpdateFilter(filteredData));
reservationDateEndSearch.valueProperty().addListener((observable, oldValue, newValue) -> reservationUpdateFilter(filteredData));
SortedList<Reservation> sortedData = new SortedList<>(filteredData);
sortedData.comparatorProperty().bind(reservationTable.comparatorProperty());
reservationTable.setItems(sortedData);
}
private void reservationUpdateFilter(FilteredList<Reservation> filteredData) {
String filter = reservationSearchBar.getText();
String statusFilter = reservationStatusSearchComboBox.getValue();
String paymentFilter = reservationPaymentSearchComboBox.getValue();
LocalDate dateStartFilter = reservationDateStartSearch.getValue();
LocalDate dateEndFilter = reservationDateEndSearch.getValue();
filteredData.setPredicate(reservation -> {
if (reservation == null) {
return false;
}
return isMatchesSearchReservation(reservation, filter) && isMatchesStatusReservation(reservation, statusFilter)
&& isMatchesPaymentReservation(reservation, paymentFilter)
&& isMatchesDateReservation(reservation, dateStartFilter, dateEndFilter);
});
}
private boolean isMatchesDateReservation(Reservation reservation, LocalDate dateStartFilter, LocalDate dateEndFilter) {
boolean matchesSearch = true;
if (dateStartFilter != null && dateEndFilter != null) {
matchesSearch = reservation.getData_poczatkowa().isAfter(dateStartFilter) && reservation.getData_koncowa().isBefore(dateEndFilter);
}
return matchesSearch;
}
private boolean isMatchesPaymentReservation(Reservation reservation, String paymentFilter) {
boolean matchesSearch = true;
if (paymentFilter != null && !paymentFilter.isBlank() && !paymentFilter.equals("Select status")) {
matchesSearch = reservation.getPlatnosc().toString().equals(paymentFilter);
}
return matchesSearch;
}
private boolean isMatchesStatusReservation(Reservation reservation, String statusFilter) {
boolean matchesSearch = true;
if (statusFilter != null && !statusFilter.isBlank() && !statusFilter.equals("Select status")) {
matchesSearch = reservation.getStatus().toString().equals(statusFilter);
}
return matchesSearch;
}
private boolean isMatchesSearchReservation(Reservation reservation, String filter) {
boolean matchesSearch = true;
if (filter != null && !filter.isBlank()) {
boolean paramIdMatches = Integer.toString(reservation.getId()).contains(filter);
boolean paramCustomerIdMatches = Integer.toString(reservation.getId_klient()).contains(filter);
boolean paramEquIdMatches = Integer.toString(reservation.getId_narty()).contains(filter);
matchesSearch = paramIdMatches || paramCustomerIdMatches || paramEquIdMatches;
}
return matchesSearch;
}
private void reservationRemove() {
reservationRemoveButton.setOnAction(event -> {
Reservation reservation = reservationTable.getSelectionModel().getSelectedItem();
if (reservation != null) {
databaseService.deleteReservation(reservation.getId());
reservationObservableList.remove(reservation);
}
});
}
private void updateReservation() {
reservationUpdateButton.setOnAction(event -> {
Reservation reservation = reservationTable.getSelectionModel().getSelectedItem();
if (reservation != null) {
int customerId = reservation.getId_klient();
int equId = reservation.getId_narty();
LocalDate dateStart = (reservationDateStartUpdate.getValue() == null) ? reservation.getData_poczatkowa() : reservationDateStartUpdate.getValue();
LocalDate dateEnd = (reservationDateEndUpdate.getValue() == null) ? reservation.getData_koncowa() : reservationDateEndUpdate.getValue();
if(dateStart.isBefore(LocalDate.now()) || dateEnd.isBefore(LocalDate.now())) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna data");
alert.setContentText("Data początkowa i końcowa nie może być wcześniejsza niż dzisiejsza data");
alert.showAndWait();
return;
}
if (dateStart.isAfter(dateEnd) || dateStart.isEqual(dateEnd) || dateEnd.isBefore(dateStart) || dateEnd.isEqual(dateStart)) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna data");
alert.setContentText("Data początkowa nie może być późniejsza niż data końcowa");
alert.showAndWait();
return;
}
Status status = (reservationStatusUpdateComboBox.getValue() == null || reservationStatusUpdateComboBox.getValue().equals("Select status")) ? reservation.getStatus() : Status.valueOf(reservationStatusUpdateComboBox.getValue());
Payment payment = (reservationPaymentUpdateComboBox.getValue() == null || reservationPaymentUpdateComboBox.getValue().equals("Select status")) ? reservation.getPlatnosc() : Payment.valueOf(reservationPaymentUpdateComboBox.getValue());
Reservation updatedReservation = new Reservation()
.setId(reservation.getId())
.setId_klient(customerId)
.setId_narty(equId)
.setData_poczatkowa(dateStart)
.setData_koncowa(dateEnd)
.setStatus(status)
.setPlatnosc(payment)
.build();
if (databaseService.updateReservation(updatedReservation)) {
prepareReservationData();
reservationDateStartUpdate.getEditor().clear();
reservationDateEndUpdate.getEditor().clear();
reservationStatusUpdateComboBox.setValue("Select status");
reservationPaymentUpdateComboBox.setValue("Select status");
}
}
});
}
private void addReservation() {
reservationAddButton.setOnAction(event -> {
LocalDate dateStart = reservationDateStartAdd.getValue();
LocalDate dateEnd = reservationDateEndAdd.getValue();
if (dateStart == null || dateEnd == null
||dateStart.isAfter(dateEnd)
|| dateStart.isEqual(dateEnd)
|| dateEnd.isBefore(dateStart)
|| dateEnd.isEqual(dateStart)) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna data");
alert.setContentText("Data początkowa nie może być późniejsza niż data końcowa");
alert.showAndWait();
return;
}
if(dateStart.isBefore(LocalDate.now()) || dateEnd.isBefore(LocalDate.now())) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna data");
alert.setContentText("Data początkowa i końcowa nie może być wcześniejsza niż dzisiejsza data");
alert.showAndWait();
return;
}
int customerId;
try {
customerId = Integer.parseInt(reservarionAddCustomerIDTextField.getText());
} catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna wartość");
alert.setContentText("Wprowadź poprawną wartość dla ID klienta");
alert.showAndWait();
return;
}
int equId;
try {
equId = Integer.parseInt(reservationAddSkiEquIDTextField.getText());
} catch (NumberFormatException e) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna wartość");
alert.setContentText("Wprowadź poprawną wartość dla ID sprzętu");
alert.showAndWait();
return;
}
if(reservationStatusAddComboBox == null || reservationStatusAddComboBox.getValue() == null || reservationStatusAddComboBox.getValue().equals("Select status")
|| reservationPaymentAddComboBox == null || reservationPaymentAddComboBox.getValue() == null || reservationPaymentAddComboBox.getValue().equals("Select status")) {
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Błąd");
alert.setHeaderText("Błędna wartość");
alert.setContentText("Wprowadź poprawną wartość");
alert.showAndWait();
return;
}
Status status = Status.valueOf(reservationStatusAddComboBox.getValue());
Payment payment = Payment.valueOf(reservationPaymentAddComboBox.getValue());
Reservation reservation = new Reservation()
.setId_klient(customerId)
.setId_narty(equId)
.setData_poczatkowa(dateStart)
.setData_koncowa(dateEnd)
.setStatus(status)
.setPlatnosc(payment)
.build();
if (databaseService.insertReservation(reservation)) {
prepareReservationData();
reservationAddSkiEquIDTextField.clear();
reservarionAddCustomerIDTextField.clear();
reservationDateStartAdd.getEditor().clear();
reservationDateEndAdd.getEditor().clear();
}
});
}
} | Golec5000/Projects-BWP | RentalSkiEquCRUD/src/main/java/org/application/bwp/rentalskiequcrud/gui/manager/ManagerMainPageController.java |
180,331 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.domain.owner.equipment;
import jakarta.inject.Inject;
import jakarta.servlet.annotation.WebServlet;
import lombok.extern.slf4j.Slf4j;
import pl.polsl.skirentalservice.core.AbstractAppException;
import pl.polsl.skirentalservice.core.ServerConfigBean;
import pl.polsl.skirentalservice.core.servlet.AbstractWebServlet;
import pl.polsl.skirentalservice.core.servlet.HttpMethodMode;
import pl.polsl.skirentalservice.core.servlet.WebServletRequest;
import pl.polsl.skirentalservice.core.servlet.WebServletResponse;
import pl.polsl.skirentalservice.dto.AlertTupleDto;
import pl.polsl.skirentalservice.dto.login.LoggedUserDataDto;
import pl.polsl.skirentalservice.service.EquipmentService;
import pl.polsl.skirentalservice.util.AlertType;
import pl.polsl.skirentalservice.util.SessionAlert;
@Slf4j
@WebServlet("/owner/delete-equipment")
public class OwnerDeleteEquipmentServlet extends AbstractWebServlet {
private final EquipmentService equipmentService;
@Inject
public OwnerDeleteEquipmentServlet(
EquipmentService equipmentService,
ServerConfigBean serverConfigBean
) {
super(serverConfigBean);
this.equipmentService = equipmentService;
}
@Override
protected WebServletResponse httpGetCall(WebServletRequest req) {
final Long equipmentId = req.getAttribute("equipmentId", Long.class);
final LoggedUserDataDto loggedUser = req.getLoggedUser();
final AlertTupleDto alert = new AlertTupleDto(true);
try {
equipmentService.deleteEquipment(equipmentId, loggedUser);
alert.setType(AlertType.INFO);
alert.setMessage(
"Pomyślnie usunięto sprzęt narciarski z ID <strong>#" + equipmentId + "</strong> z systemu."
);
} catch (AbstractAppException ex) {
alert.setMessage(ex.getMessage());
log.error("Unable to remove equipment with id: {}. Cause: {}", equipmentId, ex.getMessage());
}
req.setSessionAttribute(SessionAlert.COMMON_EQUIPMENTS_PAGE_ALERT, alert);
return WebServletResponse.builder()
.mode(HttpMethodMode.REDIRECT)
.pageOrRedirectTo("owner/equipments")
.build();
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/domain/owner/equipment/OwnerDeleteEquipmentServlet.java |
180,333 | package client.controller;
import client.TCPClientFX;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import server.*;
import java.util.*;
public class ManagerController {
private TCPClientFX tcpClientFX;
private Employee employee;
private List<Order> orders;
private List<Task> tasks;
private List<Employee> employees;
private List<Equipment> equipmentList;
@FXML
private Label name;
@FXML
private Label lastName;
@FXML
private Label role;
@FXML
private Label zone;
@FXML
private TabPane tabPane;
List<String> taskCategories;
List<String> equipmentCategories;
List<License> licenseList;
List<String> zoneList;
public ManagerController(TCPClientFX tcpClientFX, Employee employee, List<Order> orders, List<Task> tasks,
List<Employee> employees, List<Equipment> equipmentList,List<String> taskCategories,
List<String> equipmentCategories,List<License> licenseList, List<String> zoneList) {
this.tcpClientFX = tcpClientFX;
this.employee = employee;
this.orders = orders;
this.tasks = tasks;
this.employees = employees;
this.equipmentList=equipmentList;
this.taskCategories=taskCategories;
this.equipmentCategories=equipmentCategories;
this.licenseList=licenseList;
this.zoneList=zoneList;
}
@FXML
private void initialize() {
name.setText("Name: " + employee.getName());
lastName.setText("Last name: " + employee.getLastName());
role.setText("Role: " + employee.getRole());
zone.setText("Zone: " + employee.getZone());
// Dodajemy zakładki i ich zawartość
addOrdersTab();
addTasksTab(tasks);
addEmployeesTab(employees);
addEquipmentsTab(equipmentList);
addOther();
}
private void addOther() {
Tab otherTab = new Tab("Other");
// Napis: Dodaj kategorię zadania
Label taskCategoryLabel = new Label("Add task category:");
taskCategoryLabel.getStyleClass().add("textInfo2");
taskCategoryLabel.setMinWidth(100);
TextField taskCategoryTextField = new TextField();
Button addTaskCategoryButton = new Button("Add");
addTaskCategoryButton.setOnAction(actionEvent -> {
tcpClientFX.addTaskCategory(taskCategoryTextField.getText());
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("Added");
alert.showAndWait();
});
// Napis: dodaj licencje do kategorii
Label licenseLabel = new Label("Add license to categoty:");
licenseLabel.getStyleClass().add("textInfo2");
licenseLabel.setMinWidth(100);
ObservableList<String> licenseOptions = FXCollections.observableArrayList();
licenseList.forEach(license -> licenseOptions.add(license.getName()));
ObservableList<String> taskCategoryOptions = FXCollections.observableArrayList();
taskCategoryOptions.addAll(taskCategories);
ComboBox<String> licenseComboBox1 = new ComboBox<>(taskCategoryOptions);
licenseComboBox1.setMinWidth(170);
ComboBox<String> licenseComboBox2 = new ComboBox<>(licenseOptions);
licenseComboBox2.setMinWidth(170);
Button addLicenseButton = new Button("Add");
addLicenseButton.setOnAction(actionEvent -> {
tcpClientFX.addLicenseToTaskCategory(licenseComboBox1.getValue(), licenseComboBox2.getValue());
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("Added");
alert.showAndWait();
});
// Napis: dodaj sprzęt do kategorii zadania
Label equipmentLabel = new Label("Add equipment to category:");
equipmentLabel.setMinWidth(100);
equipmentLabel.getStyleClass().add("textInfo2");
ObservableList<String> equipmentOptions = FXCollections.observableArrayList();
equipmentOptions.addAll(equipmentCategories);
ComboBox<String> equipmentComboBox1 = new ComboBox<>(taskCategoryOptions);
equipmentComboBox1.setMinWidth(170);
ComboBox<String> equipmentComboBox2 = new ComboBox<>(equipmentOptions);
equipmentComboBox2.setMinWidth(170);
Button addEquipmentButton = new Button("Add");
addEquipmentButton.setOnAction(actionEvent -> {
tcpClientFX.addEquipmentToTaskCategory(equipmentComboBox1.getValue(),equipmentComboBox2.getValue());
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("Added");
alert.showAndWait();
});
// Napis: Add new equipment
Label newEquipmentLabel = new Label("Add new equipment:");
newEquipmentLabel.getStyleClass().add("textInfo2");
newEquipmentLabel.setMinWidth(100);
ObservableList<String> statusOptions = FXCollections.observableArrayList("available","out of use");
ObservableList<String> zoneOptions = FXCollections.observableArrayList();
zoneOptions.addAll(zoneList);
TextField newEquipmentTextField = new TextField();
ComboBox<String> newEquipmentComboBox1 = new ComboBox<>(equipmentOptions);
newEquipmentComboBox1.setMinWidth(170);
ComboBox<String> newEquipmentComboBox2 = new ComboBox<>(statusOptions);
newEquipmentComboBox2.setMinWidth(170);
ComboBox<String> newEquipmentComboBox3 = new ComboBox<>(zoneOptions);
newEquipmentComboBox3.setMinWidth(170);
Button addNewEquipmentButton = new Button("Add");
addNewEquipmentButton.setOnAction(actionEvent -> {
tcpClientFX.addNewEquipment(newEquipmentTextField.getText(), newEquipmentComboBox1.getValue(),newEquipmentComboBox2.getValue(),newEquipmentComboBox3.getValue());
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("Added");
alert.showAndWait();
});
// Napis: Add permissions to the employee
Label permissionsLabel = new Label("Add license to employee:");
permissionsLabel.getStyleClass().add("textInfo2");
permissionsLabel.setMinWidth(100);
ObservableList<String> employeeOptions = FXCollections.observableArrayList();
employees.forEach(e->employeeOptions.add(e.getName()+" "+e.getLastName()));
ComboBox<String> permissionsComboBox1 = new ComboBox<>(employeeOptions);
permissionsComboBox1.setMinWidth(170);
ComboBox<String> permissionsComboBox2 = new ComboBox<>(licenseOptions);
permissionsComboBox2.setMinWidth(170);
// Użyj DatePicker dla daty
DatePicker datePicker = new DatePicker();
// Napis: Do
Label emptyLabel = new Label("");
Label emptyLabel2 = new Label("");
//emptyLabel.getStyleClass().add("textInfo2");
// Użyj DatePicker dla drugiej daty
DatePicker endDatePicker = new DatePicker();
// Dodanie przycisku "Add"
Button addPermissionsButton = new Button("Add");
addPermissionsButton.setOnAction(actionEvent -> {
tcpClientFX.addLicenseToEmployee(permissionsComboBox1.getValue(),permissionsComboBox2.getValue(),datePicker.getValue().toString(), endDatePicker.getValue().toString());
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Information Dialog");
alert.setHeaderText(null);
alert.setContentText("Added");
alert.showAndWait();
});
// Ustawienie układu (layout)
GridPane gridPane = new GridPane();
gridPane.setHgap(4);
gridPane.setVgap(10);
gridPane.setPadding(new Insets(10, 10, 10, 10));
gridPane.addRow(0, taskCategoryLabel, taskCategoryTextField, addTaskCategoryButton);
gridPane.addRow(1, licenseLabel, licenseComboBox1, licenseComboBox2, addLicenseButton);
gridPane.addRow(2, equipmentLabel, equipmentComboBox1, equipmentComboBox2, addEquipmentButton);
gridPane.addRow(3, newEquipmentLabel, newEquipmentTextField, newEquipmentComboBox1, newEquipmentComboBox2);
gridPane.addRow(4, emptyLabel, newEquipmentComboBox3, addNewEquipmentButton);
gridPane.addRow(5, permissionsLabel, permissionsComboBox1, permissionsComboBox2);
gridPane.addRow(6, emptyLabel2, datePicker, endDatePicker, addPermissionsButton);
otherTab.setContent(gridPane);
tabPane.getTabs().add(otherTab);
}
private void addOrdersTab() {
Tab ordersTab = new Tab("Orders");
// Tworzymy TableView dla zamówień
TableView<Order> ordersTable = new TableView<>();
ordersTab.setContent(ordersTable);
// Tworzymy kolumny tabeli
TableColumn<Order, Integer> idColumn = new TableColumn<>("ID");
TableColumn<Order, String> productColumn = new TableColumn<>("Product");
TableColumn<Order, Integer> quantityOrderedColumn = new TableColumn<>("Quantity Ordered");
TableColumn<Order, Integer> quantityInProductionColumn = new TableColumn<>("Quantity In Production");
TableColumn<Order, Integer> quantityFinishedColumn = new TableColumn<>("Quantity Finished");
TableColumn<Order, String> statusColumn = new TableColumn<>("Status");
TableColumn<Order, Void> startColumn = new TableColumn<>("Start");
// Ustawiamy, jakie wartości mają być wyświetlane w kolumnach
idColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getId()).asObject());
productColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getProduct().getName()));
quantityOrderedColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getProduct().getQuantityOrdered()).asObject());
quantityInProductionColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getProduct().getQuantityInProduction()).asObject());
quantityFinishedColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getProduct().getQuantityFinished()).asObject());
statusColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getStatus()));
// Ustawiamy przyciski w kolumnie "Start"
startColumn.setCellFactory(col -> {
TableCell<Order, Void> cell = new TableCell<>() {
private final Button startButton = new Button("Start");
{
startButton.setOnAction(event -> {
Order order = getTableView().getItems().get(getIndex());
int orderId = order.getId();
// Tutaj dodaj logikę do obsługi przycisku Start dla danego zamówienia (orderId)
List<Object> objects = tcpClientFX.getOrderInfo(order);
List<Equipment> equipment = (List<Equipment>) objects.get(0);
List<Component> components = (List<Component>) objects.get(1);
// Otwórz nowe okno "New Task"
openNewTaskWindow(order,equipment,components, ordersTable);
});
}
@Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow().getItem() == null) {
setGraphic(null);
} else {
Order order = (Order) getTableRow().getItem();
String status = order.getStatus();
// Wyświetl przycisk tylko dla zamówień z statusami "accepted" lub "inprogress"
if ("accepted".equalsIgnoreCase(status) || "progress".equalsIgnoreCase(status)) {
setGraphic(startButton);
} else {
setGraphic(null);
}
}
}
};
return cell;
});
// Dodajemy kolumny do tabeli
ordersTable.getColumns().addAll(idColumn, productColumn, quantityOrderedColumn, quantityInProductionColumn, quantityFinishedColumn, statusColumn, startColumn);
// Dodajemy wszystkie zamówienia do tabeli
ordersTable.getItems().addAll(orders);
// Dodajemy zakładkę do TabPane
tabPane.getTabs().add(ordersTab);
}
private void openNewTaskWindow(Order selectedOrder, List<Equipment> equipmentList, List<Component> components, TableView<Order> ordersTable) {
Stage newTaskStage = new Stage();
newTaskStage.setTitle("New Task");
// Tworzymy elementy interfejsu użytkownika
Label nameLabel = new Label("Name:");
nameLabel.getStyleClass().add("textInfo");
TextField nameTextField = new TextField();
Label priorityLabel = new Label("Priority:");
priorityLabel.getStyleClass().add("textInfo");
ComboBox<String> priorityComboBox = new ComboBox<>();
priorityComboBox.getItems().addAll("High", "Normal", "Low");
Label descriptionLabel = new Label("Description:");
descriptionLabel.getStyleClass().add("textInfo");
TextArea descriptionTextArea = new TextArea();
Label normLabel = new Label("Norm:");
normLabel.getStyleClass().add("textInfo");
TextField normTextField = new TextField();
Label componentLabel = new Label("Components:");
componentLabel.getStyleClass().add("textInfo");
VBox componentsVBox = new VBox();
List<CheckBox> componentCheckboxes = new ArrayList<>();
components.forEach(component -> {
CheckBox checkBox = new CheckBox(component.getName());
checkBox.getStyleClass().add("textInfo2");
componentCheckboxes.add(checkBox);
});
componentsVBox.getChildren().addAll(componentCheckboxes);
Label equipmentLabel = new Label("Equipment:");
equipmentLabel.getStyleClass().add("textInfo");
ComboBox<String> equipmentComboBox = new ComboBox<>();
equipmentList.forEach(equipment -> equipmentComboBox.getItems().add(equipment.getName()));
// Dodajemy pole Spinner dla ilości (Quantity)
Label quantityLabel = new Label("Quantity:");
quantityLabel.getStyleClass().add("textInfo");
Spinner<Integer> quantitySpinner = new Spinner<>(0, calculateMaxQuantity(selectedOrder), 0, 1);
// Tworzymy przyciski "Apply" i "Cancel"
Button applyButton = new Button("Apply");
Button cancelButton = new Button("Cancel");
// Ustawiamy akcję dla przycisku "Apply"
applyButton.setOnAction(event -> {
// Tutaj dodaj logikę do zastosowania wprowadzonych danych
List<Component> selectedComponents = new ArrayList<>();
for (CheckBox checkBox : componentCheckboxes) {
if (checkBox.isSelected()) {
String componentName = checkBox.getText();
// Szukaj obiektu Component po nazwie w liście components
Optional<Component> foundComponent = components.stream()
.filter(component -> component.getName().equals(componentName))
.findFirst();
foundComponent.ifPresent(selectedComponents::add);
}
}
// Pobierz nazwę wybranego sprzętu
String selectedEquipmentName = equipmentComboBox.getValue();
// Szukaj obiektu Equipment o danej nazwie w equipmentList
Equipment selectedEquipment = equipmentList.stream()
.filter(equipment -> equipment.getName().equals(selectedEquipmentName))
.findFirst()
.orElse(null);
assert selectedEquipment != null;
Task task = new Task(1, nameTextField.getText(), priorityComboBox.getValue(), descriptionTextArea.getText(), Integer.parseInt(normTextField.getText()), selectedComponents, selectedEquipment, selectedEquipment.getZone(), quantitySpinner.getValue(),selectedOrder.getProduct().getId(), selectedOrder.getId());
tcpClientFX.addTask(task);
selectedOrder.getProduct().setQuantityInProduction(selectedOrder.getProduct().getQuantityInProduction()+quantitySpinner.getValue());
selectedOrder.setStatus("progress");
// Aktualizuj dane w tabeli
ordersTable.getItems().clear(); // Wyczyść aktualne dane
ordersTable.getItems().addAll(orders); // Dodaj nowe dane
newTaskStage.close();
});
// Ustawiamy akcję dla przycisku "Cancel"
cancelButton.setOnAction(event -> {
// Tutaj dodaj logikę do anulowania wprowadzonych zmian
newTaskStage.close();
});
// Ustawiamy layout za pomocą GridPane
GridPane gridPane = new GridPane();
gridPane.setVgap(10);
gridPane.setHgap(10);
gridPane.setAlignment(Pos.CENTER);
// Dodajemy etykiety i pola do wprowadzania danych do GridPane
gridPane.add(nameLabel, 0, 0);
gridPane.add(nameTextField, 1, 0);
gridPane.add(priorityLabel, 0, 1);
gridPane.add(priorityComboBox, 1, 1);
gridPane.add(descriptionLabel, 0, 2);
gridPane.add(descriptionTextArea, 1, 2);
gridPane.add(normLabel, 0, 3);
gridPane.add(normTextField, 1, 3);
gridPane.add(componentLabel, 0, 4);
gridPane.add(componentsVBox, 1, 4);
gridPane.add(equipmentLabel, 0, 5);
gridPane.add(equipmentComboBox, 1, 5);
gridPane.add(quantityLabel, 0, 7);
gridPane.add(quantitySpinner, 1, 7);
gridPane.add(new HBox(10, applyButton, cancelButton), 1, 8);
// Ustawiamy scenę
Scene scene = new Scene(gridPane, 800, 600); // Zwiększam wysokość okna
scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());
newTaskStage.setScene(scene);
// Pokazujemy nowe okno
newTaskStage.show();
}
private void addTasksTab(List<Task> tasks) {
Tab tasksTab = new Tab("Tasks");
// Tworzymy TableView dla zadań
TableView<Task> tasksTable = new TableView<>();
tasksTab.setContent(tasksTable);
// Tworzymy kolumny tabeli
TableColumn<Task, Integer> idColumn = new TableColumn<>("ID");
TableColumn<Task, String> nameColumn = new TableColumn<>("Name");
TableColumn<Task, String> priorityColumn = new TableColumn<>("Priority");
TableColumn<Task, String> descriptionColumn = new TableColumn<>("Description");
TableColumn<Task, Integer> normColumn = new TableColumn<>("Norm");
TableColumn<Task, String> zoneColumn = new TableColumn<>("Zone");
TableColumn<Task, Integer> quantityColumn = new TableColumn<>("Quantity");
TableColumn<Task, Void> viewColumn = new TableColumn<>("View");
// Ustawiamy, jakie wartości mają być wyświetlane w kolumnach
idColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getId()).asObject());
nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
priorityColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getPriority()));
descriptionColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getDescription()));
normColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getNorm()).asObject());
zoneColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getZone()));
quantityColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getQuantity()).asObject());
// Ustawiamy przyciski w kolumnie "View"
viewColumn.setCellFactory(col -> {
TableCell<Task, Void> cell = new TableCell<>() {
private final Button viewButton = new Button("View");
{
viewButton.setOnAction(event -> {
Task task = getTableView().getItems().get(getIndex());
int taskId = task.getId();
// Tutaj dodaj logikę do obsługi przycisku View dla danego zadania (taskId)
System.out.println("View button clicked for task with ID: " + taskId);
openViewTaskWindow(task);
});
}
@Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow().getItem() == null) {
setGraphic(null);
} else {
setGraphic(viewButton);
}
}
};
return cell;
});
// Dodajemy kolumny do tabeli
tasksTable.getColumns().addAll(idColumn, nameColumn, priorityColumn, descriptionColumn, normColumn, zoneColumn, quantityColumn, viewColumn);
// Dodajemy wszystkie zadania do tabeli
tasksTable.getItems().addAll(tasks);
// Dodajemy zakładkę do TabPane
tabPane.getTabs().add(tasksTab);
}
private void openViewTaskWindow(Task task) {
List<String> taskInfo = tcpClientFX.getTaskInfo(task);
Stage window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle("Task Details");
VBox layout = new VBox(10);
layout.setPadding(new Insets(10));
for (String info : taskInfo) {
Label label = new Label(info);
label.getStyleClass().add("textInfo");
layout.getChildren().add(label);
}
Button closeButton = new Button("OK");
closeButton.setOnAction(e -> window.close());
layout.getChildren().add(closeButton);
Scene scene = new Scene(layout, 300, 500);
scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());
window.setScene(scene);
window.showAndWait();
}
private int calculateMaxQuantity(Order selectedOrder) {
if (selectedOrder != null) {
int maxQuantity = selectedOrder.getProduct().getQuantityOrdered()
- selectedOrder.getProduct().getQuantityInProduction()
- selectedOrder.getProduct().getQuantityFinished();
return Math.max(maxQuantity, 0); // Nie pozwalamy na ujemne wartości
}
return 0;
}
private void addEmployeesTab(List<Employee> employees) {
Tab employeesTab = new Tab("Employees");
// Tworzymy TableView dla pracowników
TableView<Employee> employeesTable = new TableView<>();
employeesTab.setContent(employeesTable);
// Tworzymy kolumny tabeli
TableColumn<Employee, Integer> idColumn = new TableColumn<>("ID");
TableColumn<Employee, String> nameColumn = new TableColumn<>("Name");
TableColumn<Employee, String> lastNameColumn = new TableColumn<>("Last Name");
TableColumn<Employee, String> roleColumn = new TableColumn<>("Role");
TableColumn<Employee, String> zoneColumn = new TableColumn<>("Zone");
TableColumn<Employee, Void> viewColumn = new TableColumn<>("View");
// Ustawiamy, jakie wartości mają być wyświetlane w kolumnach
idColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getId()).asObject());
nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
lastNameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getLastName()));
roleColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getRole()));
zoneColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getZone()));
// Ustawiamy przyciski w kolumnie "View"
viewColumn.setCellFactory(col -> {
TableCell<Employee, Void> cell = new TableCell<>() {
private final Button viewButton = new Button("View");
{
viewButton.setOnAction(event -> {
Employee employee = getTableView().getItems().get(getIndex());
int employeeId = employee.getId();
// Tutaj dodaj logikę do obsługi przycisku View dla danego pracownika (employeeId)
System.out.println("View button clicked for employee with ID: " + employeeId);
// Otwórz nowe okno "View Employee"
openViewEmployeeWindow(employee);
});
}
@Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow().getItem() == null) {
setGraphic(null);
} else {
setGraphic(viewButton);
}
}
};
return cell;
});
// Dodajemy kolumny do tabeli
employeesTable.getColumns().addAll(idColumn, nameColumn, lastNameColumn, roleColumn, zoneColumn, viewColumn);
// Dodajemy wszystkich pracowników do tabeli
employeesTable.getItems().addAll(employees);
// Dodajemy zakładkę do TabPane
tabPane.getTabs().add(employeesTab);
}
private void openViewEmployeeWindow(Employee employee) {
List<List<String>> empInfo = tcpClientFX.getEmployeeInfo(employee);
Stage window = new Stage();
window.initModality(Modality.APPLICATION_MODAL);
window.setTitle("Task Details");
VBox layout = new VBox(10);
layout.setPadding(new Insets(10));
for (List<String> info : empInfo) {
Label label = new Label(info.get(0)+" "+info.get(1)+" "+info.get(2)+" "+info.get(3)+" "+info.get(4));
label.getStyleClass().add("textInfo");
layout.getChildren().add(label);
}
Button closeButton = new Button("OK");
closeButton.setOnAction(e -> window.close());
layout.getChildren().add(closeButton);
Scene scene = new Scene(layout, 500, 300);
scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());
window.setScene(scene);
window.showAndWait();
}
private void addEquipmentsTab(List<Equipment> equipments) {
Tab equipmentsTab = new Tab("Equipments");
// Tworzymy TableView dla sprzętu
TableView<Equipment> equipmentsTable = new TableView<>();
equipmentsTab.setContent(equipmentsTable);
// Tworzymy kolumny tabeli
TableColumn<Equipment, Integer> idColumn = new TableColumn<>("ID");
TableColumn<Equipment, String> nameColumn = new TableColumn<>("Name");
TableColumn<Equipment, String> statusColumn = new TableColumn<>("Status");
TableColumn<Equipment, String> zoneColumn = new TableColumn<>("Zone");
TableColumn<Equipment, Void> viewColumn = new TableColumn<>("View");
// Ustawiamy, jakie wartości mają być wyświetlane w kolumnach
idColumn.setCellValueFactory(cellData -> new SimpleIntegerProperty(cellData.getValue().getId()).asObject());
nameColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getName()));
statusColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getStatus()));
zoneColumn.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getZone()));
// Ustawiamy przyciski w kolumnie "View"
viewColumn.setCellFactory(col -> {
TableCell<Equipment, Void> cell = new TableCell<>() {
private final Button viewButton = new Button("View");
{
viewButton.setOnAction(event -> {
Equipment equipment = getTableView().getItems().get(getIndex());
List<List<String>> equipmentUse = tcpClientFX.getUseEquipment(equipment.getId());
openViewEquipmentWindow(equipment,equipmentUse);
});
}
@Override
protected void updateItem(Void item, boolean empty) {
super.updateItem(item, empty);
if (empty || getTableRow().getItem() == null) {
setGraphic(null);
} else {
setGraphic(viewButton);
}
}
};
return cell;
});
// Dodajemy kolumny do tabeli
equipmentsTable.getColumns().addAll(idColumn, nameColumn, statusColumn, zoneColumn, viewColumn);
// Dodajemy wszystkie sprzęty do tabeli
equipmentsTable.getItems().addAll(equipments);
// Dodajemy zakładkę do TabPane
tabPane.getTabs().add(equipmentsTab);
}
private void openViewEquipmentWindow(Equipment equipment, List<List<String>> equipmentUse) {
// Tworzymy nowe okno "View Equipment"
Stage viewEquipmentStage = new Stage();
viewEquipmentStage.setTitle("View Equipment");
// Tworzymy kontener VBox dla układu okna
VBox vbox = new VBox(10);
vbox.getStyleClass().add("padd");
// Dodajemy etykiety i pola tekstowe do VBox
Label nameLabel = new Label("Name: " + equipment.getName());
nameLabel.getStyleClass().add("textInfo");
// Lista rozwijana (ComboBox) dla statusu
Label statusLable = new Label("Status: ");
statusLable.getStyleClass().add("textInfo");
ComboBox<String> statusComboBox = new ComboBox<>();
statusComboBox.getItems().addAll("available", "in use", "out of use");
statusComboBox.setValue(equipment.getStatus()); // Ustawienie domyślnego statusu
Label zoneLabel = new Label("Zone: " + equipment.getZone());
zoneLabel.getStyleClass().add("textInfo");
// Dodajemy elementy do VBox
vbox.getChildren().addAll(nameLabel, statusLable, statusComboBox, zoneLabel);
// Dodaj informacje z equipmentUse
for (List<String> innerList : equipmentUse) {
StringJoiner stringJoiner = new StringJoiner(" ");
for (String value : innerList) {
stringJoiner.add(value);
}
Label label = new Label(stringJoiner.toString());
label.getStyleClass().add("textInfo");
vbox.getChildren().add(label);
}
// Tworzymy HBox dla przycisków Apply i Cancel
HBox buttonBox = new HBox(10);
Button applyButton = new Button("Apply");
Button cancelButton = new Button("Cancel");
// Obsługa przycisku Apply
applyButton.setOnAction(event -> {
equipment.setStatus(statusComboBox.getValue());
tcpClientFX.updateEquipment(equipment);
// Zamknij okno po zastosowaniu zmian
viewEquipmentStage.close();
});
// Obsługa przycisku Cancel
cancelButton.setOnAction(event -> {
// Zamknij okno bez zastosowywania zmian
viewEquipmentStage.close();
});
// Dodaj przyciski do HBox
buttonBox.getChildren().addAll(applyButton, cancelButton);
// Dodaj HBox do VBox
vbox.getChildren().add(buttonBox);
// Ustawiamy VBox jako scenę
Scene scene = new Scene(vbox, 500, 300); // Zwiększyłem szerokość okna, aby pomieścić więcej informacji
scene.getStylesheets().add(getClass().getResource("/view/style.css").toExternalForm());
viewEquipmentStage.setScene(scene);
// Pokazujemy nowe okno
viewEquipmentStage.show();
}
@FXML
private void managerButtonAction() {
tcpClientFX.logOut();
}
} | SylwiaJa/Pojekt-System-do-zarzadzania-zasobami | projekt2023_24/src/client/controller/ManagerController.java |
180,334 | /*
* Copyright (c) 2024 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.dao.hibernate;
import org.hibernate.Session;
import pl.polsl.skirentalservice.core.servlet.pageable.FilterDataDto;
import pl.polsl.skirentalservice.dao.EquipmentDao;
import pl.polsl.skirentalservice.dao.core.AbstractHibernateDao;
import pl.polsl.skirentalservice.dto.PageableDto;
import pl.polsl.skirentalservice.dto.deliv_return.RentReturnEquipmentRecordResDto;
import pl.polsl.skirentalservice.dto.equipment.AddEditEquipmentReqDto;
import pl.polsl.skirentalservice.dto.equipment.EquipmentDetailsResDto;
import pl.polsl.skirentalservice.dto.equipment.EquipmentRecordResDto;
import pl.polsl.skirentalservice.dto.rent.EquipmentRentRecordResDto;
import pl.polsl.skirentalservice.dto.rent.RentEquipmentsDetailsResDto;
import pl.polsl.skirentalservice.util.RentStatus;
import java.util.List;
import java.util.Optional;
public class EquipmentDaoHib extends AbstractHibernateDao implements EquipmentDao {
public EquipmentDaoHib(Session session) {
super(session);
}
@Override
public void decreaseAvailableSelectedEquipmentCount(Object equipmentId, Object count) {
final String jpqlDecreaseAvailableEqCount = """
UPDATE EquipmentEntity e SET e.availableCount = e.availableCount - :rentedCount
WHERE e.id = :eid
""";
session.createMutationQuery(jpqlDecreaseAvailableEqCount)
.setParameter("eid", equipmentId)
.setParameter("rentedCount", count)
.executeUpdate();
}
@Override
public void increaseAvailableSelectedEquipmentCount(Object equipmentId, Object count) {
final String jpqlIncreaseEquipmentCount = """
UPDATE EquipmentEntity e SET e.availableCount = e.availableCount + :rentedCount
WHERE e.id = :eid
""";
session.createMutationQuery(jpqlIncreaseEquipmentCount)
.setParameter("eid", equipmentId)
.setParameter("rentedCount", count)
.executeUpdate();
}
@Override
public Optional<EquipmentRentRecordResDto> findEquipmentDetails(Object equipmentId) {
final String jpqlEquipmentDetails = """
SELECT new pl.polsl.skirentalservice.dto.rent.EquipmentRentRecordResDto(
e.id, e.name, t.name, e.model, e.barcode, e.availableCount, e.pricePerHour,
e.priceForNextHour, e.pricePerDay, ''
) FROM EquipmentEntity e
INNER JOIN e.type t
WHERE e.id = :id
""";
final EquipmentRentRecordResDto equipmentDetails = session
.createQuery(jpqlEquipmentDetails, EquipmentRentRecordResDto.class)
.setParameter("id", equipmentId)
.getSingleResultOrNull();
return Optional.ofNullable(equipmentDetails);
}
@Override
public Optional<AddEditEquipmentReqDto> findAddEditEquipmentDetails(Object equipmentId) {
final String jpqlFindEquipmentBaseId = """
SELECT new pl.polsl.skirentalservice.dto.equipment.AddEditEquipmentReqDto(
e.name, e.model, e.description, CAST(e.countInStore AS string), CAST(e.size AS string),
CAST(e.pricePerHour AS string), CAST(e.priceForNextHour AS string),
CAST(e.pricePerDay AS string), CAST(e.valueCost AS string), CAST(t.id AS string),
CAST(b.id AS string), CAST(c.id AS string), e.gender
) FROM EquipmentEntity e
INNER JOIN e.type t INNER JOIN e.brand b INNER JOIN e.color c
WHERE e.id = :eid
""";
final AddEditEquipmentReqDto equipmentDetails = session
.createQuery(jpqlFindEquipmentBaseId, AddEditEquipmentReqDto.class)
.setParameter("eid", equipmentId)
.getSingleResultOrNull();
return Optional.ofNullable(equipmentDetails);
}
@Override
public Optional<EquipmentDetailsResDto> findEquipmentDetailsPage(Object equipmentId) {
final String jpqlFindEquipmentDetails = """
SELECT new pl.polsl.skirentalservice.dto.equipment.EquipmentDetailsResDto(
e.id, e.name, t.name, e.model, e.gender, e.barcode,
CASE WHEN e.size IS NULL THEN '<i>brak danych</i>' ELSE CAST(e.size AS string) END,
b.name, c.name, CONCAT(e.availableCount, '/', e.countInStore),
e.countInStore - e.availableCount, e.pricePerHour, e.priceForNextHour,
e.pricePerDay, e.valueCost,
CASE WHEN e.description IS NULL THEN '<i>brak danych</i>' ELSE e.description END
) FROM EquipmentEntity e
INNER JOIN e.type t INNER JOIN e.brand b INNER JOIN e.color c
WHERE e.id = :eid
""";
final EquipmentDetailsResDto equipmentDetails = session
.createQuery(jpqlFindEquipmentDetails, EquipmentDetailsResDto.class)
.setParameter("eid", equipmentId)
.getSingleResultOrNull();
return Optional.ofNullable(equipmentDetails);
}
@Override
public boolean checkIfEquipmentExist(Object equipmentId) {
final String jpqlEquipmentDetails = """
SELECT COUNT(e.id) > 0 FROM EquipmentEntity e INNER JOIN e.type t WHERE e.id = :id
""";
return session.createQuery(jpqlEquipmentDetails, Boolean.class)
.setParameter("id", equipmentId)
.getSingleResult();
}
@Override
public boolean checkIfEquipmentModelExist(String modelName, Object equipmentId) {
final String jpqlEquipmentModelExist = """
SELECT COUNT(e.id) > 0 FROM EquipmentEntity e
WHERE LOWER(e.model) = LOWER(:model) AND (e.id <> :eid OR :eid IS NULL)
""";
return session.createQuery(jpqlEquipmentModelExist, Boolean.class)
.setParameter("model", modelName)
.setParameter("eid", equipmentId)
.getSingleResult();
}
@Override
public boolean checkIfBarCodeExist(String barcode) {
final String jpqlFindBarcode = "SELECT COUNT(e.id) > 0 FROM EquipmentEntity e WHERE e.barcode = :barcode";
return session.createQuery(jpqlFindBarcode, Boolean.class)
.setParameter("barcode", barcode)
.getSingleResult();
}
@Override
public boolean checkIfEquipmentHasOpenedRents(Object equipmentId) {
final String jpqlFindHasConnections = """
SELECT COUNT(r.id) > 0 FROM RentEntity r INNER JOIN r.equipments e INNER JOIN e.equipment eq
WHERE eq.id = :eid AND r.status <> :rst
""";
return session.createQuery(jpqlFindHasConnections, Boolean.class)
.setParameter("eid", equipmentId)
.setParameter("rst", RentStatus.RETURNED)
.getSingleResult();
}
@Override
public Long getCountIfSomeEquipmentsAreAvailable() {
final String getAllCounts = "SELECT SUM(e.availableCount) FROM EquipmentEntity e";
return session.createQuery(getAllCounts, Long.class).getSingleResultOrNull();
}
@Override
public List<RentReturnEquipmentRecordResDto> findAllEquipmentsConnectedWithRentReturn(Object rentId) {
final String jpqlFindAllEquipmentsConnectedWithRent = """
SELECT new pl.polsl.skirentalservice.dto.deliv_return.RentReturnEquipmentRecordResDto(
re.id, red.pricePerHour, red.priceForNextHour, red.pricePerDay, re.count,
re.depositPrice, red.id, re.description
) FROM RentEquipmentEntity re
INNER JOIN re.rent r INNER JOIN r.employer e INNER JOIN e.role rl INNER JOIN re.equipment red
WHERE r.id = :rentid ORDER BY re.id
""";
return session.createQuery(jpqlFindAllEquipmentsConnectedWithRent, RentReturnEquipmentRecordResDto.class)
.setParameter("rentid", rentId)
.getResultList();
}
@Override
public List<RentEquipmentsDetailsResDto> findAllEquipmentsConnectedWithReturn(Object returnId) {
final String jpqlFindAllEquipments = """
SELECT new pl.polsl.skirentalservice.dto.rent.RentEquipmentsDetailsResDto(
re.id, IFNULL(e.name, '<i>sprzęt usunięty</i>'), rer.count, e.barcode, re.description,
re.totalPrice, CAST((r.tax / 100) * re.totalPrice + re.totalPrice AS bigdecimal),
re.depositPrice, CAST((r.tax / 100) * re.depositPrice + re.depositPrice AS bigdecimal)
) FROM RentReturnEquipmentEntity re
INNER JOIN re.rentEquipment rer
INNER JOIN rer.rent r INNER JOIN re.rentReturn rrer LEFT OUTER JOIN re.equipment e
WHERE rrer.id = :rid ORDER BY re.id
""";
return session.createQuery(jpqlFindAllEquipments, RentEquipmentsDetailsResDto.class)
.setParameter("rid", returnId)
.getResultList();
}
@Override
public List<RentEquipmentsDetailsResDto> findAllEquipmentsConnectedWithRent(Object rentId) {
final String jpqlFindAllEquipments = """
SELECT new pl.polsl.skirentalservice.dto.rent.RentEquipmentsDetailsResDto(
re.id, IFNULL(e.name, '<i>sprzęt usunięty</i>'), re.count, e.barcode, re.description,
re.totalPrice, CAST((r.tax / 100) * re.totalPrice + re.totalPrice AS bigdecimal),
re.depositPrice, CAST((r.tax / 100) * re.depositPrice + re.depositPrice AS bigdecimal)
) FROM RentEquipmentEntity re
INNER JOIN re.rent r LEFT OUTER JOIN re.equipment e LEFT OUTER JOIN r.employer emp
WHERE r.id = :rid ORDER BY re.id
""";
return session.createQuery(jpqlFindAllEquipments, RentEquipmentsDetailsResDto.class)
.setParameter("rid", rentId)
.getResultList();
}
@Override
public Integer findAllEquipmentsInCartCount(Object equipmentId) {
final String jpqlCheckEquipmentCount = "SELECT e.availableCount FROM EquipmentEntity e WHERE e.id = :id";
return session.createQuery(jpqlCheckEquipmentCount, Integer.class)
.setParameter("id", equipmentId)
.getSingleResult();
}
@Override
public Long findAllEquipmentsCount(FilterDataDto filterData) {
String jpqlFindAll = """
SELECT COUNT(e.id) FROM EquipmentEntity e INNER JOIN e.type t WHERE :searchColumn LIKE :search
""";
jpqlFindAll = jpqlFindAll.replace(":searchColumn", filterData.getSearchColumn());
return session.createQuery(jpqlFindAll, Long.class)
.setParameter("search", "%" + filterData.getSearchText() + "%")
.getSingleResult();
}
@Override
public List<EquipmentRecordResDto> findAllPageableEquipmentRecords(PageableDto pageableDto) {
String jpqlFindAllEquipments = """
SELECT new pl.polsl.skirentalservice.dto.equipment.EquipmentRecordResDto(
e.id, e.name, t.name, e.barcode, e.availableCount, e.pricePerHour, e.priceForNextHour,
e.pricePerDay, e.valueCost
) FROM EquipmentEntity e
INNER JOIN e.type t
WHERE :searchColumn LIKE :search
ORDER BY :sortedColumn
""";
jpqlFindAllEquipments = jpqlFindAllEquipments
.replace(":searchColumn", pageableDto.filterData().getSearchColumn())
.replace(":sortedColumn", pageableDto.sorterData().getJpql());
return session.createQuery(jpqlFindAllEquipments, EquipmentRecordResDto.class)
.setParameter("search", "%" + pageableDto.filterData().getSearchText() + "%")
.setFirstResult((pageableDto.page() - 1) * pageableDto.total())
.setMaxResults(pageableDto.total())
.getResultList();
}
@Override
public List<EquipmentRentRecordResDto> findAllPageableEquipments(PageableDto pageableDto) {
String jpqlFindAllEquipments = """
SELECT new pl.polsl.skirentalservice.dto.rent.EquipmentRentRecordResDto(
e.id, e.name, t.name, e.model, e.barcode, e.availableCount, e.pricePerHour,
e.priceForNextHour, e.pricePerDay, ''
) FROM EquipmentEntity e
INNER JOIN e.type t
WHERE :searchColumn LIKE :search GROUP BY e.id
ORDER BY :sortedColumn
""";
jpqlFindAllEquipments = jpqlFindAllEquipments
.replace(":searchColumn", pageableDto.filterData().getSearchColumn())
.replace(":sortedColumn", pageableDto.sorterData().getJpql());
return session.createQuery(jpqlFindAllEquipments, EquipmentRentRecordResDto.class)
.setParameter("search", "%" + pageableDto.filterData().getSearchText() + "%")
.setFirstResult((pageableDto.page() - 1) * pageableDto.total())
.setMaxResults(pageableDto.total())
.getResultList();
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/dao/hibernate/EquipmentDaoHib.java |
180,335 | package gui;
import logic.Database;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Usun extends JFrame{
private JPanel panel1;
private JComboBox tabelaCombo;
private JTextField IdField;
private JButton usunButton;
private JButton powrotButton;
private JScrollPane listaPane;
public Usun(){
setContentPane(panel1);
setTitle("Usuń");
setSize(600, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
Database base = new Database();
tabelaCombo.addItem("");
tabelaCombo.addItem("Piłkarz");
tabelaCombo.addItem("Trener");
tabelaCombo.addItem("Fizjoterapeuta");
tabelaCombo.addItem("Sala");
tabelaCombo.addItem("Sprzęt");
tabelaCombo.addItem("Trening");
tabelaCombo.addItem("Ćwiczenia Fizjoterapeutyczne");
tabelaCombo.addItem("Wypisz piłkarza z treningu");
JTextArea lista = new JTextArea();
lista.setEditable(false);
tabelaCombo.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Connection c = base.connect();
String wypisLista="";
switch (tabelaCombo.getSelectedItem().toString()){
case ("Piłkarz"):
try{
PreparedStatement pst = c.prepareStatement("SELECT pilkarz_id, imie,nazwisko from pilkarz");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("pilkarz_id") + " - " + rs.getString("imie")+ " " + rs.getString("nazwisko")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Trener"):
try{
PreparedStatement pst = c.prepareStatement("SELECT trener_id, imie,nazwisko from trener");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("trener_id") + " - " + rs.getString("imie")+ " " + rs.getString("nazwisko")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Fizjoterapeuta"):
try{
PreparedStatement pst = c.prepareStatement("SELECT fizjoterapeuta_id, imie,nazwisko from fizjoterapeuta");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("fizjoterapeuta_id") + " - " + rs.getString("imie")+ " " + rs.getString("nazwisko")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Sala"):
try{
PreparedStatement pst = c.prepareStatement("SELECT sala_id, nazwa from sala");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("sala_id") + " - " + rs.getString("nazwa")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Sprzęt"):
try{
PreparedStatement pst = c.prepareStatement("SELECT sprzet_id, nazwa from sprzet");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("sprzet_id") + " - " + rs.getString("nazwa")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Trening"):
try{
PreparedStatement pst = c.prepareStatement("SELECT trening_id, dzien_treningu, trener_imie_nazwisko from widok_treningu");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("trening_id") + " - " + rs.getString("dzien_treningu")+ " "+rs.getString("trener_imie_nazwisko") +"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Ćwiczenia Fizjoterapeutyczne"):
try{
PreparedStatement pst = c.prepareStatement("SELECT cwiczenia_fizjoterapeuta_id, dzien_cwiczen from cwiczenia_fizjoterapeuta");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("cwiczenia_fizjoterapeuta_id") + " - " + rs.getString("dzien_cwiczen")+"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Wypisz piłkarza z treningu"):
try{
PreparedStatement pst = c.prepareStatement("Select tp.trening_pilkarz_id ,wk.trener_imie_nazwisko,p.imie, p.nazwisko from widok_treningu wk join trening_pilkarz tp on wk.trening_id = tp.trening_id join pilkarz p on p.pilkarz_id = tp.pilkarz_id group by tp.trening_pilkarz_id, wk.trener_imie_nazwisko, p.imie, p.nazwisko order by tp.trening_pilkarz_id");
ResultSet rs = pst.executeQuery();
while(rs.next()){
wypisLista+= rs.getString("trening_pilkarz_id") + " - " + rs.getString("imie")+ " "+rs.getString("nazwisko")+ ", trener: "+ rs.getString("trener_imie_nazwisko") +"\n";
}
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
default:
break;
}
lista.setText(wypisLista);
listaPane.setViewportView(lista);
base.closeConnection(c);
}
});
powrotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new Admin();
dispose();
}
});
usunButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Connection c = base.connect();
try{
String kolumna="";
String tabela ="";
switch (tabelaCombo.getSelectedItem().toString()){
case ("Piłkarz"):
kolumna = "pilkarz_id";
tabela = "pilkarz";
break;
case ("Trener"):
kolumna = "trener_id";
tabela = "trener";
break;
case ("Fizjoterapeuta"):
kolumna = "fizjoterapeuta_id";
tabela = "fizjoterapeuta";
break;
case ("Trening"):
kolumna = "trening_id";
tabela = "trening";
break;
case ("Sala"):
kolumna = "sala_id";
tabela = "sala";
break;
case ("Sprzęt"):
kolumna = "sprzet_id";
tabela = "sprzet";
break;
case ("Ćwiczenia Fizjoterapeutyczne"):
kolumna = "cwiczenia_fizjoterapeuta_id";
tabela = "cwiczenia_fizjoterapeuta";
break;
case ("Wypisz piłkarza z treningu"):
kolumna = "trening_pilkarz_id";
tabela = "trening_pilkarz";
break;
default:
break;
}
PreparedStatement pst = c.prepareStatement("delete from " + tabela+" where "+ kolumna+ " = ?");
pst.setInt(1,Integer.parseInt(IdField.getText()));
pst.executeUpdate();
}catch (SQLException ex){throw new RuntimeException(ex);}
IdField.setText("");
base.closeConnection(c);
}
});
}
}
| ZEN4est/Projects-from-studies | Java + SQL/Java+SQL Project/Projekt/src/main/java/gui/Usun.java |
180,336 | package owdaqapp;
import java.sql.Timestamp;
import java.util.List;
import com.dalsemi.onewire.OneWireException;
import com.dalsemi.onewire.container.TemperatureContainer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.dalsemi.onewire.OneWireAccessProvider;
import com.dalsemi.onewire.adapter.DSPortAdapter;
import com.dalsemi.onewire.container.OneWireContainer;
import owdaqapp.one_wire.OwAdapter;
import owdaqapp.one_wire.OwEventLog;
import owdaqapp.one_wire.OwReading;
import owdaqapp.repositories.*;
import owdaqapp.one_wire.OwSensor;
@Component
public class OwDaqProcessor {
private static final Logger log = LoggerFactory.getLogger(OwDaqProcessor.class);
@Autowired
private OwReadingsRepository owReadingsRepository;
@Autowired
private OwAdaptersRepository owAdaptersRepository;
@Autowired
private OwSensorsRepository owSensorsRepository;
@Autowired
private OwSitesRepository owSitesRepository;
@Autowired
private OwEventLogRepository owEventLogRepository;
private void processTemp(DSPortAdapter adapter, OwSensor owsensor) throws OneWireException {
OneWireContainer owc = adapter.getDeviceContainer(owsensor.getADDRESS());
if (!(owc instanceof TemperatureContainer)) {
log.info("Sensor is not a temperature container");
return;
}
System.out.println("= " + owc.getAddressAsString());
TemperatureContainer tc = (TemperatureContainer) owc;
boolean selectable = tc.hasSelectableTemperatureResolution();
double[] resolution = null;
System.out.println("= This device is a " + owc.getName());
try{
byte[] state = tc.readDevice();
if (selectable) {
try {
resolution = tc.getTemperatureResolutions();
for (int i = 0; i < resolution.length; i++) {
System.out.println("= Available resolution " + i + " : " + resolution[i]);
}
System.out.println("= Setting temperature resolution to " + resolution[resolution.length - 1] + "...");
tc.setTemperatureResolution(resolution[resolution.length - 1], state);
} catch (Exception e) {
log.info(
"= Could not get available resolutions : "
+ e.toString());
}
try {
tc.doTemperatureConvert(state);
} catch (Exception e) {
log.info("= Could not complete temperature conversion...");
}
state = tc.readDevice();
double temp = tc.getTemperature(state);
System.out.println("= Reported temperature: " + temp);
if (temp>=85)
{
log.info("Sprzętowy błąd pomiaru: temp= " +temp);
OwEventLog owel = new OwEventLog();
owel.setTIMESTAMP(new Timestamp(System.currentTimeMillis()));
owel.setTYPE("ERROR");
owel.setDESCRIPTION("Sprzętowy błąd pomiaru dla czujnika o adresie: " + owc.getAddressAsString()+ "\n temperature="+temp+"℃");
this.owEventLogRepository.save(owel);
return;
}
OwReading owr = new OwReading();
owr.setSITE_ID(owsensor.getSITE_ID());
owr.setTIMESTAMP(new Timestamp(System.currentTimeMillis()));
owr.setVALUE(temp);
this.owReadingsRepository.save(owr);
}
}catch(Exception e){
log.info("Problem z czujnikiem");
OwEventLog owel = new OwEventLog();
owel.setTIMESTAMP(new Timestamp(System.currentTimeMillis()));
owel.setTYPE("ERROR");
owel.setDESCRIPTION("Problem z czujnikiem o adresie: " + owc.getAddressAsString() + "\n (wiecej info w logach)");
this.owEventLogRepository.save(owel);
log.info("Exception: " + e.toString());
}
}
void doMeasurement(){
OneWireContainer owd;
List<OwAdapter> activeAdapters= owAdaptersRepository.findActiveAdapters();
for(OwAdapter owa: activeAdapters){
try {
DSPortAdapter adapter = OneWireAccessProvider.getAdapter(owa.getNAME(), owa.getPORT());
// get exclusive use of adapter
adapter.beginExclusive(true);
// clear any previous search restrictions
adapter.setSearchAllDevices();
adapter.targetAllFamilies();
adapter.setSpeed(adapter.SPEED_REGULAR);
log.info("adapter ready");
List<OwSensor> activeSensors= owSensorsRepository.findActiveSensorsForAdapter(owa.getID());
for(OwSensor owsensor:activeSensors)
{
this.processTemp(adapter, owsensor);
}
// end exclusive use of adapter
adapter.endExclusive();
// free port used by adapter
adapter.freePort();
}
catch(Exception e)
{
OwEventLog owel = new OwEventLog();
owel.setTIMESTAMP(new Timestamp(System.currentTimeMillis()));
owel.setTYPE("ERROR");
owel.setDESCRIPTION("Problem z adapterem o nazwie: " + owa.getNAME() +" i porcie "+ owa.getPORT() + " (wiecej info w logach)");
this.owEventLogRepository.save(owel);
System.out.println(e);
}
}
//lista adapterów, otwieranie, zamykanie
}
}
| plorens/ow-daq-app | src/main/java/owdaqapp/OwDaqProcessor.java |
180,340 | package gui;
import logic.Database;
import javax.swing.*;
import javax.swing.border.Border;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class WyswietlDane extends JFrame{
private JPanel panel1;
private JComboBox comboBox1;
private JScrollPane tabelaScrollPane;
private JButton powrotButton;
public WyswietlDane(){
setContentPane(panel1);
setTitle("Wyświetl dane");
setSize(600, 600);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
Database base = new Database();
JTextArea textArea = new JTextArea();
textArea.setEditable(false);
tabelaScrollPane.setViewportView(textArea);
comboBox1.addItem("");
comboBox1.addItem("Trenerzy");
comboBox1.addItem("Piłkarze");
comboBox1.addItem("Sale");
comboBox1.addItem("Sprzęt");
comboBox1.addItem("Fizjoterapeuci");
comboBox1.addItem("Treningi");
comboBox1.addItem("Treningi piłkarzy");
comboBox1.addItem("Ćwiczenia fizjoterapeutyczne");
powrotButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
new StronaStartowa();
dispose();
}
});
comboBox1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Connection connection = base.connect();
Border trenerzyBorder = BorderFactory.createEtchedBorder();
switch (comboBox1.getSelectedItem().toString()){
case("Trenerzy") :
Border trenerzyBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Trener");
tabelaScrollPane.setBorder(trenerzyBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from trener",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"trener_id", "imie", "nazwisko","specjalizacja","zarobki_za_trening"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][5];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("trener_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("imie");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("nazwisko");
data[TrenerzyRs.getRow()-1][3] = TrenerzyRs.getString("specjalizacja");
data[TrenerzyRs.getRow()-1][4] = TrenerzyRs.getString("zarobki_za_trening");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Fizjoterapeuci") :
Border fizjoBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Fizjoterapeuta");
tabelaScrollPane.setBorder(fizjoBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from fizjoterapeuta",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"fizjoterapeuta_id", "imie", "nazwisko","zarobki_za_trening"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][4];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("fizjoterapeuta_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("imie");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("nazwisko");
data[TrenerzyRs.getRow()-1][3] = TrenerzyRs.getString("zarobki_za_trening");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Sale") :
Border saleBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Sala");
tabelaScrollPane.setBorder(saleBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from sala",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"sala_id", "nazwa", "koszt"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][3];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("sala_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("nazwa");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("koszt");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Sprzęt") :
Border sprzetBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Sprzęt");
tabelaScrollPane.setBorder(sprzetBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from sprzet",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"sprzet_id", "nazwa", "koszt"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][3];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("sprzet_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("nazwa");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("koszt");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Piłkarze") :
Border pilkarzBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Piłkarz");
tabelaScrollPane.setBorder(pilkarzBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from pilkarz",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"pilkarz_id", "imie", "nazwisko","pozycja"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][4];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("pilkarz_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("imie");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("nazwisko");
data[TrenerzyRs.getRow()-1][3] = TrenerzyRs.getString("pozycja");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Treningi"):
Border treningBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "Trening");
tabelaScrollPane.setBorder(treningBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from trening",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"trening_id", "dzien_treningu", "trener_id","sala_id","sprzet_id"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][5];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("trening_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("dzien_treningu");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("trener_id");
data[TrenerzyRs.getRow()-1][3] = TrenerzyRs.getString("sala_id");
data[TrenerzyRs.getRow()-1][4] = TrenerzyRs.getString("sprzet_id");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Treningi piłkarzy"):
Border treningPBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "trening_pilkarz");
tabelaScrollPane.setBorder(treningPBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from trening_pilkarz",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"trening_pilkarz_id", "trening_id","pilkarz_id"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][3];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("trening_pilkarz_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("trening_id");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("pilkarz_id");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
case("Ćwiczenia fizjoterapeutyczne"):
Border cwiczeniaBorderE = BorderFactory.createTitledBorder(trenerzyBorder, "cwiczenia_fizjoterapeuta");
tabelaScrollPane.setBorder(cwiczeniaBorderE);
try{
PreparedStatement Trenerzy = connection.prepareStatement("SELECT * from cwiczenia_fizjoterapeuta",ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet TrenerzyRs = Trenerzy.executeQuery();
String [] columnNames = {"cwiczenia_fizjoterapeuta_id", "fizjoterapeuta_id","pilkarz_id","dzien_cwiczen"};
TrenerzyRs.last();
String [][] data = new String[TrenerzyRs.getRow()][4];
TrenerzyRs.first();
do {
data[TrenerzyRs.getRow()-1][0] = TrenerzyRs.getString("cwiczenia_fizjoterapeuta_id");
data[TrenerzyRs.getRow()-1][1] = TrenerzyRs.getString("fizjoterapeuta_id");
data[TrenerzyRs.getRow()-1][2] = TrenerzyRs.getString("pilkarz_id");
data[TrenerzyRs.getRow()-1][3] = TrenerzyRs.getString("dzien_cwiczen");
}while(TrenerzyRs.next());
JTable specificReviewsTable = new JTable(data, columnNames);
tabelaScrollPane.setViewportView(specificReviewsTable);
}catch (SQLException ex){throw new RuntimeException(ex);}
break;
default:
break;
}
base.closeConnection(connection);
}
});
}
}
| ZEN4est/Projects-from-studies | Java + SQL/Java+SQL Project/Projekt/src/main/java/gui/WyswietlDane.java |
180,344 | package org.polsl.backend.dto.affiliation;
import org.polsl.backend.service.export.ExportColumn;
import java.util.Set;
public class AffiliationListOutputDTO {
private Long id;
private Boolean deleted;
@ExportColumn("Imię")
private String firstName;
@ExportColumn("Nazwisko")
private String lastName;
@ExportColumn("Lokalizacja")
private String location;
@ExportColumn("Numery inwentarzowe powiązanych zestawów komputerowych")
private Set<String> computerSetsInventoryNumbers;
@ExportColumn("Numery inwentarzowe powiązanych sprzętów")
private Set<String> hardwareInventoryNumbers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Set<String> getComputerSetsInventoryNumbers() {
return computerSetsInventoryNumbers;
}
public void setComputerSetsInventoryNumbers(Set<String> computerSetsInventoryNumbers) {
this.computerSetsInventoryNumbers = computerSetsInventoryNumbers;
}
public Set<String> getHardwareInventoryNumbers() {
return hardwareInventoryNumbers;
}
public void setHardwareInventoryNumbers(Set<String> hardwareInventoryNumbers) {
this.hardwareInventoryNumbers = hardwareInventoryNumbers;
}
}
| Samograje/co-gdzie-kiedy | backend/src/main/java/org/polsl/backend/dto/affiliation/AffiliationListOutputDTO.java |
180,345 | package org.polsl.backend.dto.computerset;
import org.polsl.backend.service.export.ExportColumn;
import java.util.Set;
public class ComputerSetListOutputDTO {
private Long id;
private Boolean deleted;
@ExportColumn("Nazwa")
private String name;
@ExportColumn("Numer inwentarzowy")
private String computerSetInventoryNumber;
@ExportColumn("Przynależy do")
private String affiliationName;
@ExportColumn("Numery inwentarzowe powiązanych oprogramowań")
private Set<String> softwareInventoryNumbers;
@ExportColumn("Numery inwentarzowe powiązanych sprzętów")
private Set<String> hardwareInventoryNumbers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComputerSetInventoryNumber() {
return computerSetInventoryNumber;
}
public void setComputerSetInventoryNumber(String computerSetInventoryNumber) {
this.computerSetInventoryNumber = computerSetInventoryNumber;
}
public String getAffiliationName() {
return affiliationName;
}
public void setAffiliationName(String affiliationName) {
this.affiliationName = affiliationName;
}
public Set<String> getSoftwareInventoryNumbers() {
return softwareInventoryNumbers;
}
public void setSoftwareInventoryNumbers(Set<String> softwareInventoryNumbers) {
this.softwareInventoryNumbers = softwareInventoryNumbers;
}
public Set<String> getHardwareInventoryNumbers() {
return hardwareInventoryNumbers;
}
public void setHardwareInventoryNumbers(Set<String> hardwareInventoryNumbers) {
this.hardwareInventoryNumbers = hardwareInventoryNumbers;
}
}
| Samograje/co-gdzie-kiedy | backend/src/main/java/org/polsl/backend/dto/computerset/ComputerSetListOutputDTO.java |
180,347 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.exception;
import pl.polsl.skirentalservice.core.AbstractAppException;
import java.time.LocalDate;
public class DateException {
public static class DateInFutureException extends AbstractAppException {
public DateInFutureException(String formField, int circaYears) {
super("Wartość daty w polu <strong>" + formField + "</strong> musi być przed <strong>" +
LocalDate.now().minusYears(circaYears) + "</strong>.");
}
public DateInFutureException(String formField) {
super("Wartość daty w polu <strong>" + formField + "</strong> musi być przed <strong>" +
LocalDate.now() + "</strong>.");
}
}
public static class BornAfterHiredDateException extends AbstractAppException {
public BornAfterHiredDateException() {
super("Data zatrudnienia nie może być wcześniejsza niż data urodzenia pracownika.");
}
}
public static class RentDateBeforeIssuedDateException extends AbstractAppException {
public RentDateBeforeIssuedDateException() {
super("Data wypożyczenia sprzętu nie może być wcześniejsza od daty wystawienia nowego wypożyczenia.");
}
}
public static class ReturnDateBeforeRentDateException extends AbstractAppException {
public ReturnDateBeforeRentDateException() {
super("Data zwrotu wypożyczenia nie może być wcześniejsza niż data wypożyczenia sprzętu.");
}
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/exception/DateException.java |
180,351 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.pdf;
import pl.polsl.skirentalservice.pdf.dto.PdfDocumentData;
public class RentPdfDocumentGenerator extends AbstractPdfGenerator {
public RentPdfDocumentGenerator() {
super("wypożyczenia", "Wypożyczone sprzęty:");
}
@Override
protected String setHeaderDate(PdfDocumentData pdfDocumentData) {
return pdfDocumentData.getIssuedDate();
}
@Override
protected void appendToRightComponents(PdfDocumentData pdfDocumentData) {
rightComponents.put("Data utworzenia dokumentu", pdfDocumentData.getIssuedDate());
rightComponents.put("Data wypożyczenia", pdfDocumentData.getRentDate());
rightComponents.put("Przewidywana data zwrotu", pdfDocumentData.getReturnDate());
rightComponents.put("Przewidywany czas wypożyczenia", pdfDocumentData.getRentTime());
rightComponents.put("Wartość podatku VAT", pdfDocumentData.getTax() + "%");
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/pdf/RentPdfDocumentGenerator.java |
180,352 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.pdf;
import pl.polsl.skirentalservice.pdf.dto.PdfDocumentData;
import pl.polsl.skirentalservice.util.DateUtils;
public class ReturnPdfDocumentGenerator extends AbstractPdfGenerator {
public ReturnPdfDocumentGenerator() {
super("zwrotu", "Zwrócone sprzęty:");
}
@Override
protected String setHeaderDate(PdfDocumentData pdfDocumentData) {
return pdfDocumentData.getReturnDate();
}
@Override
protected void appendToRightComponents(PdfDocumentData pdfDocumentData) {
rightComponents.put("Data wypożyczenia", DateUtils.toISO8601Format(pdfDocumentData.getRentDate()));
rightComponents.put("Data zwrotu", pdfDocumentData.getReturnDate());
rightComponents.put("Czas wypożyczenia", pdfDocumentData.getRentTime());
rightComponents.put("Wartość podatku VAT", pdfDocumentData.getTax() + "%");
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/pdf/ReturnPdfDocumentGenerator.java |
180,353 | /*
* Copyright (c) 2023 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.dto.rent;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.Pattern;
import jakarta.validation.constraints.Size;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import pl.polsl.skirentalservice.core.ReqValidatePojo;
import pl.polsl.skirentalservice.core.servlet.WebServletRequest;
import pl.polsl.skirentalservice.util.Regex;
@Data
public class AddEditEquipmentCartReqDto implements ReqValidatePojo {
@NotEmpty(message = "Pole ilości sprzętów w wypożyczeniu nie może być puste.")
@Pattern(
regexp = Regex.POS_NUMBER_INT,
message = "Pole ilości sprzętów w wypożyczeniu może przyjmować wartości od 1 do 9999.")
private String count;
@Pattern(
regexp = Regex.DECIMAL_2_ROUND,
message = "Pole kaucji musi być w formacie 0,00 lub 0.00, wartość min 1,00.")
private String depositPrice;
@Size(max = 200, message = "Pole dodatkowych uwag może mieć maksymalnie 200 znaków.")
private String description;
public AddEditEquipmentCartReqDto(WebServletRequest req) {
this.count = StringUtils.trimToEmpty(req.getParameter("count"));
this.depositPrice = StringUtils.trimToEmpty(req.getParameter("depositPrice")).replace(',', '.');
this.description = StringUtils.trimToNull(req.getParameter("description"));
}
@Override
public String toString() {
return "{" +
"count=" + count +
", depositPrice=" + depositPrice +
", description=" + description +
'}';
}
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/dto/rent/AddEditEquipmentCartReqDto.java |
180,355 | package java26.zad1.zad1.WypozyczalniaWodna;
import java26.zad1.zad1.zad2.TypPojazdu;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws NieMaTakiegoSprzetuException {
Wypozyczalnia wypozyczalnia = new Wypozyczalnia();
Scanner input = new Scanner(System.in);
String komenda;
do {
System.out.println("Podaj komendę:\n Wypozyczenie nrBurtowy, jaki sprzet\n Oddanie nrBurtowy \n Sprawdzenie nrBurtowy" +
"\nWyjscie");
komenda = input.nextLine();
String[] slowa = komenda.split(" ");
if (slowa[0].equalsIgnoreCase("wjazd")) {
if (slowa.length == 3) {
String nrBurtowyPodanyPrzezUzytkownika = slowa[1];
String sprzetPodanyPrzezUzytkownika = slowa[2];
try { //wyłuskanie typu sprzętu: JAcht, KAJAK.., żeby to wpisac w metodę
Sprzet sprzet = Sprzet.valueOf(slowa[2].toUpperCase());
wypozyczalnia.wypozyczenie(nrBurtowyPodanyPrzezUzytkownika, sprzet);
}catch (IllegalArgumentException illae) {
System.err.println("Nie ma takiego rodzaju SPRZęTU");
}
}
}else if (slowa[0].equalsIgnoreCase("oddanie")){
if (slowa.length ==2){
String numerBurtowyWpisany = slowa[1];
System.out.println(wypozyczalnia.zakonczenieWypozyczenia(numerBurtowyWpisany));
}
}else if (slowa[0].equalsIgnoreCase("sprawdzenie")){
if (slowa.length==2){
String numerBurtowyWpisany = slowa[1];
System.out.println(wypozyczalnia.znajdzSprzet(numerBurtowyWpisany));
}
}
}while (!komenda.equalsIgnoreCase("Wyjscie"));
}
}
| MattWroclaw/collections_exc2 | src/main/java/java26/zad1/zad1/WypozyczalniaWodna/Main.java |
180,357 | package com.myprojects.gza.myGymApp.controller;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.DateTimeFormat.ISO;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.myprojects.gza.myGymApp.captcha.ICaptchaService;
import com.myprojects.gza.myGymApp.entity.Equipment;
import com.myprojects.gza.myGymApp.entity.FitnessEvent;
import com.myprojects.gza.myGymApp.entity.Trainer;
import com.myprojects.gza.myGymApp.entity.Workout;
import com.myprojects.gza.myGymApp.service.EquipmentService;
import com.myprojects.gza.myGymApp.service.FitnessEventService;
import com.myprojects.gza.myGymApp.service.TrainerService;
import com.myprojects.gza.myGymApp.service.WorkoutService;
@Controller
public class MainController {
@Autowired
private ICaptchaService captchaService;
@Autowired
private TrainerService trainerService;
@Autowired
private WorkoutService workoutService;
@Autowired
private FitnessEventService fitnessEventService;
@Autowired
private EquipmentService equipmentService;
@GetMapping("/")
public String showIndex() {
return "index";
}
@GetMapping("/access-denied")
public String showAccessDenied() {
return "access-denied";
}
@GetMapping("/fitnessEvents")
public String showFitnessEvents(Model model) {
LocalDate localDate=LocalDate.now();
addToModelFitnessEventsInSelectedWeek(localDate, model);
return "fitnessEvents";
}
@PostMapping("/fitnessEvents/nextWeek")
public String showFitnessEventsInNextWeek(@ModelAttribute("selectedDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate, Model model) {
localDate=localDate.plusDays(7);
addToModelFitnessEventsInSelectedWeek(localDate, model);
return "fitnessEvents";
}
@PostMapping("/fitnessEvents/previousWeek")
public String showFitnessEventsInPreviousWeek(@ModelAttribute("selectedDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate localDate, Model model) {
localDate=localDate.minusDays(7);
addToModelFitnessEventsInSelectedWeek(localDate, model);
return "fitnessEvents";
}
private void addToModelFitnessEventsInSelectedWeek(LocalDate localDate, Model model) {
List<FitnessEvent> fitnessEvents=fitnessEventService.getAllEventsInSpecifiedWeek(localDate);
model.addAttribute("events", fitnessEvents);
setDateParameters(model, localDate);
}
private void setDateParameters(Model model, LocalDate localDate) {
model.addAttribute("selectedDate",localDate);
model.addAttribute("mondayOfCurrentWeek",localDate.minusDays(localDate.getDayOfWeek().getValue()-1));
model.addAttribute("sundayOfCurrentWeek", localDate.plusDays(7-localDate.getDayOfWeek().getValue()));
model.addAttribute("localDateTimeFormat", DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm"));
}
@GetMapping("/logIn")
public String showLogIn(Model model) {
String site=captchaService.getReCaptchaSite();
model.addAttribute("siteKey", site);
return "log-in";
}
@GetMapping("/trainers/list")
public String showTrainers(Model model) {
List<Trainer> trainers=trainerService.getTrainers();
model.addAttribute("trainers", trainers);
System.out.println(trainers.toString());
return "trainers";
}
@GetMapping("/workouts/list")
public String showWorkouts(Model model) {
List<Workout> workouts=workoutService.getWorkouts();
model.addAttribute("workouts", workouts);
return "workouts";
}
@GetMapping("/equipment")
public String showEquipment(Model model) {
List<Equipment> equipments=equipmentService.getAll();
if(equipments.size()==0) {
model.addAttribute("info", "Brak dodanego sprzętu.");
}
model.addAttribute("equipments", equipments);
return "equipments";
}
}
| gzacharski/System-Obslugi-Silowni | src/main/java/com/myprojects/gza/myGymApp/controller/MainController.java |
180,358 | /*
* Copyright (c) 2024 by MILOSZ GILGA <https://miloszgilga.pl>
* Silesian University of Technology
*/
package pl.polsl.skirentalservice.pdf;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.element.Paragraph;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.entity.ContentType;
import pl.polsl.skirentalservice.dto.PriceUnitsDto;
import pl.polsl.skirentalservice.exception.ServletException;
import pl.polsl.skirentalservice.pdf.dto.GeneratedPdfData;
import pl.polsl.skirentalservice.pdf.dto.PdfDocumentData;
import pl.polsl.skirentalservice.pdf.dto.PdfEquipmentDataDto;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public abstract class AbstractPdfGenerator {
private final String headerText;
private final String contentText;
protected final Map<String, String> leftComponents;
protected final Map<String, String> rightComponents;
private static final ContentType APPLICATION_PDF = ContentType.create("application/pdf");
private static final String[] TABLE_HEADERS = {
"Nazwa sprzętu", "Ilość", "Cena netto", "Cena brutto", "Kaucja netto", "Kaucja brutto",
};
AbstractPdfGenerator(String headerText, String contentText) {
this.headerText = headerText;
this.contentText = contentText;
leftComponents = new HashMap<>();
rightComponents = new HashMap<>();
}
public GeneratedPdfData generate(PdfDocumentData pdfData) {
GeneratedPdfData generatedPdfData;
final String fileName = pdfData.getIssuedIdentifier().replaceAll("/", "-") + ".pdf";
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try (final PdfWriter pdfWriter = new PdfWriter(outputStream)) {
final CustomPdfDocument document = createDocument(pdfWriter);
final PriceUnitsDto units = pdfData.getPriceUnits();
appendToLeftComponents(pdfData);
appendToRightComponents(pdfData);
// header
final CustomPdfTable headerTable = new CustomPdfTable(new float[]{ 60, 40 });
headerTable.addCell(CustomPdfCell.createHeaderTableCell(headerText));
final CustomPdfTable headerRightContentTable = new CustomPdfTable(2);
headerRightContentTable.addInlineKeyValueData("Nr " + headerText, pdfData.getIssuedIdentifier());
headerRightContentTable.addInlineKeyValueData("Data " + headerText, setHeaderDate(pdfData));
headerTable.appendTableToTable(headerRightContentTable);
document.add(headerTable);
document.addHorizontalDivider();
// left and right details
final CustomPdfTable detailsTable = new CustomPdfTable(2);
detailsTable.appendColumnCells("Dane klienta", leftComponents);
detailsTable.appendColumnCells("Dane " + headerText, rightComponents);
document.add(detailsTable);
document.addHorizontalDivider();
// equipments table data
document.addHeader(contentText);
final CustomPdfTable equipmentsTable = new CustomPdfTable(TABLE_HEADERS.length, 10f);
equipmentsTable.addHeader(TABLE_HEADERS);
for (final PdfEquipmentDataDto pdfEquipment : pdfData.getEquipments()) {
equipmentsTable.addDataCell(pdfEquipment.getName());
equipmentsTable.addDataCell(pdfEquipment.getCount() + " szt.");
equipmentsTable.addDataCell(pdfEquipment.getPriceNetto() + " zł");
equipmentsTable.addDataCell(pdfEquipment.getPriceBrutto() + " zł");
equipmentsTable.addDataCell(pdfEquipment.getDepositPriceNetto() + " zł");
equipmentsTable.addDataCell(pdfEquipment.getDepositPriceBrutto() + " zł");
}
document.add(equipmentsTable);
// prices section
document.addPriceUnitBruttoParagraph("Cena za wypożyczenie (brutto): " + units.getTotalPriceBrutto());
document.addPriceUnitNettoParagraph("(netto): " + units.getTotalPriceNetto() + " zł");
document.add(new Paragraph("\n").setFixedLeading(2f));
document.addPriceUnitBruttoParagraph("+ kaucja (brutto): " + units.getTotalDepositPriceBrutto());
document.addPriceUnitNettoParagraph("(netto): " + units.getTotalDepositPriceNetto() + " zł");
document.addPricesDivider();
// summary prices section
document.addSummaryPriceUnitBruttoParagraph("Łącznie (brutto): " + pdfData.getTotalSumPriceBrutto());
document.addSummaryPriceUnitNettoParagraph("(netto): " + pdfData.getTotalSumPriceNetto());
document.addHorizontalDivider();
// description section
document.addDetailsDescription(pdfData.getDescription());
document.close();
generatedPdfData = GeneratedPdfData.builder()
.filename(fileName)
.pdfData(outputStream.toByteArray())
.type(APPLICATION_PDF)
.build();
outputStream.close();
log.info("Pdf FV file: {} was successfully generated. Pdf data: {}", fileName, pdfData);
} catch (IOException ex) {
throw new ServletException.PdfGeneratorException(ex);
}
return generatedPdfData;
}
protected CustomPdfDocument createDocument(PdfWriter pdfWriter) throws IOException {
final PdfDocument pdfDocument = new PdfDocument(pdfWriter);
pdfDocument.setDefaultPageSize(PageSize.A4);
return new CustomPdfDocument(pdfDocument);
}
protected void appendToLeftComponents(PdfDocumentData pdfDocumentData) {
leftComponents.put("Imię i nazwisko", pdfDocumentData.getFullName());
leftComponents.put("Nr PESEL", pdfDocumentData.getPesel());
leftComponents.put("Nr telefonu", pdfDocumentData.getPhoneNumber());
leftComponents.put("Adres email", pdfDocumentData.getEmail());
leftComponents.put("Adres", pdfDocumentData.getAddress());
}
protected abstract String setHeaderDate(PdfDocumentData pdfDocumentData);
protected abstract void appendToRightComponents(PdfDocumentData pdfDocumentData);
}
| milosz08/ski-rental-service | src/main/java/pl/polsl/skirentalservice/pdf/AbstractPdfGenerator.java |
180,367 | import java.util.Scanner;
public class Triangle
{
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Write how many rows of triangle you want to have");
int nofrows = reader.nextInt();
int i,k,z;
int nofpossiblesums = 2 ^ (nofrows -1);
int[][] chart2 = new int[nofrows][nofpossiblesums];
int l = 0;
int[][] chart1 = new int[nofrows][nofrows];
for(i = 0; i<nofrows; i++){
System.out.println("Podajesz liczby do rzedu " + (i+1));
for( z = 0; z<i +1; z++){
System.out.println("Input a number to a triangle");
chart1[i][z] = reader.nextInt();}
}
System.out.println("Twoj trojkat wyglada tak");
for(i = 0; i<nofrows; i++){
for(z = l; z<nofrows; z++){
System.out.print(" ");
}
for(k = 0; k<i+1; k++){
System.out.print(chart1[i][k] + " ");
}
System.out.println();
l = l+1;
}
for(int q =0; q<nofrows; q++){
for(int w = 0; w<nofrows; w++){
System.out.print(chart1[q][w] + " ");
}
System.out.println();
}
}
}
| sourcecodeQC/Computer-Science-IB-DP1 | Loops/Triangle.java |
180,379 | public class Loops {
public static void main(String[] args) {
int[] numbers = {2, 5, 1, 3, 4};
System.out.println("Suma liczb wynosi " + sumOfnumbers(numbers));
}
public static int sumOfnumbers(int[] numbers) {
int sumOfNumbers = 0; //inicjujesz zmienna do sumowania wyniku przed petla
for (int i = 0; i < numbers.length; i++) { //petla przejdzie 5 razy -> dla i = 0 do i = 4
sumOfNumbers = sumOfNumbers + numbers[i]; //do sumy 0 dodajesz element i z tablicy, gdzie i masz od 0 do 4 xD
System.out.println(i + 1 + " przejscie petli, gdzie suma wynosi dotychczas " + sumOfNumbers);
}
return sumOfNumbers;
}
} | Jaglano/jakub_glanas-kodilla_tester | kodilla-intro/src/main/java/Loops.java |
180,386 | package trading;
import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import net.dv8tion.jda.api.EmbedBuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.Member;
import net.dv8tion.jda.api.entities.MessageEmbed;
import net.dv8tion.jda.api.entities.Role;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.emoji.Emoji;
import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent;
import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.interactions.components.Modal;
import net.dv8tion.jda.api.interactions.components.text.TextInput;
import net.dv8tion.jda.api.interactions.components.text.TextInputStyle;
import net.dv8tion.jda.api.requests.RestAction;
import org.bson.Document;
import java.awt.*;
import java.util.ArrayList;
import java.util.Collection;
public class funcMethods extends tradingChannels {
public static MongoClient MongoConnection(){
ConnectionString connectionString = new ConnectionString("mongodb+srv://losokos:" + System.getenv("MONGO")+ "@darkanddarkerpolska.ksmqiog.mongodb.net/");
MongoClientSettings settings = MongoClientSettings.builder()
.applyConnectionString(connectionString)
.build();
return MongoClients.create(settings);
}
public static Modal tradingModal(ButtonInteractionEvent event , String rola){
if(rola != "middleman") {
TextInput graczInput = TextInput.create("graczInput", "Nazwa/ID gracza do handlu", TextInputStyle.SHORT)
.setPlaceholder(event.getMember().getEffectiveName() + " lub " + event.getMember().getUser().getId())
.setRequiredRange(0, 100)
.setRequired(true)
.build();
TextInput przedmiotInput = null;
if (rola == "kupiec")
przedmiotInput = TextInput.create("przedmiotInput", "Jaki przedmiot kupujesz?", TextInputStyle.SHORT)
.setPlaceholder("np: 10 kluczy")
.setRequiredRange(0, 100)
.setRequired(false)
.build();
else if (rola == "sprzedawca")
przedmiotInput = TextInput.create("przedmiotInput", "Jaki przedmiot sprzedajesz?", TextInputStyle.SHORT)
.setPlaceholder("np: 10 kluczy")
.setRequiredRange(0, 100)
.setRequired(false)
.build();
TextInput rolaInput = TextInput.create("rolaInput", "Kupiec czy sprzedawca? (nie zmieniaj)", TextInputStyle.SHORT)
.setValue(rola)
.setPlaceholder(rola)
.setRequiredRange(0, 100)
.setRequired(true)
.build();
Modal modal = Modal.create("handelGraczyModal", "Nowy kana\u0142 handlu")
.addActionRows(ActionRow.of(graczInput), ActionRow.of(przedmiotInput), ActionRow.of(rolaInput)).build();
return modal;
}
else{
//TUTAJ DO ZMIANY!!!!
TextInput graczInput = TextInput.create("graczInput", "Nazwa/ID gracza do handlu", TextInputStyle.SHORT)
.setPlaceholder(event.getMember().getEffectiveName() + " lub " + event.getMember().getUser().getId())
.setRequiredRange(0, 100)
.setRequired(true)
.build();
TextInput przedmiotInput = null;
if (rola == "kupiec")
przedmiotInput = TextInput.create("przedmiotInput", "Jaki przedmiot kupujesz?", TextInputStyle.SHORT)
.setPlaceholder("np: 10 kluczy")
.setRequiredRange(0, 100)
.setRequired(false)
.build();
else if (rola == "sprzedawca")
przedmiotInput = TextInput.create("przedmiotInput", "Jaki przedmiot sprzedajesz?", TextInputStyle.SHORT)
.setPlaceholder("np: 10 kluczy")
.setRequiredRange(0, 100)
.setRequired(false)
.build();
TextInput rolaInput = TextInput.create("rolaInput", "Kupiec czy sprzedawca? (nie zmieniaj)", TextInputStyle.SHORT)
.setValue(rola)
.setPlaceholder(rola)
.setRequiredRange(0, 100)
.setRequired(true)
.build();
Modal modal = Modal.create("handelMiddlemanModal", "Nowy kana\u0142 handlu")
.addActionRows(ActionRow.of(graczInput), ActionRow.of(przedmiotInput), ActionRow.of(rolaInput)).build();
return modal;
}
}
public static void createTradingChannel(ModalInteractionEvent event, boolean isMiddleManPresent, String invitedMemberID, String tradedItem, String creatorTradeRole){
MongoClient mongoClient = funcMethods.MongoConnection();
MongoDatabase database = mongoClient.getDatabase("Trading");
MongoCollection<Document> channelsCollection = database.getCollection("channels");
if(!isMiddleManPresent) {
if(tradedItem.isBlank())
tradedItem = "Nie podano przedmiotu.";
Guild guild = event.getGuild();
Role everyoneRole = guild.getRoleById("1046510699809079448"); // ZMIENIAC ID MIEDZY SERWEREM TESTOWYM A ZWYKŁYM
Role graczRole = guild.getRoleById("1154522982769774734");// ZMIENIAC ID MIEDZY SERWEREM TESTOWYM A ZWYKŁYM
Member creator = event.getMember();
Member invitedMember = guild.getMemberById(invitedMemberID);
Category RMTmarketCategory = guild.getCategoryById("1154518031435837440");
Collection<Permission> memberAllowPerms = new ArrayList<>();
memberAllowPerms.add(Permission.VIEW_CHANNEL);
Collection<Permission> memberDenyPerms = new ArrayList<>();
memberDenyPerms.add(Permission.MESSAGE_MANAGE);
memberDenyPerms.add(Permission.CREATE_PRIVATE_THREADS);
memberDenyPerms.add(Permission.CREATE_PUBLIC_THREADS);
memberDenyPerms.add(Permission.MESSAGE_SEND);
memberDenyPerms.add(Permission.MESSAGE_ADD_REACTION);
Collection<Permission> roleDenyPerms = new ArrayList<>();
roleDenyPerms.add(Permission.VIEW_CHANNEL);
String finalTradedItem = tradedItem;
RMTmarketCategory.createTextChannel(creator.getUser().getName().toLowerCase() + " room")
.addMemberPermissionOverride(creator.getIdLong(), memberAllowPerms, memberDenyPerms)
.addMemberPermissionOverride(invitedMember.getIdLong(), memberAllowPerms, memberDenyPerms)
.addRolePermissionOverride(everyoneRole.getIdLong(), null, roleDenyPerms)
.addRolePermissionOverride(graczRole.getIdLong(), null, roleDenyPerms)
.setTopic("Prywatny kana\u0142 handlu mi\u0119dzy: " + creator.getAsMention() + " a " + invitedMember.getAsMention())
.queue(channel -> {
channel.sendMessageEmbeds(newChannelMessage(false, creator, creatorTradeRole, invitedMember, finalTradedItem)).queue(message -> {
message.pin().queue();
message.addReaction(Emoji.fromUnicode("\uD83D\uDC4D")).queue();
System.out.println(channel.getPermissionOverrides());
});
Document document = new Document()
.append("channelID", channel.getId())
.append("creatorID", creator.getId())
.append("invitedMemberID", invitedMemberID)
.append("tradedItem", finalTradedItem)
.append("isMiddleManPresent", false)
.append("isActive", false);
channelsCollection.insertOne(document);
event.getHook().editOriginal("Nowy kana\u0142 do RMT zosta\u0142 stworzony: " + channel.getAsMention()).queue();
});
}
}
public static MessageEmbed newChannelMessage(boolean isMiddleManPresent, Member creator, String creatorTradeRole, Member invitedMember, String tradedItem){
EmbedBuilder embedBuilder = new EmbedBuilder();
MessageEmbed messageEmbed = null;
embedBuilder.setColor(Color.ORANGE);
embedBuilder.addField("Ustalony przedmiot wymiany: ", "**" + tradedItem + "**", false);
if(!isMiddleManPresent)
if(creatorTradeRole.equals("kupiec"))
messageEmbed = embedBuilder.setTitle("Stworzono prywatny trade room!")
.addField("", "**Kupuj\u0105cy:**" + creator.getAsMention(), false)
.addField("", "**Sprzedawca:**" + invitedMember.getAsMention(), false)
.build();
else if(creatorTradeRole.equals("sprzedawca"))
messageEmbed = embedBuilder.setTitle("Stworzono prywatny trade room!")
.addField("", "**Kupuj\u0105cy:** " + invitedMember.getAsMention(), false)
.addField("", "**Sprzedawca:** " + creator.getAsMention(), false)
.build();
else{
messageEmbed = embedBuilder.setTitle("Stworzono prywatny trade room!")
.addField("test", "DSADSAa", false)
.build();
}
return messageEmbed;
}
} | LosokosG/Matchmaker-bot | src/main/java/trading/funcMethods.java |
180,387 | package pl.rentowne.apartment.model;
import jakarta.persistence.*;
import lombok.*;
import pl.rentowne.address.model.Address;
import pl.rentowne.common.model.BaseEntity;
import pl.rentowne.housing_provider.model.HousingProvider;
import pl.rentowne.rented_object.model.RentedObject;
import pl.rentowne.user.model.User;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
@Getter
@Setter
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(
name = "APARTMENT",
uniqueConstraints = {
@UniqueConstraint(name = "PK_APARTMENT", columnNames = "APARTMENT_ID"),
@UniqueConstraint(name = "UK_APARTMENT_1", columnNames = "ADDRESS_ID")
},
indexes = {
@Index(name = "PK_APARTMENT", columnList = "APARTMENT_ID", unique = true),
@Index(name = "UK_APARTMENT_1", columnList = "ADDRESS_ID", unique = true),
@Index(name = "I_APARTMENT_1", columnList = "APARTMENT_NAME"),
}
)
public class Apartment extends BaseEntity {
@Id
@SequenceGenerator(name = "apartment_seq", sequenceName = "APARTMENT_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "apartment_seq")
@Column(name = "APARTMENT_ID", nullable = false)
private Long id;
@Column(name = "APARTMENT_NAME", nullable = false, length = 60)
private String apartmentName;
@Column(name = "LEASES_NUMBER", nullable = false)
private BigInteger leasesNumber;
@Column(name = "AREA", nullable = false)
private BigDecimal area;
@Column(name = "IS_RENTED", nullable = false)
private boolean isRented;
@Column(name = "IMAGE", length = 128)
private String image;
@Column(name = "PINNED", nullable = false)
private boolean pinned;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "ADDRESS_ID", unique = true)
private Address address;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "apartment")
private Set<RentedObject> rentedObjects;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "USER_ACCOUNT_ID")
private User user;
@ManyToMany(mappedBy = "apartments")
private Set<HousingProvider> housingProviders = new HashSet<>();
public Apartment(Long id) {
this.id = id;
}
//set nie zadziała, tzn gdy dodajesz nowe obiekty, wtedy one mają id = null, jak trzeba dodaj UUID lub nowy uniqueContraint z polem
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Apartment apartment = (Apartment) o;
return Objects.equals(id, apartment.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
}
| S4lemq/Rentowne | src/main/java/pl/rentowne/apartment/model/Apartment.java |
180,388 | package sample.gui.views;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.BooleanBinding;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import sample.database.Grade;
import sample.database.Student;
import sample.database.Subject;
import sample.database.Teacher;
import sample.databaseCommunication.DatabaseCommunicator;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class TableStudent {
private final String[] possibleGrades = {"1", "2", "3", "4", "5", "6"};
private ArrayList<Button> grades;
private HBox gradesBox;
private Button button;
private final Subject subject;
private final Student student;
private final Teacher teacher;
private final TeacherViewController teacherViewController;
private final ViewSwitcher viewSwitcher;
private final DatabaseCommunicator communicator;
public TableStudent(Student student, Subject subject, Teacher teacher, List<Grade> grades,
ViewSwitcher viewSwitcher, TeacherViewController teacherViewController) {
this.teacherViewController = teacherViewController;
this.student = student;
this.teacher = teacher;
this.subject = subject;
this.viewSwitcher = viewSwitcher;
this.gradesBox = new HBox();
this.grades = new ArrayList<>();
this.communicator = viewSwitcher.getCommunicator();
startAddGradeButton();
startGradeButtons(grades);
}
private void startAddGradeButton() {
this.button = new Button();
this.button.setText("Dodaj");
this.button.setOnAction((event) -> {
TextInputDialog addGradeDialog = new TextInputDialog();
addGradeDialog.setTitle("Dodawanie ocen");
addGradeDialog.setHeaderText("Dodajesz ocenę " + student.getFullName());
Button okButton = (Button) addGradeDialog.getDialogPane().lookupButton(ButtonType.OK);
TextField inputField = addGradeDialog.getEditor();
BooleanBinding isInvalid = Bindings.createBooleanBinding(() -> isInvalid(inputField.getText()), inputField.textProperty());
okButton.disableProperty().bind(isInvalid);
Optional<String> result = addGradeDialog.showAndWait();
result.ifPresent(this::addGrade);
});
}
private void startGradeButtons(List<Grade> grades) {
for (Grade g : grades) {
Button gradeButton = new Button();
gradeButton.setText(Integer.toString(g.getMark()));
gradeButton.setOnAction((event) -> {
TextInputDialog editGradeDialog = new TextInputDialog();
ButtonType editButton = new ButtonType("Edytuj");
ButtonType deleteButton = new ButtonType("Usuń");
ButtonType cancelButton = new ButtonType("Anuluj", ButtonBar.ButtonData.CANCEL_CLOSE);
editGradeDialog.getDialogPane().getButtonTypes().clear();
editGradeDialog.getDialogPane().getButtonTypes().addAll(editButton, deleteButton, cancelButton);
editGradeDialog.setTitle("Edytowanie ocen");
editGradeDialog.setHeaderText("Edytujesz ocenę " + student.getFullName());
editGradeDialog.setContentText("Ocena: " + gradeButton.getText());
editGradeDialog.setResultConverter((dialogButton) -> {
if (dialogButton == editButton) return editGradeDialog.getEditor().getText();
else if (dialogButton == deleteButton) deleteGrade(g);
return null;
});
Optional<String> result = editGradeDialog.showAndWait();
result.ifPresent(str -> editGrade(str, g));
});
this.grades.add(gradeButton);
this.gradesBox.getChildren().add(gradeButton);
}
}
private boolean isInvalid(String gradeText) {
for (String s : possibleGrades) {
if (gradeText.equals(s)) return false;
}
return true;
}
private void addGrade(String gradeStr) {
Grade gradeToInsert = new Grade(Integer.parseInt(gradeStr), subject, student, teacher);
communicator.insertGradeToDatabase(gradeToInsert);
teacherViewController.updateTable();
}
private void editGrade(String gradeStr, Grade grade) {
communicator.editGrade(grade, Integer.parseInt(gradeStr));
teacherViewController.updateTable();
}
private void deleteGrade(Grade grade) {
communicator.deleteGrade(grade);
teacherViewController.updateTable();
}
/* DO NOT DELETE */
public String getFirstname() {
return student.getFirstname();
}
public Student getStudent() {
return student;
}
public String getLastname() {
return student.getLastname();
}
public ArrayList<Button> getGrades() {
return grades;
}
public Button getButton() {
return button;
}
public HBox getGradesBox() {
return gradesBox;
}
/**/
}
| Sirtus/eDziennik | src/main/java/sample/gui/views/TableStudent.java |
180,394 | package org.example.advanced.escape_room;
public class ActionFactory {
public Item createAction(String item) {
if (item.equals("window")) {
return new WindowItem();
} else if (item.equals("key")) {
return new KeyItem();
}
throw new IllegalStateException("Nie przewidziano przedmiotu o nazwie " + item);
}
//gdy dodajesz nowy typ obiektu w hierarchi dziedziczenia do programu to program powinien zostać zmodyfikowany max w jednym miejscu
//L soLid
} | Konrad66/small-projects | male-zadania/src/main/java/org/example/advanced/escape_room/ActionFactory.java |
180,396 | package iteracja.trzecia.kolekcje.listy.wprowadzenie;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Zadania4Grudnia {
public static void main(String[] args) {
//Napisz metode która odwraca kolejnosc liczb w liscie ktora jest podana jako parametr\
System.out.println("Zadanie1");
List<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(4);
numbers.add(6);
System.out.println("Original list: " + numbers);
System.out.println("Reversed list: " + reverseList(numbers));
//Napisz metoda ktora sortuje kolekcje malejaco
System.out.println("Zadanie2");
List<Integer> numbersTwo = new ArrayList<>();
numbersTwo.add(5);
numbersTwo.add(2);
numbersTwo.add(8);
numbersTwo.add(1);
System.out.println("Original list: " + numbersTwo);
System.out.println("Sorted descending list: " + sortDescending(numbersTwo));
// 3) Napisz metode ktora jako argument pobiera liste integerow a jako wynik zwraca ilosc
// roznych liczb na liscie. (np: podajesz [1,1,1,2,2,2] powinno zwrocic 2) - pomocna bedzie metoda contains.
System.out.println("Zadanie3");
List<Integer> numbers2 = new ArrayList<>();
numbers2.add(1);
numbers2.add(1);
numbers2.add(1);
numbers2.add(2);
numbers2.add(2);
numbers2.add(2);
System.out.println("List of numbers: " + numbers2);
int distinctCount = countDistinctNumbers(numbers2);
System.out.println("Number of distinct numbers: " + distinctCount);
// 2) Napisz metode ktora jako argument pobiera liste integerow
// a jako wynik zwraca najpopularniejszego inta na liscie (np: podajesz [1,2,3,3,3,3,4,4,5]
// to powinno zwrocic 3]
System.out.println("Zadanie4");
List<Integer> manyNumbers = Arrays.asList(1, 2, 3, 3, 3, 3, 4, 4, 5);
// List<Integer> manyNumbers = Arrays.asList(2, 2, 2, 2, 1, 2, 3, 3, 3, 3, 4, 4, 5);
System.out.println("List of numbers: " + manyNumbers);
int mostFrequent = findMostFrequent(manyNumbers);
System.out.println("Most frequent number: " + mostFrequent);
// 3) Napisz metode ktora jako argument pobiera liste imion i jako wynik zwraca najdluzsze imie meskie.
//przetestuj dla min dwoch przypadkow [Aleksandra, Jurek, Zenek, Amadeusz] oraz [Ola, Ania, Ula].
System.out.println("Zadanie5");
List<String> names1 = Arrays.asList("Aleksandra", "Jurek", "Zenek", "Amadeusz");
List<String> names2 = Arrays.asList("Ola", "Ania", "Ula");
System.out.println("List of names 1: " + names1);
System.out.println("Longest male name 1: " + findLongestMaleName(names1));
System.out.println("List of names 2: " + names2);
System.out.println("Longest male name 2: " + findLongestMaleName(names2));
}
public static List<Integer> reverseList(List<Integer> list) {
List<Integer> index = new ArrayList<>(list);
Collections.reverse(index);
return index;
}
public static List<Integer> sortDescending(List<Integer> list) {
List<Integer> index = new ArrayList<>(list);
Collections.sort(index, Collections.reverseOrder());
return index;
}
public static int countDistinctNumbers(List<Integer> number2) {
List<Integer> differentNumbers = new ArrayList<>();
for (Integer number : number2) {
if (!differentNumbers.contains(number)) {
differentNumbers.add(number);
}
}
return differentNumbers.size();
}
public static int findMostFrequent(List<Integer> list) {
int currentNumber = list.get(0);
int currentCount = 1;
int mostFrequentNumber = currentNumber;
int mostFrequentCount = currentCount;
for (int i = 1; i < list.size(); i++) {
int number = list.get(i);
if (number == currentNumber) {
currentCount++;
} else {
if (currentCount > mostFrequentCount) {
mostFrequentNumber = currentNumber;
mostFrequentCount = currentCount;
}
currentNumber = number;
currentCount = 1;
}
}
if (currentCount > mostFrequentCount) {
mostFrequentNumber = currentNumber;
}
return mostFrequentNumber;
}
public static String findLongestMaleName(List<String> names) {
List<String> maleNames = new ArrayList<>();
for (String name : names) {
if (!name.toLowerCase().endsWith("a")) {
maleNames.add(name);
}
}
if (maleNames.isEmpty()) {
return "No male names";
}
String longestMaleName = maleNames.get(0);
for (String name : maleNames) {
if (name.length() > longestMaleName.length()) {
longestMaleName = name;
}
}
return longestMaleName;
}
}
| JakubMroczka/kurs | src/iteracja/trzecia/kolekcje/listy/wprowadzenie/Zadania4Grudnia.java |
180,400 | package com.pjatk.turtlegame.controllers;
import com.pjatk.turtlegame.config.TurtleUserDetails;
import com.pjatk.turtlegame.models.DTOs.EggsForm;
import com.pjatk.turtlegame.models.DTOs.SellTurtle;
import com.pjatk.turtlegame.models.User;
import com.pjatk.turtlegame.repositories.ItemOwnerMarketRepository;
import com.pjatk.turtlegame.repositories.UserRepository;
import com.pjatk.turtlegame.services.ItemService;
import com.pjatk.turtlegame.services.TurtleEggService;
import com.pjatk.turtlegame.services.TurtleService;
import com.pjatk.turtlegame.services.UserService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping(path = "/nest")
@AllArgsConstructor
public class NestController {
UserRepository userRepository;
ItemOwnerMarketRepository itemOwnerMarketRepository;
UserService userService;
TurtleService turtleService;
ItemService itemService;
TurtleEggService turtleEggService;
@GetMapping
public String index(Model model, @AuthenticationPrincipal TurtleUserDetails turtleUserDetails) {
model.addAttribute("context", "nest");
model.addAttribute("eggs", itemService.getEggs(turtleUserDetails.getId()));
model.addAttribute("eggsForm", new EggsForm());
model.addAttribute("sellTurtle", new SellTurtle());
return "pages/nest";
}
@PostMapping("/{id}/sell")
public String sellEgg(@ModelAttribute("sellTurtle") SellTurtle sellTurtle,
@AuthenticationPrincipal TurtleUserDetails turtleUserDetails,
@PathVariable int id,
@RequestParam("Gold") int gold,
@RequestParam("Quantity") int quantity,
Model model,
RedirectAttributes redirectAttributes){
if (!itemOwnerMarketRepository.existsByItemIdAndUserId(id, turtleUserDetails.getId())) {
try {
itemService.sellEgg(turtleUserDetails.getId(), id, gold, quantity);
} catch (Exception e) {
model.addAttribute("eggs", itemService.getEggs(turtleUserDetails.getId()));
redirectAttributes.addFlashAttribute("failedMessage", e.getMessage());
}
} else {
model.addAttribute("eggs", itemService.getEggs(turtleUserDetails.getId()));
redirectAttributes.addFlashAttribute("failedMessage", "Już sprzedajesz to jajko!");
return "pages/nest";
}
return "redirect:/nest";
}
@PostMapping("/{id}/adopt")
public String adoptEgg(@ModelAttribute("eggsForm") EggsForm eggsForm,
@AuthenticationPrincipal TurtleUserDetails turtleUserDetails,
@PathVariable int id,
@RequestParam("Name") String name,
@RequestParam("Gender") int gender,
Model model){
User user = userRepository.findById(turtleUserDetails.getId());
try {
itemService.adoptEgg(user, id, name, gender);
} catch (Exception e) {
model.addAttribute("eggs", itemService.getEggs(turtleUserDetails.getId()));
model.addAttribute("failedMessage", e.getMessage());
return "pages/nest";
}
return "redirect:/nest";
}
@PostMapping("/{id}/warm")
public String warmEgg(@AuthenticationPrincipal TurtleUserDetails turtleUserDetails, @PathVariable int id) throws Exception {
turtleEggService.warmEgg(turtleUserDetails.getId(), id);
return "redirect:/nest";
}
} | TurtleGame/TurtleGame | src/main/java/com/pjatk/turtlegame/controllers/NestController.java |
180,402 | package jgor.heartstealplugin.auctions;
import jgor.heartstealplugin.HeartStealPlugin;
import jgor.heartstealplugin.PlayerLocalOffer;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.block.Skull;
import org.bukkit.entity.Player;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.inventory.meta.SkullMeta;
import org.bukkit.metadata.FixedMetadataValue;
import java.util.*;
public class SellGui {
public static final HashSet<String> categoryNames = new HashSet<>();
public static final String Title = ChatColor.BOLD + "" + ChatColor.GRAY + "["
+ ChatColor.RESET + ChatColor.BOLD + ChatColor.GOLD + "Rynek"
+ ChatColor.RESET + ChatColor.BOLD + ChatColor.GRAY + "]"
+ ChatColor.RESET + ChatColor.BOLD + ChatColor.GOLD + " Sprzedaż";
public static void openSellGui(Player player) {
Inventory sellGui = Bukkit.createInventory(player, 9 * 6, Title);
schematicGuiDesign(sellGui);
categoryNames.clear();
setCategoryItems(sellGui);
createBottomNotPaged(sellGui, false, false);
if (AuctionListeners.playerPriceItemList.containsKey(player.getUniqueId())) {
ItemStack playerConfirmSellButton = new ItemStack(Material.PLAYER_HEAD);
SkullMeta buttonMeta = (SkullMeta) playerConfirmSellButton.getItemMeta();
buttonMeta.setOwningPlayer(player);
buttonMeta.setDisplayName(ChatColor.GOLD + "✮ Kliknij mnie, żeby potwierdźić sprzedaż ✮");
UUID playerUUID = player.getUniqueId();
ArrayList<ItemStack> sellingItems = AuctionCommand.getPlayerSellingItems().get(playerUUID);
ArrayList<Integer> wishedAmounts = AuctionCommand.getPlayerWishedAmountToRemove().get(playerUUID);
int lastIndex = sellingItems.size() - 1;
ItemStack item = sellingItems.get(lastIndex);
int amount = wishedAmounts.get(lastIndex);
buttonMeta.setLore(Arrays.asList(
" ",
ChatColor.GRAY + "Oferujesz " + ChatColor.RESET + ChatColor.GREEN + getDisplayName(item) + ChatColor.RESET + ChatColor.GRAY + " w ilości " + ChatColor.RESET + ChatColor.GREEN + amountToReadable(amount),
" ",
ChatColor.GRAY + "❁ Cena ❁"
));
if (AuctionListeners.playerPriceItemList.containsKey(playerUUID)) {
List<String> lore = buttonMeta.getLore();
ArrayList<ItemStack> price = AuctionListeners.playerPriceItemList.get(playerUUID);
for (ItemStack i : price) {
lore.add(ChatColor.GREEN + " ✔ " + ChatColor.RESET + ChatColor.GRAY + "- " + ChatColor.RESET + ChatColor.DARK_PURPLE + getDisplayName(i) + ChatColor.RESET + ChatColor.GRAY + " ilość " + ChatColor.RESET + ChatColor.DARK_PURPLE + amountToReadable(i.getAmount()));
}
lore.add(" ");
int remainSize = 5 - price.size();
lore.add(ChatColor.GRAY + "Możesz dodać jescze " + ChatColor.RESET + ChatColor.DARK_AQUA + remainSize + ChatColor.RESET + ChatColor.GRAY + " itemy !");
int remainAmount = AuctionListeners.MAX_ITEM_AMOUNT - AuctionListeners.sumPlayerItemAmount.get(playerUUID);
lore.add(ChatColor.GRAY + "Nie możesz przekroczyć " + ChatColor.RESET + ChatColor.DARK_AQUA + remainAmount + ChatColor.RESET + ChatColor.GRAY + " ilości itemów !");
lore.add(" ");
lore.add(compreserTo64(remainAmount));
buttonMeta.setLore(lore);
}
playerConfirmSellButton.setItemMeta(buttonMeta);
sellGui.setItem(4, playerConfirmSellButton);
}
placeStatusItem(sellGui, player);
fillEmptySlots(sellGui, fillItem());
player.openInventory(sellGui);
player.setMetadata(AuctionListeners.SELL_GUI, new FixedMetadataValue(HeartStealPlugin.getInstance(), sellGui));
}
public static void openSellGui(Player player, String s) {
Inventory sellGui = Bukkit.createInventory(player, 9 * 6, Title);
schematicGuiDesign(sellGui);
categoryNames.clear();
setCategoryItems(sellGui);
createBottomNotPaged(sellGui, false, false);
if (AuctionListeners.playerPriceItemList.containsKey(player.getUniqueId())) {
ItemStack playerConfirmSellButton = new ItemStack(Material.PLAYER_HEAD);
SkullMeta buttonMeta = (SkullMeta) playerConfirmSellButton.getItemMeta();
buttonMeta.setOwningPlayer(player);
buttonMeta.setDisplayName(ChatColor.GOLD + "✮ Kliknij mnie, żeby potwierdźić sprzedaż ✮");
UUID playerUUID = player.getUniqueId();
ArrayList<ItemStack> sellingItems = AuctionCommand.getPlayerSellingItems().get(playerUUID);
ArrayList<Integer> wishedAmounts = AuctionCommand.getPlayerWishedAmountToRemove().get(playerUUID);
int lastIndex = sellingItems.size() - 1;
ItemStack item = sellingItems.get(lastIndex);
int amount = wishedAmounts.get(lastIndex);
buttonMeta.setLore(Arrays.asList(
" ",
ChatColor.GRAY + "Oferujesz " + ChatColor.RESET + ChatColor.GREEN + getDisplayName(item) + ChatColor.RESET + ChatColor.GRAY + " w ilości " + ChatColor.RESET + ChatColor.GREEN + amountToReadable(amount),
" ",
ChatColor.GRAY + "❁ Cena ❁"
));
if (AuctionListeners.playerPriceItemList.containsKey(playerUUID)) {
List<String> lore = buttonMeta.getLore();
ArrayList<ItemStack> price = AuctionListeners.playerPriceItemList.get(playerUUID);
for (ItemStack i : price) {
lore.add(ChatColor.GREEN + " ✔ " + ChatColor.RESET + ChatColor.GRAY + "- " + ChatColor.RESET + ChatColor.DARK_PURPLE + getDisplayName(i) + ChatColor.RESET + ChatColor.GRAY + " ilość " + ChatColor.RESET + ChatColor.DARK_PURPLE + amountToReadable(i.getAmount()));
}
lore.add(" ");
int remainSize = 5 - price.size();
lore.add(ChatColor.GRAY + "Możesz dodać jescze " + ChatColor.RESET + ChatColor.DARK_AQUA + remainSize + ChatColor.RESET + ChatColor.GRAY + " itemy !");
int remainAmount = AuctionListeners.MAX_ITEM_AMOUNT - AuctionListeners.sumPlayerItemAmount.get(playerUUID);
lore.add(ChatColor.GRAY + "Nie możesz przekroczyć " + ChatColor.RESET + ChatColor.DARK_AQUA + remainAmount + ChatColor.RESET + ChatColor.GRAY + " ilości itemów !");
lore.add(" ");
lore.add(compreserTo64(remainAmount));
buttonMeta.setLore(lore);
}
playerConfirmSellButton.setItemMeta(buttonMeta);
sellGui.setItem(4, playerConfirmSellButton);
}
placeStatusItem(sellGui, player);
fillEmptySlots(sellGui, fillItem());
player.openInventory(sellGui);
player.setMetadata(AuctionListeners.SELL_GUI, new FixedMetadataValue(HeartStealPlugin.getInstance(), sellGui));
}
private static String amountToReadable(int amount) {
String value;
if (amount <= 64) {
value = String.valueOf(amount);
} else if (amount % 64 == 0) {
int lack = amount / 64;
value = lack + "x64";
} else {
int lack = amount / 64;
int rest = amount - (lack * 64);
value = lack + "x64" + ChatColor.RESET + ChatColor.GRAY + " i " + ChatColor.RESET + ChatColor.DARK_PURPLE + rest;
}
return value;
}
private static String compreserTo64(int amount) {
String text;
if (amount <= 64) {
text = ChatColor.GRAY + "Przelicznik " + ChatColor.RESET + ChatColor.DARK_AQUA + amount + ChatColor.RESET + ChatColor.GRAY + " ► " + ChatColor.RESET + ChatColor.DARK_AQUA + amount;
} else if (amount % 64 == 0) {
int lack = amount / 64;
text = ChatColor.GRAY + "Przelicznik " + ChatColor.RESET + ChatColor.DARK_AQUA + amount + ChatColor.RESET + ChatColor.GRAY + " ► " + ChatColor.RESET + ChatColor.DARK_AQUA + lack + ChatColor.RESET + ChatColor.GRAY + " stacków";
} else {
int lack = amount / 64;
int rest = amount - (lack * 64);
text = ChatColor.GRAY + "Przelicznik " + ChatColor.RESET + ChatColor.DARK_AQUA + amount + ChatColor.RESET + ChatColor.GRAY + " ► " + ChatColor.RESET + ChatColor.DARK_AQUA + lack + ChatColor.RESET + ChatColor.GRAY + " stacków i " + ChatColor.RESET + ChatColor.DARK_AQUA + rest;
}
return text;
}
public static void openPagedCategoryMenu(Player player, String categoryName, int page) {
CategoryMenu.openCategoryMenu(player, categoryName, page);
}
public static void createBottomNotPaged(Inventory menu, boolean previousPageFlag, boolean nextPageFlag) {
ItemStack cancel = new ItemStack(Material.BARRIER);
ItemMeta cancelMeta = cancel.getItemMeta();
cancelMeta.setDisplayName(ChatColor.BOLD + "" + ChatColor.RED + "Powrót");
cancel.setItemMeta(cancelMeta);
menu.setItem(46, cancel);
menu.setItem(52, cancel);
ItemStack nothing = new ItemStack(Material.WHITE_STAINED_GLASS_PANE);
ItemMeta meta = nothing.getItemMeta();
meta.setDisplayName(" ");
nothing.setItemMeta(meta);
menu.setItem(47, nothing);
menu.setItem(51, nothing);
ItemStack previous = getItemStackPrevious(previousPageFlag);
menu.setItem(48, previous);
ItemStack next = getItemStackNext(nextPageFlag);
menu.setItem(50, next);
}
private static ItemStack getItemStackNext(boolean previousPageFlag) {
ItemStack previous;
if (previousPageFlag) {
previous = new ItemStack(Material.LIME_CANDLE);
ItemMeta meta = previous.getItemMeta();
meta.setDisplayName(ChatColor.BOLD + "" + ChatColor.BLUE + "Następna strona");
previous.setItemMeta(meta);
} else {
previous = new ItemStack(Material.WHITE_STAINED_GLASS_PANE);
ItemMeta meta = previous.getItemMeta();
meta.setDisplayName(" ");
previous.setItemMeta(meta);
}
return previous;
}
private static ItemStack getItemStackPrevious(boolean previousPageFlag) {
ItemStack previous;
if (previousPageFlag) {
previous = new ItemStack(Material.RED_CANDLE);
ItemMeta meta = previous.getItemMeta();
meta.setDisplayName(ChatColor.BOLD + "" + ChatColor.BLUE + "Poprzednia strona");
previous.setItemMeta(meta);
} else {
previous = new ItemStack(Material.WHITE_STAINED_GLASS_PANE);
ItemMeta meta = previous.getItemMeta();
meta.setDisplayName(" ");
previous.setItemMeta(meta);
}
return previous;
}
public static void placeStatusItem(Inventory menu, Player player) {
ItemStack status = new ItemStack(Material.BOOK);
ItemMeta meta = status.getItemMeta();
UUID playerUUID = player.getUniqueId();
if (AuctionCommand.getPlayerSellingItems().containsKey(playerUUID) &&
AuctionCommand.getPlayerWishedAmountToRemove().containsKey(playerUUID)) {
ArrayList<ItemStack> sellingItems = AuctionCommand.getPlayerSellingItems().get(playerUUID);
ArrayList<Integer> wishedAmounts = AuctionCommand.getPlayerWishedAmountToRemove().get(playerUUID);
if (sellingItems.size() == 1 && wishedAmounts.size() == 1) {
ItemStack item = sellingItems.get(0);
int amount = wishedAmounts.get(0);
meta.setDisplayName(ChatColor.BOLD + "" + ChatColor.GREEN + "Sprzedajesz: " +
getDisplayName(item) + " w ilości " + amount);
} else {
int lastIndex = sellingItems.size() - 1;
ItemStack item = sellingItems.get(lastIndex);
int amount = wishedAmounts.get(lastIndex);
meta.setDisplayName(ChatColor.BOLD + "" + ChatColor.GREEN + "Sprzedajesz: " +
getDisplayName(item) + " w ilości " + amount);
}
meta.setLore(Arrays.asList(
"",
"◆ Można wybrać maksymalnie 5 itemów ◆",
ChatColor.BOLD + "" + ChatColor.BLUE + "▣ Wybrane itemy nie mogą przekroczyć łącznie 36 stacków ▣"
));
status.setItemMeta(meta);
menu.setItem(49, status);
} else if (AuctionCommand.getPlayerLocalOffers().containsKey(playerUUID)) {
PlayerLocalOffer playerLocalOffer = AuctionCommand.getPlayerLocalOffers().get(playerUUID).getLast();
meta.setDisplayName(ChatColor.BOLD + "" + ChatColor.GREEN + "Sprzedajesz: " +
getDisplayName(playerLocalOffer.item()) + " w ilości ofert " + playerLocalOffer.offerAmount() + " w ilości " + playerLocalOffer.itemAmountInOneOffer());
meta.setLore(Arrays.asList(
"",
"◆ Można wybrać maksymalnie 5 itemów ◆",
ChatColor.BOLD + "" + ChatColor.BLUE + "▣ Wybrane itemy nie mogą przekroczyć łącznie 36 stacków ▣"
));
status.setItemMeta(meta);
menu.setItem(49, status);
}
}
public static String getDisplayName(ItemStack item) {
// Check for null ItemStack
if (item == null) {
return "Unknown Item";
}
// Check for null ItemMeta
if (item.hasItemMeta()) {
ItemMeta itemMeta = item.getItemMeta();
// Check for null DisplayName
if (itemMeta.hasDisplayName()) {
return itemMeta.getDisplayName();
} else {
// Fallback to default name
return getDefaultName(item.getType());
}
} else {
// Fallback to default name
return getDefaultName(item.getType());
}
}
private static String getDefaultName(Material material) {
// Provide default names for specific materials if needed
// For now, returning the material name
return material.toString();
}
private static ItemStack fillItem() {
ItemStack fill = new ItemStack(Material.MAGENTA_STAINED_GLASS_PANE);
ItemMeta meta = fill.getItemMeta();
meta.setDisplayName(" ");
fill.setItemMeta(meta);
return fill;
}
private static void fillEmptySlots(Inventory menu, ItemStack fillItem) {
for (int i = 0; i < menu.getSize(); i++) {
if (menu.getItem(i) == null || menu.getItem(i).getType() == Material.AIR) {
menu.setItem(i, fillItem);
}
}
}
private static ItemStack createCategoryItem(Material material, String name) {
ItemStack natural = new ItemStack(material);
ItemMeta nMeta = natural.getItemMeta();
nMeta.setDisplayName(ChatColor.BOLD + "" + ChatColor.BLUE + name);
categoryNames.add(ChatColor.BLUE + name);
natural.setItemMeta(nMeta);
return natural;
}
public static void setCategoryItems(Inventory menu) {
menu.setItem(12, createCategoryItem(Material.GRASS_BLOCK, "Naturalne Bloki"));
menu.setItem(14, createCategoryItem(Material.BRICKS, "Budowlane Bloki"));
menu.setItem(20, createCategoryItem(Material.ENCHANTING_TABLE, "Funkcjonalne Bloki"));
menu.setItem(22, createCategoryItem(Material.DIAMOND_SWORD, "Walka"));
menu.setItem(24, createCategoryItem(Material.REDSTONE, "Mechanizmy"));
menu.setItem(30, createCategoryItem(Material.BEEF, "Jedzenie"));
menu.setItem(32, createCategoryItem(Material.DIAMOND, "Surowce"));
menu.setItem(40, createCategoryItem(Material.ORANGE_GLAZED_TERRACOTTA, "Kolorowe Bloki"));
menu.setItem(43, createCategoryItem(Material.ENCHANTED_GOLDEN_APPLE, "Specjalne Itemy"));
}
public static void schematicGuiDesign(Inventory menu) {
//TODO GRAY GLASS====================
menu.setItem(0, grayBorderItem());
menu.setItem(2, grayBorderItem());
menu.setItem(4, grayBorderItem());
menu.setItem(6, grayBorderItem());
menu.setItem(8, grayBorderItem());
menu.setItem(18, grayBorderItem());
menu.setItem(36, grayBorderItem());
menu.setItem(26, grayBorderItem());
menu.setItem(44, grayBorderItem());
//TODO GRAY GLASS====================
//TODO BLUE GLASS====================
menu.setItem(1, blueBorderItem());
menu.setItem(3, blueBorderItem());
menu.setItem(5, blueBorderItem());
menu.setItem(7, blueBorderItem());
menu.setItem(9, blueBorderItem());
menu.setItem(17, blueBorderItem());
menu.setItem(27, blueBorderItem());
menu.setItem(35, blueBorderItem());
menu.setItem(45, blueBorderItem());
menu.setItem(53, blueBorderItem());
//TODO BLUE GLASS====================
}
private static ItemStack grayBorderItem() {
ItemStack g = new ItemStack(Material.GRAY_STAINED_GLASS_PANE);
ItemMeta meta = g.getItemMeta();
meta.setDisplayName(" ");
g.setItemMeta(meta);
return g;
}
private static ItemStack blueBorderItem() {
ItemStack b = new ItemStack(Material.BLUE_STAINED_GLASS_PANE);
ItemMeta meta = b.getItemMeta();
meta.setDisplayName(" ");
b.setItemMeta(meta);
return b;
}
}
| jgoraal/HeartStealPlugin | src/main/java/jgor/heartstealplugin/auctions/SellGui.java |
180,403 | package com.pjatk.turtlegame.controllers;
import com.pjatk.turtlegame.config.TurtleUserDetails;
import com.pjatk.turtlegame.exceptions.TurtleNotFoundException;
import com.pjatk.turtlegame.exceptions.UnauthorizedAccessException;
import com.pjatk.turtlegame.models.DTOs.SellTurtle;
import com.pjatk.turtlegame.models.User;
import com.pjatk.turtlegame.repositories.ItemOwnerMarketRepository;
import com.pjatk.turtlegame.repositories.UserRepository;
import com.pjatk.turtlegame.services.ItemService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
@RequestMapping("/items")
@AllArgsConstructor
public class ItemsController {
private final UserRepository userRepository;
ItemOwnerMarketRepository itemOwnerMarketRepository;
private final ItemService itemService;
@GetMapping
public String index(Model model, @AuthenticationPrincipal TurtleUserDetails turtleUserDetails) {
User user = userRepository.findById(turtleUserDetails.getId());
model.addAttribute("context", "items");
model.addAttribute("items", user.getUserItemList());
model.addAttribute("sellTurtle", new SellTurtle());
return "pages/itemsPage";
}
@GetMapping("/{id}/details")
public String itemDetail(Model model,
@AuthenticationPrincipal TurtleUserDetails turtleUserDetails,
@PathVariable int id) throws UnauthorizedAccessException, TurtleNotFoundException {
User user = userRepository.findById(turtleUserDetails.getId());
model.addAttribute("context", "items");
model.addAttribute("item", itemService.getItemDetails(id, user.getId()));
model.addAttribute("statistics", itemService.getItemsStatistics());
return "pages/itemDetails";
}
@PostMapping("/{id}/details")
public String sellItem(Model model,
@ModelAttribute("sellTurtle") SellTurtle sellTurtle,
@AuthenticationPrincipal TurtleUserDetails turtleUserDetails,
@PathVariable int id,
@RequestParam("Gold") int gold,
@RequestParam("Quantity") int quantity,
BindingResult bindingResult, RedirectAttributes redirectAttributes) throws Exception {
User user = userRepository.findById(turtleUserDetails.getId());
if (bindingResult.hasErrors()) {
return "pages/itemDetails";
}
if (!itemOwnerMarketRepository.existsByItemIdAndUserId(id, user.getId())) {
try {
itemService.sellItem(user.getId(), id, gold, quantity);
} catch (Exception e) {
redirectAttributes.addFlashAttribute("failedMessage", e.getMessage());
}
}
else {
redirectAttributes.addFlashAttribute("failedMessage", "Już sprzedajesz ten przedmiot!");
model.addAttribute("context", "items");
model.addAttribute("item", itemService.getItemDetails(id, user.getId()));
model.addAttribute("statistics", itemService.getItemsStatistics());
return "redirect:/items/{id}/details";
}
if (itemService.getItem(id, user.getId())) {
model.addAttribute("context", "items");
model.addAttribute("item", itemService.getItemDetails(id, user.getId()));
model.addAttribute("statistics", itemService.getItemsStatistics());
return "redirect:/items/{id}/details";
}
return "redirect:/items";
}
}
| TurtleGame/TurtleGame | src/main/java/com/pjatk/turtlegame/controllers/ItemsController.java |
180,426 | /*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
---
Copyright (C) 2009, Krzysztof Kundzicz <athantor@gmail.com>
*/
/**
*
*/
package server;
import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import javax.xml.parsers.ParserConfigurationException;
import logging.XHTMLLogger;
import logging.Logger.Lvl;
import settings.SettingsManager;
/**
* @author athantor
*
*/
public final class Server {
private final ServerSocket ssock;
private volatile SettingsManager smngr;
private XHTMLLogger logger;
private ClientManager cmngr;
/**
* @throws IOException
* @throws ParserConfigurationException
*
*/
public Server(SettingsManager sm) throws IOException,
ParserConfigurationException {
ssock = new ServerSocket();
cmngr = new ClientManager();
smngr = sm;
XHTMLLogger.setFile(new File(smngr.getTheDir().getAbsolutePath()
+ File.separatorChar + "eftepd.log.xml"));
logger = XHTMLLogger.getInstance();
}
public void dajesz() throws IOException {
logger.addMiscMsg(null, "Server starting", Lvl.NOTICE);
cmngr.start();
String addr = null;
int port = 21;
Integer climit = 50;
if (smngr.getServerSett().hasProperty("BindPort")) {
try {
port = Integer.parseInt(smngr.getServerSett().getProperty(
"BindPort"));
} catch (Exception e) {
}
}
try {
if (smngr.getServerSett().hasProperty("BindAddress")) {
addr = smngr.getServerSett().getProperty("BindAddress");
ssock.bind(new InetSocketAddress(addr, port));
} else {
ssock.bind(new InetSocketAddress(port));
}
logger.addMiscMsg(null, "Bound to address: "
+ ssock.getInetAddress().toString() + ":"
+ ssock.getLocalPort(), Lvl.NORMAL);
} catch (Exception e) {
logger.addMiscMsg(null, "Failed to bind: "
+ e.getLocalizedMessage(), Lvl.CRITICAL);
return;
}
if (smngr.getServerSett().hasProperty("ConnectionsLimit")) {
try {
climit = Integer.parseInt(smngr.getServerSett().getProperty(
"ConnectionsLimit"));
} catch (Exception e) {
}
}
while (true) {
Socket cs = ssock.accept();
if (cmngr.getClientsCount() >= climit) {
logger.addConnectionMsg(cs, "limit exceeded: "
+ cmngr.getClientsCount(), Lvl.NOTICE);
cs.getOutputStream().write(
"421 There is too many clients connected\r\n"
.getBytes());
cs.close();
} else {
ClientConnection cc = new ClientConnection(cs, logger, smngr);
cmngr.addClient(cc);
}
}
}
public void finalize() {
logger.addMiscMsg(null, "Server exiting", Lvl.NOTICE);
}
}
| Athantor/eftepd | eftepd/src/server/Server.java |
180,427 | package pages.Header.DropdownSection;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import pages.BasePage;
public class DropdownPage extends BasePage {
WebDriver driver;
public DropdownPage(WebDriver driver) {
super(driver);
this.driver = driver;
PageFactory.initElements(driver,this);
}
@FindBy(css = "[data-dropdown-id=\"account_dropdown\"]")
private WebElement mojeAllegroDropdown;
@FindBy(css = "._8ntnf > div > a:nth-child(2)")
private WebElement mojeAllegroDropdownWystawPrzedmiot;
@FindBy(css = "._8ntnf > div > a:nth-child(4)")
private WebElement mojeAllegroDropdownObserwowane;
@FindBy(css = "._8ntnf > div > a:nth-child(5)")
private WebElement mojeAllegroDropdownLicytujesz;
@FindBy(css = "._8ntnf > div > a:nth-child(6)")
private WebElement mojeAllegroDropdownKupione;
@FindBy(css = "._8ntnf > div > a:nth-child(7)")
private WebElement mojeAllegroDropdownOcenSprzedawce;
@FindBy(css = "._8ntnf > div > a:nth-child(8)")
private WebElement mojeAllegroDropdownOcenProdukty;
@FindBy(css = "._8ntnf > div > a:nth-child(9)")
private WebElement mojeAllegroDropdownMonetyiKupony;
@FindBy(css = "._8ntnf > div > a:nth-child(11)")
private WebElement mojeAllegroDropdownMojeOferty;
@FindBy(css = "._8ntnf > div > a:nth-child(12)")
private WebElement mojeAllegroDropdownSprzedajesz;
@FindBy(css = "._8ntnf > div > a:nth-child(13)")
private WebElement mojeAllegroDropdownSprzedane;
@FindBy(css = "._8ntnf > div > a:nth-child(14)")
private WebElement mojeAllegroDropdownMojeOceny;
@FindBy(css = "._8ntnf > div > a:nth-child(15)")
private WebElement mojeAllegroDropdownCentrumZnizek;
@FindBy(css = "._8ntnf > div > a:nth-child(17)")
private WebElement mojeAllegroDropdownMojeKonto;
@FindBy(css = ".opbox-metrum-header__account-login > a:nth-child(2)")
private WebElement mojeAllegroDropdownZalogujButton;
@FindBy(css = "a[href=\"/logout.php\"]")
private WebElement mojeAllegroDropdownWylogujButton;
@FindBy(css = ".opbox-metrum-header__account-login > a:nth-child(3)")
private WebElement mojeAllegroDropdownZalozKontoButton;
@FindBy(css = "._8ntnf > div > div:nth-child(19) > div > div > div > div > div > p > a:nth-child(1)")
private WebElement mojeAllegroDropdownKupTerazGraphics;
@FindBy(css = "._8ntnf > div > div:nth-child(19) > div > div > div > div > div > p > a:nth-child(2) > img")
private WebElement mojeAllegroDropdownSmartGraphics;
public DropdownPage mojeAllegroDropdownClick() {
mojeAllegroDropdown.click();
return this;
}
public boolean waitForAccoutNameVisiblity() {
WebDriverWait wait = new WebDriverWait(driver,5);
wait.until(ExpectedConditions.textToBePresentInElement(mojeAllegroDropdown, "client"));
if (mojeAllegroDropdown.getText().contains("client")) {return true;}
return false;
}
public DropdownPage mojeAllegroDropdownWystawPrzedmiotClick() {
mojeAllegroDropdownWystawPrzedmiot.click();
return this;
}
public DropdownPage mojeAllegroDropdownObserwowaneClick() {
mojeAllegroDropdownObserwowane.click();
return this;
}
public DropdownPage mojeAllegroDropdownLicytujeszClick() {
mojeAllegroDropdownLicytujesz.click();
return this;
}
public DropdownPage mojeAllegroDropdownKupioneClick() {
mojeAllegroDropdownKupione.click();
return this;
}
public DropdownPage mojeAllegroDropdownOcenSprzedawceClick() {
mojeAllegroDropdownOcenSprzedawce.click();
return this;
}
public DropdownPage mojeAllegroDropdownOcenProduktyClick() {
mojeAllegroDropdownOcenProdukty.click();
return this;
}
public DropdownPage mojeAllegroDropdownMonetyiKuponyClick() {
mojeAllegroDropdownMonetyiKupony.click();
return this;
}
public DropdownPage mojeAllegroDropdownMojeOfertyClick() {
mojeAllegroDropdownMojeOferty.click();
return this;
}
public DropdownPage mojeAllegroDropdownSprzedajeszClick() {
mojeAllegroDropdownSprzedajesz.click();
return this;
}
public DropdownPage mojeAllegroDropdownSprzedaneClick() {
mojeAllegroDropdownSprzedane.click();
return this;
}
public DropdownPage mojeAllegroDropdownMojeOcenyClick() {
mojeAllegroDropdownMojeOceny.click();
return this;
}
public DropdownPage mojeAllegroDropdownCentrumZnizekClick() {
mojeAllegroDropdownCentrumZnizek.click();
return this;
}
public DropdownPage mojeAllegroDropdownMojeKontoClick() {
mojeAllegroDropdownMojeKonto.click();
return this;
}
public DropdownPage mojeAllegroDropdownZalogujButtonClick() {
mojeAllegroDropdownZalogujButton.click();
return this;
}
public DropdownPage mojeAllegroDropdownWylogujButtonClick() {
mojeAllegroDropdownWylogujButton.click();
return this;
}
public DropdownPage mojeAllegroDropdownZalozKontoButtonClick() {
mojeAllegroDropdownZalozKontoButton.click();
return this;
}
public DropdownPage mojeAllegroDropdownKupTerazGraphicsClick() {
mojeAllegroDropdownKupTerazGraphics.click();
return this;
}
public DropdownPage mojeAllegroDropdownSmartGraphicsClick() {
mojeAllegroDropdownSmartGraphics.click();
return this;
}
public boolean mojeAllegroDropdownCheckIfUserNameIsVisible(){
String userName = mojeAllegroDropdown.getText();
if (userName.contains("Moje Allegro")) {
return true;
}
else {
return false;
}
}
public WebElement getMojeAllegroDropdown() {
return mojeAllegroDropdown;
}
}
| dariusztu/AllegroTestSuite | src/test/java/pages/Header/DropdownSection/DropdownPage.java |
180,428 | /*
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
---
Copyright (C) 2009, Krzysztof Kundzicz <athantor@gmail.com>
*/
package server;
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.SAXException;
import settings.SettingsManager;
public final class eftepd {
/**
* @param args
* @throws SAXException
* @throws ParserConfigurationException
* @throws IOException
*/
public static void main(String[] args) throws IOException,
ParserConfigurationException, SAXException {
if (args.length != 1) {
System.err.println("Niepoprawna ilosc argumentow: " + args.length
+ "!");
System.exit(1);
} else {
SettingsManager.setSettingsDir(new File(args[0]));
SettingsManager sm = SettingsManager.getInstance();
Server s = new Server(sm);
s.dajesz();
}
}
}
| Athantor/eftepd | eftepd/src/server/eftepd.java |
180,429 | package main.java.UZ.Lab1_P;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Zad4 {
private double min;
private double max;
private double average;
private int quantity;
final private ArrayList<Double> userNumbers = new ArrayList<>();
public static void main(String[] args) throws Exception {
Zad4 temp = new Zad4();
temp.displayStats(12);
}
Zad4() throws Exception {
takeNumberFromUser();
computeStats();
}
private void computeStats() throws Exception {
if (userNumbers.isEmpty()) {
throw new Exception("No numbers to compute stats");
}
quantity = userNumbers.size();
min = Collections.min(userNumbers);
max = Collections.max(userNumbers);
double sum = 0;
for (double number : userNumbers) {
sum += number;
}
average = sum / quantity;
}
private void takeNumberFromUser() {
Scanner scanner = new Scanner(System.in);
printfInstructions();
while (true) {
String input = scanner.nextLine();
if (isQuitCommand(input)) {
break;
}
addNumber(input);
}
scanner.close();
}
private void addNumber(String input) {
/*
Podsumowując, używając Double.parseDouble(input),
uzyskujesz wartość prymitywną double, ale kiedy dodajesz tę wartość do listy userNumbers,
Java automatycznie przekształca tę wartość prymitywną na jej odpowiednik - typ obiektowy Double.
Double.valueOf(input) --> obiekty Double
*/
try {
// double number = Double.parseDouble(input);
Double number = Double.valueOf(input);
userNumbers.add(number);
} catch (NumberFormatException e) {
System.out.println("Wrong input. Try again.");
}
}
private void printfInstructions() {
System.out.println("Enter a number and confirm it with Enter. If you want to quit, press 'q' and Enter or just Enter on empty line.");
}
private boolean isQuitCommand(String input) {
String trimmedInput = input.trim();
return trimmedInput.equalsIgnoreCase("q") || trimmedInput.isEmpty();
}
public void displayStats(int numbersAfterComma) throws IllegalArgumentException {
if (numbersAfterComma < 0 || numbersAfterComma > 16) {
throw new IllegalArgumentException("numbersAfterComma must be greater than 0 and less than 16");
}
String printFormat = STR."%.\{numbersAfterComma}f";
System.out.println(STR."Min: \{String.format(printFormat, min)}");
System.out.println(STR."Max: \{String.format(printFormat, max)}");
System.out.println(STR."Average: \{String.format(printFormat, average)}");
System.out.println(STR."Quantity: \{quantity}");
}
public double[] get() {
return new double[]{min, max, average, quantity};
}
}
| DziedzicGrzegorz/Javuz | src/main/java/UZ/Lab1_P/Zad4.java |
180,431 | package com.lupus.commands.sub;
import com.lupus.managers.InviteManager;
import com.lupus.managers.RegionManager;
import com.lupus.messages.GeneralMessages;
import com.lupus.messages.MessageReplaceQuery;
import com.lupus.region.Region;
import com.lupus.command.framework.commands.PlayerCommand;
import com.lupus.command.framework.commands.arguments.ArgumentList;
import org.bukkit.entity.Player;
public class AddToPlotCMD extends PlayerCommand {
public AddToPlotCMD() {
super("dodaj",
usage("/dzialka dodaj", "[Gracz]"),
"&6Dodajesz gracza do działki",
1);
}
@Override
public void run(Player executor, ArgumentList args) throws Exception {
if(args.size() < 1){
executor.sendMessage(usage());
return;
}
Player p2 = args.getArg(Player.class,0);
if(p2 == null){
executor.sendMessage(GeneralMessages.PLAYER_OFFLINE.toString());
return;
}
if(p2.equals(executor)){
executor.sendMessage(GeneralMessages.CANT_USE_ON_MYSELF.toString());
return;
}
Region r = RegionManager.getRegionOfOwner(executor);
if(r == null){
executor.sendMessage(GeneralMessages.NO_PLOT.toString());
return;
}
InviteManager.addInvite(p2,r);
MessageReplaceQuery query = new MessageReplaceQuery().addString("player",p2.getName());
executor.sendMessage(GeneralMessages.INVITE_SUCCESSFUL.toString(query));
}
}
| LupusVirtute/MCRegionPlugin | src/main/java/com/lupus/commands/sub/AddToPlotCMD.java |
180,432 | package com.lupus.commands.admin;
import com.lupus.managers.RegionManager;
import com.lupus.messages.GeneralMessages;
import com.lupus.messages.MessageReplaceQuery;
import com.lupus.region.Region;
import com.lupus.command.framework.commands.LupusCommand;
import com.lupus.command.framework.commands.arguments.ArgumentList;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.jetbrains.annotations.NotNull;
import java.util.List;
public class ForceAddCommand extends LupusCommand {
public ForceAddCommand(){
super("forceadd",
usage("/plots forceadd","[Gracz] [Dzialka]"),
"&6Dodajesz do działki gracza",
2);
}
@Override
public void run(CommandSender executor, ArgumentList args) throws Exception{
Player p = args.getArg(Player.class,0);
if(p == null) {
executor.sendMessage(GeneralMessages.PLAYER_OFFLINE.toString());
return;
}
Region r = args.getArg(Region.class,1);
if(r == null){
executor.sendMessage(GeneralMessages.NULL_PLOT.toString());
return;
}
RegionManager.addPlayerToRegion(p,r);
MessageReplaceQuery query = new MessageReplaceQuery().
addString("player",p.getName()).
addString("name",r.getName());
executor.sendMessage(GeneralMessages.SUCCESSFUL_FORCE_ADD.toString(query));
}
@NotNull
@Override
public List<String> tabComplete(@NotNull CommandSender sender, @NotNull String alias, @NotNull String[] args) throws IllegalArgumentException {
if (args.length == 2) {
String lastWord = args[args.length - 1];
return RegionManager.findRegionsBeginningWith(lastWord);
}
else
return super.tabComplete(sender, alias, args);
}
}
| LupusVirtute/MCRegionPlugin | src/main/java/com/lupus/commands/admin/ForceAddCommand.java |
180,433 | import com.diablo3CharViewer.data_models.FollowerDataModel;
import com.diablo3CharViewer.data_models.HeroDataModel;
import com.diablo3CharViewer.data_models.ItemDataModel;
import com.diablo3CharViewer.data_models.SkillDataModel;
import com.diablo3CharViewer.json_mappers.HeroMapper;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.*;
@ExtendWith(MockitoExtension.class)
public class HeroMapperTest {
@Mock
private HeroMapper testHeroMapperMock;
private HeroMapper testHeroMapper = new HeroMapper();
private String accountData;
private final String heroId = "170761702";
private final int expectedHeroId = 170761702;
private final String expectedHeroName = "Barbera";
private final String expectedHeroClass = "barbarian";
private final Map<String, Integer> heroKills = new HashMap<String, Integer>() {{
put("elites", 403);
}};
private final List<SkillDataModel> heroSkills = new ArrayList<>(Arrays.asList(
new SkillDataModel("active", "frenzy", "Amok", 11, "Generuje: 4 pkt. furii przy ataku."),
new SkillDataModel("passive", "ruthless", "Bezwzglednosc", 10, "Zadajesz dodatkowe 40% obrazen przeciwnikom, ktorzy maja mniej niz 30% zycia.")
));
private final List<ItemDataModel> heroItems = new ArrayList<>(Arrays.asList(
new ItemDataModel("head", "Unique_Helm_002_p1", "Korona Leoryka"),
new ItemDataModel("mainHand", "Unique_Mace_2H_104_x1", "Kruszyciel Dusz")
));
private final List<ItemDataModel> followerTemplarItems = new ArrayList<>(Arrays.asList(
new ItemDataModel("mainHand", "Spear_001", "Oszczep")
));
private final Map<String, Integer> followerTemplarStats = new HashMap<String, Integer>() {{
put("goldFind", 0);
}};
private final List<FollowerDataModel> followers = new ArrayList<>(Arrays.asList(
new FollowerDataModel("templar", 70, followerTemplarItems, followerTemplarStats)
));
private final Map<String, Integer> heroStats = new HashMap<String, Integer>() {{
put("life", 437161);
put("damage", 276225);
}};
private final HeroDataModel heroDataModel = new HeroDataModel(170761702, "Barbera", "barbarian", 70, 1111,
false, false, false, heroKills, heroSkills, heroItems, followers, heroStats);
@Test
public void correctHeroFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertEquals(expectedHeroId, testHeroMapperMock.mapHeroToDataModel(accountData).getId());
Assertions.assertEquals(expectedHeroName, testHeroMapperMock.mapHeroToDataModel(accountData).getName());
Assertions.assertEquals(expectedHeroClass, testHeroMapperMock.mapHeroToDataModel(accountData).getClassHero());
}
@Test
public void correctHeroKillsFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getKills().containsKey("elites"));
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getKills().containsValue(403));
}
@Test
public void correctHeroStatsFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getStats().containsKey("life"));
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getStats().containsValue(437161));
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getStats().containsKey("damage"));
Assertions.assertTrue(testHeroMapperMock.mapHeroToDataModel(accountData).getStats().containsValue(276225));
}
@Test
public void correctHeroSkillsListSizeFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertEquals(2, testHeroMapperMock.mapHeroToDataModel(accountData).getSkills().size());
}
@Test
public void correctHeroItemsListSizeFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertEquals(2, testHeroMapperMock.mapHeroToDataModel(accountData).getItems().size());
}
@Test
public void correctHeroFollowersListSizeFetchedToDataModel() {
Mockito.when(testHeroMapperMock.mapHeroToDataModel(accountData)).thenReturn(heroDataModel);
Assertions.assertEquals(1, testHeroMapperMock.mapHeroToDataModel(accountData).getFollowers().size());
}
@Test
public void providedBattleTagDoesntExistThrowsException() {
Assertions.assertThrows(RuntimeException.class, ()-> {
testHeroMapper.mapHeroToDataModel(ShareableDataForTests.battleTagAsDosentExist);
});
}
@Test
public void providedAccountDataNullThrowsException() {
Assertions.assertThrows(IllegalArgumentException.class, ()-> {
testHeroMapper.mapHeroToDataModel(null);
});
}
/*@Test //testowac w api handler
public void providedHeroIdIsNullThrowsException() {
Assertions.assertThrows(NullPointerException.class, ()-> {
testHeroMapper.fetchHeroToDataModel(ShareableDataForTests.battleTag, null, ShareableDataForTests.testFetchTokenMock);
});
}*/
/*@Test //testowac w api handler
public void providedTokenNullThrowsException() {
Assertions.assertThrows(NullPointerException.class, ()-> {
testHeroMapper.fetchHeroToDataModel(ShareableDataForTests.battleTag, heroId, null);
});
}*/
}
| Arturnix/Diablo-3-character-viewer | src/test/java/HeroMapperTest.java |
180,434 | package com.kodilla.exeption.homework;
import junit.framework.TestCase;
import org.junit.Test;
import java.util.Optional;
public class WarehouseTestSuite {
@Test(expected = OrderDoesntExistException.class)
public void shouldGetOrder() throws OrderDoesntExistException{
// given
Warehouse warehouse = new Warehouse();
// when
warehouse.getOrder("1");
// then
}
// poprzednia wersja
// uwaga mentora: Jeśli dodajesz @Test(expected = to try/catch nie jest potrzebny
// @Test(expected = OrderDoesntExistException.class)
// public void test1() {
// given
// Order order = new Order("1");
// Warehouse warehouse = new Warehouse();
// warehouse.addOrder(order);
// when
// then
// try {
// warehouse.getOrder("5");
// } catch (OrderDoesntExistException e) {
// assertEquals(OrderDoesntExistException.class, e.getClass());
// }
@Test
public void shouldAddOrder() {
// given
Warehouse warehouse = new Warehouse();
Order order = new Order("1");
// when
// then
warehouse.addOrder(order);
}
} | Vertradt/kodilla-tester | kodilla-stream/src/test/java/com/kodilla/exeption/homework/WarehouseTestSuite.java |
180,435 | package com.soundstock.it;
import com.soundstock.enums.UserRole;
import com.soundstock.mapper.UserMapper;
import com.soundstock.mapper.UserMapperImpl;
import com.soundstock.model.dto.UserDTO;
import com.soundstock.repository.UserRepository;
import jakarta.persistence.EntityExistsException;
import org.hamcrest.Matchers;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.testcontainers.containers.PostgreSQLContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.shaded.com.fasterxml.jackson.databind.ObjectMapper;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@Testcontainers
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
class UserControllerTest {
static Connection connection;
@Container
static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16.0")
.withDatabaseName("soundstock")
.withUsername("postgres")
.withPassword("password")
.withExposedPorts(5432)
.withInitScript("init.sql");
@Autowired
UserRepository userRepository;
UserMapper userMapper = new UserMapperImpl();
@Autowired
private MockMvc mockMvc;
@DynamicPropertySource
static void dynamicPropertyRegistry(DynamicPropertyRegistry registry) {
registry.add("spring.datasource.url", () -> postgres.getJdbcUrl());
registry.add("spring.datasource.username", () -> postgres.getUsername());
registry.add("spring.datasource.password", () -> postgres.getPassword());
}
@BeforeAll
static void beforeAll() throws SQLException {
connection = DriverManager.getConnection(postgres.getJdbcUrl(), postgres.getUsername(), postgres.getPassword());
postgres.start();
}
@Test
void testRegisterUser() throws Exception {
//given
UserDTO userDTO = UserDTO.builder()
.username("test1")
.email("test1@wp.pl")
.password("password")
.build();
//then
mockMvc.perform(post("/user/v1/register")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(userDTO)))
.andExpect(status().isCreated());
}
@Test
void should_throw_exception_because_username_exists() throws Exception {
UserDTO userDTO = UserDTO.builder()
.username("dominik")
.email("a@wp.pl")
.password("password")
.role(UserRole.USER)
.build();
userRepository.save(userMapper.toEntity(userDTO));
mockMvc.perform(post("/user/v1/register")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(userDTO)))
.andExpect(status().isBadRequest())
.andExpect(result -> assertTrue(result.getResolvedException() instanceof EntityExistsException))
.andExpect(result -> assertEquals("Username or Email already exists", result.getResolvedException().getMessage()));
}
@Test
void testRegistrationAndConfirmationFlow() throws Exception {
UserDTO userDTO = UserDTO.builder()
.username("test2")
.email("test2@wp.pl")
.password("password")
.build();
MvcResult registrationResult = mockMvc.perform(post("/user/v1/register")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(userDTO)))
.andExpect(status().isCreated())
.andReturn();
// Pobranie tokena z odpowiedzi rejestracji
String token = registrationResult.getResponse().getContentAsString();
// Wykonanie żądania potwierdzenia z użytym tokenem
mockMvc.perform(post("/user/v1/confirm")
.param("token", token)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
@Test
void testLogin() throws Exception {
UserDTO userDTO = UserDTO.builder()
.username("test3")
.email("test3@wp.pl")
.password("password")
.build();
MvcResult registrationResult = mockMvc.perform(post("/user/v1/register")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(userDTO)))
.andExpect(status().isCreated())
.andReturn();
// Pobranie tokena z odpowiedzi rejestracji
String token = registrationResult.getResponse().getContentAsString();
// Wykonanie żądania potwierdzenia z użytym tokenem
MvcResult confirmationResult = mockMvc.perform(post("/user/v1/confirm")
.param("token", token)
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andReturn();
mockMvc.perform(post("/user/v1/login")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(userDTO)))
.andExpect(status().isOk());
}
@Test
void testLoginWithWrongCredentials() throws Exception {
// Użytkownik z błędnymi danymi
UserDTO wrongUserDTO = UserDTO.builder()
.email("wrongEmail")
.password("wrongPassword")
.username("wrongUsername")
.build();
// Próba logowania z błędnymi danymi
mockMvc.perform(post("/user/v1/login")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(wrongUserDTO)))
.andExpect(status().isBadRequest());/*todo tutaj nie dostajesz 404.
W konsoli widzę log "user not found for username", a pojawia się on przed rzuceniem ObjectNotFound.
Dla ObjectNotFound w GlobalExceptionHandler jest dodawane do response bad request, a nie not found :)
*/
}
@Test
void testGetAllUsersAsAdmin() throws Exception {
UserDTO adminLogin = UserDTO.builder()
.username("A")
.password("password")
.email("admin@wp.pl")
.build();
// Logowanie jako admin i pobranie tokenu JWT
MvcResult loginResult = mockMvc.perform(post("/user/v1/login")
.contentType(MediaType.APPLICATION_JSON)
.content(new ObjectMapper().writeValueAsString(adminLogin)))
.andExpect(status().isOk())
.andReturn();
String adminToken = loginResult.getResponse().getHeader("JWT_token"); //todo tutaj zwykły bug. sprawdź co nadajesz w loginie do nagłówków
System.out.println(adminToken);
// Wykonanie żądania do endpointu z tokenem JWT w nagłówku
mockMvc.perform(get("/user/v1/userlist")
.header("Authorization", "Bearer " + adminToken))
.andExpect(status().isOk())
.andExpect(jsonPath("$[0].id", Matchers.equalTo(1)))
.andExpect(jsonPath("$[0].username", Matchers.equalTo("A")));
}
}
| senmay/Soundstock | src/test/java/com/soundstock/it/UserControllerTest.java |
180,443 | package prototypeDeep;
public class TestDeep {
public static void main(String[] args) throws CloneNotSupportedException {
Playlista playlista = new Playlista();
playlista.setNazwa("Italian Hits");
playlista.dodajPiosenki();
System.out.println("Playlista Italian Hits stan początkowy:");
System.out.println(playlista);
Playlista cloned = playlista.clone();
cloned.setNazwa("Cloned Italian Hits");
System.out.println("\nUsuwam 2 piosenkę z playlisty Italian Hits:");
playlista.getPiosenki().remove(1);
System.out.println("\nPlaylista Italian Hits:");
System.out.println(playlista);
System.out.println("\nPlaylista Cloned Italian Hits (sklonowana):");
System.out.println(cloned);
}
}
| jkowalska/Wzorce-projektowe | Prototype/prototypeDeep/TestDeep.java |
180,444 | package com.nohkumado.intstringsynchro;
import java.util.*;
import java.util.regex.*;
/**
* @author Noh Kuma Do <nohkumado at gmail dot com>
* @licence GLP v3
* @version "%I%, %G%",
*
* code representation of the string ressource plural
*/
public class PluralEntry extends StringEntry
{
private static final String TAG="Plur"; /** needed for Log.d */
private HashMap<String,StringEntry> hashmap; /** the map for the different plural strings */
Pattern availableKEys;
/** CTOR */
public PluralEntry(String n)
{
this(n, null);
}//public PluralEntry(String n)
/** CTOR */
public PluralEntry(String n, HashMap<String,StringEntry> a)
{
super(n, new CdataString());
if (a != null) hashmap = a;
else hashmap = new HashMap<>();
}
public PluralEntry(PluralEntry n)
{
super(n);
hashmap = new HashMap<>();
{
if(n.availableKEys != null) availableKEys = Pattern.compile(n.availableKEys.toString());
if(n.hashmap != null)
{
for(Map.Entry<String, StringEntry> keyVal : n.hashmap.entrySet())
{
hashmap.put(keyVal.getKey(), StringEntryFactory.instantiate(keyVal.getValue()));
}// for(Map.Entry<String, StringEntry> keyVal : n.hashmap.entrySet())
}//if(n.hashmap != null)
}//if(n != null)
}//copy CTOR
public StringEntry get(String key)
{
return hashmap.get(key);
}
public Collection keySet()
{
return hashmap.keySet();
}
/**
* make a string representation, for pretty printing
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("Plural[").append(token).append("]");
if (hashmap != null) sb.append(hashmap.toString());
return sb.toString();
}//public String toString()
/**
* create the xml representation, the stuff needed to write into strings.xml
example
<plurals name="numberOfSongsAvailable">
<item quantity="one">Znaleziono %d piosenkę.</item>
<item quantity="few">Znaleziono %d piosenki.</item>
<item quantity="other">Znaleziono %d piosenek.</item>
</plurals>
*/
public String toXml(String indent)
{
StringBuilder sb = new StringBuilder();
sb.append(indent).append("<plurals name=\"").append(token).append("\">\n");
for (String quant : hashmap.keySet())
sb.append(indent).append(indent).append("<item quantity=\"").append(quant).append("\">").append(hashmap.get(quant).asString().trim()).append("</item>\n");
sb.append(indent).append("</plurals>\n");
return sb.toString();
}//public String toXml(String indent)
public void put(String key, CdataString value)
{
if (availableKEys == null) availableKEys = Pattern.compile("zero|one|two|few|many|other");
Matcher m = availableKEys.matcher(key);
if (m.find())
{
hashmap.put(key, new StringEntry(key, value));
}
}//public PluralEntry(String n, HashMap<String,StringEntry> a)
}//public class PluralEntry extends StringEntry
| nohkumado/intstringsynchro | app/src/main/java/com/nohkumado/intstringsynchro/PluralEntry.java |
180,447 | package com.example.hyplayer;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import model.SongModel;
import java.net.URL;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;
public class SongPlaneController implements Initializable {
@FXML
private ImageView songImage;
@FXML
private Label songName;
@FXML
private Label songAuthor;
@FXML
private Label songAlbum;
@FXML
private Label songPrice;
@FXML
private Label songGenre;
@FXML
private Label userBalance;
@FXML
private Label errorMsg;
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
CurrentSong currentSong = CurrentSong.getInstance();
String songId = String.valueOf(currentSong.getSongId());
try {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT * FROM songs where song_id=?");
ps.setString(1, songId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Image image = new Image(getClass().getResourceAsStream(rs.getString("image_url")));
songImage.setImage(image);
songName.setText(rs.getString("song_title"));
try{
PreparedStatement ps2 = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT al.album_title AS album_name FROM songs s LEFT JOIN albums al ON s.album_id = al.album_id WHERE s.song_id = ?;");
ps2.setString(1, songId);
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
songAlbum.setText(rs2.getString("album_name"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
songPrice.setText(String.valueOf(rs.getFloat("price")));
songGenre.setText(rs.getString("genre"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try{
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT * FROM users where user_id=?");
ps.setString(1, String.valueOf(CurrentUserData.getInstance().getUserId()));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
userBalance.setText(String.valueOf(rs.getFloat("balance")));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
try{
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT a.name AS author_name FROM songs s JOIN authors_songs ASr ON s.song_id = ASr.songs_id JOIN authors a ON ASr.authors_id = a.author_id WHERE s.song_id = ?;");
ps.setString(1, songId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
songAuthor.setText(rs.getString("author_name"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
private void didUserOwnSong(String userId, String songId) throws SQLException {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT * FROM transactions WHERE user_id = ? AND song_id = ?");
ps.setString(1, userId);
ps.setString(2, songId);
ResultSet rs = ps.executeQuery();
if(rs.next()){
errorMsg.setText("Już posiadasz tą piosenkę!");
}
else{
buyHandle();
}
}
public void buyHandle(){
CurrentUserData currentUserData = CurrentUserData.getInstance();
String userId = String.valueOf(currentUserData.getUserId());
CurrentSong currentSong = CurrentSong.getInstance();
String songId = String.valueOf(currentSong.getSongId());
try{
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT * FROM users where user_id=?");
ps.setString(1, userId);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
if(rs.getFloat("balance") >= Float.parseFloat(songPrice.getText())){
try{
PreparedStatement ps2 = DatabaseConnection.getDatabaseConnection().prepareStatement("INSERT INTO transactions (user_id, song_id,price,data) VALUES (?, ?,?,NOW())");
ps2.setString(1, userId);
ps2.setString(2, songId);
ps2.setString(3, songPrice.getText());
ps2.executeUpdate();
PreparedStatement ps3 = DatabaseConnection.getDatabaseConnection().prepareStatement("UPDATE users SET balance = ? WHERE user_id = ?");
ps3.setString(1, String.valueOf(rs.getFloat("balance") - Float.parseFloat(songPrice.getText())));
ps3.setString(2, userId);
ps3.executeUpdate();
userBalance.setText(String.valueOf(rs.getFloat("balance") - Float.parseFloat(songPrice.getText())));
errorMsg.setText("Zakupiono piosenkę!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
else{
errorMsg.setText("Nie masz wystarczająco środków!");
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
public void buyAction() throws SQLException {
didUserOwnSong(String.valueOf(CurrentUserData.getInstance().getUserId()), String.valueOf(CurrentSong.getInstance().getSongId()));
}
}
| sebastianksiazek/hyPlayer | src/main/java/com/example/hyplayer/SongPlaneController.java |
180,451 | package com.example.musicplayer;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class MusicListActivity extends AppCompatActivity implements OnAddToPlaylistClickListener {
TextView playlistName;
RecyclerView songsListRecyclerView;
ArrayList<AudioModel> songsList;
PlaylistModel currPlaylist;
ArrayList<PlaylistModel> playlistList;
private ExecutorService executorService;
DatabaseManager database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songs_list);
playlistName = findViewById(R.id.playlist_title_name);
songsListRecyclerView = findViewById(R.id.song_list_recycler_view);
executorService = Executors.newSingleThreadExecutor();
database = DatabaseManager.getInstance();
songsList = (ArrayList<AudioModel>) getIntent().getSerializableExtra("SONGSLIST");
currPlaylist = (PlaylistModel) getIntent().getSerializableExtra("PLAYLIST");
playlistList = (ArrayList<PlaylistModel>) getIntent().getSerializableExtra("PLAYLISTLIST");
playlistName.setText(currPlaylist.playlistName);
Log.d("letsee", "WIELKOSC LISTY: " + songsList.size());
MusicListAdapter adapter = new MusicListAdapter(songsList, this, playlistList);
adapter.setOnAddToPlaylistClickListener(this);
songsListRecyclerView.setLayoutManager(new LinearLayoutManager(MusicListActivity.this));
songsListRecyclerView.setAdapter(adapter);
}
@Override
public void onAddToPlaylistClick(AudioModel audioModel) {
AlertDialog.Builder builder = new AlertDialog.Builder(MusicListActivity.this);
builder.setTitle("Dodaj do Playlisty");
// Pobieramy listę nazw playlist
List<String> playlistNames = new ArrayList<>();
for (PlaylistModel playlist : playlistList) {
if(playlist.playlistId != 1)
playlistNames.add(playlist.playlistName);
}
// Konwertujemy listę na tablicę dla ArrayAdapter
String[] playlistArray = playlistNames.toArray(new String[0]);
builder.setItems(playlistArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Dodajemy wybraną piosenkę do wybranej playlisty
String selectedPlaylistName = playlistArray[i];
addSongToPlaylist(audioModel, selectedPlaylistName);
}
});
builder.show();
}
private void addSongToPlaylist(AudioModel audioModel, String playlistName) {
// Tutaj dodaj kod do obsługi dodawania piosenki do playlisty
// np. znalezienie odpowiedniej playlisty, dodanie piosenki i odświeżenie widoku
for (PlaylistModel playlist : playlistList) {
if (playlist.playlistName.equals(playlistName)) {
executorService.execute(new Runnable() {
@Override
public void run() {
PlaylistSongCrossRef relaction = new PlaylistSongCrossRef();
relaction.playlistId = playlist.playlistId;
relaction.songId = audioModel.songId;
database.playlistDao().addSongToPlaylist(relaction);
}
});
//playlist.addSong(audioModel);
//playlistRecyclerView.getAdapter().notifyDataSetChanged();
break;
}
}
}
} | palaszek/ProjektMobilki | app/src/main/java/com/example/musicplayer/MusicListActivity.java |
180,452 | package prototypeShallow;
public class TestShallow {
public static void main(String[] args) throws CloneNotSupportedException {
Playlista playlista = new Playlista();
playlista.setNazwa("Italian Hits");
playlista.dodajPiosenki();
System.out.println("Playlista Italian Hits stan początkowy:");
System.out.println(playlista);
Playlista cloned = (Playlista)playlista.clone();
System.out.println("\nNazwa sklonowanej playlisty:");
System.out.println(cloned.getNazwa());
cloned.setNazwa("Cloned Italian Hits");
System.out.println("\nUsuwam 2 piosenkę z playlisty Italian Hits:");
playlista.getPiosenki().remove(1);
System.out.println("\nPlaylista Italian Hits:");
System.out.println(playlista);
System.out.println("\nPlaylista Cloned Italian Hits (sklonowana):");
System.out.println(cloned);
}
}
| jkowalska/Wzorce-projektowe | Prototype/prototypeShallow/TestShallow.java |
180,453 | package com.example.hyplayer;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import java.io.File;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;
public class SongCreatePlaneController {
@FXML
private Label errorMsg;
@FXML
private TextField nameField;
@FXML
private TextField authorField;
@FXML
private TextField albumField;
@FXML
private TextField genreField;
@FXML
private TextField priceField;
@FXML
private TextField idField;
@FXML
private ImageView imageUrl;
private String albumId;
private String authorId;
private String imagePathUrl;
public void albumIdSearch(){
String album = albumField.getText();
if (album == null || album.isEmpty()) {
errorMsg.setText("Pole nie może być puste!");
}
else{
try {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT album_id FROM albums WHERE album_title = ?;");
ps.setString(1, album);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
albumId =String.valueOf(rs.getInt("album_id"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public void authorIdSearch(){
String author = authorField.getText();
if (author == null || author.isEmpty()) {
errorMsg.setText("Pole nie może być puste!");
}
else{
try {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT author_id FROM authors WHERE name = ?;");
ps.setString(1, author);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
authorId =String.valueOf(rs.getInt("author_id"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public void imageAction() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Wybierz obrazek");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Obrazy", "*.png", "*.jpg", "*.gif"),
new FileChooser.ExtensionFilter("Wszystkie pliki", "*.*")
);
// Pokaż okno dialogowe wyboru pliku
File selectedFile = fileChooser.showOpenDialog(null);
// Jeśli użytkownik wybrał plik, wczytaj go i ustaw jako obrazek
if (selectedFile != null) {
try {
Image image = new Image(selectedFile.toURI().toString());
String imagePath = selectedFile.toURI().toString();
// Zmiana ścieżki do pliku na zaczynającą się od "/songsImages"
imagePath = "/songsImages" + imagePath.substring(imagePath.lastIndexOf('/'));
System.out.println(imagePath);
image = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));
imageUrl.setImage(image);
imagePathUrl = imagePath;
} catch (Exception e) {
// Obsługa błędów, jeśli wystąpią problemy z ładowaniem obrazka
e.printStackTrace();
errorMsg.setText("Wystąpił błąd podczas wczytywania obrazka!");
}
}
}
public void submitAction(){
String name = nameField.getText();
String author = authorField.getText();
String album = albumField.getText();
String genre = genreField.getText();
String price = priceField.getText();
authorIdSearch();
albumIdSearch();
if (albumId == null || authorId == null ||name == null || name.isEmpty() || author == null || author.isEmpty() || album == null || album.isEmpty() || genre == null || genre.isEmpty() || price == null || price.isEmpty()) {
errorMsg.setText("Pola nie mogą być puste!");
}
else{
try {
int songId;
float songPrice = Float.parseFloat(price);
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("INSERT INTO songs (song_title,genre,price,album_id,image_url) VALUES (?,?,?,?,?);");
ps.setString(1, name);
ps.setString(2, genre);
ps.setFloat(3, songPrice);
ps.setInt(4, Integer.parseInt(albumId));
String urs = imagePathUrl;
ps.setString(5, urs);
ps.executeUpdate();
PreparedStatement ps3 = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT song_id FROM songs WHERE song_title = ? AND price =?;");
ps3.setString(1, name);
ps3.setFloat(2, songPrice);
ResultSet rs3 = ps3.executeQuery();
while (rs3.next()) {
songId = rs3.getInt("song_id");
PreparedStatement ps2 = DatabaseConnection.getDatabaseConnection().prepareStatement("INSERT INTO authors_songs (authors_id, songs_id) VALUES (?, ?);");
ps2.setInt(1, Integer.parseInt(authorId));
ps2.setInt(2, songId);
ps2.executeUpdate();
}
errorMsg.setText("Pomyślnie zaktualizowano piosenkę!");
} catch (NumberFormatException e) {
errorMsg.setText("Niepoprawny format ID lub ceny!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
| sebastianksiazek/hyPlayer | src/main/java/com/example/hyplayer/SongCreatePlaneController.java |
180,456 | package com.example.hyplayer;
import javafx.application.Application;
import javafx.fxml.FXML;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.stage.FileChooser;
import java.io.File;
import java.nio.file.Paths;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Objects;
public class SongEditPlaneController {
@FXML
private Label errorMsg;
@FXML
private TextField nameField;
@FXML
private TextField authorField;
@FXML
private TextField albumField;
@FXML
private TextField genreField;
@FXML
private TextField priceField;
@FXML
private TextField idField;
@FXML
private ImageView imageUrl;
private String albumId;
private String authorId;
private String imagePathUrl;
public void loadAction(){
String id = idField.getText();
if (id == null || id.isEmpty()) {
errorMsg.setText("Pole nie może być puste!");
}
else{
try {
int songId = Integer.parseInt(id);
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT * FROM songs where song_id=?");
ps.setString(1, String.valueOf(songId));
ResultSet rs = ps.executeQuery();
while (rs.next()) {
nameField.setText(rs.getString("song_title"));
genreField.setText(rs.getString("genre"));
priceField.setText(String.valueOf(rs.getFloat("price")));
Image image = new Image(getClass().getResourceAsStream(rs.getString("image_url")));
imageUrl.setImage(image);
}
PreparedStatement ps2 = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT al.album_title AS album_name FROM songs s LEFT JOIN albums al ON s.album_id = al.album_id WHERE s.song_id = ?;");
ps2.setString(1, String.valueOf(songId));
ResultSet rs2 = ps2.executeQuery();
while (rs2.next()) {
albumField.setText(rs2.getString("album_name"));
}
PreparedStatement ps3 = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT a.name AS author_name FROM songs s JOIN authors_songs ASr ON s.song_id = ASr.songs_id JOIN authors a ON ASr.authors_id = a.author_id WHERE s.song_id = ?;");
ps3.setString(1, String.valueOf(songId));
ResultSet rs3 = ps3.executeQuery();
while (rs3.next()) {
authorField.setText(rs3.getString("author_name"));
}
} catch (NumberFormatException e) {
errorMsg.setText("Niepoprawny format ID!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public void albumIdSearch(){
String album = albumField.getText();
if (album == null || album.isEmpty()) {
errorMsg.setText("Pole nie może być puste!");
}
else{
try {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT album_id FROM albums WHERE album_title = ?;");
ps.setString(1, album);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
albumId =String.valueOf(rs.getInt("album_id"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public void authorIdSearch(){
String author = authorField.getText();
if (author == null || author.isEmpty()) {
errorMsg.setText("Pole nie może być puste!");
}
else{
try {
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("SELECT author_id FROM authors WHERE name = ?;");
ps.setString(1, author);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
authorId =String.valueOf(rs.getInt("author_id"));
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
public void imageAction() {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Wybierz obrazek");
fileChooser.getExtensionFilters().addAll(
new FileChooser.ExtensionFilter("Obrazy", "*.png", "*.jpg", "*.gif"),
new FileChooser.ExtensionFilter("Wszystkie pliki", "*.*")
);
// Pokaż okno dialogowe wyboru pliku
File selectedFile = fileChooser.showOpenDialog(null);
// Jeśli użytkownik wybrał plik, wczytaj go i ustaw jako obrazek
if (selectedFile != null) {
try {
Image image = new Image(selectedFile.toURI().toString());
String imagePath = selectedFile.toURI().toString();
// Zmiana ścieżki do pliku na zaczynającą się od "/songsImages"
imagePath = "/songsImages" + imagePath.substring(imagePath.lastIndexOf('/'));
System.out.println(imagePath);
image = new Image(Objects.requireNonNull(getClass().getResourceAsStream(imagePath)));
imageUrl.setImage(image);
imagePathUrl = imagePath;
} catch (Exception e) {
// Obsługa błędów, jeśli wystąpią problemy z ładowaniem obrazka
e.printStackTrace();
errorMsg.setText("Wystąpił błąd podczas wczytywania obrazka!");
}
}
}
public void submitAction(){
String id = idField.getText();
String name = nameField.getText();
String author = authorField.getText();
String album = albumField.getText();
String genre = genreField.getText();
String price = priceField.getText();
authorIdSearch();
albumIdSearch();
if (id == null || albumId == null || authorId == null || id.isEmpty() || name == null || name.isEmpty() || author == null || author.isEmpty() || album == null || album.isEmpty() || genre == null || genre.isEmpty() || price == null || price.isEmpty()) {
errorMsg.setText("Pola nie mogą być puste!");
}
else{
try {
int songId = Integer.parseInt(id);
float songPrice = Float.parseFloat(price);
PreparedStatement ps = DatabaseConnection.getDatabaseConnection().prepareStatement("UPDATE songs SET song_title = ?, genre = ?, price = ? ,album_id = ? WHERE song_id = ?;");
ps.setString(1, name);
ps.setString(2, genre);
ps.setFloat(3, songPrice);
ps.setInt(4, Integer.parseInt(albumId));
ps.setInt(5, songId);
ps.executeUpdate();
PreparedStatement ps2 = DatabaseConnection.getDatabaseConnection().prepareStatement("INSERT INTO authors_songs (authors_id, songs_id) VALUES (?, ?);");
ps2.setInt(1, Integer.parseInt(authorId));
ps2.setInt(2, songId);
ps2.executeUpdate();
PreparedStatement ps3 = DatabaseConnection.getDatabaseConnection().prepareStatement("UPDATE songs SET image_url = ? WHERE song_id = ?;");
String urs = imagePathUrl;
ps3.setString(1, urs);
ps3.setInt(2, songId);
ps3.executeUpdate();
errorMsg.setText("Pomyślnie zaktualizowano piosenkę!");
} catch (NumberFormatException e) {
errorMsg.setText("Niepoprawny format ID lub ceny!");
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
}
| sebastianksiazek/hyPlayer | src/main/java/com/example/hyplayer/SongEditPlaneController.java |
180,458 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.lint.checks;
import com.android.annotations.NonNull;
import com.android.tools.lint.client.api.LintClient;
import com.android.tools.lint.detector.api.Detector;
import com.android.tools.lint.detector.api.Issue;
import com.android.tools.lint.detector.api.Project;
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
@SuppressWarnings("javadoc")
public class PluralsDetectorTest extends AbstractCheckTest {
@Override
protected Detector getDetector() {
return new PluralsDetector();
}
public void test1() throws Exception {
mEnabled = Sets.newHashSet(PluralsDetector.MISSING, PluralsDetector.EXTRA);
assertEquals(""
+ "res/values-pl/plurals2.xml:3: Error: For locale \"pl\" (Polish) the following quantities should also be defined: many [MissingQuantity]\n"
+ " <plurals name=\"numberOfSongsAvailable\">\n"
+ " ^\n"
+ "1 errors, 0 warnings\n",
lintProject(
"res/values/plurals.xml",
"res/values/plurals2.xml",
"res/values-pl/plurals2.xml"));
}
public void test2() throws Exception {
mEnabled = Sets.newHashSet(PluralsDetector.MISSING, PluralsDetector.EXTRA);
assertEquals(""
+ "res/values-cs/plurals3.xml:3: Error: For locale \"cs\" (Czech) the following quantities should also be defined: few [MissingQuantity]\n" +
" <plurals name=\"draft\">\n" +
" ^\n" +
"res/values-zh-rCN/plurals3.xml:3: Warning: For language \"zh\" (Chinese) the following quantities are not relevant: one [UnusedQuantity]\n" +
" <plurals name=\"draft\">\n" +
" ^\n" +
"res/values-zh-rCN/plurals3.xml:7: Warning: For language \"zh\" (Chinese) the following quantities are not relevant: one [UnusedQuantity]\n" +
" <plurals name=\"title_day_dialog_content\">\n" +
" ^\n" +
"1 errors, 2 warnings\n",
lintProject(
"res/values-zh-rCN/plurals3.xml",
"res/values-cs/plurals3.xml"));
}
public void testEmptyPlural() throws Exception {
mEnabled = Sets.newHashSet(PluralsDetector.MISSING, PluralsDetector.EXTRA);
assertEquals(""
+ "res/values/plurals4.xml:3: Error: There should be at least one quantity string in this <plural> definition [MissingQuantity]\n"
+ " <plurals name=\"minutes_until_num\">\n"
+ " ^\n"
+ "1 errors, 0 warnings\n",
lintProject(
"res/values/plurals4.xml"));
}
public void testPolish() throws Exception {
// Test for https://code.google.com/p/android/issues/detail?id=67803
mEnabled = Sets.newHashSet(PluralsDetector.MISSING, PluralsDetector.EXTRA);
assertEquals(""
+ "res/values-pl/plurals5.xml:3: Error: For locale \"pl\" (Polish) the following quantities should also be defined: many [MissingQuantity]\n"
+ " <plurals name=\"my_plural\">\n"
+ " ^\n"
+ "res/values-pl/plurals5.xml:3: Warning: For language \"pl\" (Polish) the following quantities are not relevant: zero [UnusedQuantity]\n"
+ " <plurals name=\"my_plural\">\n"
+ " ^\n"
+ "1 errors, 1 warnings\n",
lintProject(
"res/values/plurals5.xml=>res/values-pl/plurals5.xml"));
}
public void testRussian() throws Exception {
// Regression test for https://code.google.com/p/android/issues/detail?id=75799
mEnabled = Sets.newHashSet(PluralsDetector.MISSING, PluralsDetector.EXTRA);
assertEquals("No warnings.",
lintProject(
"res/values-ru/plurals6.xml=>res/values-ru/plurals6.xml"));
}
public void testImpliedQuantity() throws Exception {
mEnabled = Collections.singleton(PluralsDetector.IMPLIED_QUANTITY);
assertEquals(""
+ "res/values-sl/plurals2.xml:4: Error: The quantity 'one' matches more than one specific number in this locale (1, 101, 201, 301, 401, 501, 601, 701, 1001, \u2026), but the message did not include a formatting argument (such as %d). This is usually an internationalization error. See full issue explanation for more. [ImpliedQuantity]\n"
+ " <item quantity=\"one\">Znaleziono jedną piosenkę.</item>\n"
+ " ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
+ "1 errors, 0 warnings\n",
lintProject(
"res/values/plurals.xml",
"res/values/plurals2.xml",
"res/values-pl/plurals2.xml",
// Simulate locale message for locale which has multiple values for one
"res/values-pl/plurals2.xml=>res/values-sl/plurals2.xml"));
}
private Set<Issue> mEnabled = new HashSet<Issue>();
@Override
protected TestConfiguration getConfiguration(LintClient client, Project project) {
return new TestConfiguration(client, project, null) {
@Override
public boolean isEnabled(@NonNull Issue issue) {
return super.isEnabled(issue) && mEnabled.contains(issue);
}
};
}
}
| tranleduy2000/javaide | aosp/lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/PluralsDetectorTest.java |
180,459 | package com.example.musicplayer;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AllMusicListActivity extends AppCompatActivity implements OnAddToPlaylistClickListener {
RecyclerView songsListRecyclerView;
ArrayList<AudioModel> songsList;
ArrayList<PlaylistModel> playlistList;
private ExecutorService executorService;
DatabaseManager database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_music_list);
songsListRecyclerView = findViewById(R.id.song_list_recycler_view);
songsList = (ArrayList<AudioModel>) getIntent().getSerializableExtra("SONGSLIST");
playlistList = (ArrayList<PlaylistModel>) getIntent().getSerializableExtra("PLAYLISTLIST");
executorService = Executors.newSingleThreadExecutor();
database = DatabaseManager.getInstance();
Log.d("letsee", songsList.toString());
MusicListAdapter adapter = new MusicListAdapter(songsList, this, playlistList);
adapter.setOnAddToPlaylistClickListener(this);
songsListRecyclerView.setLayoutManager(new LinearLayoutManager(AllMusicListActivity.this));
songsListRecyclerView.setAdapter(adapter);
}
@Override
public void onAddToPlaylistClick(AudioModel audioModel) {
AlertDialog.Builder builder = new AlertDialog.Builder(AllMusicListActivity.this);
builder.setTitle("Dodaj do Playlisty");
// Pobieramy listę nazw playlist
List<String> playlistNames = new ArrayList<>();
for (PlaylistModel playlist : playlistList) {
if(playlist.playlistId != 1)
playlistNames.add(playlist.playlistName);
}
// Konwertujemy listę na tablicę dla ArrayAdapter
String[] playlistArray = playlistNames.toArray(new String[0]);
builder.setItems(playlistArray, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// Dodajemy wybraną piosenkę do wybranej playlisty
String selectedPlaylistName = playlistArray[i];
addSongToPlaylist(audioModel, selectedPlaylistName);
}
});
builder.show();
}
private void addSongToPlaylist(AudioModel audioModel, String playlistName) {
// Tutaj dodaj kod do obsługi dodawania piosenki do playlisty
// np. znalezienie odpowiedniej playlisty, dodanie piosenki i odświeżenie widoku
for (PlaylistModel playlist : playlistList) {
if (playlist.playlistName.equals(playlistName)) {
executorService.execute(new Runnable() {
@Override
public void run() {
PlaylistSongCrossRef relaction = new PlaylistSongCrossRef();
relaction.playlistId = playlist.playlistId;
relaction.songId = audioModel.songId;
Log.d("letsee", "PRÓBA DODANIA PIOSENKI DO PLAYLISTY: " + relaction.toString());
database.playlistDao().addSongToPlaylist(relaction);
}
});
//playlist.addSong(audioModel);
//playlistRecyclerView.getAdapter().notifyDataSetChanged();
break;
}
}
}
} | palaszek/ProjektMobilki | app/src/main/java/com/example/musicplayer/AllMusicListActivity.java |