file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
1,464 |
import javax.swing.*;
import java.awt.*;
import static java.awt.SystemColor.info;
import java.awt.event.*;
import java.io.*;
import static java.lang.String.valueOf;
import java.net.Socket;
import java.rmi.RemoteException;
import java.text.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.swing.JFrame.EXIT_ON_CLOSE;
import javax.swing.border.TitledBorder;
public class PClient2_GUI extends JFrame {
protected static final String date_pattern = "(01|02|03|04|05|06|07|08|09|([12][0-9]|3[01]))-(01|02|03|04|05|06|07|08|09|10|11|12)-202[0-9]";// pattern to check proper date format
protected static JMenuBar menuBars(JFrame frame, Operations look_up) {// UI bar that includes options , exit , about and details buttons
JMenuBar mainBar;
JMenu menu1, menu2;
JMenuItem booking, exit;
JMenuItem about;
mainBar = new JMenuBar();
menu1 = new JMenu("Options");
booking = new JMenuItem("Book Tickets for an Event");
exit = new JMenuItem("Exit");
menu2 = new JMenu("About");
about = new JMenuItem("Details");
mainBar.add(menu1);
mainBar.add(menu2);
menu1.add(booking);
menu1.add(exit);
menu2.add(about);
booking.addActionListener(new ActionListener() {// Clicking on the booking button
@Override
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(null, "Would you like to book tickets for an Event ?", "Booking", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, Lists.choices, Lists.choices[1]);
if (n == 0) {
frame.dispose();
firstframe(look_up);
}
}
});
exit.addActionListener(new ActionListener() { // Clicking on the exit button
@Override
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(null, "Are you sure you want to exit?", "EXIT", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, Lists.choices, Lists.choices[1]);
if (n == 0) {
System.exit(0);
}
}
});
about.addActionListener(new ActionListener() {// app dev info
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "CINEMA BOOKING SERVICES \n Coded by:\n Theo B \n", "About", JOptionPane.INFORMATION_MESSAGE);
}
});
return mainBar;
}
protected static void firstframe(Operations look_up) { //Πρώτο Μενού με Log in , Register ή Exit/ First Graphical Interface that lets the user Log in , Register or Exit the app
JFrame firstframe = new JFrame();
JPanel row1, row2;
JButton login, register, exit;
JLabel info;
firstframe.setJMenuBar(menuBars(firstframe, look_up));
firstframe.setLayout(new FlowLayout());
firstframe.setTitle("Karlovasi Cinema Booking");
row1 = new JPanel();
info = new JLabel("Welcome!", JLabel.CENTER);
info.setFont(new Font("Arial", Font.BOLD, 20));
row1.add(info);
FlowLayout flowlayout = new FlowLayout();
row1.setLayout(flowlayout);
row2 = new JPanel();
login = new JButton("Log in");
register = new JButton("Register");
exit = new JButton("Exit");
row2.add(login);
row2.add(register);
row2.add(exit);
row2.setLayout(flowlayout);
Container panel = firstframe.getContentPane();
GridLayout layout = new GridLayout(2, 1);
panel.setLayout(layout);
firstframe.add(row1);
firstframe.add(row2);
firstframe.setContentPane(panel);
firstframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
firstframe.pack();
firstframe.setLocationRelativeTo(null);
firstframe.setVisible(true);
login.addActionListener(new ActionListener() { // login button
public void actionPerformed(ActionEvent e) {
firstframe.dispose();
login(look_up);
}
});
register.addActionListener(new ActionListener() { // register button
public void actionPerformed(ActionEvent e) {
firstframe.dispose();
register_menu(look_up);
}
});
exit.addActionListener(new ActionListener() { // exit button that asks confirmation
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(null, "Do you want to exit?", "Exit", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, Lists.choices, Lists.choices[1]);
if (n == 0) {
System.exit(0);
}
}
});
}
protected static void login(Operations look_up) {// Log in Window
JFrame login = new JFrame();
JPanel row1, row2, row3, row4, row5;
JLabel username, password;
JTextField username1;
JPasswordField password1;
JButton connect, cancel;
login.setDefaultCloseOperation(EXIT_ON_CLOSE);
login.setTitle("Program");
login.setLayout(new FlowLayout());
login.setJMenuBar(menuBars(login, look_up));
row1 = new JPanel();
username = new JLabel("Username: ");
row2 = new JPanel();
username1 = new JTextField(20);
row3 = new JPanel();
password = new JLabel("Password: ");
row4 = new JPanel();
password1 = new JPasswordField(20);
row5 = new JPanel();
connect = new JButton("Login");
cancel = new JButton("Cancel");
Container panel = login.getContentPane();
GridLayout layout = new GridLayout(5, 1);
panel.setLayout(layout);
FlowLayout flowlayout = new FlowLayout();
row1.setLayout(flowlayout);
row1.add(username);
row2.setLayout(flowlayout);
row2.add(username1);
row3.setLayout(flowlayout);
row3.add(password);
row4.setLayout(flowlayout);
row4.add(password1);
row5.setLayout(flowlayout);
row5.add(connect);
row5.add(cancel);
login.add(row1);
login.add(row2);
login.add(row3);
login.add(row4);
login.add(row5);
connect.addActionListener(new ActionListener() {// Connect button that lets the user have access to the menus if his credentials are matching a user in the datebase
public void actionPerformed(ActionEvent e) {
if (username1.getText().equals("")) {// blank username
JOptionPane.showMessageDialog(login, "Please, Fill the gaps!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else if (username1.getText() != null) {
if (new String(password1.getPassword()).equals("")) { // blank password
JOptionPane.showMessageDialog(login, "Please, Fill the gaps!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
User user = null;
try {
user = look_up.login(username1.getText(), new String(password1.getPassword()));//Looks up the user in the User Database of the 1st Server
if (user != null) {//If the user exists in the database then user will have either an "ADMIN" or a "USER" value on his getType() function
if (user.getType().equals("ADMIN")) {// if the user account is an Admin
login.dispose();
admin_menu(look_up);// prompts to the admin menu
} else if (user.getType().equals("USER")) { // If the user is a normal user
login.dispose();
look_up.readboolean();
user_menu(look_up, user);//prompts to the user menu
}
} else {///if the user didnt exist in the database
JOptionPane.showMessageDialog(login, "Check your credentials!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
});
cancel.addActionListener(new ActionListener() {//exiting button
public void actionPerformed(ActionEvent e) {
login.dispose();
firstframe(look_up);
}
});
login.setContentPane(panel);
login.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
login.setSize(400, 250);
login.setLocationRelativeTo(null);
login.setVisible(true);
}
protected static void admin_menu(Operations look_up) {// Admin's menu
JFrame admin = new JFrame();
JLabel tab1Message;
JLabel tab2Message;
JTabbedPane choices;
JPanel p1;
JPanel p2;
JButton create_event;
JButton cancel_event;
JButton logout;
admin.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
admin.setVisible(true);
admin.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
admin.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new GridLayout(3, 2));
p2 = new JPanel();
p2.setLayout(new GridLayout(3, 2));
tab1Message = new JLabel("Tickets", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
create_event = new JButton("Make a new Event");
p1.add(create_event);
cancel_event = new JButton("Cancel An Event");
p1.add(cancel_event);
tab2Message = new JLabel("Account Settings:", JLabel.CENTER);
tab2Message.setFont(new Font("Arial", Font.BOLD, 20));
p2.add(tab2Message);
logout = new JButton("Log out!");
p2.add(logout);
create_event.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("ADD EVENT")) {// Sends a "ADD EVENT" string to the 2nd server and if the 2nd server received the message then
admin.dispose();//closes the admin window
look_up.readfromserver();//reads message from the 2nd server
add_event(look_up);// prompts to the "Add an Event" Window
} else {// in case we get a message we didnt expect
JOptionPane.showMessageDialog(admin, "What would you like to do?", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
cancel_event.addActionListener(new ActionListener() {// cancel/delete an event button
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("DELETE")) {// sends DELETE to the 2nd server
admin.dispose();
look_up.readfromserver();//expects confirmation
delete_event(look_up);// opens up the delete event menu
} else {
JOptionPane.showMessageDialog(admin, "What would you like to do?", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
logout.addActionListener(new ActionListener() {// log out button
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("EXIT")) {//sends exiting message to the 2nd server
look_up.readfromserver();//Περιμένει επιβεβαίωση από το server// expects verification reply from server
admin.dispose();//closes down the admin menu
login(look_up);// goes back to the login screen
} else {
JOptionPane.showMessageDialog(admin, "What would you like to do?", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
choices.addTab("Ticket Menu", null, p1, "Ticket Related Options");
choices.addTab("Admin Menu", null, p2, "Account Related Options");
admin.setSize(400, 200);
admin.setLocationRelativeTo(null);
}
protected static void add_event(Operations look_up) {// Graphical Menu that allows the Admin to add an event
JFrame frame = new JFrame();
JLabel tab1Message;
JPanel p1;
JLabel title_of_event_l;
JLabel genre_label;
JLabel date_l;
JLabel av_seats_label;
JLabel time_label;
JLabel cost_label;
JTextField title1;
JTextField date;
JTextField av_seats;
JTextField cost;
JButton add_button;
JButton cancel_button;
ButtonGroup sgroup;////Button Group responsible for the type of the event (ex. Horror , Comedy,etc.)
JRadioButton horror, action, comedy, other;//Event type buttons
String[] hours = {"09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"};
p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
tab1Message = new JLabel("Add an Event", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
title1 = new JTextField();
date = new JTextField();
av_seats = new JTextField();
cost = new JTextField();
horror = new JRadioButton("Horror");
horror.setMnemonic(KeyEvent.VK_B);
horror.setActionCommand("Horror");
horror.setSelected(true);
action = new JRadioButton("Action");
action.setMnemonic(KeyEvent.VK_C);
action.setActionCommand("Action");
comedy = new JRadioButton("Comedy");
comedy.setMnemonic(KeyEvent.VK_D);
comedy.setActionCommand("Comedy");
other = new JRadioButton("Other");
other.setMnemonic(KeyEvent.VK_E);
other.setActionCommand("Other");
sgroup = new ButtonGroup();
sgroup.add(horror);
sgroup.add(action);
sgroup.add(comedy);
sgroup.add(other);
JComboBox time = new JComboBox(hours);// Combo box that makes a scroll down selection menu
time.setEditable(false);
title_of_event_l = new JLabel("Title:");
date_l = new JLabel("Date (dd-mm-yyyy):");
time_label = new JLabel("Time:");
genre_label = new JLabel("Genre:");
av_seats_label = new JLabel("Available Seats:");
cost_label = new JLabel("Cost per seat:");
p1.add(title_of_event_l);
p1.add(title1);
p1.add(genre_label);
p1.add(horror);
p1.add(action);
p1.add(comedy);
p1.add(other);
p1.add(date_l);
p1.add(date);
p1.add(time_label);
p1.add(time);
p1.add(av_seats_label);
p1.add(av_seats);
p1.add(cost_label);
p1.add(cost);
add_button = new JButton("Add the Event");
cancel_button = new JButton("Cancel");
p1.add(add_button);
p1.add(cancel_button);
frame.add(p1);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
add_button.addActionListener(new ActionListener() {// Button that adds a new event
public void actionPerformed(ActionEvent e) {
if (date.getText().matches(date_pattern))// if the date is in the correct format
{
String clock = hours[time.getSelectedIndex()];//sets clock to what the user picked on the hour scrolldown menu
String genre = "";
if (horror.isSelected()) {
genre = "Horror";
} else if (action.isSelected()) {
genre = "Action";
} else if (comedy.isSelected()) {
genre = "Comedy";
} else if (other.isSelected()) {
genre = "Other";
}
//Αν υπάρχει κενό
if (title1.getText().equals("") || date.getText().equals("") || genre.equals("") || av_seats.getText().equals("") || cost.getText().equals("")) {// if there's a blank
JOptionPane.showMessageDialog(frame, "Please, Fill the blanks!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
try {
//Event(String title, String genre, String event_date, String time, int available_seats, int cost_per_seat)
Event event1 = new Event(title1.getText(), genre, date.getText(), clock, Integer.parseInt(av_seats.getText()), Integer.parseInt(cost.getText()));
if (look_up.addevent(event1)) {// Στέλνει την εκδήλωση sends the event to the 2nd server and if it was succesfully added then it
look_up.readfromserver();//reads answer
JOptionPane.showMessageDialog(null, "The event has been successfully added!!!", "Success", JOptionPane.INFORMATION_MESSAGE);
title1.setText("");
date.setText("");
av_seats.setText("");
cost.setText("");
} else {// if it the request was accepted then it sends a positive reply
look_up.readfromserver();
JOptionPane.showMessageDialog(frame, "The event was NOT added!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else {// if the date is wrong
JOptionPane.showMessageDialog(frame, "Wrong Date Format!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
});
cancel_button.addActionListener(new ActionListener() {// closes the window and goes back to the admin menu
public void actionPerformed(ActionEvent e) {
try {
look_up.writeobj(null);
frame.dispose();
look_up.readfromserver();
admin_menu(look_up);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.setSize(400, 500);
frame.setLocationRelativeTo(null);
//popup window me apantisi
// this.dispose();
//Below we add Actionlisteners to our buttons
}
protected static void delete_event(Operations look_up) {// window that lets the admin delete an event
JFrame frame = new JFrame();
JLabel tab1Message;
JTabbedPane choices;
JPanel p1;
JLabel title_of_event_l;
JLabel date_l, time_l;
JTextField title1;
JTextField date1;
JButton delete_button, cancel_button;
String[] hours = {"09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"};
JComboBox time = new JComboBox(hours);//dropdown combobox for time
time.setEditable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
frame.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new GridLayout(12, 1));
tab1Message = new JLabel("Deleting an Event", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
title1 = new JTextField();
date1 = new JTextField();
time_l = new JLabel("Time:");
title_of_event_l = new JLabel("Title:");
date_l = new JLabel("Date (dd-mm-yyyy):");
p1.add(title_of_event_l);
p1.add(title1);
p1.add(date_l);
p1.add(date1);
p1.add(time_l);
p1.add(time);
delete_button = new JButton("Delete the Event");
p1.add(delete_button);
cancel_button = new JButton("Cancel");
p1.add(cancel_button);
choices.addTab("Delete An Event", null, p1, "");
frame.add(choices);
delete_button.addActionListener(new ActionListener() {// event deletion button
public void actionPerformed(ActionEvent e) {
if (title1.getText().equals("") || date1.getText().equals("")) {
JOptionPane.showMessageDialog(frame, "Please, Fill the blanks!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
if (date1.getText().matches(date_pattern)) {
String clock = hours[time.getSelectedIndex()];
//Event(String title, String genre, String event_date, String time, int available_seats, int cost_per_seat)
Event event1 = new Event(title1.getText(), "", date1.getText(), clock, 0, 0);
try {
if (look_up.deleteevent(event1)) {//Sends an object to be deleted if it is found
look_up.readfromserver();
JOptionPane.showMessageDialog(null, "The event has been successfully deleted!!!", "Success", JOptionPane.INFORMATION_MESSAGE);
title1.setText("");
date1.setText("");
} else { //else it shows a rejection message
look_up.readfromserver();
JOptionPane.showMessageDialog(null, "The event was not found", "Success", JOptionPane.INFORMATION_MESSAGE);
title1.setText("");
date1.setText("");
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(frame, "Wrong Date Format!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
});
cancel_button.addActionListener(new ActionListener() {// / back
public void actionPerformed(ActionEvent e) {
try {
look_up.writeobj(null);
frame.dispose();
look_up.readfromserver();
admin_menu(look_up);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.setSize(280, 400);
frame.setLocationRelativeTo(null);
}
protected static void user_menu(Operations look_up, User current_user) {//user menu
JFrame frame = new JFrame();
JLabel tab1Message;
JLabel tab2Message;
JTabbedPane choices;
JPanel p1;
JPanel p2;
JButton search_event;
JButton order_tickets;
JButton delete_account;
JButton cancel_order;
JButton logout;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
frame.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new GridLayout(4, 1));
p2 = new JPanel();
p2.setLayout(new GridLayout(3, 2));
tab1Message = new JLabel("Tickets", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
search_event = new JButton("Search Event");
p1.add(search_event);
order_tickets = new JButton("Order Tickets");
p1.add(order_tickets);
cancel_order = new JButton("Cancel Your Bookings");
p1.add(cancel_order);
tab2Message = new JLabel("Account Settings:", JLabel.CENTER);
tab2Message.setFont(new Font("Arial", Font.BOLD, 20));
p2.add(tab2Message);
delete_account = new JButton("Delete Your Account");
p2.add(delete_account);
logout = new JButton("Log out!");
p2.add(logout);
choices.addTab("Ticket Menu", null, p1, "Ticket Related Options");
choices.addTab("User Menu", null, p2, "Account Related Options");
logout.addActionListener(new ActionListener() {//log out button that returns the user to the log in menu
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("EXIT")) {
look_up.readfromserver();
frame.dispose();
login(look_up);
} else {
JOptionPane.showMessageDialog(frame, "Exiting Error", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
search_event.addActionListener(new ActionListener() {// search button
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("SEARCH EVENT")) {// sends "SEARCH EVENT" if the request was accepted and then it proceeds to the search menu
look_up.readfromserver();
frame.dispose();
booking_menu(look_up, current_user);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
order_tickets.addActionListener(new ActionListener() {//buttons that opens the order menu
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("ORDER")) {
look_up.readfromserver();
frame.dispose();
order_tickets(look_up, current_user);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
cancel_order.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (look_up.user_string("CANCEL ORDER")) {
look_up.readfromserver();
frame.dispose();
cancel_order(look_up, current_user);
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
delete_account.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n = JOptionPane.showOptionDialog(frame, "Are you sure you want to delete your account?", "DELETE YOUR ACCOUNT", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, Lists.choices, Lists.choices[1]);
try {
if (n == 0) {
if (look_up.deleteuser(current_user)) {
if (look_up.user_string("EXIT")) {
look_up.readfromserver();
frame.dispose();
login(look_up);
}
}
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
frame.setSize(
400, 400);
frame.setLocationRelativeTo(
null);
}
protected static void order_tickets(Operations look_up, User current_user) {
JFrame frame = new JFrame();
JLabel tab1Message;
JTabbedPane choices;
JPanel p1;
JLabel title_of_event_l;
JLabel date_l;
JLabel amount_l;
JLabel time_label;
JTextField title1;
JTextField date1;
JTextField amount1;
String[] hours = {"09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"};
JComboBox patternList = new JComboBox(hours);
patternList.setEditable(false);
JButton order_button, cancel;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
frame.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new GridLayout(12, 1));
tab1Message = new JLabel("Order Your Tickets", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
title1 = new JTextField();
date1 = new JTextField();
amount1 = new JTextField();
title_of_event_l = new JLabel("Title:");
date_l = new JLabel("Date (dd-mm-yyyy):");
amount_l = new JLabel("Amount:");
time_label = new JLabel("Time :");
p1.add(title_of_event_l);
p1.add(title1);
p1.add(date_l);
p1.add(date1);
p1.add(time_label);
p1.add(patternList);
p1.add(amount_l);
p1.add(amount1);
order_button = new JButton("Order");
p1.add(order_button);
cancel = new JButton("Cancel");
p1.add(cancel);
choices.addTab("Order Tickets", null, p1, "Order Your Tickets");
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
//order_button
order_button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (title1.getText().equals("") || date1.getText().equals("") || amount1.getText().equals("")) {// if there's blanks
JOptionPane.showMessageDialog(frame, "Please, Fill the blanks!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
if (date1.getText().matches(date_pattern)) { // if the date pattern is correct
String clock = hours[patternList.getSelectedIndex()];
Booking booking = new Booking(title1.getText(), date1.getText(), clock, Integer.parseInt(amount1.getText()), 0, current_user.getUsername());
try {
look_up.writeobj(booking);//sends the booking desired
float result = look_up.resultorder(); // sends the result of the request
if (result == -1) { //if there's not enough seats
JOptionPane.showMessageDialog(frame, "Insufficient Amount of seats!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else if (result == -2) {// if the event wasnt found
JOptionPane.showMessageDialog(frame, "No event with such info was found!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
booking.setCost(result);
JOptionPane.showMessageDialog(null, "Result" + "\n Username: " + booking.getUsername() + "\nTitle: " + booking.getTitle() + "\nDate: " + booking.getEvent_date() + "\nTime: " + booking.getTime() + "\nCost: " + booking.getCost(),
"Result", JOptionPane.INFORMATION_MESSAGE);
}//proceeds to close the server connection and returns to the user menu
look_up.writeobj(null);
look_up.readfromserver();
frame.dispose();
user_menu(look_up, current_user);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
JOptionPane.showMessageDialog(frame, "Wrong Date Format!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
});
//Κουμπι επιστροφής στο μενού επιλογών του χρήστη Returning back to the user options menu
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
frame.dispose();
look_up.writeobj(null);
look_up.readfromserver();
user_menu(look_up, current_user);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
//cancel
}
protected static void cancel_order(Operations look_up, User current_user) { // graphs for canceling an event
JFrame frame = new JFrame();
JLabel tab1Message;
JTabbedPane choices;
JPanel p1;
JLabel title_of_event_l;
JLabel date_l;
JLabel time_label;
JTextField title1;
JTextField date1;
JButton cancel_order, back;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
frame.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new GridLayout(12, 1));
tab1Message = new JLabel("Cancel Your Order", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 20));
p1.add(tab1Message);
title1 = new JTextField();
date1 = new JTextField();
time_label = new JLabel("Time:");
String[] hours = {"09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"};
JComboBox patternList = new JComboBox(hours);
patternList.setEditable(false);
title_of_event_l = new JLabel("Title:");
date_l = new JLabel("Date (dd-mm-yyyy):");
cancel_order = new JButton("Cancel Order");
back = new JButton("Back");
p1.add(title_of_event_l);
p1.add(title1);
p1.add(date_l);
p1.add(date1);
p1.add(time_label);
p1.add(patternList);
p1.add(cancel_order);
p1.add(back);
choices.addTab("Cancel your Order", null, p1, "");
cancel_order.addActionListener(new ActionListener() {//Cancel an event button
public void actionPerformed(ActionEvent e) {
if (title1.getText().equals("") || date1.getText().equals("")) {
JOptionPane.showMessageDialog(frame, "Please, Fill the blanks!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {
if (date1.getText().matches(date_pattern)) {
try {
String clock = hours[patternList.getSelectedIndex()];
Booking toCancel = new Booking(title1.getText(), date1.getText(), clock, 0, 0, current_user.getUsername());
look_up.writeobj(toCancel);
float cancel = look_up.resultorder();//receiving result of booking an order
if (cancel == 0) {// if the event is on the same day
JOptionPane.showMessageDialog(frame, "Not able to cancel the Booking!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {// succesful cancellation
JOptionPane.showMessageDialog(null, "The Booking was succesfully cancelled",
"Result", JOptionPane.INFORMATION_MESSAGE);
}
look_up.writeobj(null);
look_up.readfromserver();
frame.dispose();
user_menu(look_up, current_user);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else {// λάθος ημερομηνία
JOptionPane.showMessageDialog(frame, "Wrong Date Format!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
}
});
back.addActionListener(new ActionListener() {// Button that goes back to the previous window
public void actionPerformed(ActionEvent e) {
try {
Lists.list.clear();
frame.dispose();
look_up.writeobj(null);
look_up.readfromserver();
user_menu(look_up, current_user);
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.setSize(400, 400);
frame.setLocationRelativeTo(null);
}
protected static void register_menu(Operations look_up) { // Registration Menu Graphs
JFrame frame = new JFrame();
JLabel tab1Message;
JTabbedPane choices;
JPanel p1;
JLabel username_l;
JLabel password_l;
JLabel email_l;
JLabel name_l;
JTextField username;
JTextField password;
JTextField email;
JTextField name;
JButton create_button;
JButton cancel;
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.getContentPane().setLayout(new FlowLayout());
choices = new JTabbedPane();
frame.getContentPane().add(choices);
p1 = new JPanel();
p1.setLayout(new BoxLayout(p1, BoxLayout.PAGE_AXIS));
tab1Message = new JLabel("Please , Insert Your Info", JLabel.CENTER);
tab1Message.setFont(new Font("Arial", Font.BOLD, 18));
p1.add(tab1Message);
username = new JTextField();
password = new JTextField();
email = new JTextField();
name = new JTextField();
username_l = new JLabel("Username:");
password_l = new JLabel("Password:");
email_l = new JLabel("Email:");
name_l = new JLabel("Name:");
p1.add(username_l);
p1.add(username);
p1.add(password_l);
p1.add(password);
p1.add(email_l);
p1.add(email);
p1.add(name_l);
p1.add(name);
create_button = new JButton("Create");
cancel = new JButton("Cancel");
p1.add(create_button);
p1.add(cancel);
choices.addTab("Register", null, p1, "Register as a new User");
create_button.addActionListener(new ActionListener() {// Button that takes inputs from the client and checks if there's such a user in the db , otherwise it creates a new user
public void actionPerformed(ActionEvent e) {
try {
if ((username.getText()).equals("") || (password.getText()).equals("") || (email.getText()).equals("") || (name.getText()).equals("")) {
JOptionPane.showMessageDialog(frame, "Please, Fill the gaps!!!", "Error Message", JOptionPane.ERROR_MESSAGE);
} else {//loads up the user
User user1 = new User(username.getText(), password.getText(), "USER", email.getText(), name.getText());
if (look_up.adduser(user1)) {//checks if the user exists in the db
if (look_up.user_string("USER")) {//opens up the user menu
frame.dispose();
user_menu(look_up, user1);
} else {//in case of any issue
JOptionPane.showMessageDialog(frame, "Wrong Credentials!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
} else {// if the user already exists
JOptionPane.showMessageDialog(frame, "Username Already Exists!", "Error Message", JOptionPane.ERROR_MESSAGE);
}
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class
.getName()).log(Level.SEVERE, null, ex);
}
}
});
//Button to exit the process
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.dispose();
firstframe(look_up);
}
});
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
}
protected static void booking_menu(Operations look_up, User current_user) {//Booking Menu
String[] days = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "20",
"21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31"};
String[] months = {"01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"};
String[] years = {"2020", "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030"};
String[] hours = {"09:00", "10:00", "11:00", "12:00", "13:00", "14:00", "15:00", "16:00", "17:00", "18:00", "19:00", "20:00", "21:00", "22:00", "23:00"};
JFrame frame = new JFrame();
JPanel row1, row2, row3, row4, row6, row7;
JLabel info, title, date, time_label;
JTextField title1, date1;
JButton search, cancel;
JComboBox dayslist = new JComboBox(days);
JComboBox monthlist = new JComboBox(months);
JComboBox yearlist = new JComboBox(years);
JComboBox time = new JComboBox(hours);
time_label = new JLabel("Time:");
ButtonGroup sgroup;
JRadioButton horror, action, comedy, other;// check buttons
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
frame.setTitle("Search");
frame.setLayout(new FlowLayout());
row1 = new JPanel();
info = new JLabel("Pick your search criteria");
row2 = new JPanel();
horror = new JRadioButton("Horror");
horror.setMnemonic(KeyEvent.VK_B);
horror.setActionCommand("Horror");
horror.setSelected(true);
action = new JRadioButton("Action");
action.setMnemonic(KeyEvent.VK_C);
action.setActionCommand("Action");
comedy = new JRadioButton("Comedy");
comedy.setMnemonic(KeyEvent.VK_D);
comedy.setActionCommand("Comedy");
other = new JRadioButton("Other");
other.setMnemonic(KeyEvent.VK_E);
other.setActionCommand("Other");
sgroup = new ButtonGroup();//button group for each event category
sgroup.add(horror);
sgroup.add(action);
sgroup.add(comedy);
sgroup.add(other);
row3 = new JPanel();
title = new JLabel("Title: ");
title1 = new JTextField(20);
row4 = new JPanel();
row6 = new JPanel();
date = new JLabel("Event Date (dd-mm-yyyy):");
date1 = new JTextField(20);
row7 = new JPanel();
search = new JButton("Search Event");
cancel = new JButton("Cancel");
Container panel = frame.getContentPane();
GridLayout layout = new GridLayout(7, 2);
panel.setLayout(layout);
FlowLayout flowlayout = new FlowLayout();
row1.setLayout(flowlayout);
row1.add(info);
row2.setLayout(flowlayout);
row2.add(horror);
row2.add(action);
row2.add(comedy);
row2.add(other);
row3.setLayout(flowlayout);
row3.add(title);
row3.add(title1);
row4.setLayout(flowlayout);
row4.add(time_label);
row4.add(time);
row6.setLayout(flowlayout);
row6.add(date);
row6.add(dayslist);
row6.add(monthlist);
row6.add(yearlist);
row7.setLayout(flowlayout);
row7.add(search);
row7.add(cancel);
frame.add(row1);
frame.add(row2);
frame.add(row3);
frame.add(row6);
frame.add(row4);
frame.add(row7);
search.addActionListener(new ActionListener() {//search button
public void actionPerformed(ActionEvent e) {
//Converts the button into date Strings
String fullDate = days[dayslist.getSelectedIndex()] + "-" + months[monthlist.getSelectedIndex()] + "-" + years[yearlist.getSelectedIndex()];
System.out.println("fulldate: " + fullDate);
if (horror.isSelected()) {// horror type event
//String title, String genre, String event_date, int available_seats, int cost_per_seat
String clock = hours[time.getSelectedIndex()];
Event toSearch = new Event(title1.getText(), "Horror", fullDate, clock, 0, 0);
try {
look_up.writeobj(toSearch);
look_up.readfromserver();
boolean check = look_up.readobj();
if (check) {
Lists.list = look_up.searchlist();
for (int i = 0; i < Lists.list.size(); i++) {
System.out.println("The Search button : \n" + (Lists.list.get(i)).toString());
}
resultSearch(frame, look_up);//Puts the result in a window
} else {// if there's no results
JOptionPane.showMessageDialog(null, "NOT FOUND!", "NOT FOUND", JOptionPane.INFORMATION_MESSAGE);
Lists.list.clear();
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (action.isSelected()) {// if its an action type
//String title, String genre, String event_date, int available_seats, int cost_per_seat
String clock = hours[time.getSelectedIndex()];
Event toSearch = new Event(title1.getText(), "Action", fullDate, clock, 0, 0);
try {
look_up.writeobj(toSearch);
look_up.readfromserver();
boolean check = look_up.readobj();
if (check) {
Lists.list = look_up.searchlist();
for (int i = 0; i < Lists.list.size(); i++) {
System.out.println("The Search button: \n" + (Lists.list.get(i)).toString());
}
resultSearch(frame, look_up);
} else {
JOptionPane.showMessageDialog(null, "NOT FOUND!", "NOT FOUND", JOptionPane.INFORMATION_MESSAGE);
Lists.list.clear();
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (comedy.isSelected()) {// if its a comedy type of event
//String title, String genre, String event_date, int available_seats, int cost_per_seat
String clock = hours[time.getSelectedIndex()];
Event toSearch = new Event(title1.getText(), "Comedy", fullDate, clock, 0, 0);
try {
look_up.writeobj(toSearch);
look_up.readfromserver();
boolean check = look_up.readobj();
if (check) {
Lists.list = look_up.searchlist();
for (int i = 0; i < Lists.list.size(); i++) {
System.out.println("The Search button: \n" + (Lists.list.get(i)).toString());
}
resultSearch(frame, look_up);
} else {
JOptionPane.showMessageDialog(null, "NOT FOUND!", "NOT FOUND", JOptionPane.INFORMATION_MESSAGE);
Lists.list.clear();
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
} else if (other.isSelected()) {//if it belongs to any other type of category
//String title, String genre, String event_date, int available_seats, int cost_per_seat
String clock = hours[time.getSelectedIndex()];
Event toSearch = new Event(title1.getText(), "Other", fullDate, clock, 0, 0);
try {
look_up.writeobj(toSearch);
look_up.readfromserver();
boolean check = look_up.readobj();
if (check) {
Lists.list = look_up.searchlist();
for (int i = 0; i < Lists.list.size(); i++) {
System.out.println("The Search button: \n" + (Lists.list.get(i)).toString());
}
resultSearch(frame, look_up);
} else {
JOptionPane.showMessageDialog(null, "NOT FOUND!", "NOT FOUND", JOptionPane.INFORMATION_MESSAGE);
Lists.list.clear();
}
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
});
cancel.addActionListener(new ActionListener() {//Exit button
public void actionPerformed(ActionEvent e) {
try {
Lists.list.clear();// empties out the list
frame.dispose();
look_up.writeobj(null);
look_up.readfromserver(); //ενημερώνει τον σερβερ ότι πάει μια θέση πίσω
user_menu(look_up, current_user); //επιστρέφει στο μενου χρήστη
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
frame.setContentPane(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
// Method that shows the results that the user searched for
protected static void resultSearch(JFrame parentframe, Operations look_up) {
parentframe.setEnabled(false);
JFrame search = new JFrame();
JPanel panel = new JPanel();
JButton ok;
String[][] rec = new String[Lists.list.size()][6];
panel.setBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), "Results", TitledBorder.CENTER, TitledBorder.TOP));
//filling the panel with event info
for (int i = 0; i < Lists.list.size(); i++) {
for (int j = 0; j < 6; j++) {
if (j == 0) {
rec[i][j] = ((Event) Lists.list.get(i)).getTitle();
} else if (j == 1) {
rec[i][j] = ((Event) Lists.list.get(i)).getGenre();
} else if (j == 2) {
rec[i][j] = ((Event) Lists.list.get(i)).getEvent_date();
} else if (j == 3) {
rec[i][j] = ((Event) Lists.list.get(i)).getTime();
} else if (j == 4) {
rec[i][j] = valueOf(((Event) Lists.list.get(i)).getAvailable_seats());// int to String
} else if (j == 5) {
rec[i][j] = valueOf(((Event) Lists.list.get(i)).getCost_per_seat());
}
}
}
String[] header = {"Title", "Genre", "Event Date", "Time", "Available Seats", "Cost Per Seat"};
JTable table = new JTable(rec, header);
table.setEnabled(false);//doesnt allow the table to be edited
panel.add(new JScrollPane(table));
search.add(panel);
ok = new JButton("OK");
panel.add(ok);
search.add(panel);
ok.addActionListener(new ActionListener() {// Button that clears the list and goes back to the menu
public void actionPerformed(ActionEvent e) {
Lists.list.clear();
try {
look_up.clearlist();
} catch (RemoteException ex) {
Logger.getLogger(PClient2_GUI.class.getName()).log(Level.SEVERE, null, ex);
}
search.dispose();
parentframe.setEnabled(true);
parentframe.setVisible(true);
}
});
search.setSize(550, 400);
search.setVisible(true);
search.setLocationRelativeTo(null);
search.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
| TheofanisB/3-Level-Event-Booking-Client-LoginServer-DatabaseServer- | Client/PClient2_GUI.java |
1,465 | /*
* Copyright 2015 Institute of Computer Science,
* Foundation for Research and Technology - Hellas.
*
* Licensed under the EUPL, Version 1.1 or - as soon they will be approved
* by the European Commission - subsequent versions of the EUPL (the "Licence");
* You may not use this work except in compliance with the Licence.
* You may obtain a copy of the Licence at:
*
* http://ec.europa.eu/idabc/eupl
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the Licence is distributed on an "AS IS" basis,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the Licence for the specific language governing permissions and limitations
* under the Licence.
*
* =============================================================================
* Contact:
* =============================================================================
* Address: N. Plastira 100 Vassilika Vouton, GR-700 13 Heraklion, Crete, Greece
* Tel: +30-2810-391632
* Fax: +30-2810-391638
* E-mail: [email protected]
* WebSite: https://www.ics.forth.gr/isl/centre-cultural-informatics
*
* =============================================================================
* Authors:
* =============================================================================
* Elias Tzortzakakis <[email protected]>
*
* This file is part of the THEMAS system.
*/
package SVGproducer;
import DB_Classes.DBGeneral;
import DB_Classes.DBThesaurusReferences;
import Users.UserInfoClass;
import Utils.ConstantParameters;
import Utils.StrLenComparator;
import Utils.Parameters;
import neo4j_sisapi.*;
import java.io.*;
import java.util.*;
import java.awt.Font;
import java.net.URLEncoder;
import javax.servlet.http.HttpSession;
/*-------------------------------------------------------------------
Class ProduceHierarchies_common:
The abstract class that implements most methods for creating an SVG
hierarchy...
--------------------------------------------------------------------*/
public abstract class ProduceHierarchies_common {
//SIS API vars
protected QClass Q;
protected IntegerObject sis_session;
protected StringObject strobj, strobj1, strobj2, strobj3;
protected StringObject /*categ,*/ categ1, categ2, categ3;
protected StringObject fromcls/*, label, cls, cls2*/;
protected CMValue /*cmv,*/ cmv1;
protected int ret_set, ret_set1, ret_set2, ret_set3;
protected IntegerObject uniq_categ, traversed, clsid, sysid;
protected CategorySet[] categs;
// Read configuration class
protected ReadSVGConfig I;
protected PrintWriter writer;
protected String HierarchiesArray[];
protected int LIDsArray[];
protected int TIDsArray[];
protected int ModesArray[];
protected ArrayList<String> V1;
protected ArrayList<String> V2;
protected ArrayList<String> V3;
protected ArrayList<SVGOBJ> svgV;
protected double relheight;
protected double svgwidth;
protected double svgheight;
protected long dataModified;
protected String theScope;
protected String navbarEnabled;
protected String resultString;
final static String SVG_HEADER = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" +
"<?xml-stylesheet href='../SVG.css' type='text/css'?>\n" +
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n" +
"'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" +
"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' >\n";
final static String SVG_HEADER_NAV = "<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n" +
"<?xml-stylesheet href='../SVG.css' type='text/css'?>\n" +
"<!DOCTYPE svg PUBLIC '-//W3C//DTD SVG 1.1//EN'\n" +
"'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'>\n" +
"<svg version='1.1' xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' width='700px' height='500px' onload=\"Init(evt)\" onmousedown=\"Grab(evt)\" onmouseup=\"Drop(evt)\" onmousemove=\"Drag(evt)\" onmouseout=\"Drop(evt)\">\n";
abstract int GetHierarchySet(UserInfoClass SessionUserInfo, String hierarchy, String lang, String style);
String termPrefix, facetPrefix; // g.e. "EL`", "EKTClass`"
String web_app_path; // g.e. http://139.91.183.22:8084
// Font SVGFont = new Font("Arial", Font.PLAIN, 12);
Font SVGFont = new Font("Verdana", Font.PLAIN, 12); // do NOT set the font family "Arial", because SVG is buggy for the combination of text "πώ" (ellhiko pi kai tonoymeno wmega)
// do NOT set the size more than 16. The layout algorithm does NOT work for big font sizes!!
// do NOT change the style (PLAIN). The code does not set it in SVG code => default (plain) is used
ArrayList<String> DBPrefixes = new ArrayList<String>();
//protected Vector CurrentlyParsedNodes;
final static String PATTERN_FOR_MARKING_CYCLIC_NODES = "||";
protected ProduceHierarchies_common() {
strobj = new StringObject();
strobj1 = new StringObject();
strobj2 = new StringObject();
strobj3 = new StringObject();
//categ = new StringObject();
categ1 = new StringObject();
categ2 = new StringObject();
categ3 = new StringObject();
fromcls = new StringObject();
//label = new StringObject();
//cls = new StringObject();
//cls2 = new StringObject();
//cmv = new CMValue();
cmv1 = new CMValue();
ret_set = -1;
ret_set1 = -1;
ret_set2 = -1;
ret_set3 = -1;
uniq_categ = new IntegerObject();
traversed = new IntegerObject();
clsid = new IntegerObject();
sysid = new IntegerObject();
//categs = new CategorySet[1];
Q = new QClass();
sis_session = new IntegerObject();
V1 = new ArrayList<String>();
V2 = new ArrayList<String>();
V3 = new ArrayList<String>();
svgV = new ArrayList<SVGOBJ>();
resultString = new String();
relheight = 0;
svgwidth = 0;
svgheight = 0;
//web_app_path = Parameters.path;
//CurrentlyParsedNodes = new Vector();
}
/*-----------------------------------------------------------------------
doJob()
-------------------------------------------------------------------------
FUNCTION: - The classes basic function doJob, calls all the necessary functions
to have the work done
RETURNS: A SVG String
-------------------------------------------------------------------------*/
protected String doJob(UserInfoClass SessionUserInfo, String name, String lang, String style)
throws IOException {
//Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix+"doJob " + ((UserInfoClass)sessionInstance.getAttribute("SessionUser")).selectedThesaurus) ;
resultString = "";
V1 = new ArrayList<String>();
V2 = new ArrayList<String>();
V3 = new ArrayList<String>();
svgV = new ArrayList<SVGOBJ>();
DBGeneral dbGen = new DBGeneral();
// BUG fix (karam): reseting of class members (without this, any graph following the first, has wrong x, y dimensions!)
relheight = 0;
svgwidth = 0;
svgheight = 0;
navbarEnabled = I.navbar_enabled;
theScope = I.hierarchy_scope;
name = ReplaceGuideTermMarks(name);
String nameUnicode = ConvertUnicodeToLatin(name, lang);
//Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix+name);
sis_session = new IntegerObject();
//open connection and start Query
if(dbGen.openConnectionAndStartQueryOrTransaction(Q, null, sis_session, null, null, true)!=QClass.APIFail){
DBPrefixes = new ArrayList<String>();
DBPrefixes = GetDBPrefixes();
if (GetHierarchySet(SessionUserInfo, nameUnicode, lang, style) != 0) {
Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + "?");
}
double w = SVGOBJ.GetStringRealWidth(name, SVGFont);
RecurseHierarchy(name, w, 0, 0, 0, 0, style);
//RecurseHierarchy(name, name.length(), 0, 0, 0, 0, style);
//Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix+"Calling RecurseHierarchy() with name = " + name + " length = " + name.length());
ProduceSVG(SessionUserInfo, lang);
//end query and close connection
Q.free_all_sets();
Q.TEST_end_query();
dbGen.CloseDBConnection(Q, null, sis_session, null, false);
} else {
Utils.StaticClass.webAppSystemOutPrintln("OPEN CONNECTION ERROR @ class ProduceHierarchies_common.");
svgConnectionErrorMsg();
}
return resultString;
}
/*---------------------------------------------------------------------
GetDBPrefixes()
-----------------------------------------------------------------------
OUTPUT: a Vector with the declared prefixes in the DB (instances of class Prefix)
----------------------------------------------------------------------*/
public ArrayList<String> GetDBPrefixes() {
int SISsession = sis_session.getValue();
Q.reset_name_scope();
Q.set_current_node(new StringObject("Prefix"));
int set_c = Q.get_instances(0);
ArrayList<String> prefixes = new ArrayList<String>();
Q.reset_set(set_c);
ArrayList<Return_Nodes_Row> retVals = new ArrayList<Return_Nodes_Row>();
if(Q.bulk_return_nodes(set_c, retVals)!=QClass.APIFail){
for(Return_Nodes_Row row:retVals){
prefixes.add(row.get_v1_cls_logicalname());
}
}
/*
StringObject Cname = new StringObject();
while ((Q.retur_nodes(set_c, Cname)) != QClass.APIFail) {
prefixes.add(Cname.getValue());
}*/
Q.free_set(set_c);
//Sort is needed for alphabetical sort bug fix when prefixes like EL` and THES1EL` are defined
StrLenComparator strLen = new StrLenComparator(StrLenComparator.Descending);
Collections.sort(prefixes, strLen);
return prefixes;
}
/*-----------------------------------------------------------------------
ConvertUnicodeToLatin()
-------------------------------------------------------------------------*/
protected String ConvertUnicodeToLatin(String name, String lang) {
/*
if (lang.equals("EN")) {
return name;
} else if (lang.equals("FR")) {
return name;
} else if (lang.equals("DE")) {
return name;
} else if (lang.equals("GR")) {
return neo4j_sisapi.GreekConverter.Uni2ISO7String(name);
} else {
*
*/
return name;
//}
}
/*-----------------------------------------------------------------------
ConvertLatinToUnicode()
-------------------------------------------------------------------------*/
protected String ConvertLatinToUnicode(String name, String lang) {
/*
if (lang.equals("EN")) {
return name;
} else if (lang.equals("FR")) {
return name;
} else if (lang.equals("DE")) {
return name;
} else if (lang.equals("GR")) {
return neo4j_sisapi.GreekConverter.ISO72UniString(name);
} else {*/
return name;
//}
}
/*-----------------------------------------------------------------------
svgConnectionErrorMsg()
-------------------------------------------------------------------------
FUNCTION: - Creates the contents of an SVG structure displaying a Connection
Error Message
CALLED_BY: doJob() of this Class
-------------------------------------------------------------------------*/
protected void svgConnectionErrorMsg() {
Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + "I'm sorry! Problem connecting with Neo4j Database");
resultString += SVG_HEADER;
resultString += "<text x=\"173.0\" y=\"29.0\" style=\"font-family:Arial; fontsize:14pt; fill:black;\">I'm sorry! Problem connecting with SIS at port of machine</text>";
resultString += "</svg>\n";
}
/*-----------------------------------------------------------------------
svgNodeNotFoundErrorMsg()
-------------------------------------------------------------------------
FUNCTION: - Creates the contents of an SVG structure displaying a Node Not
Found Error Message
CALLED_BY: doJob() of this Class
-------------------------------------------------------------------------*/
protected void svgNodeNotFoundErrorMsg() {
svgNodeNotFoundErrorMsg();
}
protected void svgNodeNotFoundErrorMsg(String node) {
Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + "Not an SIS node!");
node = ReplaceBadChars(node);
resultString += SVG_HEADER;
resultString += "<text x=\"173.0\" y=\"29.0\" style=\"font-family:Arial; fontsize:14pt; fill:black;\"> " + node + " Not an SIS node!</text>";
resultString += "</svg>\n";
}
/*---------------------------------------------------------------------
SortParallelVectors()
-----------------------------------------------------------------------
OUTPUT: sorts alphabetically the 1st Vector V1 and pararelly the parallel Vector V2
----------------------------------------------------------------------*/
public void SortParallelVectors(ArrayList V1, ArrayList V2) {
// fill Vector V2 with prefixes the corresponding values of Vector V1
// separated with "@@@@@"
int size = V1.size();
for (int i = 0; i < size; i++) {
String str1 = V1.get(i).toString();
String str2 = V2.get(i).toString();
V2.set(i,(str1 + "@@@@@" + str2));
}
// sort both Vectors V1 and V2
Collections.sort(V1);
Collections.sort(V2);
// remove from Vector V2 the prefixes added above
for (int i = 0; i < size; i++) {
String str2 = V2.get(i).toString();
String old_value = str2.substring(str2.indexOf("@@@@@") + 5);
V2.set(i,old_value);
}
}
/*-----------------------------------------------------------------------
RecurseHierarchy()
-------------------------------------------------------------------------
INPUT: - String topterm: the given "hierarchy" HttpServlet parameter
- int maxsiblingsize: the lenght of the above parameter
- int maxparentsize: 0
FUNCTION: -
CALLED_BY: doJob() of this class
-------------------------------------------------------------------------*/
//protected double RecurseHierarchy(String topterm, int maxsiblingsize, int maxparentsize, int mode, int LID, int TID, String style) {
protected double RecurseHierarchy(String topterm, double maxsiblingsize, double maxparentsize, int mode, int LID, int TID, String style) {
String x, y;
int i;
//int maxkidsize=0;
double maxkidsize = 0;
int kidno = 0;
double kidsheight = 0;
double termheight = 0;
ArrayList<String> V = new ArrayList<String>();
ArrayList<String> Vstyles = new ArrayList<String>();
ArrayList<String> hlpV = new ArrayList<String>();
double w;
/* freezed
boolean cycleDetected = CycleDetection(topterm, null);
boolean isAdded = CurrentlyParsedNodes.contains(topterm);
CurrentlyParsedNodes.add(topterm);
*/
// if (cycleDetected == false || isAdded == false) {
for (i = 0; i < V2.size(); i++) {
x = V2.get(i).toString();
if (x.compareTo(topterm) == 0) {
y = V1.get(i).toString();
V.add(y);
String currentStyle = V3.get(i).toString();
Vstyles.add(currentStyle);
// TRYING TO FIX THE BUG of wrong cordinates for FRENCH graphs SVGproducer = new ProduceISAHierarchy(conf);
//String translatedTerm = LanguageSwitch(sessionInstance, LID, y);
String translatedTerm;
translatedTerm = y;
w = SVGOBJ.GetStringRealWidth(translatedTerm, SVGFont);
if (w > maxkidsize) {
maxkidsize = w;
}
++kidno;
}
}
//}
String url = new String();
if (V.size() > 0) {
// before calling recursively this function for each node of this level,
// sort alphabetically the nodes of this level (Vector V) and pararelly the parallel Vector Vstyles
SortParallelVectors(V, Vstyles);
for (i = 0; i < V.size(); i++) {
double tmp = RecurseHierarchy(V.get(i).toString(), maxkidsize, maxparentsize + 6 + maxsiblingsize, mode, LID, TID, Vstyles.get(i).toString());
kidsheight += tmp;
hlpV.add(Double.toString(tmp));
}
for (i = 0; i < hlpV.size(); i++) {
double tmp = Double.parseDouble(hlpV.get(i).toString());
String translatedTopTerm;
translatedTopTerm = topterm;
// line
// karam bug fix: calculate the width of the rectangle without the prefix
String translatedTopTermWithoutPrefix = translatedTopTerm.substring(translatedTopTerm.indexOf("`") + 1);
w = SVGOBJ.GetStringRealWidth(translatedTopTermWithoutPrefix, SVGFont);
svgV.add(new SVGOBJ(maxparentsize + w, kidsheight / kidno, maxparentsize + 6 + maxsiblingsize, tmp));
//svgV.add(new SVGOBJ(maxparentsize + translatedTopTermWithoutPrefix.length(), kidsheight/kidno, maxparentsize + 6 + maxsiblingsize, tmp));
}
termheight = kidsheight / kidno;
// rectangular
svgV.add(new SVGOBJ(maxparentsize, termheight, topterm, url, style, SVGFont));
} else {
termheight = ++relheight;
/* freezed
if (cycleDetected == true && isAdded == true) {
topterm += "...(cycle detected)";
}
*/
// rectangular
svgV.add(new SVGOBJ(maxparentsize, termheight, topterm, url, style, SVGFont));
}
if (termheight > svgheight) {
svgheight = termheight;
}
w = SVGOBJ.GetStringRealWidth(topterm, SVGFont);
if (maxparentsize + w > svgwidth) {
//if (maxparentsize + topterm.length() > svgwidth) {
svgwidth = maxparentsize + w;
}
return termheight;
}
/*-----------------------------------------------------------------------
CycleDetection() - freezed and not used
-------------------------------------------------------------------------
it was written so as to detect any possible cycle in a graph, but when
category EKTHierarchyTerm->EKT_RT was added, SIS server crashed in
get_traverse_by_category() before RecurseHierarchy() was called
-------------------------------------------------------------------------*/
boolean CycleDetection(String rootTarget, String targetChild) {
String currentTarget = "";
if (targetChild == null) { // 1st call
currentTarget = rootTarget;
} else { // any next call
currentTarget = targetChild;
}
// for each from-value: search from current target
for (int i = 0; i < V2.size(); i++) {
String fromValue = V2.get(i).toString();
// if found
if (fromValue.compareTo(currentTarget) == 0) {
// get the to-value
String toValue = V1.get(i).toString();
// in case of link from target to itself => cycle
if (toValue.compareTo(rootTarget) == 0) {
return true;
} // otherwise, continue the check with the found child of the target
else {
return CycleDetection(rootTarget, toValue);
}
}
}
return false;
}
/*-----------------------------------------------------------------------
GivenClassIsHierarchy()
-------------------------------------------------------------------------*/
boolean GivenClassIsHierarchy(String selectedThesaurus, String className, String lang) {
String classNameDB = ConvertUnicodeToLatin(className, lang);
// looking for EKTHierarchy
DBThesaurusReferences dbtr = new DBThesaurusReferences();
StringObject thesHierarchy = new StringObject();
dbtr.getThesaurusClass_Hierarchy(selectedThesaurus, Q, sis_session.getValue(), thesHierarchy);
int API_sessionID = sis_session.getValue();
// get the classes of the given class
Q.reset_name_scope();
long xL = Q.set_current_node(new StringObject(classNameDB));
int classesSet = Q.get_all_classes(0);
// make a set with EKTHierarchy
int set = Q.set_get_new();
Q.reset_name_scope();
long yL = Q.set_current_node(thesHierarchy);
int z = Q.set_put(set);
// get their intersection
int k = Q.set_intersect(set, classesSet);
boolean GivenClassIsHierarchy = false;
int l = Q.set_get_card(set);
if (Q.set_get_card(set) == 1) {
GivenClassIsHierarchy = true;
}
Q.free_all_sets();
return GivenClassIsHierarchy;
}
/*-----------------------------------------------------------------------
ProduceSVG()
-------------------------------------------------------------------------
FUNCTION: - REPLACED the following ProduceSVGFile_OLD() function by karam at 14/6/04 to fix the
bug which didn't fill SVG file with special french characters correctly
CALLED_BY: doJob() of this Class
-------------------------------------------------------------------------*/
protected void ProduceSVG(UserInfoClass SessionUserInfo, String lang) throws java.io.UnsupportedEncodingException {
String SVGHeader = "";
StringBuffer FileContents = new StringBuffer();
String SVGFooter = "";
if (navbarEnabled.equals("true")) {
SVGHeader += SVG_HEADER_NAV;
} else if (navbarEnabled.equals("false")) {
SVGHeader += SVG_HEADER;
}
SVGHeader += "<desc> Hierarchy svg file </desc>\n";
SVGHeader += "<script xmlns:xlink='http://www.w3.org/1999/xlink' type=\"text/ecmascript\" xlink:href=\"../SVGScripts.js\"/>\n" +
"<script xmlns:xlink='http://www.w3.org/1999/xlink' type=\"text/ecmascript\" xlink:href=\"../../Javascript/graphicalView.js\"/>\n";
FileContents.append("<g id=\"group1\">\n");
for (int i = 0; i < svgV.size(); i++) {
SVGOBJ obj = (SVGOBJ) (svgV.get(i));
if (obj.type == 0) {
FileContents.append("<g>\n");
String currentText = obj.text;
if(obj.style.compareTo("styleTR")==0 || obj.style.compareTo("styleUFTranslations")==0){
currentText = currentText.replaceFirst(ConstantParameters.languageIdentifierSuffix, Parameters.TRANSLATION_SEPERATOR + " ");
obj.w = SVGOBJ.GetStringRealWidth(currentText, SVGFont) + SVGOBJ.OFFSET;
}
//String currentText = obj.text;
boolean f1 = currentText.startsWith(termPrefix);
boolean f2 = currentText.startsWith(facetPrefix);
if (currentText.endsWith(PATTERN_FOR_MARKING_CYCLIC_NODES) == true) {
currentText = currentText.substring(0, currentText.lastIndexOf(PATTERN_FOR_MARKING_CYCLIC_NODES));
}
// Toraki requirement:
// ενώ εμφανίζει τον μη προτιμώμενο, δεν δίνει τον προτιμώμενο (ίσως δεν έχει και νόημα εδώ η σύνδεση τότε).
// Πολύκαρπος: εννοούν ότι από έναν όρο εμφανίζεται το to-value(s) του category
// (AAAHierarchyTerm->AAA_UF-> AAAUsedForTerm) (μη προτιμώμενο), ενώ όταν κάνουμε κλικ σε αυτό,
// δεν εμφανίζεται το αντίστοιχο from-value (προτιμώμενο). Είναι λογικό, διότι στο configuration
// των SVG γράφων έχει επιλεχθεί να εμφανίζεται αυτό το category μόνο με forward direction.
// π.χ. AAAEL`εμπορεύματα. Οπότε και θα μπορούσε να καταργηθεί το anchor σε όλα τα AAAUsedForTerms
// (ίσως δεν έχει και νόημα εδώ η σύνδεση τότε).
boolean objectIsUsedForTerm = (obj.style.compareTo("styleUF") == 0);
if ((f1 == true || f2 == true) && objectIsUsedForTerm == false) {
//if (f1 == true || f2 == true) {
FileContents.append("<a xlink:href=\"javascript:followlink();\" onclick=\"GraphicalViewIconPressed('");
FileContents.append("/GraphicalView','");
String current;
if (f1) {
current = currentText.substring(currentText.indexOf(termPrefix) + termPrefix.length());
} else {
current = currentText.substring(currentText.indexOf(facetPrefix) + facetPrefix.length());
}
current.replaceAll("'", "\\'");
FileContents.append(URLEncoder.encode(current, "UTF-8").replaceAll("\\+", "%20"));
FileContents.append("','");
if (f1 == true) { // case of graph of a descriptor
FileContents.append("DESCRIPTOR");
}
if (f2 == true) { // case of graph of a Facet
// check the case of Facet / Hierarchy
if (GivenClassIsHierarchy(SessionUserInfo.selectedThesaurus, currentText, lang) == true) {
FileContents.append("HIERARCHY");
} else {
FileContents.append("FACET");
}
}
FileContents.append("','true','" + SessionUserInfo.userGroup + "','" + SessionUserInfo.selectedThesaurus + "','" + SessionUserInfo.SVG_CategoriesFrom_for_traverse + "','" + SessionUserInfo.SVG_CategoriesNames_for_traverse + "')\">");
}
FileContents.append("<rect" + " class=\"" + obj.style + "\"" + " x=\"" + obj.x + "\" y=\"" + obj.y + "\" width=\"" + obj.w + "\" height=\"" + obj.h + "\"></rect>\n");
//FileContents += "<text" + " x=\"" + obj.tx + "\" y=\"" + obj.ty + "\" style=\"font-family:" + obj.fontfamily + "; fontsize:" + obj.fontsize + "; fill:" + obj.textfill + ";\">" + currentText + "</text>\n";
FileContents.append("<text" + " x=\"" + obj.tx + "\" y=\"" + obj.ty + "\" font-family=\"" + obj.fontfamily + "\" font-size=\"" + obj.fontsize + "\" fill=\"" + obj.textfill + "\">" + ReplaceBadChars(currentText) + "</text>\n");
// Toraki requirement:
// ενώ εμφανίζει τον μη προτιμώμενο, δεν δίνει τον προτιμώμενο (ίσως δεν έχει και νόημα εδώ η σύνδεση τότε).
// Πολύκαρπος: εννοούν ότι από έναν όρο εμφανίζεται το to-value(s) του category
// (AAAHierarchyTerm->AAA_UF-> AAAUsedForTerm) (μη προτιμώμενο), ενώ όταν κάνουμε κλικ σε αυτό,
// δεν εμφανίζεται το αντίστοιχο from-value (προτιμώμενο). Είναι λογικό, διότι στο configuration
// των SVG γράφων έχει επιλεχθεί να εμφανίζεται αυτό το category μόνο με forward direction.
// π.χ. AAAEL`εμπορεύματα. Οπότε και θα μπορούσε να καταργηθεί το anchor σε όλα τα AAAUsedForTerms
// (ίσως δεν έχει και νόημα εδώ η σύνδεση τότε).
if ((f1 == true || f2 == true) && objectIsUsedForTerm == false) {
//if (f1 == true || f2 == true) {
FileContents.append("</a>");
}
FileContents.append("</g>\n");
}
if (obj.type == 1) {
FileContents.append("<g style=\"fill:" + obj.fill + "; stroke:" + obj.stroke + "\">\n");
FileContents.append("<line" + " x1=\"" + obj.x + "\" y1=\"" + obj.y + "\" x2=\"" + obj.w + "\" y2=\"" + obj.h + "\"/>\n");
FileContents.append("</g>\n");
}
}
FileContents.append("</g>\n");
if (navbarEnabled.equals("true")) {
FileContents.append("<g id=\"group2\" transform = \"translate(0 0) scale(0.1)\">\n");
FileContents.append("<rect x=\"0\" y=\"0\" style=\"fill:#E9E9C6; stroke:brown;\">\n");
FileContents.append("</rect>");
FileContents.append("</g>\n");
FileContents.append("<g id=\"group3\" transform=\"translate(0 0) scale(0.1)\">\n");
FileContents.append("<rect x=\"20\" y=\"20\" width=\"500px\" height=\"500px\" opacity=\"0.7\" stroke-width=\"2\" style=\"fill:cyan; stroke:black;\">\n");
FileContents.append("</rect>\n");
FileContents.append("</g>\n");
// karam
//FileContents += "<script xmlns:xlink='http://www.w3.org/1999/xlink' type=\"text/ecmascript\" xlink:href=\"./SVGScripts.js\"/>\n";
// FileContents.append("<script xmlns:xlink='http://www.w3.org/1999/xlink' type=\"text/ecmascript\" xlink:href=\"../SVGScripts.js\"/>\n");
// FileContents.append("<script xmlns:xlink='http://www.w3.org/1999/xlink' type=\"text/ecmascript\" xlink:href=\"../../Javascript/graphicalView.js\"/>\n");
}
SVGFooter += "</svg>\n";
try {
resultString += SVGHeader;
resultString += FileContents.toString();
resultString += SVGFooter;
} catch (Exception e) {
Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix + e.getMessage());
Utils.StaticClass.handleException(e);
resultString += "End of stream";
}
}
protected String ReplaceGuideTermMarks(String theString) {
// Utils.StaticClass.webAppSystemOutPrintln(Parameters.LogFilePrefix+"ReplaceGuideTermMarks " + theString);
// theString = theString.replaceAll("@#","<");
// theString = theString.replaceAll("#@",">");
return theString;
}
protected String ReplaceBadChars(String theString) {
theString = theString.replaceAll("\u00A2", "¢");
/*
theString = theString.replaceAll("&",""");
theString = theString.replaceAll("<","<");
theString = theString.replaceAll(">",">");
*/
theString = theString.replaceAll("\\\\", "\\\\");
theString = theString.replaceAll("&", "&");
theString = theString.replaceAll("<", "<");
theString = theString.replaceAll(">", ">");
theString = theString.replaceAll("'", "'");
theString = theString.replaceAll("\"", """);
//theString = neo4j_sisapi.GreekConverter.ISO72UniString(theString);
return theString;
}
}
| isl/THEMAS | src/main/java/SVGproducer/ProduceHierarchies_common.java |
1,466 | import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.input.MouseEvent;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Optional;
import java.util.ResourceBundle;
public class initializeServerControllers implements Initializable {
@FXML
private Button BTNconnect;
@FXML
private Label LBLstatus;
@FXML
private TextField TFdatabase;
@FXML
private PasswordField TFpassword;
@FXML
private TextField TFport;
@FXML
private TextField TFserverip;
@FXML
private TextField TFusername;
private double x;
private double y;
public void exitButtonClicked(ActionEvent e) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Επιβεβαίωση εξόδου");
alert.setHeaderText("Επιβεβαίωση");
alert.setContentText("Είστε σίγουροι ότι θέλετε να τερματίσετε την εφαρμογή;");
ButtonType buttonTypeOK = new ButtonType("Έξοδος", ButtonData.OK_DONE);
ButtonType buttonTypeCancel = new ButtonType("Ακύρωση", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeCancel, buttonTypeOK);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOK)
System.exit(0);
}
public void cancelButtonClicked(ActionEvent event) {
LBLstatus.setVisible(false);
TFserverip.setText(connectDB.getServer());
TFport.setText(connectDB.getPort());
TFdatabase.setText(connectDB.getDatabase());
TFusername.setText(connectDB.getUsername());
TFpassword.setText(connectDB.getPassword());
}
public void connectButtonClicked(ActionEvent event) {
connectDB.setServer(TFserverip.getText());
connectDB.setPort(TFport.getText());
connectDB.setDatabase(TFdatabase.getText());
connectDB.setUsername(TFusername.getText());
connectDB.setPassword(TFpassword.getText());
try (Connection ignored = connectDB.getConnection()) {
Parent root = FXMLLoader.load(getClass().getResource("fxml code/login.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
root.setOnMousePressed((MouseEvent e) -> {
x = e.getSceneX();
y = e.getSceneY();
});
root.setOnMouseDragged((MouseEvent e) -> {
stage.setX(e.getScreenX() - x);
stage.setY(e.getSceneY() - y);
stage.setOpacity(.8);
});
root.setOnMouseReleased((MouseEvent e) -> {
stage.setOpacity(1);
});
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
BTNconnect.getScene().getWindow().hide();
stage.show();
} catch (SQLException e) {
LBLstatus.setText("Η σύνδεση με τον server δεν ήταν δυνατή. Ελέγξτε τα στοιχεία και ξαναπροσπαθείστε!");
LBLstatus.setVisible(true);
} catch (IOException e) {
System.err.println(e);
}
}
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
TFserverip.setText(connectDB.getServer());
TFport.setText(connectDB.getPort());
TFdatabase.setText(connectDB.getDatabase());
TFusername.setText(connectDB.getUsername());
TFpassword.setText(connectDB.getPassword());
LBLstatus.setVisible(false);
}
}
| ltopalis/DB-JavaFX-JDBC | code/initializeServerControllers.java |
1,468 | package com.example.skinhealthchecker;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.RectF;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfFloat;
import org.opencv.core.MatOfInt;
import org.opencv.core.MatOfInt4;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.core.TermCriteria;
import org.opencv.imgproc.Imgproc;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static java.lang.Math.PI;
/**
* Περιέχει μεθόδους που χρησιμοποιούνται σε όλη την εφαρμογή . Είναι συγκεντρωμένες σε ένα αρχείο java για καλύτερη οργάνωση του κώδικα.
* Contains methods used throughout the application. They are gathered in a java file for better organization of the code.
*/
public class MyLib {
static String TAG;
//crops center of the images ->input mat output cropped mat
public static Mat getcenterareamat (Mat src){
int x=src.rows();
int y=src.cols();
Randar.base =Math.abs(src.cols()/10);// calculating new image side
Log.i(TAG, "center base");
Log.d(TAG,Integer.toString((int) Randar.base) );
Log.i(TAG, "image size");
Log.d(TAG,Integer.toString((int) x) );
// Rect roi = new Rect(x/2-2*x/5, y/2-2*y/5, 2*x/(3), 2*y/(3));
// Rect roi = new Rect(500-x/2, 500-y/2, 2*x/(3), 2*y/(3));
// masks for crop
Rect roi = new Rect(Math.abs(x/2)-Randar.base,Math.abs( y/2)-Randar.base, 2*Randar.base, 2*Randar.base);
Mat cropped = new Mat(src, roi);// creating new image.
// new image site will be : oldimage.hight/10^2
// out = src.getSubimage(x, y, w-2*x, h-2*y);
return cropped;
}
//returns objects within size limits
// επιστρέφει τα αντικείμενα που είναι εντός ορίων μεγέθους
// input countours list -> output id list of items in size limit
public static int [] insizecontor ( List<MatOfPoint> contours)
{int [] Contourofinterest;
int [] largestContour = new int [contours.size()];// creating the list
int num=0;
double area = 0;
int seclarge = 0;
double Area2=0;
int z=0;
TAG ="contors size";
for (int i = 0; i < contours.size(); i++)
{
double cArea =
Imgproc.contourArea(contours.get(i));
if (cArea > Randar.minsearchsize && cArea<Randar.maxsearchsize) // if the item size is in limit
{
// des=targetcircle(des,new Point(resultx,resulty),range);
Log.d(TAG,Integer.toString((int)cArea) );
area = cArea; largestContour[z]=i;z++; // save the item , make the counter z bigger
}
}
if (z>0){/// creating new list filled by ids of items
Contourofinterest = new int [z];
for(int i=0;i<z-1;i++)
{Contourofinterest[i]=largestContour[i];
}}
else // is there is no countor in size then return error "-1"
{ Contourofinterest = new int [1];
Contourofinterest[0] = -1;
}
return Contourofinterest;
}
//creating small mat obgects by croping the big one using hsv color space
// dimiourgw mikra mat arxeia se morfh hsv etsi wste na ta eksetasw ena ena
//
//input list of countours , list of obgect in size , image in hsv color space
//output : list of Mats (found items mats)
public static Mat [] firstmatresults ( List<MatOfPoint> contours,int [] list,Mat srchsv)
{
Rect[] rect = new Rect [list.length ]; // list of rects / masks for crop
Mat [] roi = new Mat [list.length ];//list of croped temp mats
// we need a list of temp mat and not a mat because the size of temp mat is not stable
Mat [] mats= new Mat [list.length];// the returning mats of obgects
for(int i=0;i< list.length ; i++)
{ // srchsv
rect[i] = Imgproc.boundingRect(contours.get( list[i] )); // getting the borders of a rect near the object
roi[i] = srchsv.submat(rect[i].y, rect[i].y + rect[i].height, rect[i].x, rect[i].x + rect[i].width);// crops the init image
mats[i] = new Mat (roi[i].height(), roi[i].width(), CvType.CV_8UC3);// just copy the cropped to mat
mats[i]= roi[i];
}
return mats;//returs the list
}
// επιστρέφει τον αριθμό απο τις εικόνες που περιέχουν σκούρο χρώμa και σωστη αναλογία
/*
epistréfei ton arithmó apo tis eikónes pou periéchoun skoúro chróma
returns the number of images that contain dark color
and acceptable height to width ratio
input: obgects mats ,list with positions of oobjects in contours list
*/
public static int [] blacklikeresults ( Mat [] matlist ,int [] list )
{ int temp=2;
int [] templist = new int [matlist.length];// list of possitions of obgects (with right blacklike pixels and
//height / weight ratio
Randar.blackpix = new int [matlist.length]; // contains the size of blacklike pixels in oobjects
int z=-1; // just a counter
//Mat [] nonZeroCoordinates = new Mat [matlist.length];
Mat [] nonZeroCoordinates = new Mat [matlist.length]; //will contain the map of obgect pixel that is
// in black range (E.G if a pixel is non zero then will have value 1 )
Mat [] tempmat = new Mat [matlist.length]; //will contain the obgect img but if somepixel
//is not in black range -> those will be 0
for(int i=0;i<matlist.length;i++)
{
if (matlist[i].height()>=matlist[i].width()) // checking the ratio
{
temp=matlist[i].height()/matlist[i].width();
}
else
{ temp=matlist[i].width()/matlist[i].height();
}
//elenxw an oi diastaseis einai konta se diastaseis tetragwnou
// checking if the ratio is less than 3
if (temp<3)
{
nonZeroCoordinates[i]=new Mat (matlist[i].height(), matlist[i].width(), CvType.CV_8UC3);
tempmat[i]= new Mat (matlist[i].height(), matlist[i].width(), CvType.CV_8UC3);
Scalar lower = new Scalar(0, 0, 0);/// lower hsv range
// Scalar upper = new Scalar(180, 255, 90,0); //blacks
Scalar upper = new Scalar(179, 255, 150); //blacks // upper hsv range
// Scalar upper = new Scalar (255,255,minskin[2]);
// Scalar upper = new Scalar(180, 255, 90,0); //blacks
Core.inRange(matlist[i], lower, upper, tempmat[i]); // all pixels not in ranges gets value of 0
Core.findNonZero(tempmat[i], nonZeroCoordinates[i]);// counting non-zero pixels
TAG= "nonzero";
Log.d(TAG,Integer.toString((int) nonZeroCoordinates[i].total()) );
//orizw oti ta epithimita xrwmata 8a prepei na einai mesa sthn komenh eikonas
// if (nonZeroCoordinates.total()>matlist[i].total()*1/1000)
if (Randar.MINBLACK<=nonZeroCoordinates[i].total() ) // if non pixel values is many
{
// if(matlist[i].total()>=Randar.MINBLACK){
z++;// up the counter
templist[z]=list[i]; // get the id of the obgect
Randar.blackpix[z]=(int) nonZeroCoordinates[i].total(); // note the number of black pixels
Log.e(TAG, "pixels blacks");
Log.d(TAG,Integer.toString((int) nonZeroCoordinates[i].total()) );
Log.e(TAG, "numbest");
Log.d(TAG,Integer.toString((int) list[i]) );
// }
}
}
}
if (z==-1){// if non object found
int [] returnlist = new int [1];
returnlist[0]=-1;// return error (-1)
return returnlist;}
else {
int [] returnlist = new int [z+1];//else return the list
for (int i=0;i<=z;i++)
{
returnlist[i]=templist[i];
}
//return list;
return returnlist;
}
}
/*
επιστρέφει το καλύτερο εντοπισμό αντικείμενο με βάση το μέγεθος το χρώμα και την θέση του
returns the best targeting object based on its size and location in the init image = the mole
input :all contours, input image , the list with black obgects
output : the id of mole (luckily)
*/
public static int bestbigcontor ( List<MatOfPoint> contours ,Mat src,int[] blackslikecon)
{
int bestContour = blackslikecon[0];// init the returning var with the id of the first object of the list
double bestx=0,besty=0; // init the best coordinates
int bestnumblack=0; //blacks of selected object
Point v;//temp var of points
Point[] points_contour; // list of points
int nbPoints=0; // length of points of each obgect.
double centerx=0 ,centery=0 ;// init object coordinates
double size =0 ;
for (int i = 0; i <blackslikecon.length; i++)
{
centerx=0 ;centery=0 ;// init object coordinates
MatOfPoint best = contours.get(blackslikecon[i]);// gets points of the checking object
points_contour = best.toArray();
nbPoints = points_contour.length;
for( int j=0; j< nbPoints;j++)
{
v=points_contour[j];
// for each point getting the sums of x's and y's
centerx =centerx+v.x;
centery =centery+v.y;
}
if(nbPoints!=0 )
{centerx=centerx/nbPoints;// // for each object calculates the avg's of x's and y's
//the avg of each one will be the center point of the obgect
centery=centery/nbPoints;
//calculating the distance of the center point and the center of the image
//if the distance is smaller comparing to best selected (for the moment ) object
if( 2.3* Math.sqrt(Math.pow(Math.abs(bestx-src.rows()/2),2)+Math.pow(Math.abs(besty-src.cols()/2),2))>Math.sqrt(Math.pow(Math.abs(centerx-src.rows()/2),2)+Math.pow(Math.abs(centery-src.cols()/2),2)) ) {
//if the object center is somewhere near image center Eg in a rect at center with size src.cols*src*rows
if (((Math.abs(centerx - src.rows()/2))<=(src.rows()/8))&&((Math.abs(centery - src.cols()/2))<=(src.cols()/8))) {
// the new best must be at least 0.68 times as big as the old best
if (Imgproc.contourArea(contours.get(blackslikecon[i])) >= Imgproc.contourArea(contours.get(bestContour))*0.68)
if (bestnumblack <= Randar.blackpix[i] * 0.8) {// and must have at least 0.8 times the black pixels of old best
bestx = centerx;// There is new best !!
besty = centery;
bestnumblack = Randar.blackpix[i];
bestContour = blackslikecon[i];
}
}
}
}
}
if ((blackslikecon.length==1 ) && (blackslikecon!=null))
{
//if there is only one object then calculates the centet x,y and returns the id number
MatOfPoint best = contours.get(blackslikecon[0]);
points_contour = best.toArray();
nbPoints = points_contour.length;
for( int j=0; j< nbPoints;j++)
{
v=points_contour[j];
centerx =centerx+v.x;
centery =centery+v.y;
}
if(nbPoints!=0 )
{centerx=centerx/nbPoints;
centery=centery/nbPoints;
if( Math.sqrt(Math.pow(Math.abs(bestx-src.width()/2),2)+Math.pow(Math.abs(besty-src.height()/2),2))>Math.sqrt(Math.pow(Math.abs(centerx-src.width()/2),2)+Math.pow(Math.abs(centery-src.height()/2),2) ) )
{
bestx=centerx;
besty=centery;
}
// retur[0]=blackslikecon[0];
// retur[0]=1;
// retur[1]=(int) centerx;
// retur[0]=(int) centery;
Randar.resultx=centerx;
Randar.resulty=centery;
return blackslikecon[0];
}
}
// }
Log.e(TAG, "best");
Log.d(TAG,Integer.toString((int) bestContour) );
Log.e(TAG, "blacks on best");
Log.d(TAG,Integer.toString((int) bestnumblack) );
//
// retur[0]=bestContour;
// retur[1]=(int) centerx;
// retur[0]=(int) centery;
Randar.resultx=centerx;
Randar.resulty=centery;
return bestContour;
}
// αναλύει τις τιμές του χρώματος γύρω απο την ελιά
//analyzes the color values around the mole
// input: the image -> outputs avg lightness
public static double[] rightedge (Mat img)
{
int x =0; int y=0 ;
Imgproc.medianBlur ( img, img, 11 ); // apply median filter to reduce noice
Randar.minskin =img.get(0,0);//init vars
Randar.maxskin =img.get(0,0);
// color sums
double[] datasum = img.get(img.height()/2,img.height()/2);
// init
datasum[0]=0 ;
datasum[1]=0 ;
datasum[2]=0 ;
// gets color value on each of 4 edges (gets 20 values of each edge and sums them )
for (int i=0;i<img.rows()*4;i=i+img.rows()/20){
if (i<img.rows())
{
x=img.rows()/30;
y=i;
}
else if (i<img.rows()*2)
{
x=img.rows()-(int)(img.rows()*0.3);
y=i-img.rows();
}
else if (i<img.rows()*3)
{
y=img.rows()/30;
x=i-img.rows()*2;
}
else if (i<img.rows()*4)
{
y=img.rows()-(int)(img.rows()*0.3);
x=i-img.rows()*3;
}
double[] data = img.get(x, y);
// the v (data[2]) of pixel on the hsv color space is the lightness of each pixel
data[0] = data[0] / 2;// gets hsv data
data[1] = data[1] / 2;
data[2] = data[2] / 2;
if (data[2]<Randar.minskin[2]) //the lowest value of hsv samples
{
if (data[2]>63){ //the sample must not be too black
Randar.minskin[2]=data[2];
}
}
if (data[2]>Randar.maxskin[2])
{
Randar.maxskin[0]=data[2]; // the biggest value of lightness sample
}
if (data[1]<Randar.minskin[1])
{
// min saturation
Randar.minskin[1]=data[1];
}
if (data[1]>Randar.maxskin[1])
{
// max saturation
Randar.maxskin[1]=data[1];
}
if (data[0]<Randar.minskin[0])
{
// min hue
Randar.minskin[0]=data[0];
}
if (data[0]>Randar.maxskin[0])
{// max hue
Randar.maxskin[0]=data[0];
}
// calculates sums for each of h s v
datasum[0]=datasum[0]+data[0] ;
datasum[1]=datasum[1]+data[1] ;
// if (data[2]<30)
// data[2]=50;
datasum[2]=datasum[2]+data[2] ;
}
// calculates avg on each h s v
datasum[0]=datasum[0]/80;
datasum[1]=datasum[1]/80 ;
datasum[2]=datasum[2]/80 ;
TAG="minskin";
Log.d(TAG,Double.toString(Randar.minskin[2])) ;
// Randar.minskin[2]= datasum[2];
// returns the avg of each of h s v
return datasum;
}
// εναλακτικός εντοπισμός αντικειμένων
//alternative object tracking
//the function gets as input an image and returns a list of points of tracked objects
public static List<MatOfPoint> findcontours (Mat srchsv3)
{ //init list of points of tracked objects
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();;
//init hierarchy of tracked objects
Mat hierarchy = new Mat();
// apply median filter to image
Imgproc.medianBlur ( srchsv3, srchsv3, 11 );
// apply gaussian filter to image
Imgproc.GaussianBlur(srchsv3, srchsv3, new Size(3, 3), 0);
//srchsv3 = removewhites(srchsv3);
// converts image to grayscale (to binary image )
Imgproc.cvtColor(srchsv3, srchsv3, Imgproc.COLOR_BGR2GRAY);
// searchs for objects
Imgproc.findContours(srchsv3, contours, hierarchy,Imgproc.RETR_LIST,Imgproc.CHAIN_APPROX_SIMPLE);
TAG ="contours2 size";
Log.d(TAG,Integer.toString(contours.size()) );
//returns a list of points of tracked objects
return contours;
}
//
public static final int MEDIA_TYPE_IMAGE = 1;
/*
/creates the image histogram in the RGB space
// δημιουργεί το ιστόγραμμα της εικόνας στον χωρο RGB
geting input of mat image in rgb color space
returns mat images of histogram
*/
public static Mat histogramrgb (Mat hsvSource )
{
List<Mat> images = new ArrayList<Mat>();
Core.split(hsvSource, images);
// set the number of bins at 40
MatOfInt histSize = new MatOfInt(40);
// only one channel
MatOfInt channels = new MatOfInt(0);
// set the ranges
MatOfFloat histRange = new MatOfFloat(0, 256);
// compute the histograms for the B, G and R components
Mat hist_b = new Mat();
Mat hist_g = new Mat();
Mat hist_r = new Mat();
// B component or gray image
Imgproc.calcHist(images.subList(0, 1), channels, new Mat(), hist_b, histSize, histRange, false);
// G and R components (if the image is not in gray scale)
Imgproc.calcHist(images.subList(1, 2), channels, new Mat(), hist_g, histSize, histRange, false);
Imgproc.calcHist(images.subList(2, 3), channels, new Mat(), hist_r, histSize, histRange, false);
// draw the histogram
int hist_w = 500; // width of the histogram image
int hist_h = 400; // height of the histogram image
int bin_w = (int) Math.round(hist_w / histSize.get(0, 0)[0]);
Mat histImage = new Mat(hist_h, hist_w, CvType.CV_8UC3, new Scalar(0, 0, 0));
// normalize the result to [0, histImage.rows()]
Core.normalize(hist_b, hist_b, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
// for G and R components
Core.normalize(hist_g, hist_g, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
Core.normalize(hist_r, hist_r, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
// effectively draw the histogram(s)
for (int i = 1; i < histSize.get(0, 0)[0]; i++)
{
// B component or gray image
Imgproc.line(histImage, new Point(bin_w * (i - 1), hist_h - Math.round(hist_b.get(i - 1, 0)[0])),
new Point(bin_w * (i), hist_h - Math.round(hist_b.get(i, 0)[0])), new Scalar(255, 0, 0), 2, 8, 0);
// G and R components (if the image is not in gray scale)
Imgproc.line(histImage, new Point(bin_w * (i - 1), hist_h - Math.round(hist_g.get(i - 1, 0)[0])),
new Point(bin_w * (i), hist_h - Math.round(hist_g.get(i, 0)[0])), new Scalar(0, 255, 0), 2, 8,
0);
Imgproc.line(histImage, new Point(bin_w * (i - 1), hist_h - Math.round(hist_r.get(i - 1, 0)[0])),
new Point(bin_w * (i), hist_h - Math.round(hist_r.get(i, 0)[0])), new Scalar(0, 0, 255), 2, 8,
0);
}
return histImage;
}
/*
// δημιουργεί το ιστόγραμμα της εικόνας στον χωρο HSV
creates the histogram of the image in the HSV space
geting input of mat image in hsv color space
returns mat images of histogram
*/ public static Mat histogram (Mat hsvSource )
{
Mat hsvRef =hsvSource.clone();
List<Mat> images = new ArrayList<Mat>();
Core.split(hsvSource, images);
// sets the bins 60 for h and 64 for S and V
int bin =60;
int bin2=64;
MatOfInt histSize1 = new MatOfInt(bin);
MatOfInt histSize2 = new MatOfInt(bin2);
MatOfInt channels = new MatOfInt(0);
// sets the ranges 180 for h because it gets values from 0 to 180
MatOfFloat histRange1 = new MatOfFloat(1, 180);
// sets the ranges for SV ->256 because it gets values from 0 to 255
// skips the first 10 values because the 0.0.255 in hsv is white!!
// but the device flash creates a lot of whites and those whites must be skipped
MatOfFloat histRange2 = new MatOfFloat(10, 255);
Mat hist_h = new Mat();
Mat hist_s = new Mat();
Mat hist_v = new Mat();
// H component
Imgproc.calcHist(images.subList(0, 1),
channels,
new Mat(),
hist_h,
histSize1,
histRange1,
false);
// S component
Imgproc.calcHist(images.subList(1, 2),
channels,
new Mat(),
hist_s,
histSize2,
histRange2,
false);
// V component
Imgproc.calcHist(images.subList(2, 3),
channels,
new Mat(),
hist_v,
histSize2,
histRange2,
false);
int hiw = 500; // width of the histogram image
int hih = 400; // height of the histogram image
int biw1 = (int) Math.round(hiw / histSize1.get(0, 0)[0]);
int biw2 = (int) Math.round(hiw / histSize2.get(0, 0)[0]);
Mat histImage = new Mat(hih, hiw, CvType.CV_8UC3, new Scalar(0, 0, 0));
// normalize the result to [0, histImage.rows()]
Core.normalize(hist_h, hist_h, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
Core.normalize(hist_s, hist_s, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
Core.normalize(hist_v, hist_v, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
double fullsize= hsvSource.cols()*hsvSource.rows() *15/600;
// ignores values smaller than fullsize and makes them zero
Imgproc.threshold(hist_h,hist_h,fullsize,0,Imgproc.THRESH_TOZERO );
Imgproc.threshold(hist_s,hist_s,fullsize,0,Imgproc.THRESH_TOZERO );
for (int i = 1; i < histSize2.get(0, 0)[0]; i++)
{
// h component or gray image
if (i<bin)
Imgproc.line(histImage, new Point(biw1 * (i - 1), hih - Math.round(hist_h.get(i - 1, 0)[0])),
new Point(biw1 * (i), hih - Math.round(hist_h.get(i, 0)[0])), new Scalar(255, 0, 0), 2, 8, 0);
// s and v components (if the image is not in gray scale)
Imgproc.line(histImage, new Point(biw2 * (i - 1), hih - Math.round(hist_s.get(i - 1, 0)[0])),
new Point(biw2 * (i), hih - Math.round(hist_s.get(i, 0)[0])), new Scalar(0, 255, 0), 2, 8,
0);
// /**
Imgproc.line(histImage, new Point(biw2 * (i - 1), hih - Math.round(hist_v.get(i - 1, 0)[0])),
new Point(biw2 * (i), hih - Math.round(hist_v.get(i, 0)[0])), new Scalar(0, 0, 255), 2, 8,
0);
// **/
}
TAG ="histtest";
for (int i=0;i<64;i++)
Log.d(TAG,Double.toString(hist_s.get(i,0)[0]));
return histImage;
}
// not used but working
/*
// αφαιρεί ότι πιξελ είναι φωτεινο και το μετατρέπει σε άσπρο
removes that pixel is bright and turns it into white
//input: Mat image
//output: processed mat image
*/
public static Mat removeskin (Mat img ){
double[] data ;
Mat C = img.clone();// copy the image
for (int i=0 ; i< img.height();i++)
{
for (int j=0; j< img.width() ;j++)
{
// for every pixel of the image if value of V is bigger than min of skin color
// make tha pixel white
data = img.get(i,j);
if (data[2]/2>Randar.minskin[2]*0.85 )
{
data[0] = 0;
data[1] = 0;
data[2] = 255;
C.put(i, j, data);
}
C.put(i, j, data);
}
}
// possessed image
return C;
}
// αφερεί οτι βρισκεται εξω απο τα όρια της ελιάς
/*
remove whatever is outside the mole
// inputs the image of the object , list of countours points , the position of the ccontourbject
// returns possessed image
*/
public static Mat cropskin (Mat img,List<MatOfPoint> contours ,int pos) {
Imgproc.cvtColor(img,img,Imgproc.COLOR_RGB2HSV);
// change the color of the image to hsv
Mat mask = Mat.zeros(img.rows(), img.cols(), CvType.CV_8UC1); // creating empty mat the same size as input image
Imgproc.drawContours(mask, contours, pos, new Scalar(255), Core.FILLED); //drawing the object
Mat crop = new Mat (img.rows(), img.cols(), CvType.CV_8UC3);
crop.setTo(new Scalar(0,0,255));//create a new mat filled by white colors pixels
img.copyTo(crop, mask);// copy the object to crop mat
//returns the only the mole . outside the edges of the mole will be white
return crop;
}
// υπολογίζει το πόσες μοίρες πρέπει να περιστραφεί η ελιά
/*
//
// inputs the edges of the object (as mat binary image), list of contours points , the position of the contour object
// returns the angle
calculates how many degrees the mole must rotate . The mole must be on upright position->
->calculates the positions of two the most away pixels of mole and also the angle that the
mole must rotate to make those two pixels to be aligned
*/
public static double FindAngle ( List<MatOfPoint> contours,int temp ,Mat src) {
double data [];
// /**
int x1 = 0;//x1y1 x2y2 is the positions of most far away pixels of mole
int x2 = 0;
int y1 = 0;
int y2 = 0;
int [][] pos;// will contains the pos of edge on each row
// pos[i][0] for right edge
//pos[i][1] for left edge
double deltaX; // x2-x1
double deltaY; // y2 - y1
if (src.rows()>src.cols()) { //if the rows are bigger than the cols . make the search by rows
pos= new int[src.rows()][2];
for (int i = 0; i < src.rows(); i++) {//first side -> for every row find the coordinate of the edge
for (int j = 0; j < src.cols(); j++) {
data = src.get(i, j);//reads every pixel
if (data[0] == 0.0D) { // the edge will be a white line
pos[i][0] = j;// save pos and go to next line
break;
}
}
for (int j = src.cols() - 1; j >= 0; j--) { //second side -> for every row find the coordinate of the edge
data = src.get(i, j);//reads every pixel
if (data[0] == 0.0D) {// the edge will be a white line
pos[i][1] = j;// save pos and go to next line
break;
}
}
}
double dist = 0; // calc the distance of each pear
double biggerdist = 0;// distance of best pear
Point[] points1 = new Point[src.rows()];
Point[] points2 = new Point[src.rows()];
for (int i = 0; i < src.rows(); i++) {// creates points from prev data
points1[i] = new Point(i, pos[i][0]);
points2[i] = new Point(i, pos[i][1]);
}
for (int i = 0; i < src.rows(); i++) {
for (int j = 0; j < src.rows(); j++) {// calculates each distance keeps best
dist = Math.hypot(i - j, pos[i][0] - pos[j][1]);
if (biggerdist <= dist) {
biggerdist = dist;
x1 = i;
x2 = j;
}
}
}
deltaY = pos[x2][1] - pos[x1][0];// dif's of ys
deltaX = x2 - x1;// difs of x's
}//if the cols are bigger than the cols . make the search by cols
else{
pos= new int[src.cols()][2];
for (int i = 0; i < src.cols(); i++) {//first side -> for every cols find the coordinate of the edge
for (int j = 0; j < src.rows(); j++) {
data = src.get(j, i);//reads every pixel
if (data[0] == 0.0D) {// the edge will be a white line
pos[i][0] = j;// save pos and go to next col
break;
}
}
for (int j = src.rows() - 1; j >= 0; j--) { //second side -> for every col find the coordinate of the edge
data = src.get(j, i);//reads every pixel
if (data[0] == 0.0D) {// the edge will be a white line
pos[i][1] = j;// save pos and go to next col
break;
}
}
}
double dist=0;
double biggerdist=0;
for (int i = 0; i < src.cols(); i++) {// calculates each distance keeps best
for (int j = 0; j < src.cols(); j++) {
dist = Math.hypot(pos[i][0] -pos[j][1], i - j);
if (biggerdist <= dist) {
biggerdist = dist;
x1 = i;
x2 = j;
}
}
}
deltaX = pos[x2][1] - pos[x1][0];// dif's of x's
deltaY = x2 - x1;// dif's of ys
int temp1 ,temp2;
temp1 =pos[x1][0];
temp2 =pos[x2][1];// swapping the values of x's and y's
pos[x1][0]=x1;
pos[x2][1]=x2;
x1=temp1;
x2=temp2;
}
double blob_angle_deg = Math.atan2(deltaY, deltaX) * 180 / PI;
blob_angle_deg=90-blob_angle_deg;// calculates the angle for them to be aligned
TAG ="angle";
Log.d(TAG,Double.toString( blob_angle_deg));
if ((pos[x2][1]<src.cols()/2)&&(x2<src.rows()/2)) {// finding in which quartile is the position
if (blob_angle_deg < 90)// and fixes the angle . all mole s must always analyzed being in same "direction "
blob_angle_deg = 90 + blob_angle_deg;
else if (blob_angle_deg > 270)
blob_angle_deg = blob_angle_deg + 90;
}else if
((pos[x2][1]>src.cols()/2)&&(x2<src.rows()/2)){
if (blob_angle_deg > 90 || blob_angle_deg < 270)
blob_angle_deg = 90 + blob_angle_deg;}
else if
((pos[x2][1]>src.cols()/2)&&(x2>src.rows()/2)){
if (blob_angle_deg > 270 || blob_angle_deg < 90)
blob_angle_deg = 90 + blob_angle_deg;}
else if
((pos[x2][1]<src.cols()/2)&&(x2>src.rows()/2)){
if (blob_angle_deg < 270 || blob_angle_deg > 90)
blob_angle_deg = 90 + blob_angle_deg;}
//blob_angle_deg = 90 + blob_angle_deg;
double upperpixels =0;
double lowerpixels =0;
for (int i=0; i< src.height()/2 ;i++) { // calculates the upper side mole's edges pixels
for (int j=0; j< src.width() ;j++) {
data =src.get(i,j);
if (data[0]==0.0D) {
upperpixels++;
}
}
}
for (int i=src.height()/2-1; i< src.height() ;i++) {// calculates the lower side mole's edges pixels
for (int j=0; j< src.width() ;j++) {
data =src.get(i,j);
if (data[0]==0.0D) {
lowerpixels++;
}
}
}
Log.d("\nupper pixels "+Double.toString(upperpixels)+"\n","lower pixels "+Double.toString(lowerpixels)+"\n");
if (lowerpixels<upperpixels)//if lower edges pixels less than the appears then pivots the mole
{
if (blob_angle_deg>180)
blob_angle_deg=blob_angle_deg-180;
else
blob_angle_deg=blob_angle_deg+180;
}
if (blob_angle_deg>360) // if the angle is out of limit -> fixes it (if it is bigger than 360 or lower than 0)
blob_angle_deg=blob_angle_deg-360;
else if (blob_angle_deg<0)
blob_angle_deg=blob_angle_deg+360;
return blob_angle_deg;
}
/*
rotates the mat at some angle
input: src img and angle
//output prossesed image
*/
public static Mat rotMat (Mat src,double angle){
Point src_center = new Point (src.cols()/2.0F, src.rows()/2.0F); // the center of the mat
Mat rot_mat = Imgproc.getRotationMatrix2D(src_center, angle, 1.0);//Calculates an affine matrix of 2D rotation.
Mat dst = new Mat();
// Imgproc.warpAffine(src, dst, rot_mat, src.size());
// Imgproc.warpAffine(src, dst, rot_mat, src.size(),Imgproc.INTER_LINEAR,Core. BORDER_WRAP ,new Scalar(255, 255, 255));
Imgproc.warpAffine(src, dst, rot_mat, src.size(),Imgproc.INTER_CUBIC, Core. BORDER_CONSTANT,new Scalar(255, 255, 255));
// rotates the mat and the outcome goes to dst mat
//the new pixels that will appear after the rot will be black !
// TAG ="img type is";
// Log.d(TAG,Double.toString(dst.type()) );
return dst;
}
// κάνει crop την εικόνα της ελιάς έτσι ώστε η ελιά να βρίσκεται σε κάθε ακρη της εικόνας
/*
crops the image as all edge of the image will contain pixel of mole
*/
public static Mat removedges (Mat src)
{
Mat clear = new Mat();
double data [];
int possitionupx=-1;// inits all 4 edges coordinates
int possitionupy=-1;
int possitiondownx=-1;
int possitiondowny=-1;
int possitionleftx=-1;
int possitionlefty=-1;
int possitionrightx=-1;
int possitionrighty=-1;
data =src.get(src.rows()/2,src.cols()/2); //init the temp data
TAG ="up";
Log.d(TAG,Double.toString(data[0])+"+"+Double.toString(data[1])+"+" +Double.toString(data[2]));
for (int i=0; i< src.cols() ;i++) {// for each edge finding the coordinates of the nearest pixel of the mole
for (int j=0; j< src.rows() ;j++) {
data =src.get(j,i);
if (data[0]==0.0D) {
possitionleftx=j;
possitionlefty=i;
break;
}
}
if (possitionleftx>-1)
break;
}
for (int i=0; i< src.rows() ;i++) {
for (int j=0; j< src.cols() ;j++) {
data =src.get(i,j);
if (data[0]==0.0D) {
possitionupx=i;
possitionupy=j;
break;
}
}
if (possitionupx>-1)
break;
}
for (int i=src.cols()-1; i>=0 ;i--) {
for (int j=src.rows()-1; j>=0 ;j--) {
data =src.get(j,i);
if (data[0]==0.0D) {
possitionrightx=j;
possitionrighty=i;
break;
}
}
if (possitionrightx>-1)
break;
}
for (int i=src.rows()-1; i>=0 ;i--) {
for (int j=src.cols()-1; j>=0 ;j--) {
data =src.get(i,j);
if (data[0]==0.0D) {
possitiondownx=i;
possitiondowny=j;
break;
}
}
if (possitiondownx>-1)
break;
}
TAG ="up";
// Log.d(TAG,Double.toString(possitionupx)+Double.toString(possitionlefty) );
TAG ="down";
// Log.d(TAG,Double.toString(possitiondownx)+Double.toString(possitionrighty) );
if((possitionupx<possitiondownx) && (possitionlefty<possitionrighty) ) { // if the coordinates seems to be right
// Point up = new Point(possitionupx, possitionlefty);
// Point down = new Point(possitiondownx, possitionrighty);
// Rect rect = new Rect(up, down);
// Rect rect = new Rect(possitionupx,possitionlefty,possitionrighty-possitionlefty,possitiondownx-possitionupx);
//clear = src.submat(rect);
clear = src.submat(possitionupx,possitiondownx,possitionlefty,possitionrighty); // crops the images
return clear;
}
return src;
}
// εξάγει την μορφολογία της ελιάς σε πίνακα
// calculates the morphology of moles's edges and returns it to double
// input 2 mats of cropped mole rotated to same way
// output double containing the morphology
//the morphology is the position of the mole edge for every line
public static double[][] morfology(Mat src1,Mat src2)
// public void morfology(Mat src1,Mat src2)
{
double data1 [];// temp data for first mat
double data2 [];// temp data for the second mat
double morph [][] = new double[src1.rows()][2] ; // the returning morphology
int rows =0;//the biggest num of rows and cols of image because one of to mats maybe have one more col .
// this situation happens when the pre- cropeed image has odd namber of col or row
int cols =0;
if (src1.rows()>src2.rows())
rows=src1.rows();
else rows=src2.rows();
if (src1.cols()>src2.cols())
cols=src1.cols();
else cols=src2.cols();
for (int i=0;i<rows;i++)
{int stop1=0;
int stop2=0;
// for (int j=src1.cols()-1; j>=0;j--)
for (int j=0; j<cols;j++) // for every row saves the position of edge for both mats
{
if ((i< src1.rows())&& (j< src1.cols())){
data1 = src1.get(i, j);
if (data1[0]==0.0D && stop1<1){
stop1=1;
morph [i][0] =j;
}}
if ((i< src2.rows())&& (j< src2.cols())) {
data2 = src2.get(i, j);
if (data2[0] == 0.0D && stop2 < 1) {
stop2 = 1;
morph[i][1] = j;
}
}
if ((stop1>0)&&(stop2>0)) // if both found the edge for the same line then stop the search of the line
{break;}
}
}
double [][] movements =movements(morph,12); //compression of the morphology to 12 pieces
return movements;// returning the compressed morphology
}
// ελέγχει αν υπάρχει συμμετρία
/*
check for asymmetry
inputs movements of mole sides and image of mole
outputs true if there is asymmetry
*/
public static boolean dangerousedges (double [][] morfology ,Mat src )
{
TAG = "10% error is";
double error=src.cols()*0.18; // the difference between two sides of mole can be up to 18%
Log.d(TAG, Double.toString(error));
// TAG = "morfology is";
int times =0;
for (int i=0;i<morfology.length;i++) {
// Log.d(TAG, Double.toString(morfology[i][0])+"+"+morfology[i][1]);
if (Math.abs(morfology[i][0]-morfology[i][1])>=(error)) // if the compare def is bigger than the error margin
{times=times+1;// counts how many times this happens
}
}
if (times>3) // if it happens 4 times (we have 12 pieces of each side .3 times error meaning that 1/3 of those pieces have different morphology -> the 1/3 of sides is different )
{
return true;
}
return false;
}
// συμπιέζει τον πίνακα μορφολογίας στον αριθμό pieces
/*compresses the morphology table to the number of pieces
*
* inputs : morphology and pieces to cut the mophology
* outputs the compressed morphology
*/
public static double[][] compress( double[][] morph,int pieces)
// public void morfology(Mat src1,Mat src2)
{
int step1 = morph.length / pieces;//calculates steps
int step2 = morph.length / pieces;
double limitedmorf[][] = new double[pieces][2];
for (int i = 0; i < pieces; i++) {
int avg = 0;
int avg2 = 0;
for (int j = i * step1; j < i * step1 + step1; j++) // for every piece
avg = avg + (int) morph[j][0];// sums the morphology
limitedmorf[i][0] = avg / step1;// calculate the avgs for right edge
for (int j = i * step2; j < i * step2 + step2; j++)
avg2 = avg2 + (int) morph[j][1];// sums the morphology
limitedmorf[i][1] = avg2 / step2;// calculate the avgs for left edge
}
return limitedmorf;
}
// εντοπίζει τις <κινήσεις> των πλευρών της ελίάς
/*
identifies the <moves> of the sides of the matrix
calculates the avg of the morph for every piece
and from every value delete its previous one
inputs the morphology and pieces
and output movements
*/
public static double[][] movements( double[][] morph,int pieces)
// public void morfology(Mat src1,Mat src2)
{
int step1 = morph.length/pieces;//calculates steps
int step2 = morph.length/pieces;
double limitedmorf [][] = new double[pieces][2] ;//creating array of doubles having in the avg of every piece of morph
double movements [][] = new double[pieces][2] ;// the returning array
for (int i=0;i<pieces;i++)// for every piece calc the avg
{
int avg =0;
int avg2=0;
for (int j =i*step1; j<i*step1+ step1 ;j++)// for right
avg=avg+(int)morph [j][0];
limitedmorf[i][0]= avg/step1;
for (int j =i*step2; j<i*step2+ step2 ;j++)// for left
avg2=avg2+(int)morph [j][1];
limitedmorf[i][1]= avg2/step2;
}
movements[0][0]=0;
movements[0][1]=0;
for (int i=1;i< pieces ; i++)
{
movements[i][0]=limitedmorf[i][0]-limitedmorf[i-1][0];// for every value removes the prev in line
movements[i][1]=limitedmorf[i][1]-limitedmorf[i-1][1];
}
return movements;
}
// ελέγχει την περίμετρο της ελιάς
/*
checks the perimeter of the mole->
checking if the mole has curves on perimeter using opencv functions
input:
list of countours
countour possition
and the image
Output:
true if there is perimeter problem
false if not
*/
public static boolean convexity (List<MatOfPoint> contours , int pos, int src){
MatOfInt convexHullMatOfInt = new MatOfInt();//contain indices of the contour points
ArrayList<Point> convexHullPointArrayList = new ArrayList<Point>();
MatOfPoint convexHullMatOfPoint = new MatOfPoint();
ArrayList<MatOfPoint> convexHullMatOfPointArrayList = new ArrayList<MatOfPoint>();
MatOfInt4 mConvexityDefectsMatOfInt4 = new MatOfInt4();// stores the list of defects
Imgproc.convexHull( contours.get(pos), convexHullMatOfInt, false );
//Convex hull obtained using convexHull() that should contain indices of the contour points that make the hull.
for(int j=0; j < convexHullMatOfInt.toList().size(); j++)//adding contour to hull
convexHullPointArrayList.add(contours.get(pos).toList().get(convexHullMatOfInt.toList().get(j)));
convexHullMatOfPoint.fromList(convexHullPointArrayList);
convexHullMatOfPointArrayList.add(convexHullMatOfPoint);
if( convexHullMatOfInt.rows() > 0)
Imgproc.convexityDefects(contours.get(pos), convexHullMatOfInt, mConvexityDefectsMatOfInt4);
List<Integer> ConvexityList = mConvexityDefectsMatOfInt4.toList();
Point data[] = contours.get(pos).toArray();
for (int i=0; i<ConvexityList.size();i=i+4){
// depth =ConvexityList.get(i);
// Point start = data[ConvexityList.get(i)];
// Point end = data[ConvexityList.get(i+1)];
// Point defect = data[ConvexityList.get(i+2)];
//Point depth = data[ConvexityList.get(i+3)];
double depth = ConvexityList.get(i+3)/256 ; // the farthest from the convex hull point within the defect
// get the floating-point value of the depth will be fixpt_depth/256.0.
// TAG ="depth"; Log.d(TAG,Double.toString(depth) );
double dis=src *0.10;
// if (src)
// checks if there is big defect on perimeter of the mole
if (src<100) {//if the mole is to small then the defect must be at least 40% of size of it
if (depth > src * 0.40) {
return true;
}
}else
if (depth> src *0.11){//if the mole is to big then the defect must be at least 11% of size of it
return true;
}
}
// TAG ="max permited";
// Log.d(TAG,Double.toString( src *0.25));
return false;
}
//ελενχος πολυχρομίας του ιστογράμματοσ
/*
this function checks if h or s or v has 2 curves in historam
input histogram mat and mode (mode can be h or s or v )
and output % of second color
The app does not use this function for the time.
*/
public static double MultiColorCheck (Mat hist, char mode){
String TAG;
int pos=-1;// init position
double data []= hist.get(0, 0); // init data
int found ; // is how many times the function meets a line
switch (mode){
case 'h':
for (int i=0;i<hist.rows();i++){
found=0;
for (int j=0;j<hist.cols();j++){
data=hist.get(i, j);
if (data[0]==255)
{
found++;
if (found>2){// if the function finds the line more than 3 times then save the pos and exit
pos=i;
break;
}
if (pos>0)
break;
}
}if (pos>0)
break;
}
break;
case 's':
for (int i=0;i<hist.rows();i++) {
found = 0;
for (int j = 0; j < hist.cols(); j++) {
data = hist.get(i, j);
TAG = "data 0";
// Log.d(TAG, Double.toString(data[0]));
TAG = "data 1";
// Log.d(TAG, Double.toString(data[1]));
TAG = "data 2";
// Log.d(TAG, Double.toString(data[2]));
if (data[1] == 255) {
found++;
TAG = "i";
Log.d(TAG, Double.toString(i));
TAG = "data 1";
Log.d(TAG, Double.toString(data[1]));
if (found > 2) {// if the function finds the line more than 3 times then save the pos and exit
pos = i;
break;
}
}
}
if (pos > 0)
break;
}
break;
case 'v':
for (int i=0;i<hist.rows();i++){
found=0;
for (int j=0;j<hist.cols();j++){
data=hist.get(i , j);
if (data[2]==255)
{
found++;
if (found>2){// if the function finds the line more than 3 times then save the pos and exit
TAG = "data 0";
Log.d(TAG, Double.toString(i));
pos=i;
break;
}
}
}if (pos>0)
break;}
break;
}
// double status =pos/hist.rows()*100;
double div=1.0/hist.rows(); // calculates % of second color using the pos that second color is found
double status =(hist.rows()-pos)*div;
TAG = "color distortion %";
Log.d(TAG, Double.toString(status));
return status;
}
//ελενχος πολυχρομίας του ιστογράμματος σε hs
//checking the multicolor by using a histogram
// input hsv image -> output the detected curves count for h and s
public static double HistogramCheck (Mat hsvSource )
{
List<Mat> images = new ArrayList<Mat>();
Core.split(hsvSource, images);//Divides a multi-channel array into several single-channel arrays.
// sets the bins 60 for h and 64 for S and V
int bin =60;
int bin2=64;
MatOfInt histSize1 = new MatOfInt(bin);
MatOfInt histSize2 = new MatOfInt(bin2);
MatOfInt channels = new MatOfInt(0);
// sets the ranges 180 for h because it gets values from 0 to 180
MatOfFloat histRange1 = new MatOfFloat(1, 175);
MatOfFloat histRange2 = new MatOfFloat(10, 256);
// sets the ranges for SV ->256 because it gets values from 0 to 255
// skips the first 10 values because the 0.0.255 in hsv is white!!
// but the device flash creates a lot of whites and those whites must be skipped
Mat hist_h = new Mat();
Mat hist_s = new Mat();
// H component
Imgproc.calcHist(images.subList(0, 1),
channels,
new Mat(),
hist_h,
histSize1,
histRange1,
false);
// S component
Imgproc.calcHist(images.subList(1, 2),
channels,
new Mat(),
hist_s,
histSize2,
histRange2,
false);
int hiw = 500; // width of the histogram image
int hih = 400; // height of the histogram image
Mat histImage = new Mat(hih, hiw, CvType.CV_8UC3, new Scalar(0, 0, 0));
// normalize the result to [0, histImage.rows()]
Core.normalize(hist_h, hist_h, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
Core.normalize(hist_s, hist_s, 0, histImage.rows(), Core.NORM_MINMAX, -1, new Mat());
double max=0;
for (int i=0;i<histSize2.get(0, 0)[0]; i++)
if (max<hist_s.get(i,0)[0])
max=hist_s.get(i,0)[0]; // finds max value
double fullsize= max*0.25;// ignores the values smaller than max*0.25 and makes them 0
Imgproc.threshold(hist_s,hist_s,fullsize,0,Imgproc.THRESH_TOZERO );
for (int i=0;i<histSize1.get(0, 0)[0]; i++)
if (max<hist_h.get(i,0)[0])
max=hist_h.get(i,0)[0];// finds max value
fullsize= max*0.25;// ignores the values smaller than max*0.25 and makes them 0
Imgproc.threshold(hist_h,hist_h,fullsize,0,Imgproc.THRESH_TOZERO );
TAG = "threshold ";
Log.d(TAG,Double.toString(fullsize));
TAG = "color distortion %";
double [][] matrix = new double [bin2][2];//the data from histogram
double [][] movements = new double [bin2][2];//the movements of lines
// double [][] compress = new double [bin2][2];//compressed matrix
for (int i = 1; i < histSize2.get(0, 0)[0]; i++)
{
// h component or gray image
if (i<bin)
matrix[i][0]=hist_h.get(i,0)[0];//filling matrix with data
else
matrix[i][0]=hist_h.get(bin-1,0)[0];// h hist has range up to 180 .. the others till 255 will fill with 0
matrix[i][1]=hist_s.get(i,0)[0];
}
// int pieces=Math.abs(bin2/2);
int pieces=bin2;
movements=movements(matrix,pieces);//find the line movements
// compress=compress(matrix,pieces);
int final0 = curves( movements ,matrix,hsvSource.rows(),0);// checks the number of curves
int final1 = curves( movements ,matrix,hsvSource.rows(),1);
return final0+final1; //for one color curves must be 2
}
/*
//η συνάρτηση έλενχει τον πίνακα με τις κινήσεις της γραμμής του ιστογράμματος αν έχει παραπάνω απο
μια καμπύλη. γίνεται έλενχος στα ιστογράμματα για h και s tou hsv.
the function checks the table with the histogram line movements. it checks if it has more than one
curve.
inputs : movements array , the array of histogram values , hsvSource is the size of mole , channel
(0 for hue and 1 for saturation )
outputs the number of curves found
*/
public static int curves (double movements[][], double matrix[][] ,int hsvSource ,int channel)
{
double u=0;//u is the sum for up movements
double d=0;//d is the sum for down movements
int before=-2; // -2 means that the line was going down before / 2 that the line was going up before
int after =0;// -2 means that the line will go down after / 2 that the line will go up after
int temp=-2; // temp value for checking if the previews position the movements of the line was up or down
TAG = "color distortion %";
double [] result = new double [movements.length]; //when the line stops going for multiple steps up / down
// the result saves what kind of movement was (up or down)
double [] poss= new double [movements.length] ; // keeps the value of the hist position when line stops going for multiple steps up / down
double [] high= new double [movements.length] ;//when the line stops going for multiple steps up / down
// the result saves how far the line gone up or down
// keeps the value of how high value had the line when stops going for multiple steps up / down
int possition=0;// init the number of step counter
for (int i = 1; i < movements.length-1; i++) {
Log.d(TAG, Double.toString(movements[i][channel]));
// Log.d(TAG, Double.toString(matrix[i][1]));
if (movements[i+1][channel]<0)//checking the movement of next step if negative -2 otherwise +2
after=-2;
else if (movements[i+1][channel]>=0)
after=2;
//TAG = "color after";
// Log.d(TAG,Integer.toString(after));
if (movements[i][channel]>0.0){//checking the movement of this step is it is possitive
u=u+movements[i][channel];// saving how far was the movement to u
// if (d<hih*0.10)
if (u<15) // if u is not big enough
{//d=0;
// before=0;
if(d>=u) // maybe the going up of the line was temporary set d= d-u and check again next round
d=d-u;
else //else the line seems to keep going up so zero the d
d=0;
}
else if ((before<1 )&& (temp +1 !=i)) { // if the move of line was big positive one then
Log.d(TAG,"ok"); // there is start of curve
poss[possition] = i; //saves the position of start the Uphill
before=2; // say to nexr round that this round the line goes up
temp=i; // //saves the position of start the Uphill
high[possition]=d; // if there was down before then it saves it
result[possition]=before; // saves the result
possition=possition+1; //up the counter
d=0; // zero the downhill meter
}
else if (u>20) // if the jump is big enough but temp had the previous i
// or before was possitive then just zero the downhill meter
// and we will see the next round if the line stops going up
d=0;
}else {
if (movements[i][channel] <= 0.0) { // if the movemnent is negative
d = d + Math.abs(movements[i][channel]);// saving how far was the movement to d
// if (u < hih * 0.10){
if ((d < 15)&&(movements[i+1][channel]!=0)){ // if d u is not big enough
// and the next move is 0
if(u>=d)// maybe the going down of the line was temporary set u= u-d and check again next round
u=u-d;
else
u=0;//else the line seems to keep going down so zero the u
// before=0;
// u = 0;
}
else if ((before > 1) &&(after>1)&&(temp+1!=i)&&(matrix[i][channel]<150)) {
// if before the line gone up
//after will go up or 0
// temp is not the previous i
// and the value of the matrix is height enough
TAG = "color distortion %";
Log.d(TAG,"ok2");
poss[possition] = i;//saves the position of start the downhill
temp=i;// //saves the position of start the downhill
before = -2;// say to nexr round that this round the line goes down
result[possition]=before;// saves the result
high[possition] = u;// if there was up before then it saves it
possition = possition + 1;//up the counter
u = 0;// zero the uphill meter
}
else if (d>20)
{
u=0;// if the jump is big enough but temp had the previous i
// or before was negative or the value of the matrix is not height enough
// or after will be -2 again (down again )
// then just zero the uphill meter
// and we will see the next round if the line stops going down
}
}
}
}
double distance=0; //for every curve calculates the distance
for (int i=1;i<possition;i++)
{
if (result[i-1]>1){
distance=distance+poss[i]-poss[i-1];
TAG = "distance";
Log.d(TAG, Double.toString(distance));
}
}
// if (possition2>possition)
// return possition2;
if (distance>(movements.length-1)/2.3) // if the distance is long enough (bigger than the half hist)
possition=possition+100; //then there is multi colors
possition=(possition+1)/2; // curvers (because every 2 possitions is a curve(one uphill & one downhill) )
if(hsvSource < 50) // if the mole has very small size , is not save to say if there is multi color
possition=0;
return possition;
}
// ελέγχει αν υπάρχει συμμετρία
/*
check for asymmetry
inputs movements of mole sides and image of mole
outputs true if there is asymmetry
*/
public static boolean dangerousedges (double [][] morfology,double [][] morfologyplus ,int src )
{
TAG = "10% error is";
double error=src *0.09; // the difference between two sides of mole can be up to 18%
Log.d(TAG, Double.toString(error));
// TAG = "morfology is";
int times =0;
for (int i=0;i<morfology.length;i++) {
// Log.d(TAG, Double.toString(morfology[i][0])+"+"+morfology[i][1]);
if (Math.abs(morfology[i][0]-morfologyplus[i][0])>=(error)) // if the compare def is bigger than the error margin
{times=times+1;// counts how many times this happens
}
}
if (times<=3) {
times = 0;
for (int i = 0; i < morfology.length; i++) {
// Log.d(TAG, Double.toString(morfology[i][0])+"+"+morfology[i][1]);
if (Math.abs(morfology[i][1] - morfologyplus[i][1]) >= (error)) // if the compare def is bigger than the error margin
{
times = times + 1;// counts how many times this happens
}
}
}
if (times>3) // if it happens 4 times (we have 12 pieces of each side .3 times error meaning that 1/3 of those pieces have different morphology -> the 1/3 of sides is different )
{Log.d("evolving",Integer.toString(times));
return true;
}
return false;
}
}
| litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/MyLib.java |
1,469 | package gui;
import api.Accommodation;
import api.CurrentUser;
import api.ProviderFunctions;
import javax.swing.*;
import javax.swing.border.LineBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Objects;
/**
* Η κλάση αναπαριστά το παράθυρο διαγραφής καταλύματος από ένα πάροχο
* @author trifon
*/
public class DeleteAccommodationFrame {
private JFrame delFrame;
public DeleteAccommodationFrame(){
delFrame = new JFrame("Τα καταλύματα του " + CurrentUser.getCurrentUser().getName());
int i=0;
int[] flag = new int[1];
ArrayList<Accommodation> list0 = Main.accommodations.getArrayList();
ArrayList<Accommodation> list = new ArrayList<>();
for(Accommodation acco : list0){
if(Objects.equals(Main.accommodations.getAccommodationProvider(acco).getUsername(), CurrentUser.getCurrentUser().getUsername())){
list.add(acco);
}
}
JButton[] butts = new JButton[list.size()];
JPanel[] panels = new JPanel[list.size()];
JLabel[] labels = new JLabel[list.size()];
for(Accommodation ac : list){
butts[i]=new JButton("Διαγραφή");
butts[i].setBackground(new Color(144,144,144));
butts[i].setBorder(new LineBorder(Color.BLACK));
butts[i].setFont(new Font("Serif",Font.BOLD,16));
butts[i].setActionCommand(Integer.toString(i));
butts[i].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
flag[0] = Integer.parseInt(e.getActionCommand());
Accommodation selectedAccommodation;
selectedAccommodation = list.get(flag[0]);
// Open edit frame with parameter the selectedAccommodation
ShowAccommodationPanel pan = new ShowAccommodationPanel(selectedAccommodation);
JFrame Frame = new JFrame(selectedAccommodation.getName());
Frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
Frame.setSize(1000,700);
Frame.setResizable(false);
Frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(true);
Frame.setVisible(false);
}
});
Frame.add(pan.getPanel());
Frame.setLocationRelativeTo(null);
Frame.setVisible(true);
setVisible(false);
JOptionPane pane = new JOptionPane("Είστε σίγουρος ότι θέλετε να διαγράψετε το συγκεκριμένο κατάλυμα;", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
JDialog dialog = pane.createDialog(null, "Επιβαιβέωση");
dialog.setVisible(true);
Object selectedValue = pane.getValue();
if(selectedValue != null && selectedValue.equals(JOptionPane.YES_OPTION)){
// user clicked Yes
ProviderFunctions.removeAccommodation(Main.accommodations,selectedAccommodation);
}
}
});
panels[i] = new JPanel();
panels[i].setBackground(new Color(144,144,144));
panels[i].setBorder(BorderFactory.createEmptyBorder(40, 50, 40, 50));
panels[i].setLayout(new GridLayout(4,1));
labels[i] = new JLabel(ac.getName());
labels[i].setFont(new Font("Serif",Font.BOLD,22));
panels[i].add(labels[i]);
panels[i].add(new JLabel(ac.getType()));
panels[i].add(new JLabel(ac.getCity()));
panels[i].add(butts[i]);
i++;
}
JPanel secPanel = new JPanel();
secPanel.setBackground(new Color(49,83,94));
secPanel.setLayout(new FlowLayout());
for(int k=0;k<list.size();k++){
secPanel.add(panels[k]);
}
secPanel.setPreferredSize(new Dimension(1000,2500));
JScrollPane sp = new JScrollPane(secPanel);
delFrame.add(sp);
sp.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
delFrame.setSize(1000,700);
delFrame.setDefaultCloseOperation(WindowConstants.HIDE_ON_CLOSE);
delFrame.setLocationRelativeTo(null);
delFrame.setResizable(true);
delFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
setVisible(false);
ProviderFunctionsFrame.setVisible(true);
}
});
}
public void setVisible(boolean b){
delFrame.setVisible(b);
}
}
| AnestisZotos/Accommodations-rating-platform | gui/DeleteAccommodationFrame.java |
1,470 | package gr.aueb.cf.c1.ch10;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Scanner;
public class MobileContactsApp {
final static String[][] contacts = new String[500][3];
static int pivot = -1;
final static Path path = Paths.get("C:/tmp/log-mobile.txt");
static Scanner in = new Scanner(System.in);
public static void main(String[] args) {
boolean quit = false;
String s;
int choice;
String phoneNumber;
do {
printMenu();
s = getChoice();
if (s.matches("[qQ]")) quit = true;
else {
try {
choice = Integer.parseInt(s);
if (!(isValid(choice))) {
throw new IllegalArgumentException("Error - Choice");
}
switch (choice) {
case 1:
printContactMenu();
insertController(getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Εισαγωγή");
break;
case 2:
phoneNumber = getPhoneNumber();
deleteController(phoneNumber);
System.out.println("Επιτυχής Διαγραφή");
break;
case 3:
phoneNumber = getPhoneNumber();
printContactMenu();
updateController(phoneNumber, getFirstname(), getLastname(), getPhoneNumber());
System.out.println("Επιτυχής Ενημέρωση");
break;
case 4:
phoneNumber = getPhoneNumber();
String[] contact = getOneController(phoneNumber);
printContact(contact);
break;
case 5:
String[][] allContacts = getAllController();
printAllContacts(allContacts);
break;
default:
throw new IllegalArgumentException("Bad choice");
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
}while (!quit);
}
public static void printContact(String[] contact) {
for (String s : contact) {
System.out.print(s + " ");
}
}
public static void printAllContacts(String[][] contacts) {
for (String[] contact : contacts) {
printContact(contact);
}
}
public static boolean isValid(int choice) {
return ((choice >= 1) && (choice <= 5));
}
public static void printMenu() {
System.out.println("Επιλέξτε ένα από τα παρακάτω");
System.out.println("1. Εισαγωγή επαφής");
System.out.println("2. Διαγραφή επαφής");
System.out.println("3. Ενημέρωση επαφής");
System.out.println("4. Αναζήτηση επαφής");
System.out.println("5. Εκτύπωση επαφής");
System.out.println("Q. Έξοδος επαφής");
}
public static String getChoice() {
System.out.println("Εισάγετε επιλογή");
return in.nextLine().trim();
}
public static void printContactMenu() {
System.out.println("Εισάγετε όνομα, επώνυμο, τηλέφωνο");
}
public static String getFirstname(){
System.out.println("Εισάγετε όνομα");
return in.nextLine().trim();
}
public static String getLastname(){
System.out.println("Εισάγετε επώνυμο");
return in.nextLine().trim();
}
public static String getPhoneNumber(){
System.out.println("Εισάγετε τηλέφωνο");
return in.nextLine().trim();
}
public static void insertController(String firstname, String lastname, String phoneNumber) {
try {
//validation
if (firstname == null || lastname == null || phoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("Firstname is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last name is not valid");
}
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
//call services
insertContactServices(firstname.trim(), lastname.trim(), phoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static void updateController(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
//validation
if (oldPhoneNumber == null || firstname == null || lastname == null || newPhoneNumber == null){
throw new IllegalArgumentException("Null are not allowed");
}
if (oldPhoneNumber.length() < 2 || oldPhoneNumber.length() > 50) {
throw new IllegalArgumentException("Old number is not valid");
}
if (firstname.length() < 2 || firstname.length() > 50) {
throw new IllegalArgumentException("First name is not valid");
}
if (lastname.length() < 2 || lastname.length() > 50) {
throw new IllegalArgumentException("Last number is not valid");
}
if (newPhoneNumber.length() < 2 || newPhoneNumber.length() > 12) {
throw new IllegalArgumentException("New phone number is not valid");
}
//call services
updateContactServices(oldPhoneNumber.trim(), firstname.trim(), lastname.trim(), newPhoneNumber.trim());
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] deleteController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return deleteController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[] getOneController(String phoneNumber) {
try {
if (phoneNumber.length() < 2 || phoneNumber.length() > 12) {
throw new IllegalArgumentException("Phone number is not valid");
}
return getOneController(phoneNumber);
}catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
public static String[][] getAllController() {
try {
return getAllContactsServices();
} catch (IllegalArgumentException e) {
e.printStackTrace();
throw e;
}
}
/*
CRUD services that are provided to
Services Layer
*/
public static int getIndexByPhone(String phoneNumber) {
for (int i = 0; i <= pivot; i++) {
if (contacts[i][2].equals(phoneNumber)) {
return i;
}
}
return -1; // if not found
}
public static boolean insert(String firstname, String lastname, String phoneNumber) {
boolean inserted = false;
if(isFull(contacts)) {
return false;
}
if (getIndexByPhone(phoneNumber) != -1) {
return false;
}
pivot++;
contacts[pivot][0] = firstname;
contacts[pivot][1] = lastname;
contacts[pivot][2] = phoneNumber;
return true;
}
public static boolean update(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
int positionToUpdate = getIndexByPhone(oldPhoneNumber);
String[] contact = new String[3];
if (positionToUpdate == -1) {
return false;
// return new String[] {};
}
// contact[0] = contacts[positionToUpdate][0];
// contact[1] = contacts[positionToUpdate][1];
// contact[2] = contacts[positionToUpdate][2];
contacts[positionToUpdate][0] = firstname;
contacts[positionToUpdate][1] = lastname;
contacts[positionToUpdate][2] = newPhoneNumber;
return true;
}
public static String[] delete(String phoneNumber) {
int positionToDelete = getIndexByPhone(phoneNumber);
String[] contact = new String[3];
if (positionToDelete == -1) {
return new String[] {};
}
System.arraycopy(contacts[positionToDelete], 0, contact, 0, contact.length);
if (!(positionToDelete == contacts.length - 1)) {
System.arraycopy(contacts, positionToDelete + 1, contacts, positionToDelete, pivot - positionToDelete);
}
pivot--;
return contact;
}
public static String[] getContactByPhoneNumber(String phoneNumber) {
int positionToReturn = getIndexByPhone(phoneNumber);
if (positionToReturn == -1) {
return new String[] {};
}
return contacts[positionToReturn];
}
public static String[][] getAllContacts() {
return Arrays.copyOf(contacts, pivot + 1);
}
// όταν ο pivot δείχνει στην arr.length - 1 αυτό σημαίνει ότι δείχνει στην τελευταία θέση και είναι full
public static boolean isFull(String[][] arr) {
return pivot == arr.length - 1;
}
/*
* Service layer
*/
public static String[] getOneContactService(String phoneNumber) {
try {
String[] contact = getContactByPhoneNumber(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Contact not found");
}
return contact;
}catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[][] getAllContactsServices() {
try {
String[][] contactsList = getAllContacts();
if (contactsList.length == 0) {
throw new IllegalArgumentException("List is empty");
}
return contactsList;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void insertContactServices(String firstname, String lastname, String phoneNumber){
try {
if (!(insert(firstname,lastname,phoneNumber))) {
throw new IllegalArgumentException("Error in insert");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static void updateContactServices(String oldPhoneNumber, String firstname, String lastname, String newPhoneNumber) {
try {
if (!(update(oldPhoneNumber, firstname, lastname, newPhoneNumber))) {
throw new IllegalArgumentException("Error in update");
}
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
public static String[] deleteContactServices(String phoneNumber) {
String[] contact;
try {
contact = delete(phoneNumber);
if (contact.length == 0) {
throw new IllegalArgumentException("Error in delete");
}
return contact;
} catch (IllegalArgumentException e) {
log(e);
throw e;
}
}
/*
* Custom logger
* ... varargs
*/
public static void log(Exception e, String... message) {
try(PrintStream ps = new PrintStream(new FileOutputStream(path.toFile(), true))) {
ps.println(LocalDateTime.now() + "\n" + e.toString());
ps.printf("%s", (message.length == 1) ? message[0] : "");
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
}
| KONSTANTINOS-EL/MobileContact | MobileContactsApp.java |
1,471 |
package aem2521;
/**
* @author Sotiria Antaranian
*/
public class Client
{
int core1,core2,core7,core11;
float totalOffer;
/**
* Ο κατασκευαστής αρχικοποιεί με μηδέν τους μετρητές για τα visual machines με 1,2,7 και 11 πυρήνες που θα χρησιμοποιηθούν για πελάτη και υπολογίζει τη συνολική προσφορά του πελάτη.
* @param cores απαιτήσεις σε πυρήνες του πελάτη
* @param singleOffer προσφορά τιμής ανά πυρήνα
*/
public Client(int cores,float singleOffer)
{
core1=0;
core2=0;
core7=0;
core11=0;
totalOffer=cores*singleOffer;
}
int getCore1 (){return core1;}
int getCore2 (){return core2;}
int getCore7 (){return core7;}
int getCore11 (){return core11;}
float getTotalOffer (){return totalOffer;}
/**
* συγκρίνει δυο ακέραιους αριθμούς και επιστρέφει το μικρότερο
* @param a
* @param b
* @return το μικρότερο
*/
int min (int a,int b)
{
return (a < b)? a : b;
}
/**
* Η πρώτη λειτουργία λύνεται όπως το πρόβλημα της ανταλλαγής ακριβούς αντίτιμου, όπου το αντίτιμο είναι οι απαιτήσεις σε πυρήνες και τα διαθέσιμα νομίσματα είναι τα visual machines με 1,2,7 και 11 πυρήνες.
* Σκοπός είναι να βρεθεί το μικρότερο πλήθος visual machines όπου το άθροισμα των πυρήνων τους να δίνουν όσους πυρήνες ζητά ο πελάτης.
* Σύμφωνα με το πρόβλημα της ανταλλαγής ακριβούς αντίτιμου, αρχικά θεωρούμε ότι διαθέσιμο είναι μόνο το πρώτο νόμισμα.
* Με την εισαγωγή του i-στου κέρματος στο υποσύνολο των διαθέσιμων νομισμάτων προκύπτουν δυο περιπτώσεις: είτε το νόμισμα αυτό θα είναι μεγαλύτερο από το απαιτούμενο αντίτιμο,
* οπότε η βέλτιστη λύση είναι ίδια με την περίπτωση των i-1 διαθέσιμων νομισμάτων, είτε δεν είναι μεγαλύτερο,
* οπότε θα χρησιμοποιηθεί αν C[i-1][j] > 1+C[i][j-VMs[i-1]] , αλλιώς η βέλτιστη λύση είναι πάλι ίδια με την περίπτωση των i-1 διαθέσιμων νομισμάτων.
* Η πολυπλοκότητα είναι Ο(n*m) όπου n ο αριθμός των διαφορετικών σε πλήθος πυρήνων διαθέσιμων visual machines και m ο αριθμός των πυρήνων που απαιτούνται και προκύπτει από τα εμφολευμένα δύο for.
* //
* Για την εύρεση του πόσα visual machines από το καθένα που είναι διαθέσιμα (με 1,2,7 και 11 πυρήνες) χρησιμοποιούνται, ξεκινώντας από το τελευταίο κελί της πιο δεξιά στήλης του πίνακα που προέκυψε από την εκτέλεση του παραπάνω αλγορίθμου,
* συγκρίνουμε κάθε κελί στη γραμμή k με το κελί πάνω του και αν είναι διαφορετικό τότε το αντίστοιχο k-στό (στο πίνακα VMs που δέχεται η συνάρτηση) διαθέσιμο visual machine χρησιμοποιείται.
* Σε αυτή την περίπτωση μετακινούμαστε προς τα αριστερά στο πίνακα,
* στο κελί που βρίσκεται στη στήλη για τους εναπομείναντες απαιτούμενους πυρήνες χωρίς τους πυρήνες που προσφέφει το visual machine που διαπιστώθηκε ότι χρησιμοποιείται,
* στην ακριβώς ίδια με πριν γραμμή(επειδή μπορεί να ξαναχρησιμοποιείται visual machine με ίδιο αριθμό πυρήνων).
* Μετά συγκρίνουμε το περιεχόμενο του κελιού με το από πάνω του κ.ο.κ.
* Σε κάθε περίπτωση, αν τα κελιά που συγκρίνουμε είναι ίδια, πάμε στην ακριβώς από πάνω γραμμή (στην ίδια στήλη) και συγκρίνουμε το κελί σε αυτή τη γραμμή με το από πάνω του κ.ο.κ.
* Η πολυπλοκότητα είναι Ο(n+m).
* Η συνολική πολυπλοκότητα είναι Ο(n*m+n+m).
*
* @param VMs πίνακας με το πλήθος των πυρήνων που έχει το καθένα από τα διαθέσιμα visual machines
* @param cores οι απαιτήσεις σε πυρήνες
*/
void calculateVM (int []VMs,int cores)
{
int[][] C=new int[VMs.length+1][cores+1];
for(int i=0;i<=VMs.length;i++)
C[i][0]=0;
for(int i=1;i<=cores;i++)
C[0][i]=10000000;
for(int i=1;i<=VMs.length;i++) //Ο(VMs.length)
{
for(int j=1;j<=cores;j++) //Ο(cores)
{
if(VMs[i-1]<=j) //μπορεί να χρησιμοποιηθεί το visual machine με πυρήνες ίσους με τον ακέραιο στη θέση i-1
C[i][j]=min(C[i-1][j],1+C[i][j-VMs[i-1]]); //min επειδή ψάχνουμε το ελάχιστο δυνατό αριθμό visual machines ανά πελάτη
else //δεν μπορεί να χρησιμοποιηθεί επειδή οι πυρήνες του είναι πιο πολλοί από αυτούς που απαιτούνται
C[i][j]=C[i-1][j];
}
}
int k=VMs.length;
int j=cores;
while(j>=0)
{
if(C[k][j]!=C[k-1][j])
{
if(k==1)
core1++;
else if(k==2)
core2++;
else if(k==3)
core7++;
else
core11++;
j=j-VMs[k-1];
}
else
k--;
if(k==0)//αν όλα τα στοιχεία μιας στήλης είναι ίδια, πάει στο τελευταίο στοιχείο της αριστερής του στήλης
{
k=VMs.length;
j--;
}
}
}
}
| sotiria3103/visual-machine-assigning | src/aem2521/Client.java |
1,472 | package com.example.skinhealthchecker;
/*
Είναι το κεντρικό activity .Η περιέχει τον απαραίτητο κώδικα για τον χειρισμό της cameras .
•Στον παρακάτω κώδικα γίνεται:
- ορισμός αυτόματης εστίασης
-ορισμός ισορροπία λευκού στο ψυχρό αν υποστηρίζεται
- υπολογίζεται η Εστιακή απόσταση του φακού
- λαμβάνεται το φυσικό μεγεθος του εσθητήρα
- υπολογίζονται τα υποστηριζόμενα μεγέθη προεπισκόπηση εικόνας της συσκευής.
• -Τα υποστηριζόμενα μεγέθη λήψης εικόνας της συσκευής.
-Και στις 2 περιπτώσεις η εφαρμογή πέρνει το μεγαλύτερο υ-ποστηριζόμενο βρίσκοντάς το πρώτα υλοποιώντας γνωστό αλγόριθ-μο εύρεσης μεγαλύτερου από λίστα και μετά αυτό το ορίζεται στις ρυθμίσεις Ορίζεται ότι η περιοχή εστίασης θα είναι στο κέντρο της εικόνας.
• -Γίνεται έλεγχος αν υπάρχει φλάς στην συσκευή. Αν υπάρχει το ε-νεργοποιεί .
• -γίνεται αναζήτηση στα specs αν υπάρχει κάποια λειτουρ-γία κατά της ακούσιας κίνησης .
-Γίνεται αναζήτηση στις ρυθμί-σεις που έχει δώσει ο κατασκευαστής της συσκευής αν υπάρχουν οι λέξεις ios η image-stabilizer αν βρεθούν αυτές οι λέξεις ενερ-γοποιεί την αντίστοιχη λειτουργεία .
Γίνεται η δημιουργία της προεπισκόπησης και ορίζεται το σημείο του xml το οποίο θα προβάλλεται .
Ορίζεται ότι όταν εντοπιστεί αφή τότε θα γίνεται εστίαση
Γίνεται η λήψη εικόνας όταν γίνει εστίαση.
• υπολογίζεται η θέση που γίνεται αποθήκευση των δεδομένων της εφαρμογής δίνε-ται από το λειτουργικό .
Η θέση είναι μο-ναδική για κάθε εφαρμογή και καμία άλλη εφαρμογή δεν έχει πρό-σβαση στην συγκεκριμένη θέση .
Το αρχείο που θα αποθηκευτεί θα έχει όνομα IMGtmp και κατάληξη .nodata για λόγους ασφαλείας.
It is the central activity. It contains the necessary code for handling the cameras.
• The code below is:
- definition of autofocus
-determination of white balance in the cold if supported
- The focal length of the lens is calculated
- obtain the natural size of the sensor
- the supported image previews of the device are calculated.
• -The supported image capture sizes of the device.
-And in two cases, the application takes the largest support by first installing a known larger-than-list finder algorithm and then defining it in the settings. Specifies that the focus area will be in the center of the image.
• Check if there is a flash on the device. If it exists, it turns on.
• -can search for specs if there is any function against inadvertent movement.
-Search the settings provided by the manufacturer of the device if there are the words ios the image-stabilizer if these words are found they activate the corresponding function.
The preview is created and the xml point to be displayed.
It is defined that when a touch is detected then focus will be on
An image is taken when focusing.
• Calculate the location where the application data is stored is given by the operating data.
The position is modular for each application and no other application has access to that location.
The file to be saved will be named IMGtmp and a .nodata extension for security reasons.
*/
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.Size;
import android.hardware.camera2.params.MeteringRectangle;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.util.Log;
import android.util.SizeF;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.Surface;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
@SuppressLint("NewApi")
public class CameraActivity extends Activity {
private static final String TAG = "CameraActivity";
public static int temp = 0; // temporary variable
private static ToggleButton lang; //the button to change the language
private Camera mCamera; // the variable referenced in the snapshot of the camera
private CameraPreview mPreview; // the variable mentioned in the camera preview
private Exception e;
static File pictureFile;// the variable that refers to the image file that will be created on disk
static int press=0; //the variable that ensures that the photo button was pressed once.
static float fl;//the focal length of the camera
// static double horizontalViewAngle;
// static double verticalViewAngle ;
static float sensorh; // the height of the sensor
static int biggerid =0; // variable that will display the id of the largest camera on the device
//private boolean safeToTakePicture = false;
private Configurations def; // snapshot of the structure with the last settings used
DatabaseHandler db; // the database handler
private boolean lan = true; // lan value contains the display language of the application
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {// starting the activity
super.onCreate(savedInstanceState);
db = new DatabaseHandler(this);//
def = db.getDEf(); //the last settings that were in place before the application was closed
if(def.GetLanguage()) // the language is checked and the correct xml file is displayed
setContentView(R.layout.activity_main);
else
setContentView(R.layout.activity_mainen);
// check if the device has a camera
PackageManager pm = this.getPackageManager();
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");
return;
}
press=0;
//create a snapshot of the camera
SizeF size = new SizeF(0,0); // initialize Size
double sizetemp =0;
// is monitored if there are cameras on the device.
//
// If there is more than one then the one with the largest sensor size is selected
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics character = manager.getCameraCharacteristics(cameraIds[0]);
double biggersize = character.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE).getHeight()*
character.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE).getWidth();
// size = physical length X width
biggerid =0;
Log.d("bigger id",Double.toString(sizetemp));
Log.d("bigger id",Integer.toString(cameraIds.length));
for (int i=1;i<cameraIds.length;i++){
character = manager.getCameraCharacteristics(cameraIds[i]);
sizetemp = character.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE).getHeight()*
character.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE).getWidth();
Log.d("bigger id",Double.toString(sizetemp));
if ((sizetemp>biggersize) && character.get(CameraCharacteristics.FLASH_INFO_AVAILABLE)) {
biggersize = sizetemp;
biggerid=i;
}
}
Log.d ("camera",Integer.toString(biggerid));
character = manager.getCameraCharacteristics(cameraIds[biggerid]); // the camera features are taken
size = character.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE);
// The pixels that fit the sensor's height are taken
int psize= character.get(CameraCharacteristics.SENSOR_INFO_PIXEL_ARRAY_SIZE).getHeight();
if (psize!=0)// Physical height / pixel height at height = physical height of each pixel
sensorh= size.getHeight()/psize;
}
catch (CameraAccessException |NullPointerException e)
{
Log.e("YourLogString", e.getMessage(), e);
}
mCamera = getCameraInstance.getCameraInstance(biggerid); // takes the snapshot of the selected camera
// mCamera = getCameraInstance.getCameraInstance(0); // takes the snapshot of the selected camera
// adjusts the preview for auto-focus mode
final Camera.Parameters params = mCamera.getParameters(); // camera parameters are taken
setCameraDisplayOrientation(this,biggerid,mCamera);// o
// *EDIT*//params.setFocusMode("continuous-picture");
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO); // definition of autofocus
String TAG ="FocalLength";
// Log.i(TAG, "White Balance setting = " + params.get("whitebalance"));
params.setWhiteBalance(Camera.Parameters.WHITE_BALANCE_INCANDESCENT); // set color temperature cold
if( params.isAutoWhiteBalanceLockSupported())
{
params.setAutoWhiteBalanceLock(true); // lock color change change
}
try {
fl=params.getFocalLength(); // capturing the focal distance of the sensor
// Log.d(TAG,Float.toString(fl) );
// second way to calculate the camera's size
// TAG ="horizontalViewAngle";
// horizontalViewAngle = params.getHorizontalViewAngle();
// Log.d(TAG,Double.toString(horizontalViewAngle) );
// TAG ="verticalViewAngle";
// verticalViewAngle = params.getVerticalViewAngle();
// Log.d(TAG,Double.toString(verticalViewAngle) );
// sensorh= Math.tan(horizontalViewAngle/2*1000)*2*fl;
}
catch (NullPointerException e)
{
Log.e("YourLogString", e.getMessage(), e);
}
List<Camera.Size> sizeList = params.getSupportedPreviewSizes();// list of supported viewing resolutions
List<Camera.Size> sizeList2 = params.getSupportedPictureSizes();// list of supported image storage resolutions
Size bestcameraSize = sizeList2.get(0);
// From the above lists we choose the largest resolution
for(int i = 1; i < sizeList2.size(); i++){
if((sizeList2.get(i).width * sizeList2.get(i).height) > (bestcameraSize.width * bestcameraSize.height)){
bestcameraSize = sizeList2.get(i);
}
}
Size bestSize = sizeList.get(0);
for(int i = 1; i < sizeList.size(); i++){
if((sizeList.get(i).width * sizeList.get(i).height) > (bestSize.width * bestSize.height)){
bestSize = sizeList.get(i);
}
}
params.setPictureSize(bestcameraSize.width, bestcameraSize.height);
TAG = "best preview size";
Log.d(TAG,Double.toString(bestSize.width)+"x"+Double.toString(bestSize.height) );
// Toast.makeText(getApplicationContext(), Double.toString(bestcameraSize.width)+"x"+Double.toString(bestcameraSize.height), Toast.LENGTH_LONG).show();
// specifies that the focus area is on the center-facing object
Rect newRect = new Rect(-100, -100, 100, 100);
Camera.Area focusArea = new Camera.Area(newRect, 1000);
List<Camera.Area> focusAreas = new ArrayList<Camera.Area>();
focusAreas.add(focusArea);
params.setFocusAreas(focusAreas);
// Check if the device has a flashlight and if it is turned on
// Camera.open();
List<String> flashModes = params.getSupportedFlashModes();
if (flashModes == null) {
// Toast.makeText(getApplicationContext(), "LED Not Available", Toast.LENGTH_LONG).show();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
} else {
//
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
}
// definition of luminance control in the center (if the center point is brighter or darker
// the image is adjusted
if (params.getMaxNumMeteringAreas() > 0){
List<Camera.Area> areas = new ArrayList<Camera.Area>();
areas.add(new Camera.Area(newRect, 1000));
params.setMeteringAreas(areas);
}
mCamera.setParameters(params);
int ios=0;
String iosparameter ;
// Checks if there is support to improve the image in case of unintentional traffic
// search words in camera features for ios image-stabilizer
String goodysios = mCamera.getParameters().flatten();
List<String> goodys = mCamera.getParameters().getSupportedSceneModes();
StringTokenizer tokenizer = new StringTokenizer(goodysios, ";");
while(tokenizer.hasMoreTokens()) {
iosparameter = tokenizer.nextToken();
if (iosparameter.toLowerCase().contains("ios") || iosparameter.toLowerCase().contains("image-stabilizer")) {
ios = 1;
params.set(iosparameter, "ios");
params.set("image-stabilizer", "ois");
}
}
// previews the image on the mobile screen
mPreview = new CameraPreview(this, mCamera);
final FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
preview.addView(mPreview);
// the viewfinder for the mole inserted
mybox box = new mybox(this);
// το κουμπί γλώσσας πέρνει την τιμή της ενεργής γλώσσας
lang = (ToggleButton) findViewById(R.id.language);
lang.setChecked(def.GetLanguage());
lang.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{//definition that the button presses will be taken into account
lan=lang.isChecked();
// if the language button is pressed, the new language is set and intent is restarted
def.SetLanguage(lan);
db.updateDef(def);
finish();
startActivity(getIntent());
// Toast.makeText(getApplicationContext(), "Click!", Toast.LENGTH_SHORT).show();
}
});
//View myView = findViewById(R.id.camera_preview); //refocus on touch
preview.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
// ... Respond to touch events
// If a part of the screen is pressed, focus is refocused
Log.d("down", "focusing now");
mCamera.autoFocus(null);
return true;
}
});
// the snapshot of the target is entered on the screen
addContentView(box, new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
// Add a listener to the Capture button
Button captureButton = (Button) findViewById(R.id.button_capture);
captureButton.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButton.requestFocus();
captureButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
// If the button with the lens is pressed, the following function is executed
focusandspray();
// the function starts the image acquisition process.
//
}
});
Button captureButton32 = (Button) findViewById(R.id.info);
captureButton32.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButton32.requestFocus();
captureButton32.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
// if the button for the manual is pressed the corresponding intent is started
Intent intent23 = new Intent(getApplicationContext(), Manual.class);
startActivity(intent23);
//
}
});
Button captureButtonU = (Button) findViewById(R.id.profil);
captureButtonU.setFocusable(true);
//captureButton.setFocusableInTouchMode(true);
captureButtonU.requestFocus();
captureButtonU.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//
// if the button for the profile manager is pressed, the corresponding intent is started
Intent intentU = new Intent(getApplicationContext(), Users.class);
startActivity(intentU);
//
}
});
if (flashModes != null) { // if there is a flash on the device then the buttons will be taken into account
//
ToggleButton captureButton2 = (ToggleButton ) findViewById(R.id.flash);
captureButton2.setFocusable(true);
//captureButton2.setFocusableInTouchMode(true);
captureButton2.requestFocus();
captureButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//if pressed on it will be done off otherwise the opposite
if (params.getFlashMode().equals(Parameters.FLASH_MODE_TORCH))
{
params.setFlashMode(Parameters.FLASH_MODE_OFF);
mCamera.setParameters(params);
}
else
{
params.setFlashMode(Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(params);
}
//
}
});
Button captureButton3 = (Button) findViewById(R.id.data);//if the button for the gallery is pressed
// the corresponding intent is started
captureButton3.setFocusable(true);
// captureButton3.setFocusableInTouchMode(true);
captureButton3.requestFocus();
captureButton3.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(getApplicationContext(), AppGallery.class);
startActivity(intent2);
}
});
}
}
// when the picture is captured the data is written to the storage
private PictureCallback mPicture = new PictureCallback() {
@Override
public void onPictureTaken(byte[] data, Camera camera) {
CameraPreview.safeToTakePicture = true; //disable the lock of the camera( camera will capture only one frame)
//Creating a file at MEDIA_TYPE_IMAGE directory
pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);//
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: "
+ e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
// data.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.write(data);
// fos.flush();
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
};
@Override
protected void onPause() {
releaseCamera(); // release the camera immediately on pause event
finish();
super.onPause();
/** try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}**/
}
private void releaseCamera() {
if (mCamera != null) {
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
public static final int MEDIA_TYPE_IMAGE = 1;
/** Create a file Uri for saving an image or video */
private Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/** Create a File for saving an image or video */
private File getOutputMediaFile(int type) {
String NOMEDIA=" .nomedia";
// the saving directory will be the app private directory
File mediaStorageDir = new File(
this.getExternalFilesDir(Environment.getDataDirectory().getAbsolutePath()).getAbsolutePath());
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("MyCameraApp", "failed to create directory");
return null;
}
}
// Create a media file name
// String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new
// Date());
File mediaFile;
// the image file name will be : IMGtmp.nodata
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMGtmp" + ".nodata");
}
/**
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "IMGtmp" + ".jpg");
}
**/
else {
return null;
}
return mediaFile;
}
@SuppressWarnings("deprecation")
void focusandspray() {
if(press==0){//it is controlled if the button is pressed once, the first time it is pressed will focus and take the picture
press=1;
mCamera.autoFocus(new Camera.AutoFocusCallback() {
@Override
public void onAutoFocus(boolean success, Camera camera) {
Log.d(TAG, "onAutoFocus() " + success);
// check if taking picture lock is active . if it is not then enable the lock and capture picture
if (CameraPreview.safeToTakePicture)
mCamera.takePicture(null, null, mPicture);
CameraPreview.safeToTakePicture = false;// lock the safe
SystemClock.sleep(800);// the app is waiting 1,5 sec to end the saving procedure
Intent intent = new Intent(getApplicationContext(), Preview.class); // jumping to next intent
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
//this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started.
// Intent.FLAG_ACTIVITY_NEW_TASK
// sending the parameters to the next activity
intent.putExtra("focal", fl); //Optional parameters
intent.putExtra("sensor", sensorh); //Optional parameters
startActivity(intent); // starting next activity
}
});
}
}
/**
protected void setDisplayOrientation(Camera camera, int angle){
Method downPolymorphic;
try
{
downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
if (downPolymorphic != null)
downPolymorphic.invoke(camera, new Object[] { angle });
}
catch (Exception e1)
{
}
}
**/
//defining-correcting the appropriate rotation of the preview
public static void setCameraDisplayOrientation(Activity activity, int cameraId, android.hardware.Camera camera) {
android.hardware.Camera.CameraInfo info = new android.hardware.Camera.CameraInfo();
android.hardware.Camera.getCameraInfo(cameraId, info);
int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
int degrees = 0;
switch (rotation) {
case Surface.ROTATION_0:
degrees = 0;
break;
case Surface.ROTATION_90:
degrees = 90;
break;
case Surface.ROTATION_180:
degrees = 180;
break;
case Surface.ROTATION_270:
degrees = 270;
break;
}
int result;
//int currentapiVersion = android.os.Build.VERSION.SDK_INT;
// do something for phones running an SDK before lollipop
//if (!(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT))
/** (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
result = (info.orientation + degrees) % 360;
result = (360 - result) % 360; // compensate the mirror
} else **/
// back-facing
result = (info.orientation - degrees + 360) % 360; // adding the right angle
camera.setDisplayOrientation(result);
}
public void closeCamera() { //the app set the camera free
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.lock();
mCamera.release();
mCamera=null;
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) { // on vol+ or vol- capture image
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
// calling the image capture function
focusandspray();
}
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) {
//TODO
// calling the image capture function
focusandspray();
}
return true;
default:
return super.dispatchKeyEvent(event);
}
}
@Override
public void onBackPressed() {// if the android back button is pressed , the app closing
if (mCamera != null) {
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
mCamera.lock();
mCamera.release();
mCamera=null;
}
finish();
}
}
| litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/CameraActivity.java |
1,473 | package com.example.commontasker;
import android.app.SearchManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.SearchRecentSuggestions;
import android.support.v4.widget.CursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Αρης on 1/7/2016.
*/
public class task extends AppCompatActivity {
private Button button1;
//int[]images={R.drawable.broom,R.drawable.care_icon,R.drawable.shopping,R.drawable.trekk};
HashMap<String,List<String>> Categories;
List<String> catogories_list;
ExpandableListView expandableListView;
CategoriesAdapter adapter;
private DatabaseReference database;
private DatabaseReference databaselike;
private boolean process=false;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.task);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(null);
}
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.left_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
startActivity(new Intent(task.this,ergo.class));
}
});
Intent searchIntent = getIntent();
if (Intent.ACTION_SEARCH.equals(searchIntent.getAction())) {
String query = searchIntent.getStringExtra(SearchManager.QUERY);
Toast.makeText(task.this, query, Toast.LENGTH_LONG).show();
}
button1=(Button) findViewById(R.id.button6);
// databaselike= FirebaseDatabase.getInstance().getReference().child("Likes");
database= FirebaseDatabase.getInstance().getReference().child("Tasks");
/*expandableListView = (ExpandableListView) findViewById(R.id.expandableListView2);
Categories = DataProvider.getInfo();
catogories_list = new ArrayList<String>(Categories.keySet());
adapter = new CategoriesAdapter(this, Categories, catogories_list);
expandableListView.setAdapter(adapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int i) {
Toast.makeText(getBaseContext(), "Επιλέξατε την κατηγορία " + catogories_list.get(i), Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int i) {
Toast.makeText(getBaseContext(), "Aφήσατε την κατηγορία " + catogories_list.get(i), Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int grouposition, int childposition, long id) {
view.setSelected(true);
Toast.makeText(getBaseContext(), "Επιλέξατε ότι θέλετε να ασχολειθείτε με το " + Categories.get(catogories_list.get(grouposition)).get(childposition) + " απο την Κατηγορία " + catogories_list.get(grouposition), Toast.LENGTH_LONG).show();
return false;
}
});*/
expListView = (ExpandableListView) findViewById(R.id.lvExp);
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
return false;
}
});
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
v.setSelected(true);
Intent intent_name = new Intent(getApplicationContext(), ErgoDetails.class);
if(groupPosition == 0){
//intent_name = new Intent(getApplicationContext(), AnswerDetails.class);
intent_name.putExtra("description", exwterikes1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", exwterikes1.get(childPosition).getImage());
intent_name.putExtra("title", exwterikes1.get(childPosition).getTitlos());
intent_name.putExtra("time", exwterikes1.get(childPosition).getTime());
intent_name.putExtra("date", exwterikes1.get(childPosition).getDate());
intent_name.putExtra("location", exwterikes1.get(childPosition).getLocation());
// intent_name.setClass(getApplicationContext(), AnswerDetails.class);
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent_name);
}
else if(groupPosition == 1){
// Intent intent_name = new Intent();
intent_name.putExtra("description", ekpaideytikes1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", ekpaideytikes1.get(childPosition).getImage());
intent_name.putExtra("title", ekpaideytikes1.get(childPosition).getTitlos());
intent_name.putExtra("time", ekpaideytikes1.get(childPosition).getTime());
intent_name.putExtra("date", ekpaideytikes1.get(childPosition).getDate());
intent_name.putExtra("location", ekpaideytikes1.get(childPosition).getLocation());
// intent_name.setClass(getApplicationContext(), AnswerDetails.class);
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent_name);
}
else if(groupPosition == 2){
intent_name.putExtra("description", vohtheia1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", vohtheia1.get(childPosition).getImage());
intent_name.putExtra("title", vohtheia1.get(childPosition).getTitlos());
intent_name.putExtra("time", vohtheia1.get(childPosition).getTime());
intent_name.putExtra("date", vohtheia1.get(childPosition).getDate());
intent_name.putExtra("location", vohtheia1.get(childPosition).getLocation());
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// getApplicationContext().startActivity(intent_name);
startActivity(intent_name);
}
return false;
}
});
}
private List<String> exwterikes = new ArrayList<String>();
private List<String> ekpaideytikes = new ArrayList<String>();
private List<String> vohtheia= new ArrayList<String>();
private List<TaskItem> exwterikes1 = new ArrayList<TaskItem>();
private List<TaskItem> ekpaideytikes1 = new ArrayList<TaskItem>();
private List<TaskItem> vohtheia1 = new ArrayList<TaskItem>();
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Outdoor tasks");
listDataHeader.add("Indoor tasks");
listDataHeader.add("Offering assistance");
Query query = database;
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot Question : snapshot.getChildren()) {
if(Question.child("title").getValue().equals("Outdoor tasks")){
exwterikes.add(Question.child("description").getValue().toString().trim());
TaskItem add = new TaskItem(Question.child("title").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("image").getValue().toString().trim(),Question.child("date").getValue().toString().trim(),Question.child("description").getValue().toString().trim());
exwterikes1.add(add);
}
else if(Question.child("title").getValue().equals("Indoor tasks")){
ekpaideytikes.add(Question.child("description").getValue().toString().trim());
TaskItem add = new TaskItem(Question.child("title").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("image").getValue().toString().trim(),Question.child("date").getValue().toString().trim(),Question.child("description").getValue().toString().trim());
ekpaideytikes1.add(add);
}
else if(Question.child("title").getValue().equals("Offering assistance")){
vohtheia.add(Question.child("description").getValue().toString().trim());
TaskItem add = new TaskItem(Question.child("title").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("image").getValue().toString().trim(),Question.child("date").getValue().toString().trim(),Question.child("description").getValue().toString().trim());
vohtheia1.add(add);
}
}
if(exwterikes.isEmpty())
exwterikes.add("Empty");
if(ekpaideytikes.isEmpty())
ekpaideytikes.add("Empty");
if(vohtheia.isEmpty())
vohtheia.add("Empty");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
listDataChild.put(listDataHeader.get(0), exwterikes); // Header, Child data
listDataChild.put(listDataHeader.get(1), ekpaideytikes);
listDataChild.put(listDataHeader.get(2), vohtheia);
}
@Override
protected void onStart() {
super.onStart();
/*
FirebaseRecyclerAdapter<Taskitem, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<Taskitem, BlogViewHolder>(Taskitem.class, R.layout.child_Task, BlogViewHolder.class, database) {
@Override
protected void populateViewHolder(BlogViewHolder viewHolder, Taskitem model, int position) {
final String post_key =getRef(position).getKey();
viewHolder.setTitle(model.getTitlos());
viewHolder.setPerigrafh(model.getPerigrafh());
viewHolder.setDate(model.getDate());
viewHolder.setTime(model.getTime());
viewHolder.setLocation(model.getLocation());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setPost(post_key);
viewHolder.imagelike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
process=true;
if(process){
databaselike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(String.valueOf(dataSnapshot.child("username")))){
databaselike.child(post_key).child(String.valueOf(dataSnapshot.child("username"))).removeValue();
}
else{
databaselike.child(post_key).child(String.valueOf(dataSnapshot.child("username")));
process=false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View view;
ImageButton imagelike;
DatabaseReference databaselike;
public BlogViewHolder(View itemView) {
super(itemView);
view = itemView;
imagelike=(ImageButton) view.findViewById(R.id.likepost);
databaselike= FirebaseDatabase.getInstance().getReference().child("Likes");
databaselike.keepSynced(true);
}
public void setPost(final String post_key) {
databaselike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(String.valueOf(dataSnapshot.child("username")))){
imagelike.setImageResource(R.drawable.like_red);
}
else {
imagelike.setImageResource(R.drawable.like);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title) {
TextView post_title = (TextView) view.findViewById(R.id.title);
post_title.setText(title);
}
public void setPerigrafh(String perigrafh) {
TextView post_perigrafh = (TextView) view.findViewById(R.id.perigrafh);
post_perigrafh.setText(perigrafh);
}
public void setDate(String date) {
TextView post_dating = (TextView) view.findViewById(R.id.date);
post_dating.setText(date);
}
public void setTime(String time) {
TextView post_time = (TextView) view.findViewById(R.id.time);
post_time.setText(time);
}
public void setLocation(String location) {
TextView post_location = (TextView) view.findViewById(R.id.location);
post_location.setText(location);
}
public void setUsername(String username){
TextView post_name = (TextView) view.findViewById(R.id.user);
post_name.setText(username
);
}
public void setImage(Context context, String image) {
ImageView post_image = (ImageView) view.findViewById(R.id.imaposting);
Picasso.with(context).load(image).into(post_image);
}*/
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_bottom, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent it;
switch(item.getItemId()){
case R.id.action_facebook:
it = new Intent(Intent.ACTION_VIEW);
it.setData(Uri.parse("http://www.facebook.com"));
startActivity(it);
break;
case R.id.action_phone:
Intent intent = new Intent(this, sos.class);
startActivity(intent);
break;
case R.id.action_home:
Intent intent1 = new Intent(this, MainActivity.class);
startActivity(intent1);
break;
case R.id.action_login:
Intent intent2 = new Intent(this, eggrafh.class);
startActivity(intent2);
break;
case R.id.logout:
logout();
break;
default:
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Do you want to exit the application;");
alertDialogBuilder
.setMessage("Press YES to exit!")
.setCancelable(false)
.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Toast.makeText(task.this,"Successful Logout",Toast.LENGTH_LONG).show();
startActivity(new Intent(task.this,eggrafh.class));
}
})
.setNegativeButton("NO", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
} | netCommonsEU/CommonTasker | app/src/main/java/com/example/commontasker/task.java |
1,475 |
package com.evaluation.encryption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// μπορει να μπει ότι θέλουμε μεταξυ MD2, MD5, SHA-1, SHA-224, SHA-256, SHA-384, SHA-512 //
public class Encryption {
public static String getHash (String password) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(password.getBytes());
byte[] resultByteArray = messageDigest.digest();
StringBuilder sb = new StringBuilder();
for (byte b : resultByteArray) {
sb.append(String.format("%02x", b));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
| Lefteris-Souflas/Java-Web-App-For-Military-Staff-Evaluation | application/Evaluation/src/main/java/com/evaluation/encryption/Encryption.java |
1,477 | public class RoomTypeB extends RoomTypeA
{
private static double discountPerDay=0; //Μεταβλητή για έκπτωση ανά μέρα.
//Setter
public static void setDiscountPerDay(int aaa)
{
discountPerDay=aaa;
}
public double getPriceOfRoom()//Η μέθοδος ελέγχει ποιές μέρες είναι κλεισμένο το δωμάτιο και υπολογίζει τα εσοδά του,
{ //υπολογίζωντας την καθημερινή έκπτωση.
int i=0;
double totalEarnings; //Μεταβλητή για συνολικά έσοδα.
double moneyEarnedFromRoom=0; //Μεταβλητή για έσοδα ανά μέρα.
discountPerDay=0;
for(i=1; i<31; i++)
{
if(roomAvailability[i]!=null)
{
moneyEarnedFromRoom += (getPricePerDay() - discountPerDay);
discountPerDay += 10;
if( (discountPerDay / getPricePerDay()) > 0.5)
{
discountPerDay = 0.5 * getPricePerDay();
}
}
}
return moneyEarnedFromRoom;
}
public boolean cancelBooking(int bookingID)//Η μέθοδος δείχνει ότι το δωμάτιο τύπου B δεν μπορεί να ακυρωθεί.
{
System.out.println("Can't cancel this kind of room");
return false;
}
} | DimitrisKostorrizos/UndergraduateCeidProjects | Project Οντοκεντρικός Προγραμματισμός/Java Project/Hotel Project, Swing/RoomTypeB.java |
1,478 | public class RoomTypeD extends Room//Δωμάτιο μονοήμερης διαμονής.
{
static double priceOfRoom=40; //Μεταβλητή για τιμή ανά δωμάτιο.
//Setter
public static void setPriceOfRoom(double x)
{
priceOfRoom=x;
}
public double getPriceOfRoom()//Μέθοδος υπολογισμού των εσόδων του δωματίου τύπου D.
{
double moneyEarnedFromRoom=0; //Μεταβλητή για έσοδα δωματίου.
int i=0;
boolean found=false;
for(i = 1; i<31; i++)
{
if(roomAvailability[i]!=null)
moneyEarnedFromRoom += priceOfRoom;
}
return moneyEarnedFromRoom;
}
public boolean cancelBooking(int bookingID)//Η μέθοδος δείχνει ότι το δωμάτιο τύπου D δεν μπορεί να ακυρωθεί.
{
System.out.println("Can't cancel this kind of room");
return false;
}
}
| DimitrisKostorrizos/UndergraduateCeidProjects | Project Οντοκεντρικός Προγραμματισμός/Java Project/Hotel Project, Swing/RoomTypeD.java |
1,481 | package Games;
/*
* @author Despina-Eleana Chrysou
*/
import GetData.*;
import javax.swing.*;
public class Data extends javax.swing.JApplet {
/** Initializes the applet Data */
@Override
public void init() {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Data.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the applet */
try {
java.awt.EventQueue.invokeAndWait(new Runnable() {
public void run() {
initComponents();
}
});
} catch (Exception ex) {
}
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setBackground(new java.awt.Color(255, 204, 204));
jLabel1.setFont(new java.awt.Font("Tahoma", 2, 14));
jLabel1.setForeground(new java.awt.Color(51, 0, 51));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("Αρχείο: data.txt");
jButton1.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
jButton1.setText("Δημιούργησε τα δεδομένα");
jButton1.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR));
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 2, 14)); // NOI18N
jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel2.setText("Default Path: C:\\temp");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 223, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 223, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(95, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jButton1, jLabel1, jLabel2});
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(45, 45, 45)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(75, Short.MAX_VALUE))
);
layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {jLabel1, jLabel2});
}// </editor-fold>//GEN-END:initComponents
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
JOptionPane.showMessageDialog(this, "Περίμενε μέχρι να εμφανιστεί το μήνυμα ότι είναι έτοιμο το αρχείο...");
Jena.GetResults();
/*ReadFromFile GetData = new ReadFromFile();
int [] index1=GetData.index1();
int indexall1=0;
for (int i=0;i<31;i++) {
int k=i+1;
int index2=index1[i]-1;
indexall1=index2+indexall1;
//System.out.println("Το ερώτημα "+k+" έχει "+index2+" εγγραφές");
System.out.println(index2);
}
int index=GetData.indexall();
System.out.println("Όλες οι εγγραφές είναι: "+indexall1);
System.out.println("Αν στο "+indexall1+" προστεθούν και οι 31 γραμμές που περιέχουν τα ερωτήματα, τότε το συνολικό πλήθος γραμμών του πίνακα είναι: "+index);
int arraydimension=index*4;
System.out.println("Το συνολικό πλήθος δεδομένων είναι: "+index+" x 4 (4 στήλες)= "+arraydimension);*/
JOptionPane.showMessageDialog(this, "Eτοιμο το αρχείο 31queries.txt!");
}//GEN-LAST:event_jButton1ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
// End of variables declaration//GEN-END:variables
}
| ComradeHadi/DBpedia-Game | ssg/src/Games/Data.java |
1,482 | package com.bugbusters.lajarus;
import android.content.Intent;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
public class QuestActivity extends AppCompatActivity {
private Runnable task = new Runnable() {
public void run() {
Intent intent = new Intent(QuestActivity.this,MapActivity.class);
startActivity(intent);
}
};
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radioButton:
if (checked)
Toast.makeText(getApplicationContext(),
"Nooooooo!",
Toast.LENGTH_SHORT).show();
Handler handler = new Handler();
int millisDelay = 3000;
handler.postDelayed(task, millisDelay);
break;
case R.id.radioButton2:
if (checked)
Toast.makeText(getApplicationContext(),
"Success!",
Toast.LENGTH_SHORT).show();
Handler handler1 = new Handler();
int millisDelay1 = 3000;
handler1.postDelayed(task, millisDelay1);
break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quest);
TextView editText =(TextView)findViewById(R.id.editText2);
editText.setText(" O Ηρακλής διατάχθηκε από τον Ευρυσθέα να οδηγήσει στις Μυκήνες από την Ερύθεια, ένα απομονωμένο νησί στον Ωκεανό, τα βόδια του βασιλιά Γηρυόνη, γιου του Χρυσάορα και της Καλλιρρόης. Μετά από μακρά και περιπετειώδη πορεία στις χώρες της Μεσογείου, και αφού μονομάχησε με τον Γηρυόνη στις ακτές του ποταμού Ανθεμούντα, έφτασε στις ιωνικές ακτές της Ελλάδας, όπου μια βοϊδόμυγα, σταλμένη από την Ήρα, τρέλανε το κοπάδι και το έκανε να διασκορπιστεί στα βουνά της Θράκης.\n" +
"Ο Ηρακλής κατηγόρησε τον Στρυμόνα, ότι δυσκόλεψε το έργο του να συγκεντρώσει τα ζώα. Τον γέμισε λοιπόν με πέτρες, και από τότε ο ποταμός έπαψε να είναι πλωτός (Απολλόδ. 2.112).\n" +
"Σύμφωνα με άλλη εκδοχή του μύθου, ο Ηρακλής δεν μπορούσε να διασχίσει τον ποταμό επειδή δεν υπήρχε πέρασμα. Έριξε λοιπόν τεράστιους βράχους εμποδίζοντας τα πλοία να τον διαπλέουν.\n" +
"Κατά μία άλλη εκδοχή οι κάτοικοι του κάμπου των Σερρών, παραπονέθηκαν στον ήρωα Ηρακλή όταν επέστρεφε από τη Θράκη, για τις μεγάλες ζημιές που τους προκαλούσε ο ποταμός Στρυμόνας με τις συχνές πλημμύρες του. Ο Ηρακλής τότε διευθέτησε την κοίτη και απάλλαξε τους κατοίκους από τις φοβερές καταστροφές. Οι κάτοικοι της περιοχής, που διασχίζει ο ποταμός Στρυμόνας τον θεωρούσαν Θεό. Στο Μουσείο της Αμφίπολης υπάρχει ανάλογο αρχαίο νόμισμα.\n" +
"\n" +
"ΣΕ ΠΟΙΟΝ ΑΘΛΟ ΤΟΥ ΗΡΑΚΛΗ ΕΓΙΝΑΝ ΤΑ ΠΑΡΑΠΑΝΩ;");
}
}
| vnaskos/lajarus | android-client/app/src/main/java/com/bugbusters/lajarus/QuestActivity.java |
1,483 | package GUI;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import Database.*;
import Utils.Utils;
import java.io.File;
import java.sql.ResultSet;
import java.util.Locale;
import java.util.ResourceBundle;
import java.util.regex.Pattern;
import javax.swing.JFrame;
import kdesp73.databridge.connections.DatabaseConnection;
import kdesp73.databridge.helpers.QueryBuilder;
import kdesp73.themeLib.*;
import main.Customer;
/**
*
* @author tgeorg
*/
public class GUIFunctions {
// Functions for MainFrame
public static int checkLoginInfo(MainFrame mf, ArrayList<Customer> customerList) {
DatabaseConnection db = Database.connection();
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
if (languageName.equals("English")) {
if ((mf.getUsernameField().getText().isEmpty() || mf.getUsernameField().getText().isBlank()) && mf.getPasswordField().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Username and password can not be empty or blank", "Login Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getUsernameField().getText().isEmpty() || mf.getUsernameField().getText().isBlank()) {
JOptionPane.showMessageDialog(mf, "Username can not be empty or blank", "Login Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getPasswordField().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Password can not be empty or blank", "Login Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
for (int i = 0; i < customerList.size(); i++) {
if (mf.getUsernameField().getText().equals(customerList.get(i).getAcc().getUsername())
&& GUIUtils.checkLoginPassword(mf.getPasswordField().getPassword(), customerList, i) == 1) {
db.close();
return i;
}
}
JOptionPane.showMessageDialog(mf, "Username or password are incorrect", "Login Error", JOptionPane.ERROR_MESSAGE);
return -1;
} else if (languageName.equals("Greek")) {
if ((mf.getUsernameField().getText().isEmpty() || mf.getUsernameField().getText().isBlank()) && mf.getPasswordField().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Το όνομα χρήστη και ο κωδικός δεν μπορούν να είναι άδεια ή κενά", "Σφάλμα σύνδεσης", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getUsernameField().getText().isEmpty() || mf.getUsernameField().getText().isBlank()) {
JOptionPane.showMessageDialog(mf, "Το όνομα χρήστη δεν μπορεί να είναι άδειο ή κενό", "Σφάλμα σύνδεσης", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getPasswordField().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Ο κωδικός δεν μπορεί να είναι άδειος ή κενός", "Σφάλμα σύνδεσης", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
for (int i = 0; i < customerList.size(); i++) {
if (mf.getUsernameField().getText().equals(customerList.get(i).getAcc().getUsername())
&& GUIUtils.checkLoginPassword(mf.getPasswordField().getPassword(), customerList, i) == 1) {
db.close();
return i;
}
}
JOptionPane.showMessageDialog(mf, "Το όνομα χρήστη ή ο κωδικός δεν είναι σωστός", "Σφάλμα σύνδεσης", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
} catch (SQLException ex) {
Logger.getLogger(GUIFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
return -1;
}
public static int checkSignInInfo(MainFrame mf, ArrayList<Customer> customerList) {
DatabaseConnection db = Database.connection();
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
if (languageName.equals("English")) {
if ((mf.getNameField().getText().isEmpty() || mf.getNameField().getText().isBlank()) || (mf.getSurnameField().getText().isEmpty() || mf.getSurnameField().getText().isBlank())
|| mf.getAgeSpinner().getValue().equals(0) || (mf.getUsernameField2().getText().isEmpty() || mf.getUsernameField2().getText().isBlank())
|| mf.getPasswordField2().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Complete all the fields first\nand make sure you pick a valid age", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getUsernameField2().getText().contains(" ") || GUIUtils.checkSpecialChars(mf.getUsernameField2().getText())) {
JOptionPane.showMessageDialog(mf, "Your username must not contain white spaces and these symbols:\n!,@,#,$,%,^,&,*,(,)", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getPasswordField2().getPassword().length < 5) {
JOptionPane.showMessageDialog(mf, "Your password must be at least 5 at size", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (!GUIUtils.checkNums(GUIUtils.charArrayToString(mf.getPasswordField2().getPassword()))) {
JOptionPane.showMessageDialog(mf, "Your password must contain at least one number", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if ((Integer) mf.getAgeSpinner().getValue() < 18) {
JOptionPane.showMessageDialog(mf, "You must be at least 18 years old\nto become a customer", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
boolean found = false;
for (int i = 0; i < customerList.size(); i++) {
if (mf.getUsernameField2().getText().equals(customerList.get(i).getAcc().getUsername())) {
found = true;
break;
}
}
for (int i = 0; i < 10; i++) {
if ((Integer) mf.getAgeSpinner().getValue() > 18 && GUIUtils.checkSignInPassword(mf.getPasswordField2().getPassword(), customerList, i) == 1) {
if (!found) {
customerList.add(new Customer());
Utils.generateID(customerList, customerList.size() - 1);
// Add customer info
String[] customerInfo = new String[4];
customerInfo[0] = customerList.get(customerList.size() - 1).getAcc().getId();
customerInfo[1] = mf.getNameField().getText();
customerInfo[2] = mf.getSurnameField().getText();
Object age = (Object) mf.getAgeSpinner().getValue();
customerInfo[3] = age.toString();
// Add account info
customerList.get(customerList.size() - 1).getAcc().setUsername(mf.getUsernameField2().getText());
customerList.get(customerList.size() - 1).getAcc().setPassword(GUIUtils.charArrayToString(mf.getPasswordField2().getPassword()));
customerList.get(customerList.size() - 1).getAcc().setBalance(0.0);
customerList.get(customerList.size() - 1).addInfo(customerInfo);
try {
db.close();
DBMethods.insertCustomer(customerList, customerList.size() - 1);
DBMethods.insertCustomerAcc(customerList, customerList.size() - 1);
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
return 1;
} else {
JOptionPane.showMessageDialog(mf, "This username has already been taken", "Sign In Error", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
}
}
db.close();
return -1;
} else if (languageName.equals("Greek")) {
if ((mf.getNameField().getText().isEmpty() || mf.getNameField().getText().isBlank()) || (mf.getSurnameField().getText().isEmpty() || mf.getSurnameField().getText().isBlank())
|| mf.getAgeSpinner().getValue().equals(0) || (mf.getUsernameField2().getText().isEmpty() || mf.getUsernameField2().getText().isBlank())
|| mf.getPasswordField2().getPassword().length == 0) {
JOptionPane.showMessageDialog(mf, "Συμπληρώστε πρώτα όλα τα πεδία\nκαι βεβαιωθείτε ότι θα επιλέξετε επιτρέψιμη ηλικία", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getUsernameField2().getText().contains(" ") || GUIUtils.checkSpecialChars(mf.getUsernameField2().getText())) {
JOptionPane.showMessageDialog(mf, "Το όνομα χρήστη σου δεν πρέπει να περιέχει κενά και τα ακόλουθα σύμβολα:\n!,@,#,$,%,^,&,*,(,)", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (mf.getPasswordField2().getPassword().length < 5) {
JOptionPane.showMessageDialog(mf, "Ο κωδικός σου πρέπει να έχει τουλάχιστον 5 αλφαριθμητικούς χαρακτήρες σε μέγεθος", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if (!GUIUtils.checkNums(GUIUtils.charArrayToString(mf.getPasswordField2().getPassword()))) {
JOptionPane.showMessageDialog(mf, "Ο κωδικός σου πρέπει να περιέχει τουλάχιστον έναν αριθμό", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
if ((Integer) mf.getAgeSpinner().getValue() < 18) {
JOptionPane.showMessageDialog(mf, "Πρέπει να είσαι τουλάχιστον 18 χρονών\nγια να γίνεις πελάτης", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
boolean found = false;
for (int i = 0; i < customerList.size(); i++) {
if (mf.getUsernameField2().getText().equals(customerList.get(i).getAcc().getUsername())) {
found = true;
break;
}
}
for (int i = 0; i < 10; i++) {
if ((Integer) mf.getAgeSpinner().getValue() > 18 && GUIUtils.checkSignInPassword(mf.getPasswordField2().getPassword(), customerList, i) == 1) {
if (!found) {
customerList.add(new Customer());
Utils.generateID(customerList, customerList.size() - 1);
// Add customer info
String[] customerInfo = new String[4];
customerInfo[0] = customerList.get(customerList.size() - 1).getAcc().getId();
customerInfo[1] = mf.getNameField().getText();
customerInfo[2] = mf.getSurnameField().getText();
Object age = (Object) mf.getAgeSpinner().getValue();
customerInfo[3] = age.toString();
// Add account info
customerList.get(customerList.size() - 1).getAcc().setUsername(mf.getUsernameField2().getText());
customerList.get(customerList.size() - 1).getAcc().setPassword(GUIUtils.charArrayToString(mf.getPasswordField2().getPassword()));
customerList.get(customerList.size() - 1).getAcc().setBalance(0.0);
customerList.get(customerList.size() - 1).addInfo(customerInfo);
try {
db.close();
DBMethods.insertCustomer(customerList, customerList.size() - 1);
DBMethods.insertCustomerAcc(customerList, customerList.size() - 1);
} catch (SQLException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
return 1;
} else {
JOptionPane.showMessageDialog(mf, "Αυτό το όνομα χρήστη υπάρχει ήδη", "Σφάλμα εγγραφής", JOptionPane.ERROR_MESSAGE);
db.close();
return -1;
}
}
}
db.close();
return -1;
}
} catch (SQLException ex) {
Logger.getLogger(GUIFunctions.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
return -1;
}
public static ThemeCollection getThemes() {
ThemeCollection themeCollection = new ThemeCollection();
themeCollection.loadThemes(new File(System.getProperty("user.dir").replaceAll(Pattern.quote("\\"), "/") + "/themes/"));
return themeCollection;
}
public static Theme setupFrame(JFrame frame, String title) {
DatabaseConnection db = Database.connection();
Theme theme = null;
if (frame instanceof ServicesFrame) {
frame.setTitle(title);
}
// Center frame
frame.pack();
frame.setLocationRelativeTo(null);
// Theme setup
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Theme").from("Settings").build());
rs.next();
String themeName = rs.getString(1);
ThemeCollection themes = getThemes();
theme = themes.matchTheme(themeName);
ThemeCollection.applyTheme(frame, theme);
} catch (SQLException ex) {
Logger.getLogger(SettingsFrame.class.getName()).log(Level.SEVERE, null, ex);
}
if (theme == null) {
System.out.println("Theme is null");
theme = new Theme(new YamlFile(System.getProperty("user.dir").replaceAll(Pattern.quote("\\"), "/") + "/themes/"));
ThemeCollection.applyTheme(frame, theme);
}
// Language Setup
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
if (languageName.equals("English")) {
GUIFunctions.setTexts(frame, Locale.US);
} else if (languageName.equals("Greek")) {
GUIFunctions.setTexts(frame, Locale.of("el", "GR"));
}
ThemeCollection.applyTheme(frame, theme);
} catch (SQLException ex) {
Logger.getLogger(SettingsFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
return theme;
}
public static void setTexts(JFrame frame, Locale locale) {
ResourceBundle rb = ResourceBundle.getBundle("i18n/Bundle", locale);
if (frame instanceof SettingsFrame settingsFrame) {
setSettingsFrameTexts(settingsFrame, rb);
return;
}
if (frame instanceof ChangePasswordFrame cpf) {
setChangePasswordFrameTexts(cpf, rb);
return;
}
if (frame instanceof ServicesFrame servicesFrame) {
setServicesFrameTexts(servicesFrame, rb);
return;
}
if (frame instanceof DepositFrame df) {
setDepositFrameTexts(df, rb);
return;
}
if (frame instanceof MainFrame mf) {
setMainFrameTexts(mf, rb);
return;
}
if (frame instanceof ForgotPasswordFrame fpf) {
setForgotPasswordFrameTexts(fpf, rb);
return;
}
if (frame instanceof AboutFrame af) {
setAboutFrameTexts(af, rb);
}
}
public static void setSettingsFrameTexts(SettingsFrame sf, ResourceBundle rb) {
sf.setTitle(rb.getString("sf_title"));
sf.getGeneralLabel().setText(rb.getString("general"));
sf.getLanguageLabel().setText(rb.getString("language"));
sf.getAppearanceLabel().setText(rb.getString("appearance"));
sf.getThemesLabel().setText(rb.getString("themes"));
sf.getSecurityLabel().setText(rb.getString("security"));
sf.getChangePwBtn().setText(rb.getString("change_password"));
sf.getAboutBtn().setText(rb.getString("about"));
}
public static void setChangePasswordFrameTexts(ChangePasswordFrame cpf, ResourceBundle rb) {
cpf.setTitle(rb.getString("cpf_title"));
cpf.getOldPasswordIndicator().setText(rb.getString("old_password"));
cpf.getNewPasswordIndicator().setText(rb.getString("new_password"));
cpf.getConfirmNewPasswordIndicator().setText(rb.getString("confirm_password"));
cpf.getApplyBtn().setText(rb.getString("apply"));
cpf.getCancelBtn().setText(rb.getString("cancel"));
}
public static void setServicesFrameTexts(ServicesFrame sf, ResourceBundle rb) {
sf.getMainMenuLabel().setText(rb.getString("main_menu"));
sf.getAccInfoBtn().setText(rb.getString("acc_information"));
sf.getDepBtn().setText(rb.getString("deposit"));
sf.getDelBtn().setText(rb.getString("delete"));
sf.getLogoutBtn().setText(rb.getString("logout"));
sf.getCustomerInfoLabel().setText(rb.getString("customer_info"));
sf.getNameIndicator().setText(rb.getString("name"));
sf.getSurnameIndicator().setText(rb.getString("surname"));
sf.getAgeIndicator().setText(rb.getString("age"));
sf.getAccountInfoLabel().setText(rb.getString("acc_info"));
sf.getUsernameIndicator().setText(rb.getString("username"));
sf.getBalanceIndicator().setText(rb.getString("balance"));
sf.getUploadImgBtn().setText(rb.getString("upload_img"));
sf.getRefreshBtn().setText(rb.getString("refresh"));
sf.getSettingsBtn().setText(rb.getString("settings"));
}
public static void setDepositFrameTexts(DepositFrame df, ResourceBundle rb) {
df.setTitle(rb.getString("df_title"));
df.getDepositLabel().setText(rb.getString("deposit_indicator"));
df.getApplyBtn().setText(rb.getString("apply"));
df.getCancelBtn().setText(rb.getString("cancel"));
}
public static void setMainFrameTexts(MainFrame mf, ResourceBundle rb) {
mf.setTitle(rb.getString("mf_title"));
mf.getInfoLabel().setText(rb.getString("info"));
mf.getLoginBtn().setText(rb.getString("login"));
mf.getUsernameLabel().setText(rb.getString("username"));
mf.getPasswordLabel().setText(rb.getString("password"));
mf.getForgotPwLabel().setText(rb.getString("forgot_pw"));
mf.getOkBtn1().setText(rb.getString("ok"));
mf.getSignInBtn().setText(rb.getString("sign_in"));
mf.getNameLabel().setText(rb.getString("name"));
mf.getSurnameLabel().setText(rb.getString("surname"));
mf.getAgeLabel().setText(rb.getString("age"));
mf.getUsernameLabel2().setText(rb.getString("username"));
mf.getPasswordLabel2().setText(rb.getString("password"));
mf.getOkBtn2().setText(rb.getString("ok"));
}
public static void setForgotPasswordFrameTexts(ForgotPasswordFrame fpf, ResourceBundle rb) {
fpf.setTitle(rb.getString("fpf_title"));
fpf.getUsernameIndicator().setText(rb.getString("username_indicator"));
fpf.getNewPasswordIndicator().setText(rb.getString("new_password"));
fpf.getConfirmNewPasswordIndicator().setText(rb.getString("confirm_password"));
fpf.getApplyBtn().setText(rb.getString("apply"));
fpf.getCancelBtn().setText(rb.getString("cancel"));
}
public static void setAboutFrameTexts(AboutFrame af, ResourceBundle rb) {
af.setTitle(rb.getString("af_title"));
af.getSynopsisLabel().setText(rb.getString("synopsis"));
af.getSynopsisTextArea().setText(rb.getString("synopsis_text"));
af.getSynopsisTextArea().setCaretPosition(0);
af.getLicenceLabel().setText(rb.getString("licence"));
af.getMadeByLabel().setText(rb.getString("made_by"));
af.getOwnerLabel().setText(rb.getString("owner"));
}
}
| ThanasisGeorg/Bank-Manager | src/main/java/GUI/GUIFunctions.java |
1,484 | package jukebox.jukebox;
public class JukeBox {
public static void main(String[] args) throws InterruptedException {
if (args.length == 0) { // αν ο χρήστης δεν πέρασε ορίσματα απλά τρέξε το gui
Window window = new Window(); // δημιουργεί το παράθυρο
try { // κάνει τα κουμπιά πιο καλαίσθητα
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Window.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
java.awt.EventQueue.invokeLater(new Runnable() {
@Override
public void run() { // τρέχει την εφαρμογή
window.setVisible(true); // κάνει το παράθυρο ορατό
}
});
}
else {
checkArguments JukeBox = new checkArguments(2); // Δημιουργεί νέo αντικείμενο JukeBox που είναι στιγμιότυπο της κλάσης checkArguments και θέτει NumbOfArg = 2 που αποτελεί το ἀνω ὀριο στην checkArgNumb)
if (!JukeBox.checkArgNumb(args.length)) { // Αν (είναι true ότι) ἐχει λιγότερο ἀπο 1 argument ή περισσότερα απο 2 (NumbOfArg) arguments
System.out.println(">>> Argument requirement not met"); // Κάνει print στο τερματικό την φράση ">>> Argument requirement not met"
System.exit(1); // Κάνει exit με αποτυχία
}
Song song = new Song(args[0]); // Δημιουργεί νέο αντικείμενο song που είναι στιγμιότυπο της κλάσης Song και παίρνει σαν όρισμα το 1ο argument που δίνει ο χρήστης (ανοίγει ο player)
if (args.length == 1) { // Αν το πλήθος των arguments ισούται με 1
if (JukeBox.checkFileType(args[0])) { // Αν (είναι true ότι) το 1ο argument που δίνει ο χρήστης πρόκειται για mp3 αρχείο
song.play(args[0]); // Καλεί την μέθοδο play της κλάσης Song με παράμετρο το 1ο argument που δίνει ο χρήστης (παίζει το τραγούδι)
}
else if (JukeBox.checkListType(args[0])) { // Αλλιώς αν (είναι true ότι) το 1ο argument που δίνει ο χρήστης πρόκειται για m3u λίστα
song.order(); // Καλεί την μέθοδο order της κλάσης Song χωρίς παραμέτρους (παίζει τα τραγούδια της λίστας με τη σειρά που γράφονται)
}
else { // Αλλιώς (αν δεν είναι τίποτα απ' τα δύο)
System.out.println(">>> File not supported"); // Κάνει print στο τερματικό την φράση ">>> File not supported"
}
}
else { // Αλλιώς (πλήθος των arguments διάφορο του 1, δηλαδή έχουμε 2 arguments)
if (JukeBox.checkFileType(args[0])) { // Αν (είναι true ότι) το 1ο argument που δίνει ο χρήστης πρόκειται για mp3 αρχείο
if (JukeBox.checkStrat(args[1]).equals("loop")) { // Αν (είναι true ότι) το 2ο argument που δίνει ο χρήστης ισούται με την στρατηγική "loop"
song.loop(); // Καλεί την μέθοδο loop της κλάσης Song χωρίς παραμέτρους (παίζει το τραγούδι κατ' επανάληψη)
}
else { // Αλλιώς (για οποιαδήποτε άλλη στρατηγική)
JukeBox.other(args[1], args[0]); // Καλεί την μέθοδο other της κλάσης checkArguments και δίνει ως παραμέτρους το 2ο argument του χρήστη ως StratInput και το 1ο argument ως Input
}
}
else if (JukeBox.checkListType(args[0])) { // Αλλιώς αν (είναι true ότι) το 1ο argument που δίνει ο χρήστης πρόκειται για m3u λίστα
if (JukeBox.checkStrat(args[1]).equals("random")) { // Αν (είναι true ότι) το 2ο argument που δίνει ο χρήστης ισούται με την στρατηγική "random"
song.random(); // Καλεί την μέθοδο random της κλάσης Song χωρίς παραμέτρους (παίζει τα τραγούδια της λίστας με τυχαία σειρά)
}
else if (JukeBox.checkStrat(args[1]).equals("order")) { // Αλλιώς αν (είναι true ότι) το 2ο argument που δίνει ο χρήστης ισούται με την στρατηγική "order"
song.order(); // Καλεί την μέθοδο order της κλάσης Song χωρίς παραμέτρους (παίζει τα τραγούδια της λίστας με τη σειρά που γράφονται)
}
else if (JukeBox.checkStrat(args[1]).equals("loop")) { // Αλλιώς αν (είναι true ότι) το 2ο argument που δίνει ο χρήστης ισούται με την στρατηγική "loop"
song.loop(); // Καλεί την μέθοδο loop της κλάσης Song χωρίς παραμέτρους (παίζει τη λίστα κατ' επανάληψη)
}
else { // Αλλιώς (για οποιαδήποτε άλλη στρατηγική)
JukeBox.other(args[1], args[0]); // Καλεί την μέθοδο other της κλάσης checkArguments και δίνει ως παραμέτρους το 2ο argument του χρήστη ως StratInput και το 1ο argument ως Input
}
}
else { // Αλλιώς (1ο argument ούτε mp3 αρχείο ούτε m3u λίστα)
System.out.println(">>> File not supported"); // Κάνει print στο τερματικό την φράση ">>> File not supported"
}
}
song.closePlayer(); // Καλεί την μέθοδο closePlayer της κλάσης Song χωρίς παραμέτρους (κλείνει ο player)
}
}
}
| VasileiosKokki/Jukebox_University | JukeBox2/src/main/java/jukebox/jukebox/JukeBox.java |
1,486 | package com.example.skinhealthchecker;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by chief on 2/4/2017.
*
* Το κομμάτι αυτό του κώδικα αφορά τον διαχειρηστή της βάσης δεδομένων.
* Περιέχει κώδικα για την αρχικοποίηση δημιουργεία τραπεζιών
* εισαγωγή-ανανέωση- διαγραφή γραμμών και ότι άλλο είναι σχετικό με την βάση.
*
* Περιέχονται 3 κύρια tables :
* Moles -> αφορά τα moles
* Profil->αφορά τα προφίλ
* Def-> αφορά τις πληροφορίες που πρέπει να διαθέτει- αποθηκευει η εφαρμογή.
*
* * This piece of code refers to the database handler.
* Contains code for initializing table creations
* insertion-refresh-deletion of rows and another is relative staff to the base.
*
* 3 main tables are included:
Moles ->refers to Moles
* Profile->refers to Profiles
* Def-> refers to the information it needs to store - the application stores.
*/
public class DatabaseHandler extends SQLiteOpenHelper {
//String FILENAME = "";
// DatabaseHandler db;//possibly use asynctask
//String sQuery = "";
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 9;
// Database Name
private static final String DATABASE_NAME = "Mole";
// Contacts table name
private static final String TABLE_CONTACTS = "Moles";
private static final String TABLE_DEF = "Def";
private static final String TABLE_PROFIL = "PROFIL";
// Contacts Table Columns names
public static final String Mole = "Mole";//First table name
public static final String ID = "ID";
public static final String NAME = "NAME";
public static final String AGE = "AGE";
public static final String ITCH = "ITCH";
public static final String ISHARD = "ISHARD";
public static final String HASBLOD = "HASBLOD";
public static final String ISBAD = "ISBAD";
public static final String DLD = "DLD";
public static final String INPAIN = "INPAIN";
public static final String SEX = "SEX";
public static final String REALWIDTH = "REALWIDTH";
public static final String REALHEIGHT = "REALHEIGHT";
public static final String EDGESPROBLEM = "EDGESPROBLEM";
public static final String COLORPROBLEM = "COLORPROBLEM";
public static final String EDGESSIMILATIRY = "EDGESSIMILATIRY";
public static final String HISTORY = "HISTORY";
public static final String EVOLVING = "EVOLVING";
public static final String MORFOLOGY1 = "MORFOLOGY1";
public static final String MORFOLOGY2 = "MORFOLOGY2";
public static final String DIAMETER = "DIAMETER";
public static final String PHOTO = "PHOTO";
public static final String IDM = "IDM";
public static final String PIDCOUnt="PIDC";
public static final String PID = "PID";
public static final String profilname ="PROFILNAME" ;
public static final String name ="NAME" ;
public static final String age ="AGE";
public static final String mail="MAIL" ;
public static final String phone ="PHONE";
public static final String sex="SEX";
public static final String history="HISTORY";
public static final String LANG="LANG";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ ID + " INTEGER PRIMARY KEY," + NAME + " TEXT,"
+ ITCH + " NUMERIC," + ISHARD + " NUMERIC," + HASBLOD + " NUMERIC," + INPAIN + " NUMERIC," +
REALWIDTH + " REAL," + REALHEIGHT + " REAL," + EDGESPROBLEM + " NUMERIC," +
COLORPROBLEM + " INTEGER," + EDGESSIMILATIRY + " NUMERIC," +MORFOLOGY1 + " BLOB," +MORFOLOGY2
+ " BLOB," + DIAMETER + " REAL," + PHOTO + " TEXT," +ISBAD +" NUMERIC," + PID +" NUMERIC,"+ DLD +" NUMERIC," + EVOLVING
+" NUMERIC" +")";
db.execSQL(CREATE_CONTACTS_TABLE);
String CREATE_CONTACTS_TABLE2 = "CREATE TABLE " + TABLE_DEF + "("
+ ID + " INTEGER PRIMARY KEY," + IDM +" INTEGER, "+PID +" INTEGER, "+ LANG + " NUMERIC,"+ PIDCOUnt +" INTEGER "+ ")";
db.execSQL(CREATE_CONTACTS_TABLE2);
Configurations mole = new Configurations();
ContentValues cv = new ContentValues();
cv.put(ID, Integer.toString(1));
// cv.put(AGE, Integer.toString( 0));
// cv.put(SEX, "Γυναίκα");
// cv.put(HISTORY, Boolean.toString(false));
cv.put(IDM,String.valueOf(1000)); // starting value of id
cv.put(PID,String.valueOf(0));
cv.put(LANG,Boolean.toString(false));
cv.put(PIDCOUnt,String.valueOf(0));
Log.d("SQLlite","created");
long rowID = db.insertOrThrow(TABLE_DEF, null, cv);
String CREATE_CONTACTS_TABLE3 = "CREATE TABLE " + TABLE_PROFIL + "("
+ PID + " INTEGER PRIMARY KEY," + AGE + " INTEGER,"+ SEX + " TEXT," +HISTORY + " NUMERIC," + profilname +" TEXT ,"
+ name +" TEXT ,"+ mail +" TEXT, "+ phone +" TEXT "+ ")";
db.execSQL(CREATE_CONTACTS_TABLE3);
Profile prof = new Profile();
ContentValues cv2 = new ContentValues();
cv2.put(PID, Integer.toString(0));
cv2.put(profilname, "DEFAULT");// creates default profile
cv2.put(AGE, Integer.toString( 0));
cv2.put(SEX, "Γυναίκα");
cv2.put(HISTORY, Boolean.toString(false));
cv2.put(name,"DEFAULT");
cv2.put(mail,"[email protected]");
cv2.put(phone,"phone");
Log.d("SQLlite","created");
long rowID2 = db.insertOrThrow(TABLE_PROFIL, null, cv2);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DEF);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PROFIL);
// Create tables again
onCreate(db);
}
// + PID + " INTEGER PRIMARY KEY," + AGE + " INTEGER,"+ SEX + " TEXT," +HISTORY + " NUMERIC," + profilname +" TEXT "
// + name +" TEXT "+ mail +" TEXT "+ phone +" TEXT "+ ")";
//
//adding a new profile
public void addprofile(Profile mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PID, Integer.toString(mole.GetIdM()));
values.put(AGE,Integer.toString( mole.GetAge()));
values.put(SEX, mole.GetSex());
values.put(HISTORY, Boolean.toString(mole.GetHistory()));
values.put(profilname, mole.GetProfilname());
values.put(name, mole.GetName());
values.put(mail, mole.GetMail());
values.put(phone, mole.GetPhone());
// Inserting Row
db.insert(TABLE_PROFIL, null, values);
db.close(); // Closing database connection
}
// Adding new mole
public void addMole(Mole mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, Integer.toString(mole.GetId()));
values.put(NAME, mole.GetName());
//values.put(AGE,Integer.toString( mole.GetAge()));
values.put(ITCH, Boolean.toString(mole.GetHasItch()));
values.put(ISHARD, Boolean.toString(mole.GetIsHard()));
values.put(HASBLOD, Boolean.toString(mole.GetHasBlood()));
values.put(INPAIN, Boolean.toString( mole.GetInPain()));
// values.put(SEX, mole.GetGender());
values.put(REALWIDTH, Double.toString(mole.GetWidth()));
values.put(REALHEIGHT,Double.toString( mole.Getheight()));
values.put(EDGESPROBLEM, Boolean.toString(mole.GetBadBorder()));
values.put(COLORPROBLEM,Double.toString( mole.GetColorCurve()));
values.put(EDGESSIMILATIRY,Boolean.toString( mole.GetHasAsymmetry()));
values.put(MORFOLOGY1, mole.GetMorfologyAr1());
values.put(MORFOLOGY2, mole.GetMorfologyAr2());
values.put(DIAMETER, Double.toString(mole.GetDiameter()));
values.put(PHOTO, mole.GetMole());
// values.put(HISTORY, Boolean.toString(mole.GetBadHistory()));
values.put(ISBAD, Boolean.toString( mole.GetIsbad()));
values.put(PID, Integer.toString(mole.GetPID()));
values.put(DLD, Boolean.toString(mole.GetDLD()));
values.put(EVOLVING, Boolean.toString(false));
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
//adding def row <--- this function never used
public void addDef(Configurations mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, Integer.toString(1));
// values.put(AGE, Integer.toString( mole.GetAge()));
// values.put(SEX, mole.GetGender());
// values.put(HISTORY, Boolean.toString(mole.GetHistory()));
values.put(IDM, Integer.toString(mole.GetIdM()));
values.put(PID, Integer.toString(mole.GetPID()));
values.put(LANG, Boolean.toString(mole.GetLanguage()));
values.put(PIDCOUnt,Integer.toString(mole.GetPIDCOUnt()));
// Inserting Row
db.insert(TABLE_DEF, null, values);
db.close(); // Closing database connection
}
// Getting single mole
public Mole getMole(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { ID, NAME, ITCH, ISHARD ,HASBLOD, INPAIN, REALWIDTH,
REALHEIGHT, EDGESPROBLEM, COLORPROBLEM ,EDGESSIMILATIRY ,MORFOLOGY1, MORFOLOGY2, DIAMETER, PHOTO ,ISBAD,PID,DLD,EVOLVING}, ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
// ID NAME AGE ITCH ISHARD HASBLOD INPAIN SEX REALWIDTH REALHEIGHT EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO
//Mole mole = new Mole(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
Mole mole1 = new Mole(
Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
// Integer.parseInt(cursor.getString(2)),
Boolean.parseBoolean(cursor.getString(2)),
Boolean.parseBoolean(cursor.getString(3)),
Boolean.parseBoolean(cursor.getString(4)),
Boolean.parseBoolean(cursor.getString(5)),
// cursor.getString(7),
Double.parseDouble(cursor.getString(6)),
Double.parseDouble(cursor.getString(7)),
Boolean.parseBoolean(cursor.getString(8)),
Double.parseDouble(cursor.getString(9)),
Boolean.parseBoolean(cursor.getString(10)),
// Boolean.parseBoolean(cursor.getString(13)),
cursor.getString(11),
cursor.getString(12),
Double.parseDouble(cursor.getString(13)),
cursor.getString(14),
Boolean.parseBoolean(cursor.getString(15)),
Integer.parseInt(cursor.getString(16)),
Boolean.parseBoolean(cursor.getString(17)),
Boolean.parseBoolean(cursor.getString(18))
);
// return contact
return mole1;
}
// getting a single profile by using id
// + PID + " INTEGER PRIMARY KEY," + AGE + " INTEGER,"+ SEX + " TEXT," +HISTORY + " NUMERIC," + profilname +" TEXT "
// + name +" TEXT "+ mail +" TEXT "+ phone +" TEXT "+ ")";
public Profile getProfile(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_PROFIL, new String[] { PID, AGE, SEX, HISTORY, profilname ,name, mail, phone}, PID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
Profile mole1 = new Profile(
Integer.parseInt(cursor.getString(0)),
Integer.parseInt(cursor.getString(1)),
cursor.getString(2),
Boolean.parseBoolean(cursor.getString(3)),
cursor.getString(4) ,
cursor.getString(5) ,
cursor.getString(6) ,
cursor.getString(7)
);
// return contact
return mole1;
}
// geting the app's configurations
public Configurations getDEf() {
int id=1;
SQLiteDatabase db = this.getReadableDatabase();
// Cursor cursor = db.query(TABLE_DEF, new String[] { ID, AGE, SEX,HISTORY ,IDM}, ID + "=?",
Cursor cursor = db.query(TABLE_DEF, new String[] { ID, IDM , PID,LANG ,PIDCOUnt}, ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null );
if (cursor != null)
cursor.moveToFirst();
// ID NAME AGE ITCH ISHARD INPAIN SEX REALWIDTH REALHEIGHT EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO
//Mole mole = new Mole(Integer.parseInt(cursor.getString(0)),cursor.getString(1), cursor.getString(2));
Configurations mole1 = new Configurations(
// Integer.parseInt(cursor.getString(1)),
// cursor.getString(2),
// Boolean.parseBoolean(cursor.getString(3)),
Integer.parseInt(cursor.getString(1)),
Integer.parseInt(cursor.getString(2)),
Boolean.parseBoolean(cursor.getString(3)),
Integer.parseInt(cursor.getString(4))
);
// return contact
return mole1;
}
// Getting All Moles -> return a list filled with moles
public List<Mole> getAllMoles() {
List<Mole> contactList = new ArrayList<Mole>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to lis
// ID NAME AGE ITCH ISHARD INPAIN SEX REALWIDTH REALHEIGHT EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO
if (cursor.moveToFirst()) {
do {
Mole mole = new Mole();
mole.SetId( Integer.parseInt(cursor.getString(0)) );
mole.SetName(cursor.getString(1));
// mole.SetAge(Integer.parseInt(cursor.getString(2)));
mole.SetHasItch(Boolean.parseBoolean(cursor.getString(2)));
mole.SetIsHard(Boolean.parseBoolean(cursor.getString(3)));
mole.SetHasBlood(Boolean.parseBoolean(cursor.getString(4)));
mole.SetInPain(Boolean.parseBoolean(cursor.getString(5)));
// mole.SetGender( cursor.getString(7));
mole.SetWidth( Double.parseDouble(cursor.getString(6)));
mole.SetHeight( Double.parseDouble(cursor.getString(7)));
mole.SetBadBorder(Boolean.parseBoolean(cursor.getString(8)));
mole.SetColorCurve(Double.parseDouble(cursor.getString(9)));
mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(10)));
// mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(11)));
mole.SetMorfologyAr( cursor.getString(11),cursor.getString(12));
mole.SetDiameter(Double.parseDouble(cursor.getString(13)));
mole.SetMole(cursor.getString(14));
mole.SetIsbad(Boolean.parseBoolean(cursor.getString(15)));
mole.SetPID( Integer.parseInt(cursor.getString(16)) );
mole.SetDLD( Boolean.parseBoolean(cursor.getString(17)) );
mole.SetEvolving( Boolean.parseBoolean(cursor.getString(18)) );
Log.d("hard",Boolean.toString(mole.GetIsbad()));
Log.d("is",String.valueOf(mole.GetId()));
// Adding contact to list
contactList.add(mole);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
///Getting All Profiles -> return a list filled with Profiles
public List<Profile> getAllProfiles() {
List<Profile> contactList = new ArrayList<Profile>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_PROFIL;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// + PID + " INTEGER PRIMARY KEY," + AGE + " INTEGER,"+ SEX + " TEXT," +HISTORY + " NUMERIC," + profilname +" TEXT "
// + name +" TEXT "+ mail +" TEXT "+ phone +" TEXT "+ ")";
if (cursor.moveToFirst()) {
do {
Profile mole = new Profile();
mole.SetIdM( Integer.parseInt(cursor.getString(0)) );
mole.SetAge(Integer.parseInt(cursor.getString(1)));
mole.SetSex(cursor.getString(2));
mole.SetHistory(Boolean.parseBoolean(cursor.getString(3)));
mole.SetProfilname(cursor.getString(4));
mole.SetName(cursor.getString(5));
mole.SetMail(cursor.getString(6));
mole.SetPhone( cursor.getString(7));
// Log.d("hard",Boolean.toString(mole.GetIsbad()));
// Log.d("is",String.valueOf(mole.GetId()));
// Adding contact to list
contactList.add(mole);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Getting Moles Count
public int getMolesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int retu =cursor.getCount();
cursor.close();
// return count
return retu;
}
// Getting Profiles Count
public int getProfileCount() {
String countQuery = "SELECT * FROM " + TABLE_PROFIL;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int retu =cursor.getCount();
cursor.close();
// return count
return retu;
}
// Updating single mole
public int updateMole(Mole mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, Integer.toString(mole.GetId()));
values.put(NAME, mole.GetName());
// values.put(AGE,Integer.toString( mole.GetAge()));
values.put(ITCH, Boolean.toString(mole.GetHasItch()));
values.put(ISHARD, Boolean.toString(mole.GetIsHard()));
values.put(HASBLOD, Boolean.toString(mole.GetHasBlood()));
values.put(INPAIN, Boolean.toString( mole.GetInPain()));
// values.put(SEX, mole.GetGender());
values.put(REALWIDTH, Double.toString(mole.GetWidth()));
values.put(REALHEIGHT,Double.toString( mole.Getheight()));
values.put(EDGESPROBLEM, Boolean.toString(mole.GetBadBorder()));
values.put(COLORPROBLEM,Double.toString( mole.GetColorCurve()));
values.put(EDGESSIMILATIRY,Boolean.toString( mole.GetHasAsymmetry()));
values.put(MORFOLOGY1, mole.GetMorfologyAr1());
values.put(MORFOLOGY2, mole.GetMorfologyAr2());
values.put(DIAMETER, Double.toString(mole.GetDiameter()));
values.put(PHOTO, mole.GetMole());
values.put(PID, Integer.toString(mole.GetPID()));
values.put(EVOLVING, Boolean.toString(mole.GetEvolving()));
Log.d("inupdatemole",Boolean.toString(mole.GetDLD()));
values.put(DLD,Boolean.toString( mole.GetDLD()));
// values.put(HISTORY, Boolean.toString(mole.GetBadHistory()));
values.put(ISBAD, Boolean.toString(mole.GetIsbad()));
// updating row
return db.update(TABLE_CONTACTS, values, ID + " = ?",
new String[] { String.valueOf(mole.GetId()) });}
// Updating single profile
public int updateProfil(Profile mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
// values.put(PID, Integer.toString(mole.GetIdM()));
values.put(AGE,Integer.toString( mole.GetAge()));
values.put(SEX, mole.GetSex());
values.put(HISTORY, Boolean.toString(mole.GetHistory()));
values.put(profilname, mole.GetProfilname());
values.put(name, mole.GetName());
values.put(mail, mole.GetMail());
values.put(phone, mole.GetPhone());
// updating row
return db.update(TABLE_PROFIL, values, PID + " = ?",
new String[] { String.valueOf(mole.GetIdM()) });}
//updating apps Configurations
public int updateDef(Configurations mole) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(ID, Integer.toString(1));
//values.put(AGE, Integer.toString( mole.GetAge()));
// values.put(SEX, mole.GetGender());
// values.put(HISTORY, Boolean.toString(mole.GetHistory()));
values.put(IDM, Integer.toString(mole.GetIdM()));
values.put(PID, Integer.toString(mole.GetPID()));
values.put(LANG, Boolean.toString(mole.GetLanguage()));
values.put(PIDCOUnt, Integer.toString(mole.GetPIDCOUnt()));
// updating row
return db.update(TABLE_DEF, values, ID + " = ?",
new String[] { String.valueOf(1) });}
// Deleting single mole
public void deleteMole(Mole mole) {
File file = new File(mole.GetMole());
try {
boolean deleted = file.delete();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, ID + " = ?",
new String[] { String.valueOf(mole.GetId()) });
db.close();
}
// Getting All moles of selected profile. Gets as input a Profile and returns the list of moles of the profile
public List<Mole> getAllProfileMoles(Profile prof) {
List<Mole> contactList = new ArrayList<Mole>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS +" WHERE "+PID +" = " + Integer.toString(prof.GetIdM());
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to lis
// ID NAME AGE ITCH ISHARD INPAIN SEX REALWIDTH REALHEIGHT EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO
if (cursor.moveToFirst()) {
do {
Mole mole = new Mole();
mole.SetId( Integer.parseInt(cursor.getString(0)) );
mole.SetName(cursor.getString(1));
// mole.SetAge(Integer.parseInt(cursor.getString(2)));
mole.SetHasItch(Boolean.parseBoolean(cursor.getString(2)));
mole.SetIsHard(Boolean.parseBoolean(cursor.getString(3)));
mole.SetHasBlood(Boolean.parseBoolean(cursor.getString(4)));
mole.SetInPain(Boolean.parseBoolean(cursor.getString(5)));
// mole.SetGender( cursor.getString(7));
mole.SetWidth( Double.parseDouble(cursor.getString(6)));
mole.SetHeight( Double.parseDouble(cursor.getString(7)));
mole.SetBadBorder(Boolean.parseBoolean(cursor.getString(8)));
mole.SetColorCurve(Double.parseDouble(cursor.getString(9)));
mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(10)));
// mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(11)));
mole.SetMorfologyAr( cursor.getString(11),cursor.getString(12));
mole.SetDiameter(Double.parseDouble(cursor.getString(13)));
mole.SetMole(cursor.getString(14));
mole.SetIsbad(Boolean.parseBoolean(cursor.getString(15)));
mole.SetPID( Integer.parseInt(cursor.getString(16)));
mole.SetDLD( Boolean.parseBoolean(cursor.getString(17)));
mole.SetEvolving( Boolean.parseBoolean(cursor.getString(18)));
Log.d("hard",Boolean.toString(mole.GetIsbad()));
Log.d("is",String.valueOf(mole.GetId()));
// Adding contact to list
if (prof.GetIdM()==mole.GetPID())
contactList.add(mole);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Deleting All profiles moles . Gets as input a profile id and deletes its moles from the database
public void DeleteAllProfileMoles(int id) {
// List<Mole> contactList = new ArrayList<Mole>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to lis
// ID NAME AGE ITCH ISHARD INPAIN SEX REALWIDTH REALHEIGHT EDGESPROBLEM COLORPROBLEM EDGESSIMILATIRY MORFOLOGY1 MORFOLOGY2 DIAMETER PHOTO
if (cursor.moveToFirst()) {
do {
Mole mole = new Mole();
mole.SetId( Integer.parseInt(cursor.getString(0)) );
mole.SetName(cursor.getString(1));
// mole.SetAge(Integer.parseInt(cursor.getString(2)));
mole.SetHasItch(Boolean.parseBoolean(cursor.getString(2)));
mole.SetIsHard(Boolean.parseBoolean(cursor.getString(3)));
mole.SetHasBlood(Boolean.parseBoolean(cursor.getString(4)));
mole.SetInPain(Boolean.parseBoolean(cursor.getString(5)));
// mole.SetGender( cursor.getString(7));
mole.SetWidth( Double.parseDouble(cursor.getString(6)));
mole.SetHeight( Double.parseDouble(cursor.getString(7)));
mole.SetBadBorder(Boolean.parseBoolean(cursor.getString(8)));
mole.SetColorCurve(Double.parseDouble(cursor.getString(9)));
mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(10)));
// mole.SetHasAsymmetry(Boolean.parseBoolean(cursor.getString(11)));
mole.SetMorfologyAr( cursor.getString(11),cursor.getString(12));
mole.SetDiameter(Double.parseDouble(cursor.getString(13)));
mole.SetMole(cursor.getString(14));
mole.SetIsbad(Boolean.parseBoolean(cursor.getString(15)));
mole.SetPID( Integer.parseInt(cursor.getString(16)));
mole.SetDLD( Boolean.parseBoolean(cursor.getString(17)));
mole.SetEvolving( Boolean.parseBoolean(cursor.getString(18)));
Log.d("hard",Boolean.toString(mole.GetIsbad()));
Log.d("is",String.valueOf(mole.GetId()));
if (id==mole.GetPID()) {
deleteMole(mole);
File file = new File(mole.GetMole());
try {
boolean deleted = file.delete();
}
catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Adding contact to list
// contactList.add(mole);
} while (cursor.moveToNext());
}
// return contact list
// return contactList;
}
// deleting a profile. gets as input a Profile and deletes it
public void deleteProfile(Profile mole) {
/**
DeleteAllProfileMoles
**/DeleteAllProfileMoles(mole.GetIdM());
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_PROFIL, PID + " = ?",
new String[] { String.valueOf(mole.GetIdM()) });
db.close();
}
}
| litsakis/SkinHealthChecker | skinHealthChecker/src/main/java/com/example/skinhealthchecker/DatabaseHandler.java |
1,488 | /*
* copyright 2013-2021
* codebb.gr
* ProtoERP - Open source invocing program
* [email protected]
*/
/*
* Changelog
* =========
* 08/04/2021 (gmoralis) - Can't delete measureunit if it has reference elsewhere. Stored it as inactive
* 06/04/2021 (gmoralis) - Fixed confirm after validation
* 02/04/2021 (gmoralis) - Added delete action
* 01/04/2021 (gmoralis) - Added edit
* 01/04/2021 (gmoralis) - Added save new entry and confirm dialog before save
* 31/03/2021 (gmoralis) - Initial
*/
package gr.codebb.protoerp.tables.measurementUnits;
import gr.codebb.ctl.cbbTableView.CbbTableView;
import gr.codebb.ctl.cbbTableView.columns.CbbBooleanTableColumn;
import gr.codebb.ctl.cbbTableView.columns.CbbLongTableColumn;
import gr.codebb.ctl.cbbTableView.columns.CbbStringTableColumn;
import gr.codebb.ctl.cbbTableView.columns.CbbTableColumn;
import gr.codebb.lib.crud.AbstractListView;
import gr.codebb.lib.crud.annotation.ColumnProperty;
import gr.codebb.lib.database.GenericDao;
import gr.codebb.lib.database.PersistenceManager;
import gr.codebb.lib.util.AlertDlgHelper;
import gr.codebb.lib.util.AlertHelper;
import gr.codebb.lib.util.FxmlUtil;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
public class MeasurementUnitsListView extends AbstractListView implements Initializable {
@FXML private StackPane mainStackPane;
@FXML private Button refreshButton;
@FXML private Button newButton;
@FXML private Button openButton;
@FXML private Button deleteButton;
@FXML private CbbTableView<MeasurementUnitsEntity> measurementUnitsTable;
@ColumnProperty(prefWidth = "80.0d", align = ColumnProperty.Align.RIGHT)
private CbbTableColumn<MeasurementUnitsEntity, Long> columnId;
@ColumnProperty(prefWidth = "100.0d")
private CbbTableColumn<MeasurementUnitsEntity, Boolean> columnActive;
@ColumnProperty(prefWidth = "150.0d")
private CbbTableColumn<MeasurementUnitsEntity, String> columnDescription;
@ColumnProperty(prefWidth = "140.0d")
private CbbTableColumn<MeasurementUnitsEntity, String> columnShortName;
/** Initializes the controller class. */
@Override
public void initialize(URL url, ResourceBundle rb) {
columnId = new CbbLongTableColumn<>("Id");
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnDescription = new CbbStringTableColumn<>("Περιγραφή");
columnDescription.setCellValueFactory(new PropertyValueFactory<>("description"));
columnShortName = new CbbStringTableColumn<>("Συντ/φία");
columnShortName.setCellValueFactory(new PropertyValueFactory<>("shortName"));
columnActive = new CbbBooleanTableColumn<>("Ενεργή");
columnActive.setCellValueFactory(new PropertyValueFactory<>("active"));
measurementUnitsTable
.getColumns()
.addAll(columnId, columnActive, columnShortName, columnDescription);
init(this);
selectWithService();
measurementUnitsTable.setUserData("measurementUnitsTable"); // for use with savesettings
}
@FXML
private void refreshAction(ActionEvent event) {
selectWithService();
}
@FXML
private void newAction(ActionEvent event) {
FxmlUtil.LoadResult<MeasurementUnitsDetailView> getDetailView =
FxmlUtil.load("/fxml/tables/measurementUnits/MeasurementUnitsDetailView.fxml");
Alert alert =
AlertDlgHelper.saveDialog(
"Προσθήκη Μονάδας Μέτρησης",
getDetailView.getParent(),
mainStackPane.getScene().getWindow());
Button okbutton = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
okbutton.addEventFilter(
ActionEvent.ACTION,
(event1) -> {
if (!getDetailView.getController().validateControls()) {
event1.consume();
} else {
if (!(AlertHelper.saveConfirm(
getDetailView.getController().getMainStackPane().getScene().getWindow())
.get()
== ButtonType.OK)) {
event1.consume();
}
}
});
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if (getDetailView.getController() != null) {
getDetailView.getController().save();
selectWithService();
}
}
}
@FXML
protected void openAction(ActionEvent event) {
FxmlUtil.LoadResult<MeasurementUnitsDetailView> getDetailView =
FxmlUtil.load("/fxml/tables/measurementUnits/MeasurementUnitsDetailView.fxml");
Alert alert =
AlertDlgHelper.editDialog(
"Άνοιγμα/Επεξεργασία Μονάδας Μέτρησης",
getDetailView.getParent(),
mainStackPane.getScene().getWindow());
getDetailView
.getController()
.fillData(measurementUnitsTable.getSelectionModel().getSelectedItem());
Button okbutton = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
okbutton.addEventFilter(
ActionEvent.ACTION,
(event1) -> {
if (!getDetailView.getController().validateControls()) {
event1.consume();
} else {
if (!(AlertHelper.editConfirm(
getDetailView.getController().getMainStackPane().getScene().getWindow())
.get()
== ButtonType.OK)) {
event1.consume();
}
}
});
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if (getDetailView.getController() != null) {
getDetailView.getController().SaveEdit();
selectWithService();
}
}
}
@FXML
private void deleteAction(ActionEvent event) {
int row = measurementUnitsTable.getSelectionModel().getSelectedIndex();
measurementUnitsTable.getSelectionModel().select(row);
Optional<ButtonType> response =
AlertHelper.deleteConfirm(
measurementUnitsTable.getScene().getWindow(),
"Είστε σιγουροι ότι θέλετε να διαγράψετε την Μονάδα Μέτρησης : "
+ measurementUnitsTable.getSelectionModel().getSelectedItem().getDescription());
if (response.get() == ButtonType.OK) {
GenericDao gdao = new GenericDao(MeasurementUnitsEntity.class, PersistenceManager.getEmf());
try {
gdao.deleteEntity(measurementUnitsTable.getSelectionModel().getSelectedItem().getId());
} catch (Exception e) {
AlertHelper.errorDialog(
measurementUnitsTable.getScene().getWindow(),
"Η μονάδα μέτρησης δεν μπορεί να διαγραφεί γιατί υπάρχουν άλλες εγγραφές που την χρησιμοποιούν\nΑποθηκεύτηκε σαν ανενεργή");
MeasurementUnitsEntity k =
(MeasurementUnitsEntity)
gdao.findEntity(
measurementUnitsTable.getSelectionModel().getSelectedItem().getId());
k.setActive(false);
gdao.updateEntity(k);
}
selectWithService();
}
}
@Override
protected CbbTableView getTableView() {
return measurementUnitsTable;
}
@Override
protected List getMainQuery() {
return MeasurementUnitsQueries.getMeasurementsUnitsDatabase(false);
}
@Override
protected StackPane getMainStackPane() {
return mainStackPane;
}
@Override
protected Button getDeleteButton() {
return deleteButton;
}
@Override
protected Button getOpenButton() {
return openButton;
}
}
| georgemoralis/protoERP | src/main/java/gr/codebb/protoerp/tables/measurementUnits/MeasurementUnitsListView.java |
1,489 | import java.util.HashMap;
import java.util.Iterator;
/**
* Αυτή η κλάση αναπαριστά το χαρτοφυλάκιο (portfolio) ενός επενδυτή που αγοράζει ξένα νομίσματα με ευρώ.
* Το χαρτοφυλάκιο αποθηκεύει τις εντολές που δίνει ο επενδυτής για κάθε αγορά ξένου νομίσματος.
* Οι βασικές παράμετροι της κλάσης είναι ο τίτλος του χαρτοφυλακίου {@code portfolioTitle} και το χαρτοφυλάκιο
* μέσα στο οποίο καταγράφονται οι εντολές αγοράς ως ζεύγοι: <τύπος ξένου νομίσματος, ακέραιο ποσό σε ευρώ>, π.χ.
* <currencyΧ,3000> που σημαίνει ότι αγοράστηκε (επένδυση) ποσό ξένου νομίσματος currencyΧ αξίας 3000 ευρώ.
* Για κάθε τύπο ξένου νομίσματος υπάρχει μόνο μια καταχώρηση στο χαρτοφυλάκιο.
* <p>
* This class represents the portfolio of an investor who buys foreign currency exchange using euros.
* The portfolio registers the orders of the investor for each buying of foreign currency.
* The basic parameters of the class are the portfolio title {@code portfolioTitle} and the portfolio
* in which the buying orders are registered as pairs of: <currency type, integer amount of euros>,
* e.g. <currencyX, 3000>, which means that an amount of currencyX has been bought for 3000 euros.
* For each currency type currencyX, there is only one entry in the portfolio.
*
* @author Konstantinos Prousalis
*/
public class Portfolio {
private String portfolioTitle;
private HashMap<String, Integer> portfolio;
/**
* Προκαθορισμένος κατασκευαστής.
* <p>
* Default constructor.
*/
public Portfolio() {
//portfolioTitle="";
portfolio = new HashMap<String,Integer>();
}
/**
* Κατασκευαστής που παίρνει ως παράμετρο τον τίτλο του νέου χαρτοφυλακίου
* <p>
* Constructor that gets as a parameter the portfolio title
*
* @param portfolioTitle Ο τίτλος του χαρτοφυλακίου (the portfolio title)
*/
public Portfolio(String portfolioTitle) {
this.portfolioTitle = portfolioTitle;
portfolio = new HashMap<String,Integer>();
}
/**
* Επιστρέφει τον τύπο του νομίσματος
* <p>
* Returns the currency type
*
* @return Ο τύπος του νομίσματος (the currency type)
*/
public String getPortfolioTitle() {
return this.portfolioTitle;
}
/**
* Μέθοδος για την ενημέρωση του τίτλου του χαρτοφυλακίου
* <p>
* Method for updating the portfolio title
*
* @param portfolioTitle Ο νέος τίτλος του χαρτοφυλακίου (the new title of the portfolio)
*/
public void setPortfolioTitle(String portfolioTitle) {
this.portfolioTitle=portfolioTitle;
}
/**
* Μέθοδος για την επιστροφή του καταλόγου με τις εντολές
* <p>
* Method for returning the recorded orders
*
* @return Ο κατάλογος με τις εγγραφές των εντολών (the recorded orders)
*/
public HashMap<String, Integer> getPortfolio() {
return this.portfolio;
}
/**
* Μέθοδος για την καταχώρηση μιας εντολής, δίνοντας ως παράμετρο τον ξένο τύπο νομίσματος
* {@code currency}. Η κλήση αυτής της μεθόδου σημαίνει ότι έχει καταχωρηθεί μια εντολή,
* οπότε στην ουσία καλείται η μέθοδος {@link #registerOrder(String, int)} με εξ ορισμού παράμετρο 100.
* <p>
* Method for recording an order of type {@code currency}. This method is used to record a single
* order, therefore it should call the method {@link #registerOrder(String, int)} with default parameter 100.
*
* @param currency Ο τύπος του συναλλαγματικού νομίσματος, π.χ.currencyX (the type of the currency, e.g. currencyX)
*/
public void registerOrder(String currency) {
registerOrder(currency,100);
}
/**
* Μέθοδος για την καταχώρηση μιας εντολής για την αγορά ξένου νομίσματος {@code currency} με το ποσό {@code amount} σε ευρώ.
* Αν ο τύπος νομίσματοςβρίσκεται ήδη στον κατάλογο, τότε θα πρέπει να ενημερώνεται το αντίστοιχο ποσό {@code amount}.
* Διαφορετικά θα πρέπει να προστίθεται μια νέα καταχώρηση στον κατάλογο.
* <p>
* Method for recording in the portfolio an amount {@code amount} of euros for conversion into a foreign currency
* {@code currency}. If the currency type already exists in the portfolio, then the corresponding number/amount
* should be updated. Otherwise, a new entry should be created in the portfolio.
*
* @param currency Ο τύπος του νομίσματος (the currency type)
* @param amount Το ποσό σε ευρώ που χρησιμοποιούνται για την εντολή (the amount of euros for the order)
*/
public void registerOrder(String currency, int amount) {
if(this.portfolio.containsKey(currency))
this.portfolio.put(currency,this.portfolio.get(currency)+amount);
else
this.portfolio.put(currency,amount);
}
/**
* Μέθοδος για την επιστροφή των νομισμάτων τύπου {@code currency} που υπάρχουν στο πορτφολιο
* <p>
* Method for returning the currencies of type {@code currency} that exist in the portfolio
*
* @param currency Ο τύπος του νομίσματος για τον οποιο θα επιστραφεί το ποσό (the currency type for which the
* amount will be returned)
* @return Ο αριθμός των νομισμάτων τύπου {@code currency} που υπάρχουν (the number of the currency types {@code currency}
* that exist in the registry
*/
public int getAmountOfCurrency(String currency) {
if(this.portfolio.containsKey(currency))
return this.portfolio.get(currency);
else return 0;
}
/**
* Μέθοδος για την επιστροφή ενός πίνακα που περιέχει τα νομίσματα (currencies) των εντολών που υπάρχουν στον κατάλογο.
* Κάθε νόμισμα πρέπει να υπάρχει μόνο μια φορά στον πίνακα που επιστρέφεται.
* <p>
* Method for returning an array with the currencies of the sensors that exist in the portfolio. Each currency should
* exist only once in the array.
*
* @return Ο πίνακας με τους τύπους νομισμάτων (the array with the currency types)
*/
public String[] getAllCurrencies() {
String[] allCurrencies = new String[this.portfolio.size()];
int i = 0;
for(String currency : this.portfolio.keySet())
allCurrencies[i++] = currency;
return allCurrencies;
}
}
| asimakiskydros/University-Projects | Object Oriented Programming/Lab 4/Portfolio.java |
1,491 | package gr.aueb.softeng.view.Chef.HomePage;
import android.view.View;
import androidx.recyclerview.widget.LinearLayoutManager;
public interface ChefHomePageView {
/**
* Καλείται όταν θέλουμε να επιστρέψουμε στο προηγούμενο Activity , δηλαδή στο login Page στην περίπτωσή μας(αυτό καλεί το activity μας)
*/
void goBack();
/**
* Η μέθοδος αυτή καλείται όταν η λίστα των παραγγελιών του μάγειρα είναι άδεια , ώστε να εμφανιστεί το μήνυμα
* στην οθόνη ότι η λίστα είναι άδεια.
*/
void ShowNoOrders();
/**
* Η μέθοδος αυτή καλείται όταν η λίστα με τις παραγγελίες ΔΕΝ είναι άδεια και εμφανίζεται στην οθόνη το recycler view με τα αντικείμενα του.
* σετάροντας παράλληλα τον adapter και το layout manager του recycler view
*/
void ShowOrders();
}
| vleft02/Restaurant-Application | app/src/main/java/gr/aueb/softeng/view/Chef/HomePage/ChefHomePageView.java |
1,492 | package org.afdemp.uisux.utility;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import org.afdemp.uisux.domain.Address;
import org.afdemp.uisux.domain.Category;
import org.afdemp.uisux.domain.ClientOrder;
import org.afdemp.uisux.domain.CreditCard;
import org.afdemp.uisux.domain.MemberCartItem;
import org.afdemp.uisux.domain.Product;
import org.afdemp.uisux.domain.User;
import org.afdemp.uisux.domain.security.Role;
import org.afdemp.uisux.domain.security.UserRole;
import org.afdemp.uisux.repository.CategoryRepository;
import org.afdemp.uisux.repository.RoleRepository;
import org.afdemp.uisux.repository.UserRoleRepository;
import org.afdemp.uisux.service.AddressService;
import org.afdemp.uisux.service.CartItemService;
import org.afdemp.uisux.service.CategoryService;
import org.afdemp.uisux.service.ClientOrderService;
import org.afdemp.uisux.service.CreditCardService;
import org.afdemp.uisux.service.MemberCartItemService;
import org.afdemp.uisux.service.ProductService;
import org.afdemp.uisux.service.RoleService;
import org.afdemp.uisux.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DataGenerator
{
//================================ Autowired Repositories ================================
@Autowired
private RoleRepository roleRepository;
@Autowired
private CategoryRepository categoryRepository;
@Autowired
private UserRoleRepository userRoleRepository;
//================================= Autowired Services =================================
@Autowired
private UserService userService;
@Autowired
private RoleService roleService;
@Autowired
private CategoryService categoryService;
@Autowired
private ProductService productService;
@Autowired
private MemberCartItemService memberCartItemService;
@Autowired
private CartItemService cartItemService;
@Autowired
private AddressService addressService;
@Autowired
private CreditCardService creditCardService;
@Autowired
private ClientOrderService clientOrderService;
//=========================== Functions Declarations ============================
private void createRoles()
{
Role roleAdmin= new Role();
roleAdmin.setRoleId(0);
roleAdmin.setName("ROLE_ADMIN");
roleService.createRole(roleAdmin);
Role roleMember= new Role();
roleMember.setRoleId(1);
roleMember.setName("ROLE_MEMBER");
roleService.createRole(roleMember);
Role roleClient= new Role();
roleClient.setRoleId(2);
roleClient.setName("ROLE_CLIENT");
roleService.createRole(roleClient);
}
private void createAdmin() throws Exception
{
User admin = new User();
admin.setUsername("admin");
admin.setPassword(SecurityUtility.passwordEncoder().encode("admin"));
admin.setEmail("[email protected]");
Set<UserRole> userRoles = new HashSet<>();
Role adminRole=roleRepository.findByName("ROLE_ADMIN");
userRoles.add(new UserRole(admin, adminRole));
userService.createUser(admin, userRoles);
}
private void createMember(String username, String firstName, String lastName, String phone, String email) throws Exception
{
Role memberRole=roleRepository.findByName("ROLE_MEMBER");
User member = new User();
member.setUsername(username);
member.setFirstName(firstName);
member.setLastName(lastName);
member.setPhone(phone);
member.setPassword(SecurityUtility.passwordEncoder().encode("member"));
member.setEmail(email);
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(member, memberRole));
userService.createUser(member, userRoles);
userService.addRoleToExistingUser(member, "ROLE_CLIENT");
}
private void createClient(String username, String firstName, String lastName, String phone, String email) throws Exception
{
Role clientRole=roleRepository.findByName("ROLE_CLIENT");
User client = new User();
client.setUsername(username);
client.setFirstName(firstName);
client.setLastName(lastName);
client.setPhone(phone);
client.setPassword(SecurityUtility.passwordEncoder().encode("client"));
client.setEmail(email);
Set<UserRole> userRoles = new HashSet<>();
userRoles.add(new UserRole(client, clientRole));
userService.createUser(client, userRoles);
}
private void createProductCategory(String type)
{
Category category=new Category();
category.setType(type);
categoryService.createCategory(category);
}
private void createXProduct(String name,String categoryType,String madeIn,String description,BigDecimal listPrice,BigDecimal ourPrice,BigDecimal priceBought)
{
Product product=new Product();
product.setName(name);
product.setMadeIn(madeIn);
product.setInStockNumber(1000L);
product.setListPrice(listPrice);
product.setOurPrice(ourPrice);
product.setActive(true);
product.setPriceBought(priceBought);
product.setDescription(description);
productService.createProduct(product, categoryType);
}
private Timestamp getRandomTime(long startingDate,int rangeMult100)
{
Timestamp seed = new Timestamp(new Date().getTime());
Random rand=new Random(seed.getTime());
long randomLong=Long.valueOf(rand.nextInt(rangeMult100))*100L +startingDate;
return new Timestamp(randomLong);
}
private Timestamp getRandomTimeFrom112017()
{
return getRandomTime(1483221600000L,342144000 );
}
private Timestamp get3to7DaysLater(Timestamp datetime)
{
Random rand=new Random();
long datenanos=datetime.getTime()+(rand.nextInt(3)+4)*86400000;
return new Timestamp(datenanos);
}
private List<UserRole> getMemberRoles()
{
return userRoleRepository.findByRole(roleRepository.findByName("ROLE_MEMBER"));
}
private List<UserRole> getClientRoles()
{
return userRoleRepository.findByRole(roleRepository.findByName("ROLE_CLIENT"));
}
private List<Category> getAllCategories()
{
return categoryService.findAll();
}
private List<Product> getAllProducts()
{
return productService.findAllActive();
}
private boolean createMemberProductsForMember(UserRole userRole)
{
List<Category> categories=getAllCategories();
if(!categories.isEmpty())
{
int categoryCount=categories.size();
Random rand=new Random();
int numberOfCategoriesServed=rand.nextInt(1)+2;
Category cat[]=categories.toArray(new Category[categories.size()]);
for(int i=0;i<numberOfCategoriesServed;i++)
{
int categoryRandomIterator=rand.nextInt(categoryCount-1);
List<Product> categoryProducts=productService.findByCategoryAndActiveTrue(cat[categoryRandomIterator]);
for(Product p:categoryProducts)
{
int randomQ=rand.nextInt(500)+500;
MemberCartItem mci=memberCartItemService.putUpForSale(p, randomQ, userRole.getShoppingCart());
memberCartItemService.activate(mci.getId());
}
}
return true;
}
return false;
}
private void generateSellers()
{
for(UserRole ur:getMemberRoles())
{
createMemberProductsForMember(ur);
}
}
private void generateClientCartItemsAndSale(UserRole userRole,CreditCard creditCard,Address address)
{
Random rand=new Random();
List<Product> productsList=productService.findAllActive();
int productCount=productsList.size();
Product products[]=productsList.toArray(new Product[productsList.size()]);
int noOfProducts=rand.nextInt(4)+1;
for(int i=0;i<noOfProducts;i++)
{
int productArrayIndex=rand.nextInt(products.length-1);
int qty=rand.nextInt(4)+1;
cartItemService.addToCart(userRole.getShoppingCart(), products[productArrayIndex], qty);
}
//Timestamp.valueOf(LocalDateTime.now()).getTime();
ClientOrder clientOrder=cartItemService.commitPastSale(userRole.getShoppingCart(), creditCard, address, address, "High like myself atm", getRandomTimeFrom112017());
clientOrderService.distributePastEarningsToAllMembers(clientOrder.getId());
}
private void generateRecentClientCartItemsAndSale(UserRole userRole,CreditCard creditCard,Address address)
{
Random rand=new Random();
List<Product> productsList=productService.findAllActive();
int productCount=productsList.size();
Product products[]=productsList.toArray(new Product[productsList.size()]);
int noOfProducts=rand.nextInt(4)+1;
for(int i=0;i<noOfProducts;i++)
{
int productArrayIndex=rand.nextInt(products.length-1);
int qty=rand.nextInt(4)+1;
cartItemService.addToCart(userRole.getShoppingCart(), products[productArrayIndex], qty);
}
//Timestamp.valueOf(LocalDateTime.now()).getTime();
ClientOrder clientOrder=cartItemService.commitPastSale(userRole.getShoppingCart(), creditCard, address, address, "High like myself atm", new Timestamp(1517436000000L));
}
private void generatePastSales(int salesNumber)
{
List<UserRole> clientsList=getClientRoles();
Address address=new Address();
address.setCity("7th Heaven");
address.setCountry("Neverland");
address.setReceiverName("Test Subject 417");
address.setState("Above The Rainbow");
address.setStreet1("5th Cloud from the left");
address.setZipcode("777");
address.setUserRole(userRoleRepository.findFirstByRole(roleRepository.findByName("ROLE_ADMIN")));
address=addressService.createAddress(address);
CreditCard creditCard=new CreditCard();
creditCard.setBillingAddress(address);
creditCard.setCardNumber("4000400040004000");
creditCard.setCvc(444);
creditCard.setExpiryMonth(13);
creditCard.setExpiryYear(2222);
creditCard.setHolderName("IsThisGod?");
creditCard.setType("OneOfAKind");
creditCard.setUserRole(address.getUserRole());
creditCard=creditCardService.createCreditCard(creditCard);
Random rand=new Random();
UserRole clients[]=clientsList.toArray(new UserRole[clientsList.size()]);
for(int i=0;i<salesNumber;i++)
{
int clientsRandomIndex=rand.nextInt(clients.length-1);
generateClientCartItemsAndSale(clients[clientsRandomIndex],creditCard, address);
}
}
private void generateRecentSales(int salesNumber)
{
List<UserRole> clientsList=getClientRoles();
Address address=new Address();
address.setCity("7th Heaven");
address.setCountry("Neverland");
address.setReceiverName("Test Subject 417");
address.setState("Above The Rainbow");
address.setStreet1("5th Cloud from the left");
address.setZipcode("777");
address.setUserRole(userRoleRepository.findFirstByRole(roleRepository.findByName("ROLE_ADMIN")));
address=addressService.createAddress(address);
CreditCard creditCard=new CreditCard();
creditCard.setBillingAddress(address);
creditCard.setCardNumber("4000400040004000");
creditCard.setCvc(444);
creditCard.setExpiryMonth(13);
creditCard.setExpiryYear(2222);
creditCard.setHolderName("IsThisGod?");
creditCard.setType("OneOfAKind");
creditCard.setUserRole(address.getUserRole());
creditCard=creditCardService.createCreditCard(creditCard);
Random rand=new Random();
UserRole clients[]=clientsList.toArray(new UserRole[clientsList.size()]);
for(int i=0;i<salesNumber;i++)
{
int clientsRandomIndex=rand.nextInt(clients.length-1);
generateRecentClientCartItemsAndSale(clients[clientsRandomIndex],creditCard, address);
}
}
//TestFunction
private void printAllMemberUserRoles()
{
for(UserRole ur:getMemberRoles())
{
System.out.println(ur.getUserRoleId()+"\t"+ur.getUser()+"\t"+ur.getRole());
}
}
//=========================== Hardcoded Generators ============================
private void createInitialUsers() throws Exception
{
//----Admin----
createAdmin();
//----Members----
createMember("padoura","Μιχάλης","Παντουράκης","2119122391","[email protected]");
createMember("lefteris","Λευτέρης","Μαλινδρέτος","2107348421","[email protected]");
createMember("madryoch","Γιώργος","Αθανασόπουλος","2109246187","[email protected]");
createMember("panos123","Παναγιώτης","Οικονόμου","2108761121","[email protected]");
createMember("kirmanolisopsaras","Δημήτρης","Τσιγουρής","2109361725","[email protected]");
createMember("litsa87","Ευαγγελία","Ραντή","2108416912","[email protected]");
createMember("maria","Μαρία","Τσολακίδη","2105521791","[email protected]");
//----Clients----
createClient("alexandros","Αλέξανδρος","Κούρτης","2108733490","[email protected]");
createClient("alekarios","Αλέξανδρος","Θεοφίλης","2107543281","[email protected]");
createClient("theofylaktos","Γιώργος","Θεοφύλακτος","2139522735","[email protected]");
createClient("kostas13","Κωνσταντίνος","Σταθόπουλος","2109822761","[email protected]");
createClient("agios90","Άγγελος","Αγιωργήτης","2105765665","[email protected]");
createClient("chrisdal","Χρήστος","Δαλαμήτρας","2119311479","[email protected]");
createClient("dimko","Δημήτρης","Κορμαζόγλου","2109717662","[email protected]");
createClient("rozisvasilis","Βασίλης","Ροζής","2103436772","[email protected]");
createClient("tsaki67","Γιώργος","Τσακίρης","2104241499","[email protected]");
createClient("vaso_ll","Βάσω","Λιλιτάκη","2108623482","[email protected]");
createClient("aspmin","Άσπα","Μιναϊδου","2108523541","[email protected]");
createClient("fountoukidou","Ιωάννα","Φουντουκίδου","","[email protected]");
createClient("AlxT","Αλέξανδρος","Τσότος","2107211987","[email protected]");
createClient("agisilaos90","Αγησίλαος","Γεωργούλιας","2133221957","[email protected]");
createClient("kon.prodromou","Κωνσταντίνος","Προδρόμου","2139982770","[email protected]");
createClient("dim.orest04","Ορέστης","Δημητριάδης","2108761231","[email protected]");
createClient("gregoryP","Γρηγόρης","Παρασκευάκος","2108123115","[email protected]");
createClient("phaedonkouts","Φαίδων","Κουτσογιαννόπουλος","2108781231","[email protected]");
}
private void createInitialProducts()
{
createXProduct("Αγελαδινό Γάλα 1L","Γάλα","Κρήτη","Πλήρες φρέσκο αγελαδινό γάλα, παστεριωμένο και επιμελώς συσκευασμένο σε συσκευασία του 1L για να διατηρεί την φρεσκάδα του και τα θρεπτικά συστατικά που χρειάζεται καθένας μας για ενα πλήρες πρωινό. Από αγελάδες που τρέφονται με τριφύλλι,καλαμπόκι,κριθάρι και άλλες φυτικές ίνες. Διάρκεια Ζωής 7 ημέρες.",BigDecimal.valueOf(1.98),BigDecimal.valueOf(1.83),BigDecimal.valueOf(0.61));
createXProduct("Άπαχο Αγελαδινό Γάλα 1L","Γάλα","Κρήτη","Φρέσκο άπαχο αγελαδινό γάλα, παστεριωμένο ιδανικό για αυτούς και αυτές που προσέχουν την σιλουέτα τους. Διάρκεια Ζωής 7 ημέρες.",BigDecimal.valueOf(2.07),BigDecimal.valueOf(1.89),BigDecimal.valueOf(0.63));
createXProduct("Σοκολατούχο Αγελαδινό Γάλα 0.5L","Γάλα","Κρήτη","Πλήρες σοκολατούχο αγελαδινό γάλα, υψηλής παστερίωσης με χρήση εκχυλισμάτων από το φυτό στέβια για γευστική απόλαυση χωρίς ενοχές.",BigDecimal.valueOf(1.25),BigDecimal.valueOf(1.14),BigDecimal.valueOf(0.38));
createXProduct("Κατσικίσιο Γάλα 1L","Γάλα","Κρήτη","Αγνό πλήρες κατσικίσιο γάλα, παστεριωμένο και συσκευασμένο σε συσκευασία του 1L. Απευθείας από τους παραγωγούς μας με στόχο πάντα την ποιότητα. Διάρκεια Ζωής 14 ημέρες.",BigDecimal.valueOf(2.35),BigDecimal.valueOf(2.19),BigDecimal.valueOf(0.73));
createXProduct("Φέτα ΠΟΠ 1kg","Τυρί","Κρήτη","Τυρί φέτα απευθείας από τους παραγωγούς της περιοχής μας. Εξαιρετική γεύση και ποιότητα.",BigDecimal.valueOf(10.50),BigDecimal.valueOf(8.97),BigDecimal.valueOf(2.72));
createXProduct("Κατσικίσια Φέτα ΠΟΠ 0.5kg","Τυρί","Κρήτη","Τυρί φέτα από 100% αγνό κατσικίσιο γάλα που μόνο οι παραγωγοί της περιοχής μας ξέρουν να φτιάχνουν με μεράκι περισσό.",BigDecimal.valueOf(11.47),BigDecimal.valueOf(9.21),BigDecimal.valueOf(3.05));
createXProduct("Ανθότυρο 0.5kg","Τυρί","Κρήτη","Ανθοτυρό που λιώνει στο στόμα κατάλληλο να συνοδέψει πολλά φαγητά ή να δώσει έξτρα γεύση στις σπιτικές σας σπανακό/τυρόπιτες ",BigDecimal.valueOf(1.94),BigDecimal.valueOf(1.53),BigDecimal.valueOf(0.51));
createXProduct("Γλυκιά Γραβιέρα Κρήτης ΠΟΠ 1kg","Τυρί","Κρήτη","Η γλυκιά γραβιέρα μας που έχει γνωρίσει επιτυχία και εκτός συνόρων τώρα στο πιάτο σας σε τιμή πειρασμό.",BigDecimal.valueOf(9.64),BigDecimal.valueOf(9.01),BigDecimal.valueOf(2.95));
createXProduct("Ελαιόλαδο ΑΑΑ 5L","Λάδι","Κρήτη","Αγνό παρθένο ελαιόλαδο που προέρχεται από την ποικιλία Κορωνείκη. Χαμηλότατη οξύτητα που καθιστά το λάδι μας την πρώτη επιλογή των περισσότερων νοικοκυριών τόσο και για την υγεία όσο και για την απαλή γεύση του.",BigDecimal.valueOf(41.22),BigDecimal.valueOf(37.66),BigDecimal.valueOf(11.5));
createXProduct("Ελαιόλαδο 5L","Λάδι","Κρήτη"," Ελαιόλαδο θερμής επεξεργασίας με απολαυστική γεύση κατάλληλο για όλα τα γευματα και τις σαλάτεσ σας.",BigDecimal.valueOf(36.11),BigDecimal.valueOf(31.17),BigDecimal.valueOf(10.03));
createXProduct("Πυρηνέλαιο 750ml","Λάδι","Κρήτη","Πυρήνελαιο για το καντήλι.",BigDecimal.valueOf(1.14),BigDecimal.valueOf(1.02),BigDecimal.valueOf(0.34));
createXProduct("Αλατισμένες Ελιές σε νερό 0.5kg","Ελιές","Κρήτη","Ποικιλία Θρούμπα μεγάλη σαρκώδης ελιά ιδανική για μεζέδες και κατάλληλο συνοδευτικό για το καθημερινό σας γεύμα. Σε νερό ώστε να μπορέσετε να τις διατηρήσετε για εκτεταμένα χρονικά διαστήματα.",BigDecimal.valueOf(8.11),BigDecimal.valueOf(7.92),BigDecimal.valueOf(2.56));
createXProduct("Ξυδάτες Ελιές σε λάδι 0.5kg","Ελιές","Κρητη","Ποικιλία Θρούμπα μεγάλη σαρκώδης ελιά ιδανική για μεζέδες και κατάλληλο συνοδευτικό για το καθημερινό σας γεύμα. Σε ελαιόλαδο Α κατηγορίας.",BigDecimal.valueOf(10.11),BigDecimal.valueOf(9.72),BigDecimal.valueOf(3.22));
createXProduct("Θυμάρι 1kg","Μέλι","Κρήτη","Αρωματικό θυμαρίσιο μέλι από τον τόπο μας εξαιρετικής ποιότητας και γεύσης.",BigDecimal.valueOf(14.57),BigDecimal.valueOf(13.11),BigDecimal.valueOf(4.31));
createXProduct("Έλατο 1kg","Μέλι","Κρήτη","Μέλι από τα έλατα της Κρήτης. Ιδιαίτερη γεμάτη γεύση που θα ενθουσιάσει τους πάντες.",BigDecimal.valueOf(15.61),BigDecimal.valueOf(14.33),BigDecimal.valueOf(4.7));
createXProduct("Ανθόμελο 1kg","Μέλι","Κρήτη","Κλασσικό ανθόμελο από τον τόπο μας.",BigDecimal.valueOf(11.19),BigDecimal.valueOf(10.75),BigDecimal.valueOf(3.53));
createXProduct("Ανάμεικτο 1kg","Μέλι","Κρήτη","Ανάμεικτο μέλι ΑΑ ποιότητας.",BigDecimal.valueOf(10.02),BigDecimal.valueOf(9.76),BigDecimal.valueOf(3.25));
createXProduct("Πατάτες 1kg","Λαχανικά","Κρήτη","Πατάτες κατάλληλες τόσο για τηγάνι όσο και για το ταψί.",BigDecimal.valueOf(0.60),BigDecimal.valueOf(0.52),BigDecimal.valueOf(0.16));
createXProduct("Κρεμύδια(Κόκκινα) 1kg","Λαχανικά","Κρήτη","Κρεμύδια κόκκινα γλυκά κατάλληλα για την χωριάτικη σαλάτα σας με τάκο.",BigDecimal.valueOf(0.35),BigDecimal.valueOf(0.31),BigDecimal.valueOf(0.1));
createXProduct("Κρεμύδια(Άσπρα) 1kg","Λαχανικά","Κρήτη","Κρεμύδια για μαγείρεμα. ΑΑ ποιότητα. Δεν συστήνονται για ωμή κατανάλωση.",BigDecimal.valueOf(0.35),BigDecimal.valueOf(0.28),BigDecimal.valueOf(0.08));
createXProduct("Τομάτες 1kg","Λαχανικά","Κρήτη","Οι ξεχωριστές τομάτες μας που είναι αδιανόητο να λείπουν από την καθημερινή σαλάτα μας.",BigDecimal.valueOf(1.34),BigDecimal.valueOf(1.22),BigDecimal.valueOf(0.41));
createXProduct("Πορτοκάλια 1kg","Φρούτα","Κρήτη"," Πορτοκάλια Valencia ζουμερά ιδανικά για φρέσκους υγιεινούς χυμούς και όχι μόνο.",BigDecimal.valueOf(0.80),BigDecimal.valueOf(0.76),BigDecimal.valueOf(0.25));
createXProduct("Μπανάνες 1kg","Φρούτα","Κρήτη","Baby ποικιλία της πατρίδας μας.",BigDecimal.valueOf(1.43),BigDecimal.valueOf(1.27),BigDecimal.valueOf(0.41));
createXProduct("Σταφύλι(Φράουλα) 1kg","Φρούτα","Κρήτη","Γλυκό σταφύλι με την χαρακτηριστική κόκκινη ρόγα.",BigDecimal.valueOf(1.45),BigDecimal.valueOf(1.31),BigDecimal.valueOf(0.43));
createXProduct("Σταφύλι(Μοσχάτο)","Φρούτα","Κρήτη","Έξτρα αρωματικό και απολαυστικό σταφύλι της γνωστής εκλεκτής ποικιλίας Μοσχάτο.",BigDecimal.valueOf(2.03),BigDecimal.valueOf(1.87),BigDecimal.valueOf(0.92));
createXProduct("Σταφίδα 1kg","Φρούτα","Κρήτη","Σταφίδες.",BigDecimal.valueOf(0.61),BigDecimal.valueOf(0.46),BigDecimal.valueOf(0.15));
createXProduct("Κόκκινος Γλυκός Οίνος 750ml","Κρασί","Κρήτη","Ερυθρός οίνος 12%Vol σοδιάς 2016 του συνεταιρισμού μας κατάλληλος για κρεατικά.",BigDecimal.valueOf(9.20),BigDecimal.valueOf(8.90),BigDecimal.valueOf(2.67));
createXProduct("Λευκός Ξερός Οίνος 750ml","Κρασί","Κρήτη","Λευκός οίνος ξηρός 12%Vol σοδιάς 2016 του συνεταιρισμού μας για την συνοδεία των θαλασσινών γευμάτων σας.",BigDecimal.valueOf(8.87),BigDecimal.valueOf(8.35),BigDecimal.valueOf(2.41));
createXProduct("CABERNET ΑΑΑ 750ml","Κρασί","Κρήτη","Βαθύς κόκκινος οίνος 14%Vol με την χαρακτηριστικά γεμάτη γεύση του και το άρωμα του. Για αυτούς που έχουν εκλεκτά γούστα στο κρασί. Σοδειάς 2011 ωριμάζει στα κελάρια μας περιμένοντας σας να τον απολαύσετε στις ξεχωριστές και όχι μόνο στιγμές σας.",BigDecimal.valueOf(13.72),BigDecimal.valueOf(13.07),BigDecimal.valueOf(4.09));
createXProduct("Μαυροδάφνη 250ml","Κρασί","Κρήτη","Για αυτούς που προτιμάνε το πιο γλυκό κρασί. Ευκολόπιωτο , ίσως περισσότερο από ότι θα έπρεπε. Συνιστάμε την προσοχή σας αν πρόκειται να οδηγήσετε καθώς είναι 17% Vol",BigDecimal.valueOf(3.15),BigDecimal.valueOf(3.01),BigDecimal.valueOf(1.0));
createXProduct("Ρακή 1L","Κρασί","Κρήτη","Για τους εξτρά τολμηρούς. Αν το αντέχεις αποτελεί πολύ καλή συντροφιά. Μερικοί συμπατριώτες μας το χρησιμοποιούν το χειμώνα αντί για πετρέλαιο θέρμανσης...hic!",BigDecimal.valueOf(2.25),BigDecimal.valueOf(2.01),BigDecimal.valueOf(0.67));
createXProduct("Λευκό Μαλακό 1kg","Αλεύρι","Κρήτη","Λευκό αλεύρι μαλακό για τα κουλουράκια και γλυκά σας.",BigDecimal.valueOf(1.35),BigDecimal.valueOf(1.22),BigDecimal.valueOf(0.4));
createXProduct("Λευκό Σκληρό 1kg","Αλεύρι","Κρήτη","Λευκό αλεύρι σκλήρο για το ψωμί.",BigDecimal.valueOf(1.45),BigDecimal.valueOf(1.31),BigDecimal.valueOf(0.42));
createXProduct("Μαύρο 1kg","Αλεύρι","Κρήτη","Ολικής αλέσεως ιδανικό για το χωριάτικο ψωμί της γιαγιάς.",BigDecimal.valueOf(1.27),BigDecimal.valueOf(1.13),BigDecimal.valueOf(0.35));
createXProduct("Αραβοσίτου 1kg","Αλεύρι","Κρήτη"," Γλυκό αλεύρι αραβοσίτου απαραίτητο για την περιστασιακή μπομπότα ή για γλυκό ψωμί.",BigDecimal.valueOf(1.39),BigDecimal.valueOf(1.21),BigDecimal.valueOf(0.4));
}
//===============================Generation of Data==============================
public void generate() throws Exception
{
createRoles();
createInitialUsers();
createInitialProducts();
generateSellers();
generatePastSales(1000);
generateRecentSales(35);
}
} | padoura/afdemp_uisux_admin | src/main/java/org/afdemp/uisux/utility/DataGenerator.java |
1,493 | package com.iNNOS.controllers;
import java.net.URL;
import java.util.ArrayList;
import java.util.Optional;
import java.util.ResourceBundle;
import com.iNNOS.mainengine.MainEngine;
import com.iNNOS.model.Client;
import javafx.animation.FadeTransition;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.util.Duration;
public class ClientsController implements Initializable{
@FXML
private TableColumn<Client, String> addressCol;
@FXML
private TableColumn<Client, String> detailsCol;
@FXML
private TableColumn<Client, String> nameCol;
@FXML
private TableView<Client> clientsTable;
@FXML
private TableColumn<Client, String> municipalityCol;
@FXML
private TableColumn<Client, Long> phoneNumCol;
@FXML
private TableColumn<Client, String> webpageCol;
@FXML
private TableColumn<Client, String> afmCol;
@FXML
private TextArea detailsTextField;
@FXML
private TextField phoneNumTextField;
@FXML
private TextField webpageTextField;
@FXML
private TextField addressTextField;
@FXML
private TextField afmTextField;
@FXML
private TextField municipalityTextField;
@FXML
private TextField currentProjectTextField;
@FXML
private Label fullNameLabel;
@FXML
private AnchorPane infoPane;
MainEngine mainengine;
ObservableList<Client> observableList = FXCollections.observableArrayList();
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
mainengine = MainEngine.getMainEngineInstance();
clientsTable.setOnMouseClicked((MouseEvent event) -> {
if(event.getButton().equals(MouseButton.PRIMARY)){
infoPane.setDisable(false);
updateInfo(getSelectedClient());
setNode(infoPane);
}
});
nameCol.setCellValueFactory(new PropertyValueFactory<>("fullName"));
afmCol.setCellValueFactory(new PropertyValueFactory<>("afm"));
updateClientsTable();
}
private void updateInfo(Client client) {
fullNameLabel.setText(client.getFullName());
afmTextField.setText(client.getAfm());
addressTextField.setText(client.getAddress());
phoneNumTextField.setText(String.valueOf(client.getPhoneNumber()));
municipalityTextField.setText(client.getMunicipality());
webpageTextField.setText(client.getWebpage());
detailsTextField.setText(client.getDetails());
}
private Client updateClientFromTextFields() {
Client clientToBeUpdated = new Client();
clientToBeUpdated.setFullName(fullNameLabel.getText());
clientToBeUpdated.setAfm(afmTextField.getText());
clientToBeUpdated.setAddress(addressTextField.getText());
clientToBeUpdated.setMunicipality(municipalityTextField.getText());
clientToBeUpdated.setPhoneNumber(Long.parseLong(phoneNumTextField.getText()));
clientToBeUpdated.setWebpage(webpageTextField.getText());
clientToBeUpdated.setDetails(detailsTextField.getText());
return clientToBeUpdated;
}
private void updateClientsTable() {
ArrayList<Client> clientsList = mainengine.fetchClientsFromDB();
clientsTable.setItems(observableList);
if (clientsList != null) {
for (Client client : clientsList)
clientsTable.getItems().add(client);
}
}
@FXML
void refreshClientsTable(ActionEvent event) {
observableList.removeAll(observableList);
updateClientsTable();
mainengine.generateAlertDialog(AlertType.INFORMATION, "Ανανέωση επιτυχής", "Η λίστα πελατών ανανεώθηκε επιτυχώς.").show();
}
@FXML
void editClient(ActionEvent event) {
afmTextField.setEditable(true);
addressTextField.setEditable(true);
municipalityTextField.setEditable(true);
phoneNumTextField.setEditable(true);
webpageTextField.setEditable(true);
detailsTextField.setEditable(true);
}
@FXML
void saveClientInfo(ActionEvent event) {
Alert saveClientAlert = mainengine.generateAlertDialog(AlertType.CONFIRMATION, "Επιβεβαίωση αποθήκευσης", "Είστε βέβαιοι ότι θέλετε να αποθηκέυσετε τις αλλαγές για τον πελάτη "+clientsTable.getSelectionModel().getSelectedItem().getFullName()+ " ;");
// Ask user to confirm the row's delete
Optional<ButtonType> result = saveClientAlert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
saveClientAlert.close();
else if(result.get() == ButtonType.OK) {
//oke button is pressed
mainengine.establishDbConnection();
mainengine.updateClientEntry(updateClientFromTextFields());
}else if(result.get() == ButtonType.CANCEL)
// cancel button is pressed
saveClientAlert.close();
}
@FXML
void deleteClient(ActionEvent event) {
Client selectedClient = clientsTable.getSelectionModel().getSelectedItem();
Alert deleteClientAlert = mainengine.generateAlertDialog(AlertType.INFORMATION, "Διαγραφή εγγραφής", "Είστε σίγουροι για την διαγραφή του πελάτη : "+selectedClient.getFullName()+ " ;");
// Ask user to confirm the row's delete
Optional<ButtonType> result = deleteClientAlert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
deleteClientAlert.close();
else if(result.get() == ButtonType.OK) {
//oke button is pressed
clientsTable.getItems().remove(selectedClient);
mainengine.establishDbConnection();
mainengine.removeClientEntryFromDB(selectedClient);
}else if(result.get() == ButtonType.CANCEL)
// cancel button is pressed
deleteClientAlert.close();
}
//Set selected node to a content holder
private void setNode(Node node) {
//holderPane.getChildren().clear();
//holderPane.getChildren().add((Node) node);
FadeTransition ft = new FadeTransition(Duration.millis(200));
ft.setNode(node);
ft.setFromValue(0.1);
ft.setToValue(1);
ft.setCycleCount(1);
ft.setAutoReverse(false);
ft.play();
}
public Client getSelectedClient() {
return clientsTable.getSelectionModel().getSelectedItem();
}
}
| vaggelisbarb/Business-Management-App | src/main/java/com/iNNOS/controllers/ClientsController.java |
1,494 | package GUI;
import java.awt.Color;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import Database.DBMethods;
import Database.Database;
import com.formdev.flatlaf.*;
import java.awt.Component;
import java.sql.ResultSet;
import java.util.Locale;
import java.util.ResourceBundle;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSeparator;
import kdesp73.databridge.connections.DatabaseConnection;
import kdesp73.databridge.helpers.QueryBuilder;
import kdesp73.themeLib.Theme;
import kdesp73.themeLib.ThemeCollection;
import main.Customer;
/**
*
* @author tgeorg
*/
public class ServicesFrame extends javax.swing.JFrame {
MainFrame mf;
DepositFrame df;
SettingsFrame sf;
ArrayList<Customer> customerList;
ResourceBundle rb;
Theme theme;
Color pc = new Color(162, 119, 255);
Color bg = new Color(21, 20, 27);
Color sep = new Color(187, 187, 187);
Color sc = new Color(97, 255, 202);
private int indexOfCustomerLoggedIn;
private boolean accInfoBtnPressed = false;
private boolean depBtnPressed = false;
private boolean uploadImgBtnPressed = false;
public ServicesFrame() {
FlatDarculaLaf.setup();
DatabaseConnection db = Database.connection();
// Frame setup
initComponents();
this.theme = GUIFunctions.setupFrame(this, "~");
// Center frame
this.pack();
this.setLocationRelativeTo(null);
this.setVisible(true);
// Color, focus and visibility setup of components
servicesPanel.setBackground(bg);
// menuSeparator.setBackground(sep);
accInfoBtn.setForeground(pc);
// accInfoSeparator.setBackground(sep);
depBtn.setForeground(pc);
// depSeparator.setBackground(sep);
delBtn.setForeground(pc);
// delSeparator.setBackground(sep);
logoutBtn.setForeground(pc);
// logoutSeparator.setBackground(sep);
refreshBtn.setForeground(pc);
uploadImgBtn.setForeground(pc);
settingsBtn.setForeground(pc);
// infoSeparator.setBackground(sep);
// avatarSeparator1.setBackground(sep);
// avatarSeparator2.setBackground(sep);
accInfoBtn.setFocusable(false);
depBtn.setFocusable(false);
delBtn.setFocusable(false);
logoutBtn.setFocusable(false);
refreshBtn.setFocusable(false);
uploadImgBtn.setFocusable(false);
settingsBtn.setFocusable(false);
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Font").from("Settings").build());
rs.next();
GUIUtils.changeGlobalFont(new Component[]{this}, 4, rs.getString(1));
} catch (SQLException ex) {
Logger.getLogger(this.getName()).log(Level.SEVERE, null, ex);
}
db.close();
}
public ServicesFrame(MainFrame mf, ArrayList<Customer> customerList, int indexOfCustomerLoggedIn) throws SQLException {
FlatDarculaLaf.setup();
DatabaseConnection db = Database.connection();
// Frame setup
initComponents();
this.theme = GUIFunctions.setupFrame(this, customerList.get(indexOfCustomerLoggedIn).getAcc().getUsername() + ":~");
configureFrameProperties();
// Color, focus and visibility setup of components
avatarSeparator1.setForeground(sep);
avatarSeparator2.setForeground(sep);
accInfoBtn.setFocusable(false);
depBtn.setFocusable(false);
delBtn.setFocusable(false);
logoutBtn.setFocusable(false);
refreshBtn.setFocusable(false);
uploadImgBtn.setFocusable(false);
settingsBtn.setFocusable(false);
this.mf = mf;
this.customerList = customerList;
this.indexOfCustomerLoggedIn = indexOfCustomerLoggedIn;
loadImage(DBMethods.getImg(customerList, indexOfCustomerLoggedIn));
setInfoPanel();
db.close();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
imgChooser = new javax.swing.JFileChooser();
servicesPanel = new javax.swing.JPanel();
mainMenuLabel = new javax.swing.JLabel();
menuSeparator = new javax.swing.JSeparator();
accInfoBtn = new javax.swing.JButton();
accInfoSeparator = new javax.swing.JSeparator();
depBtn = new javax.swing.JButton();
depSeparator = new javax.swing.JSeparator();
delBtn = new javax.swing.JButton();
delSeparator = new javax.swing.JSeparator();
logoutBtn = new javax.swing.JButton();
logoutSeparator = new javax.swing.JSeparator();
mainSeparator = new javax.swing.JSeparator();
infoPanel = new javax.swing.JPanel();
avatarPanel = new javax.swing.JPanel();
avatarLabel = new javax.swing.JLabel();
customerInfoLabel = new javax.swing.JLabel();
nameIndicator = new javax.swing.JLabel();
name = new javax.swing.JLabel();
surnameIndicator = new javax.swing.JLabel();
surname = new javax.swing.JLabel();
ageIndicator = new javax.swing.JLabel();
age = new javax.swing.JLabel();
accountInfoLabel = new javax.swing.JLabel();
usernameIndicator = new javax.swing.JLabel();
username = new javax.swing.JLabel();
balanceIndicator = new javax.swing.JLabel();
balance = new javax.swing.JLabel();
accIdIndicator = new javax.swing.JLabel();
accountId = new javax.swing.JLabel();
infoSeparator = new javax.swing.JSeparator();
avatarSeparator1 = new javax.swing.JSeparator();
avatarSeparator2 = new javax.swing.JSeparator();
uploadImgBtn = new javax.swing.JButton();
refreshBtn = new javax.swing.JButton();
settingsBtn = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setResizable(false);
servicesPanel.setName("bg"); // NOI18N
mainMenuLabel.setFont(new java.awt.Font("Manjari", 0, 26)); // NOI18N
mainMenuLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
mainMenuLabel.setText("<html><p style=\"text-align:center\"><b>Main Menu</p> </html>");
mainMenuLabel.setName("textbox"); // NOI18N
menuSeparator.setBackground(new java.awt.Color(187, 187, 187));
menuSeparator.setForeground(new java.awt.Color(187, 187, 187));
menuSeparator.setName("fg_2"); // NOI18N
accInfoBtn.setBackground(java.awt.Color.darkGray);
accInfoBtn.setFont(new java.awt.Font("Manjari", 0, 18)); // NOI18N
accInfoBtn.setText("<html><p style=\"text-align:center\"><b>Account<br>Information</p> </html>");
accInfoBtn.setName("btn"); // NOI18N
accInfoBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
accInfoBtnActionPerformed(evt);
}
});
accInfoSeparator.setBackground(new java.awt.Color(187, 187, 187));
accInfoSeparator.setForeground(new java.awt.Color(187, 187, 187));
accInfoSeparator.setName("fg_2"); // NOI18N
depBtn.setBackground(java.awt.Color.darkGray);
depBtn.setFont(new java.awt.Font("Manjari", 0, 18)); // NOI18N
depBtn.setText("<html><p style=\"text-align:center\"><b>Deposit</p> </html>");
depBtn.setName("btn"); // NOI18N
depBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
depBtnActionPerformed(evt);
}
});
depSeparator.setBackground(new java.awt.Color(187, 187, 187));
depSeparator.setForeground(new java.awt.Color(187, 187, 187));
depSeparator.setName("fg_2"); // NOI18N
delBtn.setBackground(java.awt.Color.darkGray);
delBtn.setFont(new java.awt.Font("Manjari", 0, 18)); // NOI18N
delBtn.setText("<html><p style=\"text-align:center\"><b>Delete<br>Account</p> </html>");
delBtn.setName("btn"); // NOI18N
delBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
delBtnActionPerformed(evt);
}
});
delSeparator.setBackground(new java.awt.Color(187, 187, 187));
delSeparator.setForeground(new java.awt.Color(187, 187, 187));
delSeparator.setName("fg_2"); // NOI18N
logoutBtn.setBackground(java.awt.Color.darkGray);
logoutBtn.setFont(new java.awt.Font("Manjari", 0, 18)); // NOI18N
logoutBtn.setText("<html><p style=\"text-align:center\"><b>Logout</p> </html>");
logoutBtn.setName("btn"); // NOI18N
logoutBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
logoutBtnActionPerformed(evt);
}
});
logoutSeparator.setBackground(new java.awt.Color(187, 187, 187));
logoutSeparator.setForeground(new java.awt.Color(187, 187, 187));
logoutSeparator.setName("fg_2"); // NOI18N
mainSeparator.setBackground(new java.awt.Color(187, 187, 187));
mainSeparator.setForeground(new java.awt.Color(187, 187, 187));
mainSeparator.setOrientation(javax.swing.SwingConstants.VERTICAL);
mainSeparator.setName("fg_2"); // NOI18N
avatarPanel.setBackground(new java.awt.Color(0, 0, 0));
avatarLabel.setBackground(new java.awt.Color(0, 0, 0));
avatarLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
javax.swing.GroupLayout avatarPanelLayout = new javax.swing.GroupLayout(avatarPanel);
avatarPanel.setLayout(avatarPanelLayout);
avatarPanelLayout.setHorizontalGroup(
avatarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(avatarLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
);
avatarPanelLayout.setVerticalGroup(
avatarPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(avatarLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 184, Short.MAX_VALUE)
);
customerInfoLabel.setFont(new java.awt.Font("Manjari", 0, 24)); // NOI18N
customerInfoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
customerInfoLabel.setText("<html><p style=\"text-align:center\"><b>Customer Info</p> </html>");
customerInfoLabel.setName("label"); // NOI18N
nameIndicator.setText("<html><p style=\"text-align:center\"><b>Name:</p> </html>");
nameIndicator.setName("label"); // NOI18N
surnameIndicator.setText("<html><p style=\"text-align:center\"><b>Surname:</p> </html>");
surnameIndicator.setName("label"); // NOI18N
ageIndicator.setText("<html><p style=\"text-align:center\"><b>Age:</p> </html>");
ageIndicator.setName("label"); // NOI18N
accountInfoLabel.setFont(new java.awt.Font("Manjari", 0, 24)); // NOI18N
accountInfoLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
accountInfoLabel.setText("<html><p style=\"text-align:center\"><b>Account Info</p> </html>");
accountInfoLabel.setName("label"); // NOI18N
usernameIndicator.setText("<html><p style=\"text-align:center\"><b>Username:</p> </html>");
usernameIndicator.setName("label"); // NOI18N
balanceIndicator.setText("<html><p style=\"text-align:center\"><b>Balance:</p> </html>");
balanceIndicator.setName("label"); // NOI18N
accIdIndicator.setText("<html><p style=\"text-align:center\"><b>Account ID:</p> </html>");
accIdIndicator.setName("label"); // NOI18N
infoSeparator.setBackground(new java.awt.Color(187, 187, 187));
infoSeparator.setForeground(new java.awt.Color(187, 187, 187));
infoSeparator.setName(""); // NOI18N
avatarSeparator1.setBackground(new java.awt.Color(187, 187, 187));
avatarSeparator1.setForeground(new java.awt.Color(187, 187, 187));
avatarSeparator1.setOrientation(javax.swing.SwingConstants.VERTICAL);
avatarSeparator1.setName(""); // NOI18N
avatarSeparator2.setBackground(new java.awt.Color(187, 187, 187));
avatarSeparator2.setForeground(new java.awt.Color(187, 187, 187));
avatarSeparator2.setName(""); // NOI18N
uploadImgBtn.setBackground(java.awt.Color.darkGray);
uploadImgBtn.setText("<html><p style=\"text-align:center\"><b>Upload Image</p> </html>");
uploadImgBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
uploadImgBtn.setName("btn"); // NOI18N
uploadImgBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
uploadImgBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout infoPanelLayout = new javax.swing.GroupLayout(infoPanel);
infoPanel.setLayout(infoPanelLayout);
infoPanelLayout.setHorizontalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, infoPanelLayout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addComponent(accountInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(193, 193, 193)
.addComponent(uploadImgBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(infoPanelLayout.createSequentialGroup()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(infoSeparator, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 268, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(infoPanelLayout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(customerInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(infoPanelLayout.createSequentialGroup()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(surnameIndicator)
.addComponent(nameIndicator)
.addComponent(ageIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(surname, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 162, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 41, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(avatarSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(avatarPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(avatarSeparator2)))
.addGroup(infoPanelLayout.createSequentialGroup()
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(accIdIndicator, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE)
.addComponent(balanceIndicator)
.addComponent(usernameIndicator))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(balance, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(accountId, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 171, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGap(17, 17, 17))
);
infoPanelLayout.setVerticalGroup(
infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(avatarPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(avatarSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 184, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(infoPanelLayout.createSequentialGroup()
.addComponent(customerInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nameIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(surnameIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(surname, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(ageIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(age, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(infoSeparator)
.addComponent(avatarSeparator2))
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(infoPanelLayout.createSequentialGroup()
.addGap(13, 13, 13)
.addComponent(uploadImgBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(infoPanelLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(accountInfoLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(41, 41, 41)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(username, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(usernameIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(balanceIndicator, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(balance, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(infoPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(accountId, javax.swing.GroupLayout.PREFERRED_SIZE, 18, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(accIdIndicator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(46, Short.MAX_VALUE))
);
refreshBtn.setBackground(java.awt.Color.darkGray);
refreshBtn.setText("<html><p style=\"text-align:center\"><b>Refresh Information</p> </html>");
refreshBtn.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
refreshBtn.setName("btn"); // NOI18N
refreshBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
refreshBtnActionPerformed(evt);
}
});
settingsBtn.setBackground(java.awt.Color.darkGray);
settingsBtn.setText("<html><p style=\"text-align:center\"><b>Settings</p> </html>");
settingsBtn.setName("btn"); // NOI18N
settingsBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
settingsBtnActionPerformed(evt);
}
});
javax.swing.GroupLayout servicesPanelLayout = new javax.swing.GroupLayout(servicesPanel);
servicesPanel.setLayout(servicesPanelLayout);
servicesPanelLayout.setHorizontalGroup(
servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(servicesPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(logoutSeparator)
.addComponent(logoutBtn)
.addComponent(accInfoBtn)
.addComponent(depBtn)
.addComponent(depSeparator)
.addComponent(delSeparator)
.addComponent(delBtn)
.addComponent(accInfoSeparator)
.addComponent(mainMenuLabel)
.addComponent(menuSeparator))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(mainSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 216, Short.MAX_VALUE)
.addGroup(servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(refreshBtn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(settingsBtn, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(infoPanel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
servicesPanelLayout.setVerticalGroup(
servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(servicesPanelLayout.createSequentialGroup()
.addGroup(servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(servicesPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(infoPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(refreshBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(settingsBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(servicesPanelLayout.createSequentialGroup()
.addGap(14, 14, 14)
.addGroup(servicesPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(mainSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 602, Short.MAX_VALUE)
.addGroup(servicesPanelLayout.createSequentialGroup()
.addComponent(mainMenuLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(menuSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(25, 25, 25)
.addComponent(accInfoBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(accInfoSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(depBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(depSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(13, 13, 13)
.addComponent(delBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(delSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(logoutSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(logoutBtn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(servicesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(servicesPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void configureFrameProperties() {
DatabaseConnection db = Database.connection();
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
if (languageName.equals("English")) {
GUIFunctions.setTexts(this, Locale.US);
} else if (languageName.equals("Greek")) {
GUIFunctions.setTexts(this, Locale.of("el", "GR"));
}
} catch (SQLException ex) {
Logger.getLogger(SettingsFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
}
private void setInfoPanel() {
name.setText(customerList.get(indexOfCustomerLoggedIn).getName());
surname.setText(customerList.get(indexOfCustomerLoggedIn).getSurname());
age.setText(customerList.get(indexOfCustomerLoggedIn).getAge());
username.setText(customerList.get(indexOfCustomerLoggedIn).getAcc().getUsername());
balance.setText(customerList.get(indexOfCustomerLoggedIn).getAcc().getBalance() + "");
accountId.setText(customerList.get(indexOfCustomerLoggedIn).getAcc().getId());
}
private void loadImage(String dir) {
ImageIcon imageIcon = new ImageIcon(dir);
avatarLabel.setIcon(imageIcon);
}
public static void resizeImage(String imgDir) {
String source = imgDir;
System.out.println(source);
BufferedImage originalImage = null;
try {
originalImage = ImageIO.read(new File(source));
} catch (IOException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedImage outputImage = GUIUtils.resizeImage(originalImage, 184, 184);
try {
ImageIO.write(outputImage, "jpg", new File(imgDir));
} catch (IOException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void accInfoBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_accInfoBtnActionPerformed
accInfoBtnPressed = !accInfoBtnPressed;
if (accInfoBtnPressed) {
infoPanel.setVisible(false);
} else {
infoPanel.setVisible(true);
}
}//GEN-LAST:event_accInfoBtnActionPerformed
private void depBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_depBtnActionPerformed
if (df != null) {
df.dispose();
}
df = new DepositFrame(this, customerList, indexOfCustomerLoggedIn);
df.setVisible(true);
}//GEN-LAST:event_depBtnActionPerformed
private void delBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_delBtnActionPerformed
DatabaseConnection db = Database.connection();
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
if (languageName.equals("English")) {
int choice = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete this account?", "Delete account", JOptionPane.WARNING_MESSAGE);
switch (choice) {
case 0: { // confirm
try {
DBMethods.deleteAccount(customerList, indexOfCustomerLoggedIn);
DBMethods.deleteCustomer(customerList, indexOfCustomerLoggedIn);
this.dispose();
mf = new MainFrame();
mf.setVisible(true);
JOptionPane.showMessageDialog(mf, "Successfull delete");
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
case 2: { // cancel
break;
}
}
} else if (languageName.equals("Greek")) {
int choice = JOptionPane.showConfirmDialog(null, "Είστε σίγουροι ότι θέλετε να διαγράψετε αυτό το λογαριασμό;", "Διαγραφή λογαριασμού", JOptionPane.WARNING_MESSAGE);
switch (choice) {
case 0: { // confirm
try {
DBMethods.deleteAccount(customerList, indexOfCustomerLoggedIn);
DBMethods.deleteCustomer(customerList, indexOfCustomerLoggedIn);
this.dispose();
mf = new MainFrame();
mf.setVisible(true);
JOptionPane.showMessageDialog(mf, "Επιτυχής διαγραφή");
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
break;
}
case 2: { // cancel
break;
}
}
}
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
}//GEN-LAST:event_delBtnActionPerformed
private void logoutBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logoutBtnActionPerformed
DatabaseConnection db = Database.connection();
try {
ResultSet rs = db.executeQuery(new QueryBuilder().select("Language").from("Settings").build());
rs.next();
String languageName = rs.getString(1);
this.dispose();
mf = new MainFrame();
mf.setVisible(true);
if (languageName.equals("English")) {
JOptionPane.showMessageDialog(mf, "Successfull Logout");
} else if (languageName.equals("Greek")) {
JOptionPane.showMessageDialog(mf, "Επιτυχής αποσύνδεση");
}
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
db.close();
}//GEN-LAST:event_logoutBtnActionPerformed
private void refreshBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshBtnActionPerformed
setInfoPanel();
}//GEN-LAST:event_refreshBtnActionPerformed
private void uploadImgBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_uploadImgBtnActionPerformed
int UserChoice = imgChooser.showOpenDialog(this);
String dir = "";
if (UserChoice == JFileChooser.APPROVE_OPTION) {
File SelectedFile = imgChooser.getSelectedFile();
dir = SelectedFile.getPath();
resizeImage(dir);
try {
DBMethods.updateImg(customerList, indexOfCustomerLoggedIn, dir);
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
loadImage(dir);
}
if (UserChoice == JFileChooser.CANCEL_OPTION) {
// mediaPlayerPath.setText("No File Selected");
}
}//GEN-LAST:event_uploadImgBtnActionPerformed
private void settingsBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_settingsBtnActionPerformed
if (sf != null) {
sf.dispose();
}
try {
sf = new SettingsFrame(this, customerList, indexOfCustomerLoggedIn);
} catch (SQLException ex) {
Logger.getLogger(ServicesFrame.class.getName()).log(Level.SEVERE, null, ex);
}
sf.setVisible(true);
}//GEN-LAST:event_settingsBtnActionPerformed
/**
* @param args the command line arguments
* @throws java.lang.ClassNotFoundException
* @throws java.lang.InstantiationException
* @throws java.lang.IllegalAccessException
* @throws javax.swing.UnsupportedLookAndFeelException
*/
public static void main(String args[]) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {
/* Set the Nimbus look and feel */
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServicesFrame().setVisible(true);
}
});
}
public Theme getTheme() {
return theme;
}
public void setTheme(Theme theme) {
this.theme = theme;
ThemeCollection.applyTheme(this, theme);
}
public DepositFrame getDf() {
return df;
}
public JLabel getAccIdIndicator() {
return accIdIndicator;
}
public JButton getAccInfoBtn() {
return accInfoBtn;
}
public JLabel getAccountInfoLabel() {
return accountInfoLabel;
}
public JLabel getAgeIndicator() {
return ageIndicator;
}
public JLabel getAvatarLabel() {
return avatarLabel;
}
public JLabel getBalanceIndicator() {
return balanceIndicator;
}
public JButton getDelBtn() {
return delBtn;
}
public JSeparator getDelSeparator() {
return delSeparator;
}
public JButton getDepBtn() {
return depBtn;
}
public JPanel getInfoPanel() {
return infoPanel;
}
public JButton getLogoutBtn() {
return logoutBtn;
}
public JLabel getMainMenuLabel() {
return mainMenuLabel;
}
public JLabel getNameIndicator() {
return nameIndicator;
}
public JButton getRefreshBtn() {
return refreshBtn;
}
public JPanel getServicesPanel() {
return servicesPanel;
}
public JButton getSettingsBtn() {
return settingsBtn;
}
public JLabel getSurnameIndicator() {
return surnameIndicator;
}
public JButton getUploadImgBtn() {
return uploadImgBtn;
}
public JLabel getUsernameIndicator() {
return usernameIndicator;
}
public JLabel getCustomerInfoLabel() {
return customerInfoLabel;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel accIdIndicator;
private javax.swing.JButton accInfoBtn;
private javax.swing.JSeparator accInfoSeparator;
private javax.swing.JLabel accountId;
private javax.swing.JLabel accountInfoLabel;
private javax.swing.JLabel age;
private javax.swing.JLabel ageIndicator;
private javax.swing.JLabel avatarLabel;
private javax.swing.JPanel avatarPanel;
private javax.swing.JSeparator avatarSeparator1;
private javax.swing.JSeparator avatarSeparator2;
private javax.swing.JLabel balance;
private javax.swing.JLabel balanceIndicator;
private javax.swing.JLabel customerInfoLabel;
private javax.swing.JButton delBtn;
private javax.swing.JSeparator delSeparator;
private javax.swing.JButton depBtn;
private javax.swing.JSeparator depSeparator;
private javax.swing.JFileChooser imgChooser;
private javax.swing.JPanel infoPanel;
private javax.swing.JSeparator infoSeparator;
private javax.swing.JButton logoutBtn;
private javax.swing.JSeparator logoutSeparator;
private javax.swing.JLabel mainMenuLabel;
private javax.swing.JSeparator mainSeparator;
private javax.swing.JSeparator menuSeparator;
private javax.swing.JLabel name;
private javax.swing.JLabel nameIndicator;
private javax.swing.JButton refreshBtn;
private javax.swing.JPanel servicesPanel;
private javax.swing.JButton settingsBtn;
private javax.swing.JLabel surname;
private javax.swing.JLabel surnameIndicator;
private javax.swing.JButton uploadImgBtn;
private javax.swing.JLabel username;
private javax.swing.JLabel usernameIndicator;
// End of variables declaration//GEN-END:variables
}
| ThanasisGeorg/Bank-Manager | src/main/java/GUI/ServicesFrame.java |
1,495 | package GUI;
import javax.swing.filechooser.FileFilter;
import java.io.File;
/**
* Η κλάση αυτή δημιουργεί φίλτρο για τα JFileChooser που δημιουργούνται κατά την προσθήκη
* νέου καταλύματος από τους παρόχους και την επιλογή του από αρχεία του υπολογιστή. Δέχεται μόνο
* αρχεία που έχουν τις παρακάτω καταλήξεις, οι οποίες δηλώνουν ότι αφορούν μόνο φωτογραφικό υλικό
*/
class ImageFilter extends FileFilter {
public final static String JPEG = "jpeg";
public final static String JPG = "jpg";
public final static String GIF = "gif";
public final static String TIFF = "tiff";
public final static String TIF = "tif";
public final static String PNG = "png";
@Override
public boolean accept(File f) {
if (f.isDirectory()) {
return true;
}
String extension = getExtension(f);
if (extension != null) {
return extension.equals(TIFF) ||
extension.equals(TIF) ||
extension.equals(GIF) ||
extension.equals(JPEG) ||
extension.equals(JPG) ||
extension.equals(PNG);
}
return false;
}
@Override
public String getDescription() {
return "Image Only";
}
String getExtension(File f) {
String ext = null;
String s = f.getName();
int i = s.lastIndexOf('.');
if (i > 0 && i < s.length() - 1) {
ext = s.substring(i + 1).toLowerCase();
}
return ext;
}
}
| NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/GUI/ImageFilter.java |
1,497 | package esk.lottery;
import esk.lottery.Statistics.StatisticsCollector;
import esk.lottery.DataHandler.*;
import esk.lottery.RegistrationUpdater.RegistrationPriority;
import esk.lottery.RegistrationUpdater.RegistrationUpdater;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import jess.*;
/**
* Συντονίζει όλη την επικοινωνία της Java με το έμπειρο σύστημα. Ο ρόλος της
* είναι να φορτώνει το έμπειρο σύστημα, να παίρνει δεδομένα μέσα από τις
* συναρτήσεις του DataHandlerSQL τα οποία τα εισάγει σαν facts στο σύστημα, να
* εξάγει τα αποτελέσματα και να δημιουργεί τα κατάλληλα αντικείμενα μετα το
* πέρας της εκτέλεσης και τέλος να τα στέλει πάλι σε κατάλληλες συναρτήσεις του
* DataHandlerSQL για να περαστούν σε ότι αποθήκες δεδομένων που χρησιμοποιούνται.
* @author Dimosthenis Nikoudis
*/
public class ESK extends Rete {
/**
* Το configuration που χρησιμοποιείται αυτή τη στιγμή από την εφαρμογή.
*/
protected Config config;
/**
* Το path όπου βρίσκονται τα αρχεία CLP του Έμπειρου Συστήματος
*/
protected String expertSystemFilesPath;
/**
* Reference της κλάσης που διαχειρίζεται το low-level access στα δεδομένα.
*/
protected IDataHandler datahandler;
/**
* Το αντικείμενο StatisticsCollector που θα συλλέγει στατιστικά.
*/
protected StatisticsCollector statisticsCollector = new StatisticsCollector();
/**
* Το αντικείμενο registrationUpdater που θα ενημερώνει την βάση.
*/
protected RegistrationUpdater registrationUpdater = new RegistrationUpdater();
/**
* Το μοναδικό ID της κλήρωσης.
*/
protected Integer lotteryID;
/**
* Δημιουργεί το σύστημα κληρώσεων για το συγκεκριμένο lotteryID. Αυτό δίνει
* τη δυνατότητα στο σύστημα να γνωρίζει συγκεκριμένα ποιά κλήρωση θα
* εκτελεστεί αυτή τη στιγμή και να φορτώνει το κατάλληλο configuration που
* την αφορά (π.χ. ειδικές προταιρεότητες). Επίσης δημιουργείται ένα σχετικό
* lock που, για αποφυγή φθοράς των δεδομένων, εμποδίζει την εκτέλεση άλλης
* κλήρωσης την ίδια στιγμή. Το lock φεύγει στον τερματισμό της εφαρμογής.
* @param lotteryID Το μοναδικό ID της κλήρωσης που θα εκτελεστεί (Integer).
*/
public ESK(Integer lotteryID, String configPath, String expertSystemFilesPath) {
this.lotteryID = lotteryID;
this.config = Config.get(configPath);
this.expertSystemFilesPath = expertSystemFilesPath;
datahandler = config.getDataHandler(this);
expertSystemLoad();
}
/**
* Δημιουργεί το σύστημα κληρώσεων για το συγκεκριμένο lotteryID. Αυτό δίνει
* τη δυνατότητα στο σύστημα να γνωρίζει συγκεκριμένα ποιά κλήρωση θα
* εκτελεστεί αυτή τη στιγμή και να φορτώνει το κατάλληλο configuration που
* την αφορά (π.χ. ειδικές προταιρεότητες). Επίσης δημιουργείται ένα σχετικό
* lock που, για αποφυγή φθοράς των δεδομένων, εμποδίζει την εκτέλεση άλλης
* κλήρωσης την ίδια στιγμή. Το lock φεύγει στον τερματισμό της εφαρμογής.
* @param lotteryID Το μοναδικό ID της κλήρωσης που θα εκτελεστεί (String).
*/
public ESK(String lotteryID, String configPath, String expertSystemFilesPath) {
this(Integer.parseInt(lotteryID), configPath, expertSystemFilesPath);
}
/**
* Φορτώνει τους κανόνες και τα templates του έμπειρου συστήματος. Αυτό
* γίνεται φορτώνοντας όλα τα αρχεία, που βρίσκονται σε τοποθεσία που
* ορίζεται στο config.properties, με αλφαβητική σειρά.
*/
public final void expertSystemLoad() {
try {
// Φόρτωμα των templates και των κανόνων
System.out.print("Loading Expert System Files... ");
File dir = new File(expertSystemFilesPath);
File fileList[] = dir.listFiles();
if(fileList == null || fileList.length <= 0) {
throw new IOException("The folder declared in the config as expertSystemFiles either doesn't exist or it contains no files.");
}
Arrays.sort(fileList);
int i; for(i = 0; i < fileList.length; i++) {
String filename = fileList[i].getName(); // Βρίσκουμε την κατάληξη του αρχείου
String ext = (filename.lastIndexOf(".")==-1)?"":filename.substring(filename.lastIndexOf(".")+1,filename.length());
if(fileList[i].isFile() && ext.equals("clp")) {
this.batch(fileList[i].getPath());
}
}
/*this.addDefglobal(new Defglobal("*statisticsCollector*", new Value(statisticsCollector)));
this.executeCommand("(add ?*statisticsCollector*)");*/
registrationUpdater.setStatisticsCollector(statisticsCollector);
this.addDefglobal(new Defglobal("*regUpdater*", new Value(registrationUpdater)));
this.executeCommand("(add ?*regUpdater*)");
System.out.println("Done");
} catch (JessException exc) {
System.err.println(exc);
System.err.println(exc.getCause());
} catch (IOException exc) {
System.err.println(exc);
System.exit(-16);
}
}
/**
* Φορτώνει στο έμπειρο σύστημα τα facts που αφορούν την τρέχουσα κατάσταση
* των εργαστηρίων. Αυτά που μπορούν να αφορούν πράγματα όπως ώρα/ημέρα,
* τυχόν ήδη εγγεγραμένους φοιτητές (π.χ. από προηγούμενη κλήρωση) κ.τ.λ.
* Οι πληροφορίες αυτές παρέχονται μέσα από συναρτήσεις του DataHandlerSQL.
*/
public final void expertSystemAddFacts() {
try {
System.out.print("Getting lab days/hours from the Database... ");
System.out.println("Done");
System.out.print("Getting lab info from the Database... ");
datahandler.addLabInfoFacts();
System.out.println("Done");
System.out.print("Getting registered students from the Database... ");
datahandler.addRegStudentFacts();
System.out.println("Done");
} catch (JessException exc) {
System.err.println(exc);
System.err.println(exc.getCause());
}
}
/**
* Φορτώνει τις προτιμήσεις των φοιτητών στο έμπειρο σύστημα (σαν facts) και
* αρχίζει την εκτέλεση θέτοντας την τιμή "go" στο template "start" σε 1.
* Όταν η εκτέλεση τελειώσει τα αποτελέσματα εξάγονται από το σύστημα και
* δίνονται στον DataHandlerSQL για την περαιτέρω επεξεργασία (εκτός αν το
* config.properties ορίζει ότι το σύστημα είναι σε simulation mode και
* δεν θα περαστούν δεδομένα στη βάση).
*/
public void execute() {
try {
if(config.getProperty("simulationMode", "1").equals("0")) {
datahandler.removeSameLotFails();
}
this.reset();
expertSystemAddFacts();
int i; for(RegistrationPriority curPriority : datahandler.getRegistrationPriorities()) {
System.out.println("Running the Expert System for registration priority "+curPriority.getPriority()+"...");
// Προσθήκη των προτιμήσεων των φοιτητών για τη συγκεκριμένη κατηγορία
ArrayList<Fact> sP = datahandler.getStudentPreferences(curPriority);
if(sP != null) {
for(i = 0; i < sP.size(); i++) {
this.assertFact(sP.get(i));
}
}
this.setFocus("POST_REGISTRATION_TASKS"); // Καθαρισμός τυχόν conflicts με τα ήδη registered τμήματα πριν μπούμε στη φάση εγγραφών
this.run();
this.setFocus("LAB_REGISTRATION_MAIN");
this.run();
registrationUpdater.join(); // Περιμένουμε να τελειώσουν όλα τα updates
}
System.out.println("Done");
// Αποθήκευση των αποτελεσμάτων στη βάση
if(config.getProperty("simulationMode", "1").equals("0")) {
datahandler.removeOldPreferences();
datahandler.markExecuted();
// Αποθήκευση στατιστικών
datahandler.updateStatisticsPreferenceBreakdown(statisticsCollector.getPreferenceBreakdown());
} else {
System.out.println("Simulation mode is active. No database changes.");
}
} catch (JessException exc) {
System.err.println(exc);
System.err.println(exc.getCause());
}
}
/**
* Επιστρέφει το μοναδικό ID της κλήρωσης που θα εκτελέσει το σύστημα.
* @return Το μοναδικό ID της κλήρωσης.
*/
public Integer getLotteryID() {
return lotteryID;
}
/**
* Επιστρέφει το Config που χρησιμοποιεί αυτή τη στιγμή το σύστημα.
* @return Το Config που χρησιμοποιεί αυτή τη στιγμή το σύστημα.
*/
public Config getConfig() {
return config;
}
/**
* Επιστρέφει το DataHandler που χρησιμοποιείται από το συγκεκριμένο σύστημα.
* @return Το DataHandler που χρησιμοποιείται από το συγκεκριμένο σύστημα.
*/
public IDataHandler getDataHandler() {
return datahandler;
}
/**
* Επεξεργάζεται τα command-line arguments για να δημιουργήσει το
* σύστημα κληρώσεων. Τα arguments που μπορεί να λάβει είναι τα εξής:
* <ol>
* <li>-lotid lotteryID: Θέτει το lotteryID.</li>
* </ol>
* @param args Τα command-line arguments.
*/
public static void main(String[] args) {
Integer lotteryID = 1;
String configPath = "config.properties";
String expertSystemFilesPath = "expertSystemFiles";
String arg; int i = 0;
while (i < args.length && args[i].startsWith("-")) {
arg = args[i++];
// Έλεγχος αν έχει οριστεί lotid
if (arg.toLowerCase().equals("-lotid".toLowerCase())) {
if (i < args.length) {
lotteryID = Integer.parseInt(args[i++]);
} else {
System.err.println("-lotid requires an id");
System.exit(-1);
}
} else if(arg.toLowerCase().equals("-configPath".toLowerCase())) {
if (i < args.length) {
configPath = args[i++];
} else {
System.err.println("-configPath requires a path");
System.exit(-1);
}
} else if(arg.toLowerCase().equals("-expertSystemFilesPath".toLowerCase())) {
if (i < args.length) {
expertSystemFilesPath = args[i++];
} else {
System.err.println("expertSystemFilesPath requires a path");
System.exit(-1);
}
}
}
final ESK es = new ESK(lotteryID, configPath, expertSystemFilesPath);
// Έλεγχος εγκυρότητας των command line arguments
if (i == args.length - 1) {
// Μη έγκυρα arguments
System.err.println("Parameters: [-lotid lotteryID]");
} else {
// Έγκυρα arguments
es.execute();
} // End else (command line arguments check)
System.exit(0);
} // End main
} // End class | dnna/seep-thesis | sourceCode/esk/src/esk/lottery/ESK.java |
1,499 | package com.example.commontasker;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Created by Αρης on 1/7/2016.
*/
public class diathesimothta extends AppCompatActivity {
HashMap<String, List<String>> Categories;
List<String> catogories_list;
ExpandableListView expandableListView;
CategoriesCommonAdapter adapter;
private DatabaseReference databaseReference;
// private DatabaseReference databaselike;
private boolean process=false;
private DatabaseReference database;
private Button button1;
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
HashMap<String, List<String>> listDataChild;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diathesimothta);
database= FirebaseDatabase.getInstance().getReference().child("Antikeimena");
//databaselike= FirebaseDatabase.getInstance().getReference().child("Likes");
Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setTitle(null);
}
toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.left_arrow));
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
startActivity(new Intent(diathesimothta.this,common.class));
}
});
/*expandableListView = (ExpandableListView) findViewById(R.id.expandableListView2);
Categories = QuestionProvider.getInfo();
catogories_list = new ArrayList<String>(Categories.keySet());
adapter = new CategoriesCommonAdapter(this, Categories, catogories_list);
expandableListView.setAdapter(adapter);
expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
@Override
public void onGroupExpand(int i) {
Toast.makeText(getBaseContext(), "Επιλέξατε την κατηγορία " + catogories_list.get(i), Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
@Override
public void onGroupCollapse(int i) {
Toast.makeText(getBaseContext(), "Aφήσατε την κατηγορία " + catogories_list.get(i), Toast.LENGTH_LONG).show();
}
});
expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView expandableListView, View view, int grouposition, int childposition, long id) {
view.setSelected(true);
Toast.makeText(getBaseContext(), "Επιλέξατε ότι θέλετε να αξιοποίησετε προς οφελός σας το διαθέσιμο " + Categories.get(catogories_list.get(grouposition)).get(childposition) + " απο την Κατηγορία " + catogories_list.get(grouposition), Toast.LENGTH_LONG).show();
return false;
}
});*/
expListView = (ExpandableListView) findViewById(R.id.lvExp);
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
expListView.setAdapter(listAdapter);
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
@Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
return false;
}
});
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
@Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
v.setSelected(true);
Intent intent_name = new Intent(getApplicationContext(), AntikeimenoDetails.class);
if(groupPosition == 0){
//intent_name = new Intent(getApplicationContext(), AnswerDetails.class);
intent_name.putExtra("description", mhxanhmata1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", mhxanhmata1.get(childPosition).getImage());
intent_name.putExtra("title", mhxanhmata1.get(childPosition).getTitle());
intent_name.putExtra("time", mhxanhmata1.get(childPosition).getTime());
intent_name.putExtra("start_date", mhxanhmata1.get(childPosition).getDatearxh());
intent_name.putExtra("last_date", mhxanhmata1.get(childPosition).getDatetel());
intent_name.putExtra("location", mhxanhmata1.get(childPosition).getLocation());
// intent_name.setClass(getApplicationContext(), AnswerDetails.class);
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent_name);
}
else if(groupPosition == 1){
// Intent intent_name = new Intent();
intent_name.putExtra("description", lipasmata1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", lipasmata1.get(childPosition).getImage());
intent_name.putExtra("title", lipasmata1.get(childPosition).getTitle());
intent_name.putExtra("time", lipasmata1.get(childPosition).getTime());
intent_name.putExtra("start_date", lipasmata1.get(childPosition).getDatearxh());
intent_name.putExtra("last_date", lipasmata1.get(childPosition).getDatetel());
intent_name.putExtra("location", lipasmata1.get(childPosition).getLocation());
// intent_name.setClass(getApplicationContext(), AnswerDetails.class);
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent_name);
}
else if(groupPosition == 2){
intent_name.putExtra("description", sporoi1.get(childPosition).getPerigrafh());
intent_name.putExtra("image", sporoi1.get(childPosition).getImage());
intent_name.putExtra("title", sporoi1.get(childPosition).getTitle());
intent_name.putExtra("time", sporoi1.get(childPosition).getTime());
intent_name.putExtra("start_date", sporoi1.get(childPosition).getDatearxh());
intent_name.putExtra("last_date", sporoi1.get(childPosition).getDatetel());
intent_name.putExtra("location", sporoi1.get(childPosition).getLocation());
// intent_name.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// getApplicationContext().startActivity(intent_name);
startActivity(intent_name);
}
return false;
}
});
}
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Tools");
listDataHeader.add("Machinery");
listDataHeader.add("Fertilizers");
Query query = database;
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot Question : snapshot.getChildren()) {
if(Question.child("title").getValue().equals("Tools")){
mhxanhmata.add(Question.child("description").getValue().toString().trim());
AntikeimenoItem add = new AntikeimenoItem(Question.child("image").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("description").getValue().toString().trim(),Question.child("title").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("start_date").getValue().toString().trim(),Question.child("last_date").getValue().toString().trim());
mhxanhmata1.add(add);
}
else if(Question.child("title").getValue().equals("Machinery")){
lipasmata.add(Question.child("description").getValue().toString().trim());
AntikeimenoItem add = new AntikeimenoItem(Question.child("image").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("description").getValue().toString().trim(),Question.child("title").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("start_date").getValue().toString().trim(),Question.child("last_date").getValue().toString().trim());
lipasmata1.add(add);
}
else if(Question.child("title").getValue().equals("Fertilizers")){
sporoi.add(Question.child("description").getValue().toString().trim());
AntikeimenoItem add = new AntikeimenoItem(Question.child("image").getValue().toString().trim(),Question.child("location").getValue().toString().trim(),Question.child("description").getValue().toString().trim(),Question.child("title").getValue().toString().trim(),Question.child("time").getValue().toString().trim(),Question.child("start_date").getValue().toString().trim(),Question.child("last_date").getValue().toString().trim());
sporoi1.add(add);
}
}
if(mhxanhmata.isEmpty())
mhxanhmata.add("Empty");
if(lipasmata.isEmpty())
lipasmata.add("Empty");
if(sporoi.isEmpty())
sporoi.add("Empty");
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
listDataChild.put(listDataHeader.get(0), mhxanhmata); // Header, Child data
listDataChild.put(listDataHeader.get(1), lipasmata);
listDataChild.put(listDataHeader.get(2), sporoi);
}
private List<String> mhxanhmata = new ArrayList<String>();
private List<String> lipasmata = new ArrayList<String>();
private List<String> sporoi= new ArrayList<String>();
private List<AntikeimenoItem> mhxanhmata1 = new ArrayList<AntikeimenoItem>();
private List<AntikeimenoItem> lipasmata1 = new ArrayList<AntikeimenoItem>();
private List<AntikeimenoItem> sporoi1 = new ArrayList<AntikeimenoItem>();
@Override
protected void onStart() {
super.onStart();
/* FirebaseRecyclerAdapter<AntikeimenoItem, BlogViewHolder> firebaseRecyclerAdapter = new FirebaseRecyclerAdapter<AntikeimenoItem, BlogViewHolder>(AntikeimenoItem.class, R.layout.child_antikeimena, BlogViewHolder.class, database) {
@Override
protected void populateViewHolder(BlogViewHolder viewHolder, AntikeimenoItem model, int position) {
final String post_key =getRef(position).getKey();
viewHolder.setTitle(model.getTitle());
viewHolder.setPerigrafh(model.getPerigrafh());
viewHolder.setDatearxh(model.getDatearxh());
viewHolder.setDatetel(model.getDatetel());
viewHolder.setTime(model.getTime());
viewHolder.setLocation(model.getLocation());
viewHolder.setImage(getApplicationContext(), model.getImage());
viewHolder.setUsername(model.getUsername());
viewHolder.setPost(post_key);
viewHolder.imagelike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
process=true;
if(process){
databaselike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(String.valueOf(dataSnapshot.child("username")))){
databaselike.child(post_key).child(String.valueOf(dataSnapshot.child("username"))).removeValue();
}
else{
databaselike.child(post_key).child(String.valueOf(dataSnapshot.child("username")));
process=false;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
});
}
};
recyclerView.setAdapter(firebaseRecyclerAdapter);*/
}
/* public static class BlogViewHolder extends RecyclerView.ViewHolder {
View view;
ImageButton imagelike;
DatabaseReference databaselike;
public BlogViewHolder(View itemView) {
super(itemView);
view = itemView;
imagelike=(ImageButton) view.findViewById(R.id.likepost);
databaselike= FirebaseDatabase.getInstance().getReference().child("Likes");
databaselike.keepSynced(true);
}
public void setPost(final String post_key) {
databaselike.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child(post_key).hasChild(String.valueOf(dataSnapshot.child("username")))){
imagelike.setImageResource(R.drawable.like_red);
}
else {
imagelike.setImageResource(R.drawable.like);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void setTitle(String title) {
TextView post_title = (TextView) view.findViewById(R.id.title);
post_title.setText(title);
}
public void setPerigrafh(String perigrafh) {
TextView post_perigrafh = (TextView) view.findViewById(R.id.perigrafh);
post_perigrafh.setText(perigrafh);
}
public void setDatearxh(String datearxh) {
TextView post_datearxh = (TextView) view.findViewById(R.id.date);
post_datearxh.setText(datearxh);
}
public void setDatetel(String datetel) {
TextView post_datetel = (TextView) view.findViewById(R.id.datelast);
post_datetel.setText(datetel);
}
public void setTime(String time) {
TextView post_time = (TextView) view.findViewById(R.id.time);
post_time.setText(time);
}
public void setLocation(String location) {
TextView post_location = (TextView) view.findViewById(R.id.location);
post_location.setText(location);
}
public void setUsername(String username){
TextView post_name = (TextView) view.findViewById(R.id.user);
post_name.setText(username);
}
public void setImage(Context context, String image) {
ImageView post_image = (ImageView) view.findViewById(R.id.imaposting);
Picasso.with(context).load(image).into(post_image);
}
}*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu_bottom, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent it;
switch(item.getItemId()){
case R.id.action_facebook:
it = new Intent(Intent.ACTION_VIEW);
it.setData(Uri.parse("http://www.facebook.com"));
startActivity(it);
break;
case R.id.action_phone:
Intent intent = new Intent(this, sos.class);
startActivity(intent);
break;
case R.id.action_home:
Intent intent1 = new Intent(this, MainActivity.class);
startActivity(intent1);
break;
case R.id.action_login:
Intent intent2 = new Intent(this, eggrafh.class);
startActivity(intent2);
break;
case R.id.logout:
logout();
break;
default:
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Θέλετε να βγείτε απο την εφαρμογή?");
alertDialogBuilder
.setMessage("Πατήστε ΝΑΙ για έξοδο!")
.setCancelable(false)
.setPositiveButton("ΝΑΙ",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
Toast.makeText(diathesimothta.this,"Επιτυχής Αποσύνδεση",Toast.LENGTH_LONG).show();
startActivity(new Intent(diathesimothta.this,eggrafh.class));
}
})
.setNegativeButton("ΟΧΙ", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
| netCommonsEU/CommonTasker | app/src/main/java/com/example/commontasker/diathesimothta.java |
1,501 | package gr.aueb.softeng.view.Customer.PlaceOrder;
import java.util.ArrayList;
import gr.aueb.softeng.domain.OrderLine;
public interface PlaceOrderView {
/**
* Προωθούμαστε στο σελίδα επισκόπησης των περιεχομενων της παραγγελίας
* περιμένωντας να επιστρέψει ή πιαθνός τροποποιημένη λιστα με orderlines
*/
void redirectToCart(ArrayList<OrderLine> orderLines);
/**
* Κρυβουμε το recyclerView και το κοθμπί για ολοκλήρωση παραγγελίας
* ενω εμφανίζουμε το μήνυμα μη ύπαρξης πιάτων.
*/
void showEmptyList();
/**
* Εμφανίζουμε και σετάρουμε το recyclerView το κουμπί για ολοκλήρωση παραγγελίας
* ενώ κρύβουμε το μήνυμα οτι δεν υπάρχουν πιάτα
*/
void showDishList();
/**
* Εμφανίζουμε Alert dialog παράθυρο για να ενημερώσουμε τον χρήστη ότι η παραγγελία απέτυχδ διότι
* δεν έχει το απαραίτητο χρηματικό υπολοιπο. Έπειτα προωθείται στο Homepage
*/
void insufficientFundsMessage();
/**
* Εμφανίζουμε Alert dialog παράθυρο για να ενημερώσουμε τον χρήστη για το συνολικό κόστος της παραγγελίας.
* 'Επειτα ο χρήστης είτε διαλέγει να την ολοκληρώσει επιλέγοντας "Ναι" και επιστρέφει στο Homepage ή επιλέγει "Οχι" και
* και κλείνει το παράθυρο
*/
void ShowConfirmationMessage(ConfirmationListener confirmationListener);
void goBack();
}
| vleft02/Restaurant-Application | app/src/main/java/gr/aueb/softeng/view/Customer/PlaceOrder/PlaceOrderView.java |
1,502 | import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.ComboBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.Tab;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellEditEvent;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.cell.ComboBoxTableCell;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.util.converter.FloatStringConverter;
import javafx.util.converter.IntegerStringConverter;
public class dashboardContollers implements Initializable {
@FXML
private Label accounting_number_summary;
@FXML
private Button addBottonDest;
@FXML
private Button addBottonEvents;
@FXML
private Button addBottonTrip;
@FXML
private Label admin_number_summary;
@FXML
private DatePicker arrivalPickerDest;
@FXML
private TableColumn<Destination, String> arrivalTableDest;
@FXML
private ComboBox<String> branchListTrip;
@FXML
private TableColumn<Trip, String> branchTableTrip;
@FXML
private Button clearBottonDest;
@FXML
private Button clearBottonEvents;
@FXML
private Button clearBottonTrip;
@FXML
private TextField costTextTrips;
@FXML
private Pane dashboard;
@FXML
private Button dashbordButton;
@FXML
private DatePicker departureDateTrips;
@FXML
private DatePicker departurePickerDest;
@FXML
private DatePicker departurePickerEvents;
@FXML
private TableColumn<Destination, String> departureTableDest;
@FXML
private TableColumn<Event, String> departureTableEvents;
@FXML
private TableColumn<Trip, String> departureTableTrips;
@FXML
private TableColumn<Destination, String> descriptionTableDest;
@FXML
private TableColumn<Event, String> descriptionTableEvents;
@FXML
private TextArea descriptionTextDest;
@FXML
private TextArea descriptionTextEvents;
@FXML
private Label destinationNumber;
@FXML
private ComboBox<String> driverListTrips;
@FXML
private TableColumn<Trip, String> driverTableTrips;
@FXML
private Label drivers_number_summary;
@FXML
private Button exitButton;
@FXML
private ComboBox<String> guideListTrips;
@FXML
private TableColumn<Trip, String> guideTableTrip;
@FXML
private Label guide_number_summary;
@FXML
private Label incomes;
@FXML
private ComboBox<String> languageListDest;
@FXML
private TableColumn<Destination, String> languageTableDest;
@FXML
private ComboBox<String> locationListDest;
@FXML
private TableColumn<Destination, String> locationTableDest;
@FXML
private Label logistics_number_summary;
@FXML
private TextField nameFieldDest;
@FXML
private TableColumn<Destination, String> nameTableDest;
@FXML
private Button newReservationButton;
@FXML
private Button offerButton;
@FXML
private Label outcomes;
@FXML
private TableColumn<Trip, Float> priceTableTrips;
@FXML
private Label profit;
@FXML
private Label reservationNumber;
@FXML
private DatePicker returnDateTrip;
@FXML
private DatePicker returnPickerEvents;
@FXML
private TableColumn<Event, String> returnTableEvents;
@FXML
private TableColumn<Trip, String> returnTableTrips;
@FXML
private Button searchBottonDest;
@FXML
private Button searchBottonEvents;
@FXML
private Button searchBottonTrip;
@FXML
private TextField seatTextTrip;
@FXML
private TableColumn<Trip, Integer> seatsTableTrips;
@FXML
private Button settingsButton;
@FXML
private Button signoutButton;
@FXML
private TableView<Destination> tableDest;
@FXML
private TableView<Event> tableEvents;
@FXML
private TableView<Trip> tableTrip;
@FXML
private AnchorPane travelMenu;
@FXML
private Button tripButton;
@FXML
private TableColumn<Event, Integer> tripIdTableEvents;
@FXML
private ComboBox<String> tripidListDest;
@FXML
private ComboBox<String> tripidListEvents;
@FXML
private ComboBox<String> tripidListTrips;
@FXML
private TableColumn<Destination, Integer> tripidTableDest;
@FXML
private TableColumn<Trip, Integer> tripidTableTrips;
@FXML
private ComboBox<String> typeListDest;
@FXML
private TableColumn<Destination, String> typeTableDest;
@FXML
private Label usernameLabel;
@FXML
private Button workerButton;
@FXML
private AnchorPane workers_summary;
@FXML
private Tab eventTabTrip;
@FXML
private Pane addOffersMenu;
@FXML
private Pane reservationMenu;
@FXML
private Pane userInformationScene;
@FXML
private Pane workersManagerMenu;
@FXML
private TableColumn<settings, String> ACTIONCOLUMNSET;
@FXML
private TextField ATTEXTSET;
@FXML
private TextField BRANCHTEXTSET;
@FXML
private TableColumn<settings, String> CHANGESCOLUMNSET;
@FXML
private Label DATETEXTSET;
@FXML
private TextField LNAMETEXTSET;
@FXML
private TextField NAMETEXTSET;
@FXML
private PasswordField PASSTEXTSET;
@FXML
private ImageView PHOTOUSERSET;
@FXML
private TextField SALARYTEXTSET;
@FXML
private TableView<settings> TABLESET;
@FXML
private TableColumn<settings, String> TIMECOLUMNSET;
@FXML
private Button UPDATESET;
@FXML
private TableColumn<settings, String> USERCOLUMNSET;
@FXML
private Button addButtonAddWorker;
@FXML
private ComboBox<String> adminBranchAddWorker;
@FXML
private ComboBox<String> adminTypeAddWorker;
@FXML
private ComboBox<String> branchAddWorker;
@FXML
private Button clearButtonAddWorker;
@FXML
private TextArea cvAddWorker;
@FXML
private TextField diplomaAddWorker;
@FXML
private TextField experienceAddWorker;
@FXML
private TextField idAddWorker;
@FXML
private TextField languageAddWorker;
@FXML
private ComboBox<String> licenseAddWorker;
@FXML
private TextField lnameAddWorker;
@FXML
private TextField nameAddWorker;
@FXML
private ComboBox<String> routeAddWorker;
@FXML
private TextField salaryAddWorker;
@FXML
private ComboBox<String> typeAddWorker;
@FXML
private Label adminLabel;
@FXML
private Label typeLabel;
@FXML
private Label branchLabel;
@FXML
private Label diplomaLabel;
@FXML
private Label licenseLabel;
@FXML
private Label routeLabel;
@FXML
private Label experienceLabel;
@FXML
private Label driverLabel;
@FXML
private Label guideLabel;
@FXML
private Label languageLabel;
@FXML
private TableView<Worker> tableWorker;
@FXML
private TableColumn<Worker, String> atColumnWorker;
@FXML
private TableColumn<Worker, String> branchColumnWorker;
@FXML
private TableColumn<Worker, String> lnameColumnWorker;
@FXML
private TableColumn<Worker, String> nameColumnWorker;
@FXML
private TableColumn<Worker, Float> salaryColumnWorker;
@FXML
private TableColumn<Worker, String> typeColumnWorker;
@FXML
private ComboBox<String> destinationListOffer;
@FXML
private ComboBox<String> idListOffer;
@FXML
private DatePicker startDatePickerOffer;
@FXML
private TextField costTextOffer;
@FXML
private DatePicker finishDatePickerOffer;
@FXML
private Button serachButtonOffer;
@FXML
private Button addButtonOffer;
@FXML
private Button clearButtonOffer;
@FXML
private TableView<Offers> offerTable;
@FXML
private TableColumn<Offers, String> idColumnOffer;
@FXML
private TableColumn<Offers, String> startColumnOffer;
@FXML
private TableColumn<Offers, String> finishColumnOffer;
@FXML
private TableColumn<Offers, Float> costColumnOffer;
@FXML
private TableColumn<Offers, String> destinationColumnOffer;
@FXML
private Tab offersTabReservation;
@FXML
private ComboBox<String> offeridListRes;
@FXML
private TextField nameTextRes;
@FXML
private TextField lnameTextRes;
@FXML
private TextField depositTextRes;
@FXML
private Label offid;
@FXML
private Label offname;
@FXML
private Label offdeposit;
@FXML
private Label offlname;
@FXML
private Button clearOfferResButton;
@FXML
private Button addResOfferButton;
@FXML
private Button searchResOfferButton;
@FXML
private TableView<reservation_offer> offerResTable;
@FXML
private TableColumn<reservation_offer, String> idColumnRes;
@FXML
private TableColumn<reservation_offer, String> nameColumnRes;
@FXML
private TableColumn<reservation_offer, String> lnameColumnRes;
@FXML
private TableColumn<reservation_offer, String> offeridColumnRes;
@FXML
private TableColumn<reservation_offer, Float> depositColumnRes;
@FXML
private ImageView imageReservationRes;
@FXML
private ComboBox<String> ageListReservationRes;
@FXML
private ComboBox<Integer> idReservationRes;
@FXML
private TextField nameFieldReservationRes;
@FXML
private TextField lnameFieldReservationRes;
@FXML
private TextField numSeatFielsReservationRes;
@FXML
private Button createITSettings;
@FXML
private ComboBox<String> workersItComboBoxSettings;
@FXML
private PasswordField passwordITSeettings;
private double x, y;
public void dashboardBottonClicked(ActionEvent e) {
dashboard.setVisible(true);
travelMenu.setVisible(false);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(false);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(false);
}
public void exitButtonClicked(ActionEvent e) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Επιβεβαίωση εξόδου");
alert.setHeaderText("Επιβεβαίωση");
alert.setContentText("Είστε σίγουροι ότι θέλετε να τερματίσετε την εφαρμογή;");
ButtonType buttonTypeOK = new ButtonType("Έξοδος", ButtonData.OK_DONE);
ButtonType buttonTypeCancel = new ButtonType("Ακύρωση", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeCancel, buttonTypeOK);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOK)
System.exit(0);
}
public void logout(ActionEvent e) {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Επιβεβαίωση εξόδου");
alert.setHeaderText("Επιβεβαίωση");
alert.setContentText("Είστε σίγουροι ότι θέλετε να αποσυνδεθείτε;");
ButtonType buttonTypeOK = new ButtonType("Αποσύνδεση", ButtonData.OK_DONE);
ButtonType buttonTypeCancel = new ButtonType("Ακύρωση", ButtonData.CANCEL_CLOSE);
alert.getButtonTypes().setAll(buttonTypeCancel, buttonTypeOK);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == buttonTypeOK)
try {
Parent root = FXMLLoader.load(getClass().getResource("fxml code/login.fxml"));
Stage stage = new Stage();
Scene scene = new Scene(root);
root.setOnMousePressed((MouseEvent h) -> {
x = h.getSceneX();
y = h.getSceneY();
});
root.setOnMouseDragged((MouseEvent h) -> {
stage.setX(h.getScreenX() - x);
stage.setY(h.getSceneY() - y);
stage.setOpacity(.8);
});
root.setOnMouseReleased((MouseEvent h) -> {
stage.setOpacity(1);
});
stage.initStyle(StageStyle.TRANSPARENT);
stage.setScene(scene);
signoutButton.getScene().getWindow().hide();
stage.show();
} catch (IOException h) {
h.printStackTrace();
}
}
public void tripButtonPressed(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
initTripIdTrips(conn);
initGuidetrips(conn);
initDrivertrips(conn);
initBranchtrips(conn);
initTripIdEvents(conn);
initTypeDestination(conn);
initLocationDestination(conn);
initLanguageDestination(conn);
initTripIdDestination(conn);
initTripTable(conn);
dashboard.setVisible(false);
travelMenu.setVisible(true);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(false);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(false);
} catch (SQLException exception) {
exception.printStackTrace();
}
}
public void workerButtonPressed(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
dashboard.setVisible(false);
travelMenu.setVisible(false);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(false);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(true);
initWorker(conn);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void offerButtonPressed(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
dashboard.setVisible(false);
travelMenu.setVisible(false);
addOffersMenu.setVisible(true);
reservationMenu.setVisible(false);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(false);
initOfferScene(conn);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void reservationButtonPressed(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
dashboard.setVisible(false);
travelMenu.setVisible(false);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(true);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(false);
initOfferidReservation(conn);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void settingsButtonPressed(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
dashboard.setVisible(false);
travelMenu.setVisible(false);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(false);
userInformationScene.setVisible(true);
workersManagerMenu.setVisible(false);
initSETTINGS(conn);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
private void initDashboardData(Connection conn) throws SQLException {
conn = connectDB.getConnection();
Statement stmt = conn.createStatement();
String query = "SELECT SUM(wrk_salary) FROM worker";
ResultSet result = stmt.executeQuery(query);
float costs = 0;
while (result.next()) {
costs = result.getFloat("SUM(wrk_salary)");
outcomes.setText(String.format(Locale.GERMAN, "%,.2f", costs));
}
query = "SELECT SUM(res_off_depoit) FROM reservation_offers";
result = stmt.executeQuery(query);
float incomesVariable = 0;
while (result.next()) {
incomesVariable = result.getFloat("SUM(res_off_depoit)");
}
query = "SELECT SUM(tr_cost) FROM trip JOIN reservation ON trip.tr_id = reservation.res_tr_id";
result = stmt.executeQuery(query);
while (result.next()) {
incomesVariable += result.getFloat("SUM(tr_cost)");
}
incomes.setText(String.format(Locale.GERMAN, "%,.2f", incomesVariable));
float profitVariable = incomesVariable - costs;
profit.setText(String.format(Locale.GERMAN, "%,.2f", profitVariable));
if (profitVariable < 0) {
profit.setStyle("-fx-text-fill: red;");
} else {
profit.setStyle("-fx-text-fill: green;");
}
query = "SELECT COUNT(*) FROM driver";
result = stmt.executeQuery(query);
while (result.next()) {
drivers_number_summary.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(*)")));
}
query = "SELECT COUNT(*) FROM guide";
result = stmt.executeQuery(query);
while (result.next()) {
guide_number_summary.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(*)")));
}
query = "SELECT COUNT(*) FROM admin WHERE adm_type = 'LOGISTICS'";
result = stmt.executeQuery(query);
while (result.next()) {
logistics_number_summary.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(*)")));
}
query = "SELECT COUNT(*) FROM admin WHERE adm_type = 'ADMINISTRATIVE'";
result = stmt.executeQuery(query);
while (result.next()) {
admin_number_summary.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(*)")));
}
query = "SELECT COUNT(*) FROM admin WHERE adm_type = 'ACCOUNTING'";
result = stmt.executeQuery(query);
while (result.next()) {
admin_number_summary.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(*)")));
}
query = "SELECT COUNT(*) FROM reservation";
int reserv = 0;
result = stmt.executeQuery(query);
while (result.next()) {
reserv = result.getInt("COUNT(*)");
}
query = "SELECT COUNT(*) FROM reservation_offers";
result = stmt.executeQuery(query);
while (result.next()) {
reserv += result.getInt("COUNT(*)");
}
reservationNumber.setText(String.format(Locale.GERMAN, "%,d", reserv));
query = "SELECT COUNT(DISTINCT dst_name) FROM destination WHERE dst_location IS NOT NULL";
result = stmt.executeQuery(query);
while (result.next()) {
destinationNumber.setText(String.format(Locale.GERMAN, "%,d", result.getInt("COUNT(DISTINCT dst_name)")));
}
}
/* TRIP TAB */
private void initTripIdTrips(Connection conn) throws SQLException {
tripidListTrips.getItems().clear();
String query = "SELECT tr_id FROM trip ORDER BY tr_id";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
tripidListTrips.getItems().add(Integer.toString(result.getInt("tr_id")));
}
}
private void initGuidetrips(Connection conn) throws SQLException {
guideListTrips.getItems().clear();
String query = "SELECT DISTINCT CONCAT(wrk_name, ' ', wrk_lname) AS name " +
"FROM guide g JOIN worker w " +
"ON g.gui_AT = w.wrk_AT " +
"ORDER BY CONCAT(wrk_name, ' ', wrk_lname);";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
guideListTrips.getItems().add(result.getString("name"));
}
}
private void initDrivertrips(Connection conn) throws SQLException {
driverListTrips.getItems().clear();
String query = "SELECT DISTINCT CONCAT(wrk_name, ' ', wrk_lname) AS name " +
"FROM driver d JOIN worker w " +
"ON d.drv_AT = w.wrk_AT " +
"ORDER BY CONCAT(wrk_name, ' ', wrk_lname)";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
driverListTrips.getItems().add(result.getString("name"));
}
}
private void initBranchtrips(Connection conn) throws SQLException {
branchListTrip.getItems().clear();
String query = "SELECT CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) AS address FROM branch ORDER BY address;";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
branchListTrip.getItems().add(result.getString("address"));
}
}
private void initTripTable(Connection conn) throws SQLException {
tableTrip.setEditable(true);
String query = "SELECT DISTINCT CONCAT(wrk_name, ' ', wrk_lname) AS name " +
"FROM guide g JOIN worker w " +
"ON g.gui_AT = w.wrk_AT " +
"ORDER BY CONCAT(wrk_name, ' ', wrk_lname);";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
ObservableList<String> guides = FXCollections.observableArrayList();
while (result.next()) {
guides.add(result.getString("name"));
}
query = "SELECT CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) AS address " +
"FROM branch ORDER BY address";
result = stmt.executeQuery(query);
ObservableList<String> branches = FXCollections.observableArrayList();
while (result.next()) {
branches.add(result.getString("address"));
}
query = "SELECT DISTINCT CONCAT(wrk_name, ' ', wrk_lname) AS name " +
"FROM driver d JOIN worker w " +
"ON d.drv_AT = w.wrk_AT " +
"ORDER BY CONCAT(wrk_name, ' ', wrk_lname)";
result = stmt.executeQuery(query);
ObservableList<String> drivers = FXCollections.observableArrayList();
while (result.next()) {
drivers.add(result.getString("name"));
}
tripidTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, Integer>("trip_id"));
departureTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, String>("departure"));
returnTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, String>("return_"));
priceTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, Float>("cost"));
priceTableTrips.setCellFactory(TextFieldTableCell.forTableColumn(new FloatStringConverter()));
priceTableTrips.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Trip, Float>>() {
@Override
public void handle(CellEditEvent<Trip, Float> arg0) {
try (Connection conn1 = connectDB.getConnection()) {
Trip trip = arg0.getRowValue();
int id = trip.getTrip_id();
String updateQuery = "SET @USER = ?";
PreparedStatement preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, userInformation.getLastname());
preparedStmt.executeQuery();
updateQuery = "UPDATE trip SET tr_cost = ? WHERE tr_id = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setFloat(1, arg0.getNewValue());
preparedStmt.setInt(2, id);
preparedStmt.executeUpdate();
preparedStmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
seatsTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, Integer>("seats"));
seatsTableTrips.setCellFactory(TextFieldTableCell.forTableColumn(new IntegerStringConverter()));
seatsTableTrips.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Trip, Integer>>() {
@Override
public void handle(CellEditEvent<Trip, Integer> arg0) {
try (Connection conn1 = connectDB.getConnection()) {
Trip trip = arg0.getRowValue();
int id = trip.getTrip_id();
String updateQuery = "SET @USER = ?";
PreparedStatement preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, userInformation.getLastname());
preparedStmt.executeQuery();
updateQuery = "UPDATE trip SET tr_maxseats = ? WHERE tr_id = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setInt(1, arg0.getNewValue());
preparedStmt.setInt(2, id);
preparedStmt.executeUpdate();
preparedStmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
branchTableTrip.setCellValueFactory(new PropertyValueFactory<Trip, String>("branch"));
branchTableTrip.setCellFactory(ComboBoxTableCell.forTableColumn(branches));
branchTableTrip.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Trip, String>>() {
@Override
public void handle(CellEditEvent<Trip, String> arg0) {
try (Connection conn1 = connectDB.getConnection()) {
Trip trip = arg0.getRowValue();
int id = trip.getTrip_id();
String updateQuery = "SET @USER = ?";
PreparedStatement preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, userInformation.getLastname());
preparedStmt.executeQuery();
updateQuery = "SELECT br_code FROM branch WHERE CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) LIKE ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, arg0.getNewValue());
ResultSet result = preparedStmt.executeQuery();
result.next();
int branchId = result.getInt("br_code");
updateQuery = "UPDATE trip SET tr_br_code = ? WHERE tr_id = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setInt(1, branchId);
preparedStmt.setInt(2, id);
preparedStmt.executeUpdate();
preparedStmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
guideTableTrip.setCellValueFactory(new PropertyValueFactory<Trip, String>("guide"));
guideTableTrip.setCellFactory(ComboBoxTableCell.forTableColumn(guides));
guideTableTrip.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Trip, String>>() {
@Override
public void handle(CellEditEvent<Trip, String> arg0) {
try (Connection conn1 = connectDB.getConnection()) {
Trip trip = arg0.getRowValue();
int id = trip.getTrip_id();
String updateQuery = "SET @USER = ?";
PreparedStatement preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, userInformation.getLastname());
preparedStmt.executeQuery();
updateQuery = "SELECT gui_AT FROM guide g JOIN worker w ON g.gui_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, arg0.getNewValue());
ResultSet result = preparedStmt.executeQuery();
result.next();
String guideAT = result.getString("gui_AT");
updateQuery = "UPDATE trip SET tr_gui_AT = ? WHERE tr_id = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, guideAT);
preparedStmt.setInt(2, id);
preparedStmt.executeUpdate();
preparedStmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
driverTableTrips.setCellValueFactory(new PropertyValueFactory<Trip, String>("driver"));
driverTableTrips.setCellFactory(ComboBoxTableCell.forTableColumn(drivers));
driverTableTrips.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<Trip, String>>() {
@Override
public void handle(CellEditEvent<Trip, String> arg0) {
try (Connection conn1 = connectDB.getConnection()) {
Trip trip = arg0.getRowValue();
int id = trip.getTrip_id();
String updateQuery = "SET @USER = ?";
PreparedStatement preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, userInformation.getLastname());
preparedStmt.executeQuery();
updateQuery = "SELECT drv_AT FROM driver d JOIN worker w ON d.drv_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, arg0.getNewValue());
ResultSet result = preparedStmt.executeQuery();
result.next();
String driverAT = result.getString("drv_AT");
updateQuery = "UPDATE trip SET tr_drv_AT = ? WHERE tr_id = ?";
preparedStmt = conn1.prepareStatement(updateQuery);
preparedStmt.setString(1, driverAT);
preparedStmt.setInt(2, id);
preparedStmt.executeUpdate();
preparedStmt.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
stmt.close();
}
public void searchTrip(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
tableTrip.getItems().clear();
String tripid = tripidListTrips.getValue();
LocalDate departure = departureDateTrips.getValue();
LocalDate ret = returnDateTrip.getValue();
String cost = costTextTrips.getText();
String seats = seatTextTrip.getText();
String branch = branchListTrip.getValue();
String guide = guideListTrips.getValue();
String driver = driverListTrips.getValue();
String query = "SELECT gui_AT FROM guide g JOIN worker w ON g.gui_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, guide);
ResultSet result = stmt.executeQuery();
String guiAT = null;
while (result.next()) {
guiAT = result.getString("gui_AT");
}
query = "SELECT drv_AT FROM driver d JOIN worker w ON d.drv_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, driver);
result = stmt.executeQuery();
String drvAT = null;
while (result.next()) {
drvAT = result.getString("drv_AT");
}
query = "SELECT br_code FROM branch WHERE CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) LIKE ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, branch);
result = stmt.executeQuery();
String branch_code = null;
while (result.next()) {
branch_code = result.getString("br_code");
}
ArrayList<String> listOfWhereClause = new ArrayList<>();
if (tripid != null)
listOfWhereClause.add("tr_id=" + tripid);
if (!costTextTrips.getText().isEmpty())
listOfWhereClause.add("tr_cost=" + cost);
if (!seatTextTrip.getText().isEmpty())
listOfWhereClause.add("tr_maxseats=" + seats);
if (branch_code != null)
listOfWhereClause.add("tr_br_code='" + branch_code + "'");
if (guiAT != null)
listOfWhereClause.add("tr_gui_AT='" + guiAT + "'");
if (drvAT != null)
listOfWhereClause.add("tr_drv_AT='" + drvAT + "'");
if (departure != null && ret != null)
listOfWhereClause.add("tr_departure BETWEEN '" + departure + " 00:00:00' " + " AND '" + departure
+ " 23:59:59' AND tr_return BETWEEN " + ret + " 00:00:00' AND '" + ret + " 23:59:59'");
else if (departure != null)
listOfWhereClause
.add("tr_departure BETWEEN '" + departure + " 00:00:00' AND '" + departure + " 23:59:59'");
else if (ret != null)
listOfWhereClause.add("tr_return BETWEEN '" + ret + " 00:00:00'" + " AND '" + ret + " 23:59:59'");
String whereClause = String.join(" AND ", listOfWhereClause);
query = "SELECT t.tr_id, t.tr_departure, t.tr_return, t.tr_maxseats, t.tr_cost, " +
"CONCAT(b.br_city, ', ', b.br_street, ' ', b.br_num) AS address," +
" CONCAT(w.wrk_name, ' ', w.wrk_lname) AS guide, " +
"CONCAT(w1.wrk_name, ' ', w1.wrk_lname) AS driver " +
"FROM trip t JOIN branch b ON t.tr_br_code = b.br_code" +
" JOIN worker w ON t.tr_gui_AT = w.wrk_AT " +
"JOIN worker w1 ON t.tr_drv_AT = w1.wrk_AT";
if (!whereClause.isEmpty())
query += " WHERE " + whereClause;
result = stmt.executeQuery(query);
while (result.next()) {
int trip_id_temp = result.getInt("t.tr_id");
String departure_temp = result.getString("t.tr_departure");
String return__temp = result.getString("t.tr_return");
float cost_temp = result.getFloat("t.tr_cost");
int seats_temp = result.getInt("t.tr_maxseats");
String branch_temp = result.getString("address");
String guide_temp = result.getString("guide");
String driver_temp = result.getString("driver");
tableTrip.getItems().add(new Trip(trip_id_temp, departure_temp, return__temp, cost_temp, seats_temp,
branch_temp, guide_temp, driver_temp));
}
} catch (SQLException ex) {
ex.getSQLState();
}
}
public void addTrip(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
java.sql.Timestamp departure = java.sql.Timestamp.from(
departureDateTrips.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
java.sql.Timestamp ret = java.sql.Timestamp.from(
returnDateTrip.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
String cost = costTextTrips.getText();
String seats = seatTextTrip.getText();
String branch = branchListTrip.getValue();
String guide = guideListTrips.getValue();
String driver = driverListTrips.getValue();
String query = "SELECT gui_AT FROM guide g JOIN worker w ON g.gui_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, guide);
ResultSet result = stmt.executeQuery();
String guiAT = null;
while (result.next()) {
guiAT = result.getString("gui_AT");
}
query = "SELECT drv_AT FROM driver d JOIN worker w ON d.drv_AT = w.wrk_AT WHERE CONCAT(wrk_name, ' ', wrk_lname) = ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, driver);
result = stmt.executeQuery();
String drvAT = null;
while (result.next()) {
drvAT = result.getString("drv_AT");
}
query = "SELECT br_code FROM branch WHERE CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) LIKE ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, branch);
result = stmt.executeQuery();
String branch_code = null;
while (result.next()) {
branch_code = result.getString("br_code");
}
stmt.executeQuery("SET @USER = '" + userInformation.getLastname() + "'");
query = "INSERT INTO trip VALUES(NULL, ?, ?, ?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setTimestamp(1, departure);
stmt.setTimestamp(2, ret);
stmt.setInt(3, Integer.parseInt(seats));
stmt.setFloat(4, Float.parseFloat(cost));
stmt.setString(5, branch_code);
stmt.setString(6, guiAT);
stmt.setString(7, drvAT);
stmt.executeUpdate();
initBranchtrips(conn);
initDrivertrips(conn);
initGuidetrips(conn);
initTripIdTrips(conn);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή ταξιδιου!");
alert.setTitle("Επιβεβαίωση Εισαγωγής ταξιδιού");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (NullPointerException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("Η ημερομηνία είναι υποχρεωτική");
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearBottonTrips(ActionEvent e) {
tripidListTrips.setValue(null);
guideListTrips.setValue(null);
driverListTrips.setValue(null);
branchListTrip.setValue(null);
departureDateTrips.setValue(null);
returnDateTrip.setValue(null);
costTextTrips.clear();
seatTextTrip.clear();
tableTrip.getItems().clear();
}
/* EVENTS TAB */
private void initTripIdEvents(Connection conn) throws SQLException {
tripidListEvents.getItems().clear();
String query = "SELECT DISTINCT ev_tr_id FROM event ORDER BY ev_tr_id";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
tripidListEvents.getItems().add(Integer.toString(result.getInt("ev_tr_id")));
}
}
public void searchEvents(ActionEvent e) {
tableEvents.getItems().clear();
try (Connection conn = connectDB.getConnection()) {
String tripId = tripidListEvents.getValue();
LocalDate departure = departurePickerEvents.getValue();
LocalDate ret = returnPickerEvents.getValue();
String description = descriptionTextEvents.getText();
ArrayList<String> listWhereClause = new ArrayList<>();
if (tripId != null)
listWhereClause.add("ev_tr_id = " + tripId);
if (departure != null && ret != null)
listWhereClause.add("ev_start BETWEEN '" + departure + " 00:00:00' " + " AND '" + departure
+ " 23:59:59' AND ev_end BETWEEN '" + ret + " 00:00:00' AND '" + ret + " 23:59:59'");
else if (departure != null)
listWhereClause
.add("ev_start BETWEEN '" + departure + " 00:00:00' AND '" + departure + " 23:59:59'");
else if (ret != null)
listWhereClause.add("ev_end BETWEEN '" + ret + " 00:00:00'" + " AND '" + ret + " 23:59:59'");
if (!descriptionTextDest.getText().isEmpty())
listWhereClause.add("ev_descr = '" + description + "'");
String whereClause = String.join(" AND ", listWhereClause);
String query = "SELECT * FROM event";
if (!whereClause.isEmpty())
query += " WHERE " + whereClause;
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
tripIdTableEvents.setCellValueFactory(new PropertyValueFactory<Event, Integer>("tripId"));
departureTableEvents.setCellValueFactory(new PropertyValueFactory<Event, String>("start"));
returnTableEvents.setCellValueFactory(new PropertyValueFactory<Event, String>("end"));
descriptionTableEvents.setCellValueFactory(new PropertyValueFactory<Event, String>("description"));
while (result.next()) {
int trip_id = result.getInt("ev_tr_id");
String start = result.getString("ev_start");
String end = result.getString("ev_end");
String desc = result.getString("ev_descr");
tableEvents.getItems().add(new Event(trip_id, start, end, desc));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void addEventsClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String tripId = tripidListEvents.getValue();
java.sql.Timestamp departure = java.sql.Timestamp.from(
departurePickerEvents.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault())
.toInstant());
java.sql.Timestamp ret = java.sql.Timestamp.from(
returnPickerEvents.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
String description = descriptionTextEvents.getText();
PreparedStatement stmt = conn.prepareStatement("SET @USER = ?");
stmt.setString(1, userInformation.getLastname());
stmt.executeQuery();
String query = "INSERT INTO event VALUES(?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, Integer.parseInt(tripId));
stmt.setTimestamp(2, departure);
stmt.setTimestamp(3, ret);
stmt.setString(4, description);
stmt.executeUpdate();
stmt.close();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή εκδήλωσης!");
alert.setTitle("Επιβεβαίωση Εισαγωγής εκδήλωσης");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (NullPointerException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("Η ημερομηνία είναι υποχρεωτική");
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearEventsClicked(ActionEvent e) {
tripidListEvents.setValue(null);
departurePickerEvents.setValue(null);
returnPickerEvents.setValue(null);
descriptionTextEvents.clear();
;
}
/* DESTINATION TAB */
private void initTripIdDestination(Connection conn) throws SQLException {
tripidListDest.getItems().clear();
String query = "SELECT DISTINCT to_tr_id FROM destination dest JOIN travel_to tro ON dest.dst_id = tro.to_dst_id ORDER BY to_tr_id";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
tripidListDest.getItems().add(Integer.toString(result.getInt("to_tr_id")));
}
}
private void initTypeDestination(Connection conn) throws SQLException {
typeListDest.getItems().clear();
String query = "SELECT DISTINCT dsrt_type FROM destination";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
typeListDest.getItems().add(result.getString("dsrt_type"));
}
}
private void initLocationDestination(Connection conn) throws SQLException {
locationListDest.getItems().clear();
String query = "SELECT DISTINCT dst_name FROM destination WHERE dst_location IS NULL";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
locationListDest.getItems().add("");
while (result.next()) {
locationListDest.getItems().add(result.getString("dst_name"));
}
}
private void initLanguageDestination(Connection conn) throws SQLException {
languageListDest.getItems().clear();
String query = "SELECT DISTINCT dst_language FROM destination ORDER BY dst_language";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
languageListDest.getItems().add(result.getString("dst_language"));
}
}
public void searchDest(ActionEvent e) {
tableDest.getItems().clear();
try (Connection conn = connectDB.getConnection()) {
String trip_id = tripidListDest.getValue();
String name = nameFieldDest.getText();
LocalDate departure = departurePickerDest.getValue();
LocalDate ret = arrivalPickerDest.getValue();
String type = typeListDest.getValue();
String location = locationListDest.getValue();
String language = languageListDest.getValue();
String description = descriptionTextDest.getText();
String query = "SELECT tro.to_tr_id, d.dst_name, tro.to_departure, tro.to_arrival," +
" d.dsrt_type, d.dst_language, d.dst_descr, d1.dst_name FROM destination d JOIN " +
"travel_to tro ON d.dst_id = tro.to_dst_id JOIN destination d1 ON d.dst_location = d1.dst_id";
ArrayList<String> listWhereClause = new ArrayList<>();
if (trip_id != null)
listWhereClause.add("tro.to_tr_id = " + trip_id);
if (!nameFieldDest.getText().isEmpty())
listWhereClause.add("d.dst_name = '" + name + "'");
if (departure != null && ret != null)
listWhereClause.add("ev_start BETWEEN '" + departure + " 00:00:00' " + " AND '" + departure
+ " 23:59:59' AND ev_end BETWEEN " + ret + " 00:00:00' AND '" + ret + " 23:59:59'");
else if (departure != null)
listWhereClause
.add("ev_start BETWEEN '" + departure + " 00:00:00' AND '" + departure + " 23:59:59'");
else if (ret != null)
listWhereClause.add("ev_end BETWEEN '" + ret + " 00:00:00'" + " AND '" + ret + " 23:59:59'");
if (type != null)
listWhereClause.add("d.dsrt_type = '" + type + "'");
if (location != null)
listWhereClause.add("d1.dst_name = '" + location + "'");
if (language != null)
listWhereClause.add("d.dst_language = '" + language + "'");
if (!descriptionTextDest.getText().isEmpty())
listWhereClause.add("d.dst_descr LIKE '" + description + "'");
String whereClause = String.join(" AND ", listWhereClause);
if (!whereClause.isEmpty())
query += " WHERE " + whereClause;
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
tripidTableDest.setCellValueFactory(new PropertyValueFactory<Destination, Integer>("trip_id"));
nameTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("name"));
departureTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("departure"));
arrivalTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("arrival"));
typeTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("type"));
locationTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("location"));
languageTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("language"));
descriptionTableDest.setCellValueFactory(new PropertyValueFactory<Destination, String>("description"));
while (result.next()) {
int tripID = result.getInt("tro.to_tr_id");
String nameString = result.getString("d.dst_name");
String departureString = result.getString("tro.to_departure");
String arrivalString = result.getString("tro.to_arrival");
String typeString = result.getString("d.dsrt_type");
String locationString = result.getString("d1.dst_name");
String languageString = result.getString("d.dst_language");
String descriptionString = result.getString("d.dst_descr");
tableDest.getItems().add(new Destination(tripID, nameString, departureString, arrivalString, typeString,
locationString, languageString, descriptionString));
}
// stmt.close();
} catch (SQLException ex) {
ex.getSQLState();
}
}
public void addDest(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String trip_id = tripidListDest.getValue();
String name = nameFieldDest.getText();
java.sql.Timestamp departure = java.sql.Timestamp.from(
departurePickerDest.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault())
.toInstant());
java.sql.Timestamp arrival = java.sql.Timestamp.from(
arrivalPickerDest.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault()).toInstant());
String type = typeListDest.getValue();
String location = locationListDest.getValue();
String language = languageListDest.getValue();
String description = descriptionTextDest.getText();
Integer location_id = null;
PreparedStatement stmt = conn.prepareStatement("SET @USER = ?");
stmt.setString(1, userInformation.getLastname());
stmt.executeQuery();
String query = "SELECT dst_id FROM destination WHERE dst_name LIKE ?";
stmt = conn.prepareStatement(query);
stmt.setString(1, location);
ResultSet result = stmt.executeQuery();
if (result.next())
location_id = result.getInt("dst_id");
if (location_id != null) {
query = "INSERT INTO destination(dst_name, dst_descr, dsrt_type, dst_language, dst_location) VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, name);
stmt.setString(2, description);
stmt.setString(3, type);
stmt.setString(4, language);
stmt.setInt(5, location_id);
} else {
query = "INSERT INTO destination(dst_name, dst_descr, dsrt_type, dst_language, dst_location) VALUES (?, ?, ?, ?, NULL)";
stmt = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
stmt.setString(1, name);
stmt.setString(2, description);
stmt.setString(3, type);
stmt.setString(4, language);
}
stmt.executeUpdate();
ResultSet genKeys = stmt.getGeneratedKeys();
query = "INSERT INTO travel_to VALUES (?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, Integer.parseInt(trip_id));
genKeys.next();
stmt.setInt(2, genKeys.getInt(1));
stmt.setTimestamp(3, arrival);
stmt.setTimestamp(4, departure);
stmt.executeUpdate();
stmt.close();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή προορισμού!");
alert.setTitle("Επιβεβαίωση Εισαγωγής προορισμού");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (NullPointerException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("Η ημερομηνία είναι υποχρεωτική");
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearDest(ActionEvent e) {
tripidListDest.setValue(null);
nameFieldDest.setText("");
departurePickerDest.setValue(null);
arrivalPickerDest.setValue(null);
typeListDest.setValue(null);
locationListDest.setValue(null);
languageListDest.setValue(null);
descriptionTextDest.clear();
tableDest.getItems().clear();
}
// WORKERS SCENE
private void initTableOfWorker(Connection conn) throws SQLException {
tableWorker.getItems().clear();
String query = "SELECT w.wrk_AT, " +
"w.wrk_name, " +
"w.wrk_lname, " +
"w.wrk_salary, " +
"CONCAT(b.br_city, ', ', b.br_street, ' ', IF(b.br_num IS NULL, '-', b.br_num)) AS branchName, " +
"'DRIVER' AS type " +
"FROM worker w JOIN branch b ON w.wrk_br_code = b.br_code " +
"JOIN driver d ON d.drv_AT = w.wrk_AT " +
"UNION " +
"SELECT w.wrk_AT, " +
"w.wrk_name, " +
"w.wrk_lname, " +
"w.wrk_salary, " +
"CONCAT(b.br_city, ', ', b.br_street, ' ', IF(b.br_num IS NULL, '-', b.br_num)) AS branchName, " +
"'GUIDE' " +
"FROM worker w JOIN branch b ON w.wrk_br_code = b.br_code " +
"JOIN guide g ON g.gui_AT = w.wrk_AT " +
"UNION " +
"SELECT w.wrk_AT, " +
"w.wrk_name, " +
"w.wrk_lname, " +
"w.wrk_salary, " +
"CONCAT(b.br_city, ', ', b.br_street, ' ', IF(b.br_num IS NULL, '-', b.br_num)) AS branchName, " +
"ad.adm_type " +
"FROM worker w JOIN branch b ON w.wrk_br_code = b.br_code " +
"JOIN admin ad ON ad.adm_AT = w.wrk_AT " +
"UNION " +
"SELECT w.wrk_AT, " +
"w.wrk_name, " +
"w.wrk_lname, " +
"w.wrk_salary, " +
"CONCAT(b.br_city, ', ', b.br_street, ' ', IF(b.br_num IS NULL, '-', b.br_num)) AS branchName, " +
"'WORKER'" +
"FROM worker w JOIN branch b " +
"ON w.wrk_br_code = b.br_code " +
"WHERE w.wrk_AT NOT IN ( " +
"SELECT w.wrk_AT " +
"FROM worker w JOIN driver d ON d.drv_AT = w.wrk_AT " +
"UNION " +
"SELECT w.wrk_AT " +
"FROM worker w JOIN guide g ON g.gui_AT = w.wrk_AT " +
"UNION " +
"SELECT w.wrk_AT " +
"FROM worker w JOIN admin ad ON ad.adm_AT = w.wrk_AT " +
") ORDER BY wrk_AT";
atColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, String>("at"));
nameColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, String>("name"));
lnameColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, String>("lname"));
salaryColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, Float>("salry"));
branchColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, String>("branch"));
typeColumnWorker.setCellValueFactory(new PropertyValueFactory<Worker, String>("type"));
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
String AT = result.getString("wrk_AT");
String name = result.getString("wrk_name");
String lastname = result.getString("wrk_lname");
float salary = result.getFloat("wrk_salary");
String branch = result.getString("branchName");
String type = result.getString("type");
tableWorker.getItems().add(new Worker(AT, name, lastname, branch, salary, type));
}
stmt.close();
}
private void initWorker(Connection conn) throws SQLException {
tableWorker.getItems().clear();
branchAddWorker.getItems().clear();
typeAddWorker.getItems().clear();
adminTypeAddWorker.getItems().clear();
licenseAddWorker.getItems().clear();
routeAddWorker.getItems().clear();
String query = "SELECT CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) FROM branch";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
// final String selectedValue;
while (result.next()) {
branchAddWorker.getItems().add(result.getString(1));
adminBranchAddWorker.getItems().add(result.getString(1));
}
initTableOfWorker(conn);
typeAddWorker.getItems().add("Worker");
typeAddWorker.getItems().add("Driver");
typeAddWorker.getItems().add("Administrator");
typeAddWorker.getItems().add("Guide");
licenseAddWorker.getItems().add("A");
licenseAddWorker.getItems().add("B");
licenseAddWorker.getItems().add("C");
licenseAddWorker.getItems().add("D");
routeAddWorker.getItems().add("LOCAL");
routeAddWorker.getItems().add("ABROAD");
adminTypeAddWorker.getItems().add("LOGISTICS");
adminTypeAddWorker.getItems().add("ADMINISTRATIVE");
adminTypeAddWorker.getItems().add("ACCOUNTING");
guideLabel.setVisible(false);
languageLabel.setVisible(false);
cvAddWorker.setVisible(false);
languageAddWorker.setVisible(false);
licenseLabel.setVisible(false);
routeLabel.setVisible(false);
experienceLabel.setVisible(false);
driverLabel.setVisible(false);
licenseAddWorker.setVisible(false);
routeAddWorker.setVisible(false);
experienceAddWorker.setVisible(false);
adminLabel.setVisible(false);
typeLabel.setVisible(false);
branchLabel.setVisible(false);
diplomaLabel.setVisible(false);
adminTypeAddWorker.setVisible(false);
adminBranchAddWorker.setVisible(false);
diplomaAddWorker.setVisible(false);
typeAddWorker.valueProperty().addListener((observable, oldValue, newValue) -> {
String selectedValue = newValue;
switch (selectedValue) {
case "Worker":
guideLabel.setVisible(false);
languageLabel.setVisible(false);
cvAddWorker.setVisible(false);
languageAddWorker.setVisible(false);
licenseLabel.setVisible(false);
routeLabel.setVisible(false);
experienceLabel.setVisible(false);
driverLabel.setVisible(false);
licenseAddWorker.setVisible(false);
routeAddWorker.setVisible(false);
experienceAddWorker.setVisible(false);
adminLabel.setVisible(false);
typeLabel.setVisible(false);
branchLabel.setVisible(false);
diplomaLabel.setVisible(false);
adminTypeAddWorker.setVisible(false);
adminBranchAddWorker.setVisible(false);
diplomaAddWorker.setVisible(false);
break;
case "Driver":
guideLabel.setVisible(false);
languageLabel.setVisible(false);
cvAddWorker.setVisible(false);
languageAddWorker.setVisible(false);
adminLabel.setVisible(false);
typeLabel.setVisible(false);
branchLabel.setVisible(false);
diplomaLabel.setVisible(false);
adminTypeAddWorker.setVisible(false);
adminBranchAddWorker.setVisible(false);
diplomaAddWorker.setVisible(false);
licenseLabel.setVisible(true);
routeLabel.setVisible(true);
experienceLabel.setVisible(true);
driverLabel.setVisible(true);
licenseAddWorker.setVisible(true);
routeAddWorker.setVisible(true);
experienceAddWorker.setVisible(true);
break;
case "Administrator":
guideLabel.setVisible(false);
languageLabel.setVisible(false);
cvAddWorker.setVisible(false);
languageAddWorker.setVisible(false);
adminLabel.setVisible(true);
typeLabel.setVisible(true);
branchLabel.setVisible(true);
diplomaLabel.setVisible(true);
adminTypeAddWorker.setVisible(true);
adminBranchAddWorker.setVisible(true);
diplomaAddWorker.setVisible(true);
licenseLabel.setVisible(false);
routeLabel.setVisible(false);
experienceLabel.setVisible(false);
driverLabel.setVisible(false);
licenseAddWorker.setVisible(false);
routeAddWorker.setVisible(false);
experienceAddWorker.setVisible(false);
break;
case "Guide":
guideLabel.setVisible(true);
languageLabel.setVisible(true);
cvAddWorker.setVisible(true);
languageAddWorker.setVisible(true);
adminLabel.setVisible(false);
typeLabel.setVisible(false);
branchLabel.setVisible(false);
diplomaLabel.setVisible(false);
adminTypeAddWorker.setVisible(false);
adminBranchAddWorker.setVisible(false);
diplomaAddWorker.setVisible(false);
licenseLabel.setVisible(false);
routeLabel.setVisible(false);
experienceLabel.setVisible(false);
driverLabel.setVisible(false);
licenseAddWorker.setVisible(false);
routeAddWorker.setVisible(false);
experienceAddWorker.setVisible(false);
break;
}
});
stmt.close();
}
public void addWorkerButtonClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String name = nameAddWorker.getText();
String lname = lnameAddWorker.getText();
String idNumber = idAddWorker.getText();
Float salary = Float.parseFloat(salaryAddWorker.getText());
String worker_type = typeAddWorker.getValue().toString();
int branch = 0;
String branchName = branchAddWorker.getValue();
String query = "SELECT br_code FROM branch WHERE CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) = '"
+
branchName + "'";
Statement branchid = conn.createStatement();
ResultSet result = branchid.executeQuery(query);
while (result.next()) {
branch = result.getInt("br_code");
}
query = "INSERT INTO worker VALUES (?, ?, ?, ?, ?)";
switch (worker_type) {
case "Worker":
PreparedStatement stmt1 = conn.prepareStatement(query);
stmt1.setString(1, idNumber);
stmt1.setString(2, name);
stmt1.setString(3, lname);
stmt1.setFloat(4, salary);
stmt1.setInt(5, branch);
stmt1.executeUpdate();
stmt1.close();
branchid.close();
break;
case "Driver":
CallableStatement stmt = conn.prepareCall("CALL addNewDriver(?, ?, ?, ?, ?, ?, ?)");
stmt.setString(1, idNumber);
stmt.setString(2, name);
stmt.setString(3, lname);
stmt.setFloat(4, salary);
stmt.setString(5, licenseAddWorker.getValue());
stmt.setString(6, routeAddWorker.getValue());
stmt.setString(7, experienceAddWorker.getText());
stmt.executeUpdate();
stmt.close();
break;
case "Administrator":
PreparedStatement stmt2 = conn.prepareStatement(query);
stmt2.setString(1, idNumber);
stmt2.setString(2, name);
stmt2.setString(3, lname);
stmt2.setFloat(4, salary);
stmt2.setInt(5, branch);
stmt2.executeUpdate();
query = "INSERT INTO admin VALUES(?, ?, ?)";
stmt2 = conn.prepareStatement(query);
stmt2.setString(1, idNumber);
stmt2.setString(2, adminTypeAddWorker.getValue());
stmt2.setString(3, diplomaAddWorker.getText());
stmt2.executeUpdate();
query = "SELECT br_code FROM branch WHERE CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) = '"
+
adminBranchAddWorker.getValue() + "'";
branchid = conn.createStatement();
result = branchid.executeQuery(query);
if (result.next()) {
branch = result.getInt("br_code");
}
branchid.close();
query = "INSERT INTO manages VALUES(?, ?)";
stmt2 = conn.prepareStatement(query);
stmt2.setString(1, idNumber);
stmt2.setInt(2, branch);
stmt2.executeUpdate();
stmt2.close();
break;
case "Guide":
PreparedStatement stmt3 = conn.prepareStatement(query);
stmt3.setString(1, idNumber);
stmt3.setString(2, name);
stmt3.setString(3, lname);
stmt3.setFloat(4, salary);
stmt3.setInt(5, branch);
stmt3.executeUpdate();
query = "INSERT INTO guide VALUES(?, ?)";
stmt3 = conn.prepareStatement(query);
stmt3.setString(1, idNumber);
stmt3.setString(2, cvAddWorker.getText());
stmt3.executeUpdate();
query = "INSERT INTO languages VALUES(?, ?)";
stmt3 = conn.prepareStatement(query);
stmt3.setString(1, idNumber);
stmt3.setString(2, languageAddWorker.getText());
stmt3.executeUpdate();
stmt3.close();
break;
}
initTableOfWorker(conn);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void clearButtonWorkersClicked(ActionEvent e) {
nameAddWorker.clear();
lnameAddWorker.clear();
idAddWorker.clear();
salaryAddWorker.clear();
experienceAddWorker.clear();
diplomaAddWorker.clear();
cvAddWorker.clear();
languageAddWorker.clear();
branchAddWorker.setValue(null);
typeAddWorker.setValue("Worker");
licenseAddWorker.setValue(null);
routeAddWorker.setValue(null);
adminTypeAddWorker.setValue(null);
adminBranchAddWorker.setValue(null);
}
// OFFER SCENE
private void initOfferScene(Connection conn) throws SQLException {
idListOffer.getItems().clear();
destinationListOffer.getItems().clear();
String query = "SELECT offer_id FROM offers ORDER BY offer_id";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
idListOffer.getItems().add(Integer.toString(result.getInt("offer_id")));
}
query = "SELECT DISTINCT dst_name FROM destination WHERE dst_location IS NOT NULL ORDER BY dst_name";
result = stmt.executeQuery(query);
while (result.next()) {
destinationListOffer.getItems().add(result.getString("dst_name"));
}
stmt.close();
}
public void searchOfferBottonClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
offerTable.getItems().clear();
String id = idListOffer.getValue();
LocalDate start = startDatePickerOffer.getValue();
LocalDate finish = finishDatePickerOffer.getValue();
String cost = costTextOffer.getText();
String destination = destinationListOffer.getValue();
String query = "SELECT offer_id, offer_start, offer_finish, offer_cost, dst_name FROM offers JOIN destination ON offer_dst_id = dst_id";
ArrayList<String> listWhereClause = new ArrayList<>();
if (id != null)
listWhereClause.add(" offer_id = '" + id + "'");
if (start != null && finish != null)
listWhereClause.add("offer_start BETWEEN '" + start + " 00:00:00' " + " AND '" + start
+ " 23:59:59' AND offer_finish BETWEEN " + finish + " 00:00:00' AND '" + finish + " 23:59:59'");
else if (start != null)
listWhereClause.add("offer_start BETWEEN '" + start + " 00:00:00' AND '" + start + " 23:59:59'");
else if (finish != null)
listWhereClause.add("ev_end BETWEEN '" + finish + " 00:00:00'" + " AND '" + finish + " 23:59:59'");
if (!costTextOffer.getText().isEmpty())
listWhereClause.add(" offer_cost = " + cost);
if (destination != null)
listWhereClause.add(" dst_name LIKE '" + destination + "'");
String whereClause = String.join(" AND ", listWhereClause);
if (!whereClause.isEmpty())
query += " WHERE " + whereClause;
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
idColumnOffer.setCellValueFactory(new PropertyValueFactory<Offers, String>("id"));
startColumnOffer.setCellValueFactory(new PropertyValueFactory<Offers, String>("start"));
finishColumnOffer.setCellValueFactory(new PropertyValueFactory<Offers, String>("finish"));
costColumnOffer.setCellValueFactory(new PropertyValueFactory<Offers, Float>("cost"));
destinationColumnOffer.setCellValueFactory(new PropertyValueFactory<Offers, String>("destination"));
while (result.next()) {
String myid = Integer.toString(result.getInt("offer_id"));
String mystart = result.getString("offer_start");
String myfinish = result.getString("offer_finish");
float mycost = result.getFloat("offer_cost");
String mydestination = result.getString("dst_name");
offerTable.getItems().add(new Offers(myid, mystart, myfinish, mycost, mydestination));
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
public void addOfferBottonClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
java.sql.Timestamp start = java.sql.Timestamp.from(
startDatePickerOffer.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault())
.toInstant());
java.sql.Timestamp finish = java.sql.Timestamp.from(
finishDatePickerOffer.getValue().atStartOfDay().atZone(java.time.ZoneId.systemDefault())
.toInstant());
Float costOffer = Float.parseFloat(costTextOffer.getText());
int destination = 0;
String query = "SELECT dst_id FROM destination WHERE dst_name LIKE '" + destinationListOffer.getValue()
+ "'";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
if (result.next()) {
destination = result.getInt("dst_id");
}
stmt.close();
query = "INSERT INTO offers(offer_start, offer_finish, offer_cost, offer_dst_id) VALUES(?, ?,?, ?)";
PreparedStatement stmt1 = conn.prepareStatement(query);
stmt1.setTimestamp(1, start);
stmt1.setTimestamp(2, finish);
stmt1.setFloat(3, costOffer);
stmt1.setInt(4, destination);
stmt1.executeUpdate();
stmt1.close();
initOfferScene(conn);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή ταξιδιου!");
alert.setTitle("Επιβεβαίωση Εισαγωγής ταξιδιού");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (NullPointerException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("Η ημερομηνία είναι υποχρεωτική");
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearBottonOffer(ActionEvent e) {
offerTable.getItems().clear();
idListOffer.setValue(null);
startDatePickerOffer.setValue(null);
finishDatePickerOffer.setValue(null);
costTextOffer.setText("");
destinationListOffer.setValue(null);
}
// SETTINGS SCENE
private void initSETTINGS(Connection conn) throws SQLException {
TABLESET.getItems().clear();
ATTEXTSET.setText(userInformation.getAT());
NAMETEXTSET.setText(userInformation.getName());
LNAMETEXTSET.setText(userInformation.getLastname());
SALARYTEXTSET.setText(Double.toString(userInformation.getSalary()));
PASSTEXTSET.setText(userInformation.getPassword());
DATETEXTSET.setText(userInformation.getStart_date().format(DateTimeFormatter.ofPattern("dd/MM/yy")));
ATTEXTSET.disableProperty();
workersItComboBoxSettings.getItems().clear();
Statement stmt = conn.createStatement();
String query = "SELECT CONCAT(br_city, ', ', br_street,' ', IF(br_num IS NULL, '-', br_num)) FROM branch WHERE br_code = "
+ userInformation.getBranch();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
BRANCHTEXTSET.setText(result.getString(1));
}
USERCOLUMNSET.setCellValueFactory(new PropertyValueFactory<settings, String>("user"));
CHANGESCOLUMNSET.setCellValueFactory(new PropertyValueFactory<settings, String>("change"));
ACTIONCOLUMNSET.setCellValueFactory(new PropertyValueFactory<settings, String>("action"));
TIMECOLUMNSET.setCellValueFactory(new PropertyValueFactory<settings, String>("date"));
query = "SELECT user_AT, action,changes,stamp FROM log";
result = stmt.executeQuery(query);
while (result.next()) {
String user = result.getString("user_AT");
String action = result.getString("action");
String changes = result.getString("changes");
String date = result.getString("stamp");
TABLESET.getItems().add(new settings(user, changes, action, date));
}
query = "SELECT CONCAT (wrk_name, ' ', wrk_lname) AS name FROM worker LEFT JOIN it ON worker.wrk_AT = it.IT_AT WHERE IT_AT IS NULL ORDER BY name";
result = stmt.executeQuery(query);
while (result.next()) {
workersItComboBoxSettings.getItems().add(result.getString("name"));
}
stmt.close();
}
public void updateButtonSettingsClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String at = ATTEXTSET.getText();
float salary = Float.parseFloat(SALARYTEXTSET.getText());
String query = "UPDATE worker SET wrk_salary = ? WHERE wrk_AT = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setFloat(1, salary);
stmt.setString(2, at);
stmt.executeUpdate();
stmt.close();
query = "SELECT wrk_salary " +
"FROM worker " +
"WHERE wrk_AT = '" + at + "'";
Statement stmt2 = conn.createStatement();
ResultSet result = stmt2.executeQuery(query);
while (result.next()) {
Float newSalary = result.getFloat("wrk_salary");
userInformation.setSalary(newSalary);
}
SALARYTEXTSET.setText(Double.toString(userInformation.getSalary()));
stmt2.close();
} catch (SQLException ex) {
ex.getSQLState();
}
}
public void createITbuttonClicked(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String name = workersItComboBoxSettings.getValue();
String query = "SELECT wrk_AT FROM worker WHERE CONCAT (wrk_name, ' ', wrk_lname) LIKE ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, name);
ResultSet result = stmt.executeQuery();
result.next();
String AT = result.getString("wrk_AT");
if(passwordITSeettings.getText().isEmpty()){
query = "INSERT INTO it(IT_AT, start_date) VALUES (?, CURRENT_TIMESTAMP)";
stmt = conn.prepareStatement(query);
stmt.setString(1, AT);
}else
{
query = "INSERT INTO it(IT_AT, password, start_date) VALUES (?, ?, CURRENT_TIMESTAMP)";
stmt = conn.prepareStatement(query);
stmt.setString(1, AT);
stmt.setString(2, passwordITSeettings.getText());
}
stmt.executeUpdate();
stmt.close();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή IT!");
alert.setTitle("Επιβεβαίωση Εισαγωγής IT");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// RESERVATION SCENE
private void initOfferidReservation(Connection conn) throws SQLException {
offeridListRes.getItems().clear();
idReservationRes.getItems().clear();
ageListReservationRes.getItems().clear();
String query = "SELECT DISTINCT res_off_id FROM reservation_offers ORDER BY res_off_id ";
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
while (result.next()) {
offeridListRes.getItems().add(Integer.toString(result.getInt("res_off_id")));
}
stmt.close();
query = "SELECT tr_id FROM trip ORDER BY tr_id";
stmt = conn.createStatement();
result = stmt.executeQuery(query);
while (result.next()) {
idReservationRes.getItems().add(result.getInt("tr_id"));
}
stmt.close();
ageListReservationRes.getItems().add("ADULT");
ageListReservationRes.getItems().add("MINOR");
imageReservationRes.setImage(new Image("photo/zoumborobot.jpg"));
}
/* RESERVATION TAB */
public void addReservationRes(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
int tr_id = idReservationRes.getValue();
String name = nameFieldReservationRes.getText();
String lname = lnameFieldReservationRes.getText();
String age = ageListReservationRes.getValue();
int numSeat = Integer.parseInt(numSeatFielsReservationRes.getText());
String query = "INSERT INTO reservation VALUES (?, ?, ?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement("SET @USER = ?");
stmt.setString(1, userInformation.getLastname());
stmt.executeQuery();
query = "INSERT INTO reservation VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setInt(1, tr_id);
stmt.setInt(2, numSeat);
stmt.setString(3, name);
stmt.setString(4, lname);
stmt.setString(5, age);
stmt.executeUpdate();
stmt.close();
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή προσφοράς!");
alert.setTitle("Επιβεβαίωση Εισαγωγής προσφοράς");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
if (ex.getErrorCode() == 1062) {
alert.setContentText("Η θέση δεν είναι ελεύθερη, επιλέξτε κάποια άλλη.");
} else {
alert.setContentText(ex.toString());
}
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (NullPointerException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText("Η ημερομηνία είναι υποχρεωτική");
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearReservationRes(ActionEvent e) {
idReservationRes.setValue(null);
nameFieldReservationRes.setText("");
lnameFieldReservationRes.setText("");
ageListReservationRes.setValue(null);
numSeatFielsReservationRes.setText("");
}
public void deleteReservationRes(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String query = null;
ArrayList<String> listWhereClause = new ArrayList<>();
if (idReservationRes.getValue() != null)
listWhereClause.add("res_tr_id = " + idReservationRes.getValue());
if (!nameFieldReservationRes.getText().isEmpty())
listWhereClause.add("res_name = '" + nameFieldReservationRes.getText() + "'");
if (!lnameFieldReservationRes.getText().isEmpty())
listWhereClause.add("res_lname = '" + lnameFieldReservationRes.getText() + "'");
if (ageListReservationRes.getValue() != null)
listWhereClause.add("res_isadult = '" + ageListReservationRes.getValue() + "'");
if (!numSeatFielsReservationRes.getText().isEmpty())
listWhereClause.add("res_seatnum = " + numSeatFielsReservationRes.getText());
if (!listWhereClause.isEmpty())
query = "DELETE FROM reservation WHERE " + String.join(" AND ", listWhereClause);
Statement stmt = conn.createStatement();
stmt.executeQuery("SET @USER = '" + userInformation.getLastname() + "'");
stmt.executeUpdate(query);
stmt.close();
} catch (SQLException ex) {
ex.getSQLState();
}
}
/* OFFERS TAB */
public void searchReservationOffer(ActionEvent e) {
offerResTable.getItems().clear();
try (Connection conn = connectDB.getConnection()) {
String offer_id = offeridListRes.getValue();
String name = nameTextRes.getText();
String lname = lnameTextRes.getText();
String deposit = depositTextRes.getText();
String query = "SELECT res_off_tr_id, res_off_lname, res_off_name, res_off_id, res_off_depoit FROM reservation_offers ";
ArrayList<String> listWhereClause = new ArrayList<>();
if (offer_id != null)
listWhereClause.add("res_off_id = " + offer_id);
if (!nameTextRes.getText().isEmpty())
listWhereClause.add("res_off_name = '" + name + "'");
if (!lnameTextRes.getText().isEmpty())
listWhereClause.add("res_off_lname = '" + lname + "'");
if (!depositTextRes.getText().isEmpty())
listWhereClause.add("res_off_depoit = " + Float.parseFloat(deposit));
String whereClause = String.join(" AND ", listWhereClause);
if (!whereClause.isEmpty())
query += " WHERE " + whereClause;
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(query);
idColumnRes.setCellValueFactory(new PropertyValueFactory<reservation_offer, String>("res_off_id"));
offeridColumnRes.setCellValueFactory(new PropertyValueFactory<reservation_offer, String>("res_off_tr_id"));
nameColumnRes.setCellValueFactory(new PropertyValueFactory<reservation_offer, String>("res_off_name"));
lnameColumnRes.setCellValueFactory(new PropertyValueFactory<reservation_offer, String>("res_off_lname"));
depositColumnRes.setCellValueFactory(new PropertyValueFactory<reservation_offer, Float>("res_off_deposit"));
while (result.next()) {
String reservation_id = Integer.toString(result.getInt("res_off_tr_id"));
String offerID = Integer.toString(result.getInt("res_off_id"));
String nameString = result.getString("res_off_name");
String lnameString = result.getString("res_off_lname");
float deposit_ = result.getFloat("res_off_depoit");
offerResTable.getItems()
.add(new reservation_offer(lnameString, reservation_id, nameString, offerID, deposit_));
}
stmt.close();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void addResOffer(ActionEvent e) {
try (Connection conn = connectDB.getConnection()) {
String offer_res_id = offeridListRes.getValue();
String name = nameTextRes.getText();
String lname = lnameTextRes.getText();
String deposit = depositTextRes.getText();
String query = "INSERT INTO reservation_offers (res_off_lname,res_off_name,res_off_id,res_off_depoit) VALUES ( ?, ?, ?,?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(2, name);
stmt.setString(1, lname);
stmt.setString(3, offer_res_id);
stmt.setFloat(4, Float.parseFloat(deposit));
stmt.executeUpdate();
stmt.close();
initOfferidReservation(conn);
Alert alert = new Alert(AlertType.INFORMATION);
alert.setContentText("Επιτυχής εισαγωγή προσφοράς!");
alert.setTitle("Επιβεβαίωση Εισαγωγής προσφοράς");
alert.setHeaderText("Επιτυχία");
alert.showAndWait();
} catch (SQLException ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setHeaderText("Σφάλμα " + ex.getErrorCode());
alert.setTitle("Σφάλμα");
alert.showAndWait();
} catch (Exception ex) {
Alert alert = new Alert(AlertType.ERROR);
alert.setContentText(ex.toString());
alert.setTitle("Σφάλμα");
alert.setHeaderText("Σφάλμα");
alert.showAndWait();
}
}
public void clearOfferRes(ActionEvent e) {
offeridListRes.setValue(null);
nameTextRes.setText("");
lnameTextRes.setText("");
depositTextRes.setText("");
offerResTable.getItems().clear();
}
@Override
public void initialize(URL location, ResourceBundle resources) {
usernameLabel.setText(userInformation.getLastname());
dashboard.setVisible(true);
travelMenu.setVisible(false);
addOffersMenu.setVisible(false);
reservationMenu.setVisible(false);
userInformationScene.setVisible(false);
workersManagerMenu.setVisible(false);
try (Connection conn = connectDB.getConnection()) {
initDashboardData(conn);
} catch (SQLException e) {
System.err.println(e.getSQLState());
}
}
}
| ltopalis/DB-JavaFX-JDBC | code/dashboardContollers.java |
1,503 | package com.example.commontask;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.example.commontask.Helper.Helper;
import com.example.commontask.utils.Constants;
import com.example.commontask.utils.EmailEncoding;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.weiwangcn.betterspinner.library.BetterSpinner;
import java.util.ArrayList;
import java.util.HashMap;
public class EditProfileActivity extends AppCompatActivity{
private static final String TAG = EditProfileActivity.class.getSimpleName();
private EditText editProfileName;
private EditText editProfileVillage;
private EditText editProfilePhoneNumber;
private EditText editProfileAge;
private EditText editProfileEmail;
String test,userTestEmail;
private DatabaseReference mCurrentUserDatabaseReference1;
Animation shake;
private Vibrator vib;
String name,location,field,job,ageuser,use,userTestField, userTestLocation, userTestAge,userTestName,userTestkind,userTestJob,userTestUse;
private FirebaseAuth mFirebaseAuth;
private String currentUserEmail;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseDatabase mFirebaseDatabase1;
private DatabaseReference mCurrentUserDatabaseReference;
Context context;
private ProgressDialog mProgress;
private TextInputLayout namel, local, emaill, phonel,surnamel,agel,jobl;
ArrayAdapter<CharSequence> arrayAdapter,arrayAdapter1;
Button saveEditButton;
Query query;
BetterSpinner spinner1,spinner2,spinner3,spinner4;
ImageButton mOrder;
EditText mItemSelected;
String[] listItems;
boolean[] checkedItems;
String item2;
TextView textView6;
private static final int ERROR_DIALOG_REQUEST = 9001;
ArrayList<Integer> mUserItems = new ArrayList<>();
private AlphaAnimation buttonClick = new AlphaAnimation(1F, 0.8F);
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
ImageView checkmark = (ImageView) findViewById(R.id.saveChanges);
editProfileName = (EditText)findViewById(R.id.name);
editProfileEmail= (EditText)findViewById(R.id.email);
spinner1=(BetterSpinner) findViewById(R.id.location);
spinner2=(BetterSpinner) findViewById(R.id.age);
spinner3=(BetterSpinner) findViewById(R.id.jobin);
spinner4=(BetterSpinner) findViewById(R.id.categoryuse);
String[] list1 = getResources().getStringArray(R.array.villages);
String[] list2 = getResources().getStringArray(R.array.age);
String[] list3 = getResources().getStringArray(R.array.job);
String[] list4 = getResources().getStringArray(R.array.use_truck);
agel=(TextInputLayout) findViewById(R.id.ag);
namel = (TextInputLayout) findViewById(R.id.singup);
local = (TextInputLayout) findViewById(R.id.loc);
jobl = (TextInputLayout) findViewById(R.id.jobout);
imageButton=(ImageButton) findViewById(R.id.alert);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(EditProfileActivity.this);
builder1.setTitle("Υπενθύμιση Λίπανσης Αλκυστήρα");
builder1.setMessage("Η ελαφρά χρήση ενός ελκυστήρα σημαίνει ότι υπάρχει ανάγκη λίπανησης κάθε τρείς μήνες...Μέτρια χρήση του ελκυστήρα σημαίνει ότι υπάρχει ανάγκη λίπανησης κάθε έξι μήνες και η βαριά χρήση ενός ελκυστήρα σημαίνει ότι υπάρχει ανάγκη λίπανησης κάθε δώδεκα μήνες!");
builder1.setCancelable(true);
builder1.setNeutralButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
ImageView backArrow = (ImageView) findViewById(R.id.backArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating back to ProfileActivity");
finish();
}
});
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list1);
spinner1.setAdapter(adapter);
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list2);
spinner2.setAdapter(adapter1);
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list3);
spinner3.setAdapter(adapter2);
ArrayAdapter<String> adapter3 = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, list4);
spinner4.setAdapter(adapter3);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinner1.getAdapter().getItem(i).toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinner2.getAdapter().getItem(i).toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
spinner3.getAdapter().getItem(i).toString();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
shake = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.shake);
vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
currentUserEmail = EmailEncoding.commaEncodePeriod(mFirebaseAuth.getCurrentUser().getEmail());
mCurrentUserDatabaseReference = mFirebaseDatabase
.getReference().child(Constants.USERS_LOCATION
+ "/" + currentUserEmail);
query = mCurrentUserDatabaseReference;
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
test= EmailEncoding.commaDecodePeriod(mFirebaseAuth.getCurrentUser().getEmail());
userTestEmail = ((HashMap) dataSnapshot.getValue()).get("email").toString();
if (userTestEmail.equalsIgnoreCase(test)) {
userTestName = ((HashMap) dataSnapshot.getValue()).get("username").toString();
userTestLocation = ((HashMap) dataSnapshot.getValue()).get("location").toString();
userTestEmail = ((HashMap) dataSnapshot.getValue()).get("email").toString();
userTestAge = ((HashMap) dataSnapshot.getValue()).get("age").toString();
userTestJob = ((HashMap) dataSnapshot.getValue()).get("job").toString();
userTestUse = ((HashMap) dataSnapshot.getValue()).get("use").toString();
if(userTestName!=null){
editProfileName.setText(userTestName);
}
if(userTestLocation!=null){
spinner1.setText(userTestLocation);
}
if(userTestAge!=null){
spinner2.setText(userTestAge);
}
if(userTestJob!=null){
spinner3.setText(userTestJob);
}
if(userTestUse!=null){
spinner4.setText(userTestUse);
}
if(userTestEmail!=null){
editProfileEmail.setText(userTestEmail);
editProfileEmail.setEnabled(false);
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
checkmark.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
update();
}
});
}
private void update() {
name = editProfileName.getText().toString();
location = spinner1.getText().toString();
ageuser = spinner2.getText().toString();
job= spinner3.getText().toString();
use= spinner4.getText().toString();
if (TextUtils.isEmpty(name) || TextUtils.isEmpty(location) || TextUtils.isEmpty(job)|| TextUtils.isEmpty(ageuser)|| TextUtils.isEmpty(use)) {
Helper.displayMessageToast(EditProfileActivity.this, "Όλα τα πεδία πρέπει να ειναι συμπληρωμένα!");
}
if (!validate()) {
onSignupFailed();
}
else{
Query query = mCurrentUserDatabaseReference;
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot snapshot) {
userTestEmail = ((HashMap) snapshot.getValue()).get("email").toString();
String currentUserEmailfinal= EmailEncoding.commaDecodePeriod(mFirebaseAuth.getCurrentUser().getEmail());
if (userTestEmail.equals(currentUserEmailfinal)) {
mCurrentUserDatabaseReference.child("username").setValue(name);
mCurrentUserDatabaseReference.child("location").setValue(location);
mCurrentUserDatabaseReference.child("age").setValue(ageuser);
mCurrentUserDatabaseReference.child("job").setValue(job);
mCurrentUserDatabaseReference.child("use").setValue(use);
}
Intent intent = new Intent(getApplicationContext(),com.example.commontask.ui.ProfileActivity.class);
onSignupSuccess();
intent.putExtra("username", name);
intent.putExtra("location",location);
intent.putExtra("age",ageuser);
intent.putExtra("job",job);
intent.putExtra("use",use);
startActivity(intent);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
private void onSignupSuccess() {
Toast.makeText(getBaseContext(), "Επιτυχής Ενημέρωση Στοιχείων Προφίλ!", Toast.LENGTH_LONG).show();
}
private void onSignupFailed() {
Toast.makeText(getBaseContext(), "Ανεπιτυχής Ενημέρωση Στοιχείων Προφίλ!", Toast.LENGTH_LONG).show();
}
public boolean validate() {
boolean valid = true;
String n = editProfileName.getText().toString();
if (n.isEmpty() || n.length() < 5) {
editProfileName.setAnimation(shake);
editProfileName.startAnimation(shake);
vib.vibrate(180);
editProfileName.setError("Το όνομα πρέπει να περιέχει τουλαχιστόν 5 χαρακτήρες..");
valid = false;
} else {
editProfileName.setError(null);
}
return valid;
}
public String getUid() {
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
currentUserEmail = EmailEncoding.commaEncodePeriod(mFirebaseAuth.getCurrentUser().getEmail());
return currentUserEmail;
}
}
| netCommonsEU/AppLea | app/src/main/java/com/example/commontask/EditProfileActivity.java |
1,504 | import java.util.ArrayList;
import java.util.Scanner;
public class AddressBook {
private ArrayList<Contact> contacts;
private Scanner scanner;
public AddressBook() {
contacts = new ArrayList<>();
scanner = new Scanner(System.in);
}
public void start() {
loadSampleContacts(); // Φορτώνει ενδεικτικές επαφές
int choice;
do {
displayMenu();
choice = getUserChoice();
processUserChoice(choice);
} while (choice != 7);
}
private void displayMenu() {
System.out.println("Μενού επιλογών:");
System.out.println("1. Προβολή όλων των επαφών");
System.out.println("2. Προσθήκη νέας επαφής");
System.out.println("3. Αναζήτηση επαφής βάσει ονόματος");
System.out.println("4. Αναζήτηση επαφής βάσει τηλεφώνου");
System.out.println("5. Επεξεργασία επαφής βάσει ονόματος");
System.out.println("6. Διαγραφή επαφής βάσει ονόματος");
System.out.println("7. Έξοδος από την εφαρμογή");
System.out.print("Επιλέξτε μια επιλογή: ");
}
private int getUserChoice() {
int choice;
try {
choice = scanner.nextInt();
} catch (Exception e) {
choice = -1;
} finally {
scanner.nextLine();
}
return choice;
}
private void processUserChoice(int choice) {
System.out.println();
switch (choice) {
case 1:
displayAllContacts();
break;
case 2:
addNewContact();
break;
case 3:
searchContactByName();
break;
case 4:
searchContactByPhone();
break;
case 5:
editContact();
break;
case 6:
deleteContact();
break;
case 7:
System.out.println("Αποχώρηση από την εφαρμογή. Αντίο!");
break;
default:
System.out.println("Μη έγκυρη επιλογή. Παρακαλώ προσπαθήστε ξανά.");
break;
}
System.out.println();
}
private void displayAllContacts() {
if (contacts.isEmpty()) {
System.out.println("Δεν υπάρχουν αποθηκευμένες επαφές.");
} else {
System.out.println("Αποθηκευμένες επαφές:");
for (Contact contact : contacts) {
System.out.println("Όνομα: " + contact.getName());
System.out.println("Τηλέφωνο: " + contact.getPhone());
System.out.println("Email: " + contact.getEmail());
System.out.println("Διεύθυνση: " + contact.getAddress());
System.out.println("-------------------------");
}
}
}
private void addNewContact() {
System.out.print("Όνομα: ");
String name = scanner.nextLine();
System.out.print("Τηλέφωνο: ");
String phone = scanner.nextLine();
System.out.print("Email: ");
String email = scanner.nextLine();
System.out.print("Διεύθυνση: ");
String address = scanner.nextLine();
Contact newContact = new Contact(name, phone, email, address);
contacts.add(newContact);
System.out.println("Η επαφή προστέθηκε επιτυχώς.");
}
private void searchContactByName() {
System.out.print("Εισαγάγετε το όνομα που αναζητάτε: ");
String name = scanner.nextLine();
boolean found = false;
for (Contact contact : contacts) {
if (contact.getName().equalsIgnoreCase(name)) {
displayContactInfo(contact);
found = true;
break;
}
}
if (!found) {
System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\".");
}
}
private void searchContactByPhone() {
System.out.print("Εισαγάγετε το τηλέφωνο που αναζητάτε: ");
String phone = scanner.nextLine();
boolean found = false;
for (Contact contact : contacts) {
if (contact.getPhone().equals(phone)) {
displayContactInfo(contact);
found = true;
break;
}
}
if (!found) {
System.out.println("Δεν βρέθηκε επαφή με το τηλέφωνο \"" + phone + "\".");
}
}
private void editContact() {
System.out.print("Εισαγάγετε το όνομα της επαφής προς επεξεργασία: ");
String name = scanner.nextLine();
boolean found = false;
for (Contact contact : contacts) {
if (contact.getName().equalsIgnoreCase(name)) {
displayContactInfo(contact);
System.out.println("Εισαγάγετε τα νέα στοιχεία:");
System.out.print("Όνομα: ");
String newName = scanner.nextLine();
System.out.print("Τηλέφωνο: ");
String newPhone = scanner.nextLine();
System.out.print("Email: ");
String newEmail = scanner.nextLine();
System.out.print("Διεύθυνση: ");
String newAddress = scanner.nextLine();
contact.setName(newName);
contact.setPhone(newPhone);
contact.setEmail(newEmail);
contact.setAddress(newAddress);
System.out.println("Η επαφή ενημερώθηκε επιτυχώς.");
found = true;
break;
}
}
if (!found) {
System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\".");
}
}
private void deleteContact() {
System.out.print("Εισαγάγετε το όνομα της επαφής προς διαγραφή: ");
String name = scanner.nextLine();
boolean found = false;
for (Contact contact : contacts) {
if (contact.getName().equalsIgnoreCase(name)) {
displayContactInfo(contact);
System.out.print("Είστε βέβαιος ότι θέλετε να διαγράψετε αυτήν την επαφή; (Ν/Ο): ");
String confirmation = scanner.nextLine();
if (confirmation.equalsIgnoreCase("Ν")) {
contacts.remove(contact);
System.out.println("Η επαφή διαγράφηκε επιτυχώς.");
} else {
System.out.println("Η διαγραφή ακυρώθηκε.");
}
found = true;
break;
}
}
if (!found) {
System.out.println("Δεν βρέθηκε επαφή με το όνομα \"" + name + "\".");
}
}
private void displayContactInfo(Contact contact) {
System.out.println("Όνομα: " + contact.getName());
System.out.println("Τηλέφωνο: " + contact.getPhone());
System.out.println("Email: " + contact.getEmail());
System.out.println("Διεύθυνση: " + contact.getAddress());
System.out.println("-------------------------");
}
private void loadSampleContacts() {
Contact contact1 = new Contact("Γιάννης", "1234567890", "[email protected]", "Αθήνα");
Contact contact2 = new Contact("Μαρία", "9876543210", "[email protected]", "Θεσσαλονίκη");
Contact contact3 = new Contact("Πέτρος", "5555555555", "[email protected]", "Πάτρα");
contacts.add(contact1);
contacts.add(contact2);
contacts.add(contact3);
}
}
| XristosKak/Contact_Book_Java_Console_Application- | src/AddressBook.java |
1,505 | package com.mobile.physiolink.ui.doctor.adapter;
import android.app.Activity;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;
import androidx.recyclerview.widget.RecyclerView;
import com.mobile.physiolink.databinding.ItemDoctorRequestBinding;
import com.mobile.physiolink.model.appointment.Appointment;
import com.mobile.physiolink.model.user.singleton.UserHolder;
import com.mobile.physiolink.service.api.API;
import com.mobile.physiolink.service.api.RequestFacade;
import com.mobile.physiolink.ui.doctor.OnButtonClickListener;
import com.mobile.physiolink.ui.popup.AppointmentRejectPopUp;
import com.mobile.physiolink.ui.popup.ConfirmationPopUp;
import com.mobile.physiolink.util.date.TimeFormatter;
import com.mobile.physiolink.util.image.ProfileImageProvider;
import java.io.IOException;
import java.util.HashMap;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class AdapterForRequests extends RecyclerView.Adapter<AdapterForRequests.MyViewHolder>
implements OnButtonClickListener
{
// Constant variables to check if the accept or the reject button is pressed
public static final int ACCEPT=1;
public static final int REJECT=2;
private final FragmentManager fm;
private Appointment[] appointments;
boolean isExpanded[];
public AdapterForRequests(FragmentManager fm)
{
appointments = new Appointment[0];
isExpanded = new boolean[appointments.length];
this.fm=fm;
}
public void setAppointments(Appointment[] appointments)
{
this.appointments = appointments;
isExpanded = new boolean[appointments.length];
notifyDataSetChanged();
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
ItemDoctorRequestBinding binding = ItemDoctorRequestBinding
.inflate(LayoutInflater.from(parent.getContext()), parent, false);
return new MyViewHolder(binding, this);
}
public void onBindViewHolder(MyViewHolder holder, int position)
{
ProfileImageProvider.setImageOfAppointment(holder.binding.requestPhotoDoctor,
appointments[position]);
holder.binding.requestNameDoctor
.setText(appointments[position].getPatName());
holder.binding.requestSurnameDoctor
.setText(appointments[position].getPatSurname());
holder.binding.requestAMKA
.setText(appointments[position].getPatAmka());
holder.binding.requestAppointmentDate
.setText(appointments[position].getDate().replace('-', '/'));
holder.binding.requestAppointmentTime
.setText(TimeFormatter.formatToPM_AM(appointments[position].getHour()));
boolean hasContent = appointments[position].getMessage().length() > 0;
holder.binding.requestProblem
.setText(hasContent ? appointments[position].getMessage() : "-");
boolean isItemExpanded = isExpanded[position];
if(hasContent){
if(isItemExpanded){
holder.binding.requestProblem.setMaxLines(Integer.MAX_VALUE);
holder.binding.requestProblem.setEllipsize(null);
} else {
holder.binding.requestProblem.setMaxLines(2);
holder.binding.requestProblem.setEllipsize(TextUtils.TruncateAt.END);
}
}
}
private void toggleExpansion(int position) {
isExpanded[position] = !isExpanded[position];
notifyItemChanged(position);
}
@Override
public int getItemCount() {
return appointments.length;
}
// Function used to remove items from the requestList when a request is either accepted or rejected
public void remove(int position)
{
Appointment[] newAppointments = new Appointment[appointments.length-1];
for(int i=0; i<position; i++){
newAppointments[i]=appointments[i];
}
for(int i=position+1; i<appointments.length; i++){
newAppointments[i-1]=appointments[i];
}
appointments = newAppointments;
}
// TODO: handle what happens when each button is pressed
@Override
public void onButtonClicked(int position,int id)
{
if(id==ACCEPT)
{
System.out.println("accept button pressed");
}
else
{
System.out.println("reject button pressed");
}
remove(position);
notifyItemRemoved(position);
}
public class MyViewHolder extends RecyclerView.ViewHolder
{
ItemDoctorRequestBinding binding;
public MyViewHolder(ItemDoctorRequestBinding binding, OnButtonClickListener listener)
{
super(binding.getRoot());
this.binding = binding;
//Switch to extended on click
binding.getRoot().setOnClickListener(view ->
{
toggleExpansion(getBindingAdapterPosition());
});
binding.requestAcceptButton.setOnClickListener(view ->
{
//creates popup to ensure the appointment confirmation
ConfirmationPopUp confirmation = new ConfirmationPopUp("Αποδοχή","Είστε σίγουρος ότι θέλετε να αποδεχτείτε το ραντεβού;",
"Αποδοχή","Πίσω");
confirmation.setPositiveOnClick((dialog, which) ->
{
// TODO: API CALL
int position = getBindingAdapterPosition();
HashMap<String, String> keyValues = new HashMap<>(5);
keyValues.put("appointment_id", String.valueOf(appointments[position].getId()));
keyValues.put("date", appointments[position].getDate().replace('-', '/'));
keyValues.put("doctor_name", UserHolder.doctor().getName());
keyValues.put("doctor_surname", UserHolder.doctor().getSurname());
keyValues.put("doctor_phone_number", UserHolder.doctor().getPhoneNumber());
RequestFacade.postRequest(API.ACCEPT_APPOINTMENT, keyValues, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {}
});
if (listener != null) {
listener.onButtonClicked(position,ACCEPT);
}
Toast.makeText(binding.getRoot().getContext(), "Το ραντεβού αποδέχθηκε!",
Toast.LENGTH_SHORT).show();
});
confirmation.setNegativeOnClick(((dialog,which)->
{
}));
confirmation.show(fm,"Confirmation pop up");
});
binding.requestRejectButton.setOnClickListener(view ->
{
//creates popup to ensure appointment rejection and give reasoning
AppointmentRejectPopUp rejection = new AppointmentRejectPopUp("Απόρριψη",
"Απόρριψη","Πίσω");
rejection.setPositiveOnClick((dialog, which) ->
{
int position = getBindingAdapterPosition();
HashMap<String, String> keyValues = new HashMap<>(6);
keyValues.put("appointment_id", String.valueOf(appointments[position].getId()));
keyValues.put("reason", rejection.getReason());
keyValues.put("date", appointments[position].getDate().replace('-', '/'));
keyValues.put("doctor_name", UserHolder.doctor().getName());
keyValues.put("doctor_surname", UserHolder.doctor().getSurname());
keyValues.put("doctor_phone_number", UserHolder.doctor().getPhoneNumber());
RequestFacade.postRequest(API.DECLINE_PAYMENT, keyValues, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
call.cancel();
}
@Override
public void onResponse(Call call, Response response) throws IOException {}
});
if (listener != null) {
listener.onButtonClicked(position,ACCEPT);
}
Toast.makeText(binding.getRoot().getContext(),"Το ραντεβού απορρίφθηκε!"
,Toast.LENGTH_SHORT).show();
});
rejection.setNegativeOnClick(((dialog,which)->
{
}));
rejection.show(fm,"Confirmation pop up");
});
}
}
} | setokk/PhysioLink | app/src/main/java/com/mobile/physiolink/ui/doctor/adapter/AdapterForRequests.java |
1,506 | package gr.grnet.dep.service.util;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import gr.grnet.dep.service.model.Candidate;
import gr.grnet.dep.service.model.InstitutionManager;
import org.apache.commons.io.IOUtils;
import javax.ejb.EJBException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
public class PdfUtil {
private static final Logger logger = Logger.getLogger(PdfUtil.class.getName());
private static final float BASE_FONT_SIZE = 10.0f;
public static InputStream generateFormaAllagisIM(InstitutionManager im) {
try {
FontFactory.register("fonts/arial.ttf");
FontFactory.register("fonts/arialbd.ttf");
Font normalFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, BASE_FONT_SIZE);
Font boldFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, normalFont.getSize(), Font.BOLD);
Font largerBoldFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, (float) 1.2 * normalFont.getSize(), Font.BOLD);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
Document doc = new Document();
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfWriter.getInstance(doc, output);
doc.open();
Image logoApella = Image.getInstance(loadImage("logo_apella.png"));
logoApella.scaleToFit(1200, 120);
logoApella.setAlignment(Element.ALIGN_RIGHT);
doc.add(logoApella);
Paragraph p = new Paragraph("Αριθμός Βεβαίωσης: " + im.getUser().getId() + " / " + sdf.format(now), boldFont);
p.setAlignment(Element.ALIGN_RIGHT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Προς το Εθνικό Δίκτυο", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Έρευνας και Τεχνολογίας", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("FAX: 215 215 7856", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Βεβαίωση Συμμετοχής Διαχειριστή Ιδρύματος στην Απέλλα", largerBoldFont);
p.setAlignment(Element.ALIGN_CENTER);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
PdfPTable institutionTable = new PdfPTable(2);
institutionTable.setWidthPercentage(100);
institutionTable.setWidths(new float[]{30, 70});
institutionTable.addCell(createCell(new Phrase("ΙΔΡΥΜΑ", normalFont), Element.ALIGN_LEFT, 1));
institutionTable.addCell(createCell(new Phrase(im.getInstitution().getName().get("el"), normalFont), Element.ALIGN_LEFT, 1));
switch (im.getVerificationAuthority()) {
case DEAN:
institutionTable.addCell(createCell(new Phrase("ΟΝ/ΜΟ ΠΡΥΤΑΝΗ", normalFont), Element.ALIGN_LEFT, 1));
break;
case PRESIDENT:
institutionTable.addCell(createCell(new Phrase("ΟΝ/ΜΟ ΠΡΟΕΔΡΟΥ", normalFont), Element.ALIGN_LEFT, 1));
break;
}
institutionTable.addCell(createCell(new Phrase(im.getVerificationAuthorityName(), normalFont), Element.ALIGN_LEFT, 1));
doc.add(institutionTable);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Βεβαιώνεται ότι το ως άνω Ίδρυμα ορίζει ως Διαχειριστή Ιδρύματος στο πρόγραμμα ΑΠΕΛΛΑ τον/την " +
im.getUser().getBasicInfo().getFirstname() +
" " +
im.getUser().getBasicInfo().getLastname() +
" με e-mail " +
im.getUser().getContactInfo().getEmail() +
", τηλέφωνο " +
im.getUser().getContactInfo().getPhone() +
" και όνομα χρήστη " +
im.getUser().getUsername()
+ "."
, normalFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Αναπληρωτής Διαχειριστής Ιδρύματος ορίζεται ο/η " +
im.getAlternateBasicInfo().getFirstname() +
" " +
im.getAlternateBasicInfo().getLastname() +
" με e-mail " +
im.getAlternateContactInfo().getEmail() +
", τηλέφωνο " +
im.getAlternateContactInfo().getPhone()
+ ".",
normalFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
PdfPTable signTable = new PdfPTable(3);
signTable.setWidthPercentage(100);
signTable.setWidths(new float[]{33, 33, 33});
signTable.addCell(createCell(new Phrase("__/__/____", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase(" ", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase(" ", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase("ΗΜΕΡΟΜΗΝΙΑ", normalFont), Element.ALIGN_CENTER, 0));
switch (im.getVerificationAuthority()) {
case DEAN:
signTable.addCell(createCell(new Phrase("Υπογραφή Πρύτανη", normalFont), Element.ALIGN_CENTER, 0));
break;
case PRESIDENT:
signTable.addCell(createCell(new Phrase("Υπογραφή Προέδρου", normalFont), Element.ALIGN_CENTER, 0));
break;
}
signTable.addCell(createCell(new Phrase("Σφραγίδα Ιδρύματος", normalFont), Element.ALIGN_CENTER, 0));
doc.add(signTable);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
doc.add(createLogoTable());
doc.close();
output.close();
return new ByteArrayInputStream(output.toByteArray());
} catch (DocumentException e) {
logger.log(Level.SEVERE, "", e);
throw new EJBException(e);
} catch (IOException e) {
logger.log(Level.SEVERE, "", e);
throw new EJBException(e);
}
}
public static InputStream generateFormaYpopsifiou(Candidate candidate) {
try {
FontFactory.register("fonts/arial.ttf");
FontFactory.register("fonts/arialbd.ttf");
Font normalFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, BASE_FONT_SIZE);
Font boldFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, normalFont.getSize(), Font.BOLD);
Font largerBoldFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, (float) 1.2 * normalFont.getSize(), Font.BOLD);
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
Document doc = new Document();
ByteArrayOutputStream output = new ByteArrayOutputStream();
PdfWriter.getInstance(doc, output);
doc.open();
Image logoApella = Image.getInstance(loadImage("logo_apella.png"));
logoApella.scaleToFit(1200, 120);
logoApella.setAlignment(Element.ALIGN_RIGHT);
doc.add(logoApella);
Paragraph p = new Paragraph("Αριθμός Αίτησης: " + candidate.getUser().getId() + " / " + sdf.format(now), boldFont);
p.setAlignment(Element.ALIGN_RIGHT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Προς το Εθνικό Δίκτυο", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Έρευνας και Τεχνολογίας", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Αίτηση Συμμετοχής Υποψηφίου", largerBoldFont);
p.setAlignment(Element.ALIGN_CENTER);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Με την παρούσα αίτηση ο/η " +
candidate.getUser().getBasicInfo().getFirstname() +
" (" +
candidate.getUser().getBasicInfoLatin().getFirstname() +
") " +
candidate.getUser().getBasicInfo().getLastname() +
" (" +
candidate.getUser().getBasicInfoLatin().getLastname() +
") " +
" με Αριθμό Ταυτότητας/Διαβατηρίου " +
candidate.getUser().getIdentification() +
", e-mail " +
candidate.getUser().getContactInfo().getEmail() +
" και τηλέφωνο " +
candidate.getUser().getContactInfo().getMobile() +
" δηλώνω ότι επιθυμώ να συμμετάσχω στο πρόγραμμα «ΑΠΕΛΛΑ - Εκλογή και Εξέλιξη Καθηγητών ΑΕΙ»" +
" ως υποψήφιος με Όνομα Χρήστη "
+ candidate.getUser().getUsername()
+ ".",
normalFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph("Δηλώνω υπεύθυνα ότι αποδέχομαι τους όρους και τις προϋποθέσεις του προγράμματος " +
"«ΑΠΕΛΛΑ - Εκλογή και Εξέλιξη Καθηγητών ΑΕΙ», όπως κάθε φορά ισχύουν.", normalFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
PdfPTable signTable = new PdfPTable(2);
signTable.setWidthPercentage(100);
signTable.setWidths(new float[]{50, 50});
signTable.addCell(createCell(new Phrase(" ", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase("Ο/Η Αιτών/ούσα", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase("__/__/____", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase(" ", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase("ΗΜΕΡΟΜΗΝΙΑ", normalFont), Element.ALIGN_CENTER, 0));
signTable.addCell(createCell(new Phrase("Υπογραφή", normalFont), Element.ALIGN_CENTER, 0));
doc.add(signTable);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
p = new Paragraph(" ", boldFont);
p.setAlignment(Element.ALIGN_LEFT);
doc.add(p);
doc.add(createLogoTable());
doc.close();
output.close();
return new ByteArrayInputStream(output.toByteArray());
} catch (DocumentException e) {
logger.log(Level.SEVERE, "", e);
throw new EJBException(e);
} catch (IOException e) {
logger.log(Level.SEVERE, "", e);
throw new EJBException(e);
}
}
private static PdfPCell createCell(Phrase p, int align, int borderWidth) {
PdfPCell cell = new PdfPCell(p);
cell.setBorderWidth(borderWidth);
cell.setHorizontalAlignment(align);
cell.setPadding(10);
return cell;
}
private static PdfPCell createImageCell(Image img, int align, int borderWidth) {
PdfPCell cell = new PdfPCell(img);
cell.setBorderWidth(borderWidth);
cell.setHorizontalAlignment(align);
cell.setPadding(10);
return cell;
}
private static PdfPTable createLogoTable() throws MalformedURLException, IOException, DocumentException {
// Load resources
Font normalFont = FontFactory.getFont("Arial", BaseFont.IDENTITY_H, BASE_FONT_SIZE);
Image logoMinedu = Image.getInstance(loadImage("logo_minedu.png"));
logoMinedu.scaleToFit(1200, 30);
Image logoGRnet = Image.getInstance(loadImage("logo_grnet.png"));
logoGRnet.scaleToFit(1200, 30);
Image logoEU = Image.getInstance(loadImage("logo_eu.jpg"));
logoEU.scaleToFit(1200, 30);
Image logoEspa = Image.getInstance(loadImage("logo_espa.jpg"));
logoEspa.scaleToFit(1200, 30);
Image logoDM = Image.getInstance(loadImage("logo_ep.jpg"));
logoDM.scaleToFit(1200, 30);
// Create table
PdfPTable logoTable = new PdfPTable(5);
logoTable.setHorizontalAlignment(Element.ALIGN_CENTER);
float [] rows = {90f,70f,40f,50f,40f};
logoTable.setTotalWidth(rows);
logoTable.addCell(createImageCell(logoMinedu, Element.ALIGN_CENTER, 0));
logoTable.addCell(createImageCell(logoGRnet, Element.ALIGN_CENTER, 0));
logoTable.addCell(createImageCell(logoEU, Element.ALIGN_CENTER, 0));
logoTable.addCell(createImageCell(logoDM, Element.ALIGN_CENTER, 0));
logoTable.addCell(createImageCell(logoEspa, Element.ALIGN_CENTER, 0));
PdfPCell cell = createCell(new Phrase("Με τη συγχρηματοδότηση της Ελλάδας και της Ευρωπαϊκής Ένωσης", normalFont), Element.ALIGN_CENTER, 0);
cell.setColspan(5);
logoTable.addCell(cell);
return logoTable;
}
private static byte[] loadImage(String img) {
InputStream is = Image.class.getClassLoader().getResourceAsStream("logos/" + img);
try {
return IOUtils.toByteArray(is);
} catch (IOException e) {
logger.log(Level.SEVERE, "Cannot Read image for pdf generation", e);
}
return new byte[0];
}
}
| grnet/apella | dep-ejb/src/main/java/gr/grnet/dep/service/util/PdfUtil.java |
1,509 | package com.iNNOS.controllers;
import java.io.File;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Optional;
import java.util.ResourceBundle;
import com.amazonaws.services.iotthingsgraph.model.SystemInstanceFilterName;
import com.iNNOS.constants.CommonConstants;
import com.iNNOS.mainengine.MainEngine;
import com.iNNOS.model.Deliverable;
import com.iNNOS.model.Project;
import com.iNNOS.model.Supervisor;
import javafx.animation.FadeTransition;
import javafx.application.Platform;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.scene.Node;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.CheckBox;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.ListView;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableColumn.CellDataFeatures;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.ButtonBar.ButtonData;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import javafx.stage.Window;
import javafx.util.Callback;
import javafx.util.Duration;
public class ProjectsController implements Initializable{
@FXML private TableView<Supervisor> supervisorsTable;
@FXML private TableView<Deliverable> deliverablesTable;
@FXML private TableView<Project> projectsTable;
@FXML private TableColumn<Supervisor, String> supervisorNameCol;
@FXML private TableColumn<Supervisor, String> supervisorPhoneCol;
@FXML private TableColumn<Supervisor, String> supervisorEmailCol;
@FXML private TableColumn<Project, String> titleCol;
@FXML private TableColumn<Project, String> clientCol;
@FXML private TableColumn<Deliverable, String> deliverableNoCol;
@FXML private TextField deliverableDeadlineText;
@FXML private TextField projectDeadlineText;
@FXML private TextField clientInfoText;
@FXML private TextField projectStartText;
@FXML private TextField adaText;
@FXML private Label projectTitleLabel;
@FXML private TextField projectBudgetText;
@FXML private TextField delvirableValueText;
@FXML private TextField protocolNoText;
@FXML private Pane deliverableInfoPane;
@FXML private AnchorPane projectInfoPane;
@FXML private CheckBox completedProjectBtn;
@FXML private RadioButton inHouseBtn;
@FXML private RadioButton outsourcingBtn;
@FXML private Label deliverableTitle;
@FXML private ListView<String> attachmentListView;
private ObservableList<Project> projectsObsList = FXCollections.observableArrayList();
private ObservableList<Supervisor> supervisorsObsList = FXCollections.observableArrayList();
private ObservableList<Deliverable> deliverablesObsList = FXCollections.observableArrayList();
private ObservableList<String> deliverableAttachmentsObsList = FXCollections.observableArrayList();
private MainEngine mainengine;
// 0-Project edit disabled, 1-Project edit enabled
private static int editMode = 0;
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
// Group of the 2 implementation buttons
ToggleGroup implementationGroup = new ToggleGroup();
inHouseBtn.setToggleGroup(implementationGroup); outsourcingBtn.setToggleGroup(implementationGroup);
inHouseBtn.setDisable(true);
outsourcingBtn.setDisable(true);
mainengine = MainEngine.getMainEngineInstance();
// CellValueFactory for Projects
titleCol.setCellValueFactory(new PropertyValueFactory<>("title"));
clientCol.setCellValueFactory(new Callback<CellDataFeatures<Project, String>,
ObservableValue<String>>() {
@Override
public ObservableValue<String> call(CellDataFeatures<Project, String> data){
return data.getValue().getClient().getNameProperty();
}
});
// CellValueFactory for Supervisors
supervisorNameCol.setCellValueFactory(new PropertyValueFactory<>("fullName"));
supervisorPhoneCol.setCellValueFactory(new PropertyValueFactory<>("phoneNumber"));
supervisorEmailCol.setCellValueFactory(new PropertyValueFactory<>("email"));
// CellValueFactory for Deliverables
deliverableNoCol.setCellValueFactory(new PropertyValueFactory<>("identificationCode"));
deliverablesTable.setItems(deliverablesObsList);
projectsTable.setOnMouseClicked((MouseEvent event) -> {
if(event.getButton().equals(MouseButton.PRIMARY)){
projectInfoPane.setDisable(false);
updateProjectsTextFields(getSelectedProject());
// Remove all supervisors in the observableList, before updating with the current selected project's supervisors
supervisorsObsList.removeAll(supervisorsObsList);
updateSupervisorsTable();
setNode(projectInfoPane);
deliverableInfoPane.setDisable(false);
deliverablesObsList.removeAll(deliverablesObsList);
updateDeliverablesTable();
}
});
deliverablesTable.setOnMouseClicked((MouseEvent event) -> {
if(event.getButton().equals(MouseButton.PRIMARY)) {
updateDeliverableTextInfo();
setNode(deliverableInfoPane);
loadDeliverableAttachments();
}
});
//mainengine.establishDbConnection();
updateProjectTable();
}
/**
* Fetching the attachments of the selected deliverable of a project from DB
*/
private void loadDeliverableAttachments() {
deliverableAttachmentsObsList.removeAll(deliverableAttachmentsObsList);
ArrayList<String> attachments = mainengine.fetchDeliverableAttachmentsFromDB(getSelectedDeliverable());
for (String att : attachments) {
deliverableAttachmentsObsList.add(att);
}
attachmentListView.setItems(deliverableAttachmentsObsList);
}
private void updateDeliverableTextInfo() {
deliverableTitle.setText(getSelectedDeliverable().getDelivTitle());
delvirableValueText.setText(String.valueOf(getSelectedDeliverable().getContractualValue()));
deliverableDeadlineText.setText(getSelectedDeliverable().getDeadlineDate().toString());
switch (getSelectedDeliverable().getImplementationMode()) {
case "In House":{
inHouseBtn.setSelected(true);
outsourcingBtn.setSelected(false);
break;
}
case "Outsourcing" : {
inHouseBtn.setSelected(false);
outsourcingBtn.setSelected(true);
break;
}
default:
throw new IllegalArgumentException("Unexpected value: " + deliverablesTable.getSelectionModel().getSelectedItem().getImplementationMode());
}
}
@FXML void deleteProject(ActionEvent event) {
Project projectToBeDeleted = projectsTable.getSelectionModel().getSelectedItem();
Alert deleteProjectAlert = mainengine.generateAlertDialog(AlertType.INFORMATION, "Διαγραφή εγγραφής", "Είστε σίγουροι για την διαγραφή του εργου : "+projectToBeDeleted.getTitle()+" ;");
// Ask user to confirm the row's delete
Optional<ButtonType> result = deleteProjectAlert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
deleteProjectAlert.close();
else if(result.get() == ButtonType.OK) {
//oke button is pressed
projectsTable.getItems().remove(projectToBeDeleted); mainengine.establishDbConnection();
mainengine.removeProjectByTitle(projectToBeDeleted);
}else if(result.get() == ButtonType.CANCEL)
// cancel button is pressed
deleteProjectAlert.close();
}
@FXML void refreshProjectsTable(ActionEvent event) {
projectsObsList.removeAll(projectsObsList);
updateProjectTable();
mainengine.generateAlertDialog(AlertType.INFORMATION, "Ανανέωση επιτυχής", "Η λίστα έργων ανανεώθηκε επιτυχώς.").show();
}
@FXML void uploadProjectContract(ActionEvent event) {
FileChooser chooser = new FileChooser();
File selectedFile = chooser.showOpenDialog(clientInfoText.getScene().getWindow());
if (selectedFile != null) {
Alert uploadNewContractAlert = mainengine.generateAlertDialog(AlertType.INFORMATION,
"Μεταφόρτωση αρχείου σύμβασης",
"Είστε σίγουρος ότι θέλετε να μεταφορτώσετε το αρχείο σύμβασης : "+selectedFile.getName()+ " ;");
Optional<ButtonType> result = uploadNewContractAlert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
uploadNewContractAlert.close();
else if(result.get() == ButtonType.OK) {
//oke button is pressed
/* If for the selected project there is an attached file in the database,
* replace it from the base with the selected file.
* Also delete it from the Amazon S3 bucket and upload the new one
*/
if ( (getSelectedProject() != null) && getSelectedProject().getAttachment() != null) {
// AMAZON S3 -> Delete previous project's contract
mainengine.removeFileFromCloud(getSelectedProject().getAttachment(), CommonConstants.CONTRACTS_BUCKET_NAME, getSelectedProject().getTitle());
// SQL DB -> update TABLE ΕΡΓΑ (ΣΥΝΗΜΜΕΝΟ)
mainengine.insertPdfIntoDB(selectedFile.getName(), getSelectedProject());
// AMAZON S3 -> Upload the selected file
mainengine.uploadFileIntoCloud(selectedFile, CommonConstants.CONTRACTS_BUCKET_NAME, getSelectedProject().getTitle());
// Updated project entries from DB
updateProjectTable();
}
}else if(result.get() == ButtonType.CANCEL)
// cancel button is pressed
uploadNewContractAlert.close();
}
}
@FXML void completedProjectOnAction(ActionEvent event) {
projectsTable.getSelectionModel().getSelectedItem().setCompleted(completedProjectBtn.isSelected());
}
@FXML void editProject(ActionEvent event) {
changeProjectInfoPaneEditability(true);
// TODO Edit disable if selected project changes. Alert must be displayed
}
/**
* Upload selected file :
* Filename -> stored into SQL DB
* File -> stored into Cloud
*/
@FXML void uploadAttachment(ActionEvent event) {
if (isDeliverableSelected()) {
FileChooser chooser = new FileChooser();
File selectedFile = chooser.showOpenDialog(clientInfoText.getScene().getWindow());
if (selectedFile != null) {
Alert uploadNewAttachmentAlert = mainengine.generateAlertDialog(AlertType.INFORMATION,
"Μεταφόρτωση συνημμένο παραδοτέου",
"Είστε σίγουρος ότι θέλετε να μεταφορτώσετε το συνημμένο παραδοτέου: "+selectedFile.getName()+ " ;");
Optional<ButtonType> result = uploadNewAttachmentAlert.showAndWait();
if(!result.isPresent())
// alert is exited, no button has been pressed.
uploadNewAttachmentAlert.close();
else if(result.get() == ButtonType.OK) {
//oke button is pressed
for (Iterator<String> iterator = deliverableAttachmentsObsList.iterator(); iterator.hasNext(); ) {
String attch = iterator.next();
if (attch.equals(selectedFile.getName())) {
//iterator.remove();
deliverableAttachmentsObsList.add(selectedFile.getName());
}
}
getSelectedDeliverable().getAttachmentsList().add(selectedFile.getName());
if (mainengine.insertDeliverablesAttachmentsIntoDB(getSelectedDeliverable()))
mainengine.generateAlertDialog(AlertType.INFORMATION,
"Επιτυχής εισαγωγή συνημμένου",
"Τα συνημμένα του παραδοτέου με τίτλο : "+getSelectedDeliverable().getDelivTitle()+" εισήχθησαν στην βάση");
getSelectedDeliverable().getAttachmentsList().removeAll(getSelectedDeliverable().getAttachmentsList());
mainengine.uploadFileIntoCloud(selectedFile, CommonConstants.ATTACHMENTS_BUCKET_NAME, getSelectedDeliverable().getDelivTitle());
loadDeliverableAttachments();
}
}
}
}
private boolean isDeliverableSelected() {
if (getSelectedDeliverable() != null)
return true;
return false;
}
/**
* Delete attachment
* File -> Remove from Cloud
* Filename -> Remove from SQL DB
*/
@FXML
void deleteSelectedAttachment(ActionEvent event) {
if (isDeliverableSelected()) {
mainengine.removeFileFromCloud(attachmentListView.getSelectionModel().getSelectedItem(), CommonConstants.ATTACHMENTS_BUCKET_NAME, getSelectedDeliverable().getDelivTitle());
mainengine.removeDelAttachmentFromDB(getSelectedDeliverable(), attachmentListView.getSelectionModel().getSelectedItem());
deliverableAttachmentsObsList.remove(attachmentListView.getSelectionModel().getSelectedItem());
}
}
@FXML void donwloadAttachment(ActionEvent event) {
if (isDeliverableSelected()) {
String attachmentName = attachmentListView.getSelectionModel().getSelectedItem();
if (attachmentListView.getSelectionModel().getSelectedItem() != null) {
Window stage = clientInfoText.getScene().getWindow();
// Show saveDialog and set Desktop as default directory
DirectoryChooser chooser = new DirectoryChooser();
File defaultDirectory = new File(System.getProperty("user.home") + "/Desktop");
chooser.setInitialDirectory(defaultDirectory);
File selectedDirectory = chooser.showDialog(stage);
// Download file drom Amazos S3 cloud to the selected directory
if (selectedDirectory != null) {
CommonConstants.LOCAL_DOWNLOAD_PATH = selectedDirectory.getAbsolutePath()+"\\";
mainengine.downloadFileFromCloud(attachmentName, CommonConstants.ATTACHMENTS_BUCKET_NAME, getSelectedDeliverable().getDelivTitle(), getSelectedDeliverable().getDelivTitle());
mainengine.generateAlertDialog(AlertType.INFORMATION, "Κατέβασμα αρχείου", "Επιτυχής λήψη του συνημμένου : "+attachmentName).showAndWait();
}
}else
mainengine.generateAlertDialog(AlertType.INFORMATION, "Μη διαθέσιμο αρχείο", "Δεν υπάρχει διαθέσιμο αρχείο σύμβασης για το έργο").show();
}
}
/**
* @param editable Boolean value if edit mode is enabled or disabled
*/
private void changeProjectInfoPaneEditability(boolean editable) {
projectStartText.setEditable(editable);
projectDeadlineText.setEditable(editable);
protocolNoText.setEditable(editable);
projectBudgetText.setEditable(editable);
adaText.setEditable(editable);
completedProjectBtn.setDisable(!editable);
}
/**
* @return True if project's textfields are edited
*/
private boolean projectInfoUpdated() throws ParseException {
Project selectedProject = projectsTable.getSelectionModel().getSelectedItem();
if (projectStartText.getText() != selectedProject.getStartingDates().get(selectedProject.getStartingDates().size()-1).toString()
|| projectDeadlineText.getText() != selectedProject.getDeadlineDates().get(selectedProject.getDeadlineDates().size()-1).toString()
|| projectBudgetText.getText() != String.valueOf(selectedProject.getContractBudget())
|| protocolNoText.getText() != selectedProject.getProtocolNumber()
|| adaText.getText() != selectedProject.getAda().get(selectedProject.getAda().size()-1)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date langDate = sdf.parse("2014/04/13");
java.sql.Date sqlDate = new java.sql.Date(langDate.getTime());
/*selectedProject.getStartingDates().set(selectedProject.getStartingDates().size()-1,
new java.sql.Date(sdf.parse(
projectStartText.getText().substring(projectStartText.getText().indexOf("[")+1, projectStartText.getText().indexOf("]"))).getTime()));
selectedProject.getDeadlineDates().set(selectedProject.getDeadlineDates().size()-1,
new java.sql.Date(sdf.parse(
projectStartText.getText().substring(projectDeadlineText.getText().indexOf("[")+1, projectDeadlineText.getText().indexOf("]"))).getTime()));
*/
selectedProject.setContractBudget(Double.parseDouble(projectBudgetText.getText()));
selectedProject.setProtocolNumber(protocolNoText.getText());
selectedProject.getAda().set(selectedProject.getAda().size()-1, adaText.getText());
selectedProject.setCompleted(completedProjectBtn.isSelected());
return true;
}
return false;
}
@FXML void addNewDeliverable(ActionEvent event) {
if (getSelectedProject() == null) {
mainengine.generateAlertDialog(AlertType.WARNING, "Μη επιλεγμένο Έργο", "Δεν έχετε επιλέξει έργο από την Καρτέλα Έργων για να εισάγεται παραδοτέο");
return;
}
// Create the custom dialog.
Dialog<Deliverable> dialog = new Dialog<>();
dialog.setTitle("Καρτέλα Εισαγωγής Παραδοτέου");
dialog.setHeaderText("Εισάγετε στοιχεία νέου Παραδοτέου");
// Set the button types.
ButtonType addButtonType = new ButtonType("Εισαγωγή", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(addButtonType, ButtonType.CANCEL);
// Create the username and password labels and fields.
GridPane grid = new GridPane();
grid.setHgap(10);
grid.setVgap(10);
grid.setPadding(new Insets(20, 100, 10, 10));
TextField delivCode = new TextField();
delivCode.setPromptText("Δώσε κωδικό παραδοτέου");
TextField delivTitle = new TextField();
delivTitle.setPromptText("Δώσε τίτλο");
TextField contractualValue = new TextField();
contractualValue.setPromptText("Ποσό συμβατικής αξίας");
ToggleGroup group = new ToggleGroup();
RadioButton inHouseBtn = new RadioButton();
inHouseBtn.setText("In House");
inHouseBtn.setToggleGroup(group);
inHouseBtn.setSelected(true);
RadioButton outsourcingBtn = new RadioButton();
outsourcingBtn.setText("Outsourcing");
outsourcingBtn.setToggleGroup(group);
DatePicker delivDeadline = new DatePicker();
grid.add(new Label("Κωδικός παραδοτέου"), 0, 0);
grid.add(delivCode, 1, 0);
grid.add(new Label("Τίτλος παραδοτέου"), 0, 1);
grid.add(delivTitle, 1, 1);
grid.add(new Label("Συμβατική αξία"), 0, 2);
grid.add(contractualValue, 1, 2);
grid.add(new Label("Τρόπος υλοποίησης"), 0, 3);
grid.add(inHouseBtn, 1, 3);
grid.add(outsourcingBtn, 2, 3);
grid.add(new Label("Ημερομηνία λήξης παραδοτέου"), 0, 4);
grid.add(delivDeadline, 1, 4);
// Enable/Disable login button depending on whether wa username was entered.
Node addButton = dialog.getDialogPane().lookupButton(addButtonType);
addButton.setDisable(true);
// Do some validation (using the Java 8 lambda syntax).
delivCode.textProperty().addListener((observable, oldValue, newValue) -> {
addButton.setDisable(newValue.trim().isEmpty());
});
dialog.getDialogPane().setContent(grid);
// Request focus on the username field by default.
Platform.runLater(() -> delivCode.requestFocus());
// Convert the result to a username-password-pair when the login button is clicked.
dialog.setResultConverter(dialogButton -> {
if (dialogButton == addButtonType) {
Deliverable deliv = new Deliverable();
deliv.setIdentificationCode(delivCode.getText());
deliv.setDelivTitle(delivTitle.getText());
deliv.setDeadlineDate(java.sql.Date.valueOf(delivDeadline.getValue()));
deliv.setContractualValue(Double.parseDouble(contractualValue.getText()));
deliv.setImplementationMode(((RadioButton)group.getSelectedToggle()).getText());
if (mainengine.insertIntoDeliverableTable(deliv, getSelectedProject()));
mainengine.generateAlertDialog(AlertType.INFORMATION, "Επιτυχής εισαγωγή στη βάση", deliv.toString()).show();
return deliv;
}
return null;
});
dialog.showAndWait();
}
@FXML void editDeliverable(ActionEvent event) {
}
@FXML void saveDeliverable(ActionEvent event) {
}
@FXML void removeDeliverable(ActionEvent event) {
mainengine.removeDeliverableFromDB(getSelectedDeliverable());
mainengine.generateAlertDialog(AlertType.INFORMATION,
"Διαγραφή Παραδοτέου",
"Διαγραφή παρακάτω παραδοτέου\nΤίτλος : "+getSelectedDeliverable().getDelivTitle()+"\nΚωδικός : "+getSelectedDeliverable().getIdentificationCode()).show();
updateDeliverablesTable();
}
@FXML void saveProjectChanges(ActionEvent event) throws ParseException {
if (projectInfoUpdated()) {
mainengine.updateProjectEntry(getSelectedProject());
mainengine.generateAlertDialog(AlertType.INFORMATION,
"Αλλαγές στη Βάση",
"Το έργο με όνομα : "+getSelectedProject().getTitle()+" ανανεώθηκε επιτυχώς στη βάση!").show();
System.out.println(getSelectedProject().toString());
}
}
/**
* A window appears for the user to select the folder in which the file will be saved.
* App connects to AWS Cloud. Downloads the selected file.
* @param event 'Λήψη σύμβασης' Button is pressed
*/
@FXML void downloadContractFromCloud(ActionEvent event) {
String fileName = getSelectedProject().getAttachment();
if (fileName != null) {
Window stage = clientInfoText.getScene().getWindow();
// Show saveDialog and set Desktop as default directory
DirectoryChooser chooser = new DirectoryChooser();
File defaultDirectory = new File(System.getProperty("user.home") + "/Desktop");
chooser.setInitialDirectory(defaultDirectory);
File selectedDirectory = chooser.showDialog(stage);
// Download file drom Amazos S3 cloud to the selected directory
if (selectedDirectory != null) {
CommonConstants.LOCAL_DOWNLOAD_PATH = selectedDirectory.getAbsolutePath()+"\\";
mainengine.downloadFileFromCloud(fileName, CommonConstants.CONTRACTS_BUCKET_NAME, getSelectedDeliverable().getDelivTitle(), CommonConstants.FOLDER_NAME);
mainengine.generateAlertDialog(AlertType.INFORMATION, "Κατέβασμα αρχείου", "Επιτυχής λήψη της σύμβασης : "+fileName).showAndWait();
}
}else
mainengine.generateAlertDialog(AlertType.INFORMATION, "Μη διαθέσιμο αρχείο", "Δεν υπάρχει διαθέσιμο αρχείο σύμβασης για το έργο").show();
}
/**
* Fetching Projects from DB
* Updating javafx tableview component
*/
private void updateProjectTable() {
ArrayList<Project> projectsListFromDB= mainengine.fetchProjectsFromDB();
if (projectsListFromDB != null) {
for (Project project : projectsListFromDB)
projectsObsList.add(project);
}
projectsTable.setItems(projectsObsList);
}
/**
* Fetching Supervisors of the selected Project from DB
* Updating javafx tableview component
*/
private void updateSupervisorsTable() {
ArrayList<Supervisor> supervisorList = mainengine.fetchSupervisorsOfProject(getSelectedProject());
if (supervisorList != null) {
for (Supervisor sv : supervisorList)
supervisorsObsList.add(sv);
}
supervisorsTable.setItems(supervisorsObsList);
}
/**
* Fetching Deliverable objects of the selected Project from ΠΑΡΑΔΟΤΕΑ table of DB
* Updating javafx tableview component
*/
public void updateDeliverablesTable() {
deliverablesObsList.removeAll(deliverablesObsList);
ArrayList<Deliverable> deliverables = mainengine.fetchProjectDeliverablesFromDB(projectsTable.getSelectionModel().getSelectedItem());
if (deliverables != null) {
for (Deliverable dv : deliverables)
deliverablesObsList.add(dv);
}
deliverablesTable.setItems(deliverablesObsList);
}
private void updateProjectsTextFields(Project project) {
projectTitleLabel.setText(project.getTitle());
clientInfoText.setText(project.getClient().getFullName());
projectStartText.setText(project.getStartingDates().toString());
projectDeadlineText.setText(project.getDeadlineDates().toString());
projectBudgetText.setText(String.valueOf(project.getContractBudget()));
adaText.setText(project.getAda().get(0));
protocolNoText.setText(project.getProtocolNumber());
completedProjectBtn.setSelected(project.isCompleted());
}
//Set selected node to a content holder
private void setNode(Node node) {
FadeTransition ft = new FadeTransition(Duration.millis(200));
ft.setNode(node);
ft.setFromValue(0.1);
ft.setToValue(1);
ft.setCycleCount(1);
ft.setAutoReverse(false);
ft.play();
}
private Project getSelectedProject() {
return projectsTable.getSelectionModel().getSelectedItem();
}
private Deliverable getSelectedDeliverable() {
return deliverablesTable.getSelectionModel().getSelectedItem();
}
}
| vaggelisbarb/Business-Management-App | src/main/java/com/iNNOS/controllers/ProjectsController.java |
1,512 | package gr.aueb.cf.ch2;
import java.util.Scanner;
/**
* Λαμβάνει από τον χρήστη έναν ακέραιο ο οποίος συμβολίζει δευτερόλεπτα
* και μετατρέπει σε ημέρες, ώρες, λεπτά, δευτερόλεπτα.
*
* @author a8ana
*/
public class SecondsToDate {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
final int SECS_PER_MINUTE = 60;
final int SECS_PER_HOUR = 60 * 60;
final int SECS_PER_DAY = 24 * 60 * 60;
int days = 0;
int hours = 0;
int minutes = 0;
int totalSeconds = 0;
int remainingSeconds = 0;
System.out.println("Please insert total seconds");
totalSeconds = in.nextInt();
days = totalSeconds / SECS_PER_DAY;
remainingSeconds = totalSeconds % SECS_PER_DAY;
hours = remainingSeconds / SECS_PER_HOUR;
remainingSeconds = remainingSeconds % SECS_PER_HOUR;
minutes = remainingSeconds / SECS_PER_MINUTE;
remainingSeconds = remainingSeconds % SECS_PER_MINUTE;
System.out.printf("Total Seconds: %,d, Days: %d, Hours: %02d, Minutes: %02d, Seconds: %02d",
totalSeconds, days, hours, minutes, remainingSeconds);
}
}
| a8anassis/cf6-java | src/gr/aueb/cf/ch2/SecondsToDate.java |
1,515 | package gui;
import api.GeneralUser;
import api.Provider;
import api.RegularUser;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
/**
* Κλάση για τη γραφική διεπαφή σύνδεσης ενός χρήστη στην εφαρμογή
*/
public class LoginGUI extends JFrame {
private JButton logInButton;
private JTextField tfUsername;
private JButton createAccountButton;
private JPasswordField passwordField1;
private JPanel loginPane;
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο με τη φόρμα σύνδεσης το χρήστη στην εφαρμογή
*/
public LoginGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(450,300);
setTitle("Login");
setContentPane(loginPane);
setLocationRelativeTo(null);
setVisible(true);
logInButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(GeneralUser.checkLogin(tfUsername.getText(), new String(passwordField1.getPassword()))==false){
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Try logging in again or create a new account");
}
else{
GeneralUser g =GeneralUser.getUserByUsername(tfUsername.getText());
if(g.getUserType().equals("Provider")){
ProviderGUI pGUI = new ProviderGUI(new Provider(g));
pGUI.show();
dispose();
}
else if (g.getUserType().equals("RegularUser")){
RegularUserGUI rGUI = new RegularUserGUI(new RegularUser(g));
rGUI.show();
dispose();
}
}
}
});
createAccountButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
CreateAccountGUI c = new CreateAccountGUI();
c.show();
dispose();
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/LoginGUI.java |
1,516 | package gr.aueb.cf.ch10;
/*
* Δημιουργήστε μία εφαρμογή επαφών για ένα κινητό τηλέφωνο, η οποία μπορεί να
περιέχει μέχρι 500 επαφές. Κάθε επαφή έχει Επώνυμο, Όνομα και Τηλέφωνο.
Για να αποθηκεύεται τις επαφές χρησιμοποιήστε ένα δυσδιάστατο πίνακα 500x3
όπου στη 1η θέση κάθε επαφής θα αποθηκεύεται το Επώνυμο, στη 2η θέση το Όνομα
και στη 3η θέση το τηλέφωνο, όλα ως String.
Υλοποιήστε τις βασικές CRUD πράξεις: Αναζήτηση Επαφής με βάση το τηλέφωνο,
Εισαγωγή Επαφής (αν δεν υπάρχει ήδη), Ενημέρωση Επαφής (εάν υπάρχει),
Διαγραφή Επαφής (εάν υπάρχει).
Η main() θα πρέπει να εμφανίζει ένα μενού στον χρήστη, οποίος θα επιλέγει την
κατάλληλη πράξη ή Έξοδο από την εφαρμογή και με την κατάλληλη καθοδήγηση της
εφαρμογής θα επιτελεί την επιλεγμένη πράξη.
* */
public class MiniProject02 {
public static void main(String[] args) {
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/MiniProject02.java |
1,519 | package UserClientV1;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
/**
* Κλάση η οποία έχει κληρονομήσει ένα JPanel
* Πρακτικά είναι το panel που βρίσκεται πίσω από τις εκάστοτε μονάδες μιας συσκευής,
* δηλαδή στο δεξί μέρος μιας καρτέλας({@link Ptab}) που έχει μέσα τα Units με πολύγωνη μορφή.
* Έχει δημιουργηθεί κυρίως για να μπορούμε να έχουμε κάποια εικόνα πίσω από τις μονάδες
* και φυσικά η εικόνα αυτή να μπορεί να αλλάζει .
* @author Michael Galliakis
*/
public class BackgroundPanel extends javax.swing.JPanel{
Image image ;
public Device device ;
/**
* Default κατασκευαστής ο οποίος σχηματίζει το πάνελ με την εικόνα προεπιλογής που έχουμε.
*/
public BackgroundPanel() {
initComponents();
image = Globals.imageBackground ;
}
/**
* Κατασκευαστής της κλάσης ο οποίος σχηματίζει το πάνελ με την εικόνα προεπιλογής
* που έχουμε όπως επίσης συσχετίζει την κλάση μας με κάποιο συγκεκριμένο {@link Device}
* @param dev Το {@link Device} που είναι συσχετισμένο το συγκεκριμένο panel .
*/
public BackgroundPanel(Device dev) {
initComponents();
device = dev ;
this.addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent e) {
// device.fixUnitControlToResize();
//System.out.println("New width: " + getWidth() + " New height: " + getHeight());
}
});
image = Globals.imageBackground ;
}
/**
* Μέθοδος που μας επιτρέπει να αλλάζουμε την εικόνα του panel.
* @param imagePathFile Ένα αρχείο εικόνας για να φορτωθεί στο panel .
*/
public void setImage(File imagePathFile) {
try {
this.image = ImageIO.read(imagePathFile);
} catch (IOException ex) {
device.setPathFile("");
image = Globals.imageBackground ;
//Logger.getLogger(BackgroundPanel.class.getName()).log(Level.SEVERE, null, ex);
}
this.updateUI();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 300, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
/**
* Μέθοδος που εκτελείτε όταν πατήσει κάποιος χρήστης κάποιο κουμπί του ποντικιού
* μέσα στο πάνελ.
* @param evt Το Default MouseEvent που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται.
*/
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
device.clearSelection();
}//GEN-LAST:event_formMouseClicked
/**
* Μέθοδος που εκτελείτε κάθε φορά που επαναζωγραφίζεται το panel.
* @param g Το Default Graphics αντικείμενο που έχει το συγκεκριμένο event το οποίο
* χρησιμοποιούμε για να κάνουμε την εικόνα του panel να ίση με όλο το μέγεθος του (stretch).
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, getWidth(), getHeight(), this); // see javadoc for more info on the parameters
//device.fixUnitControlToResize() ;
}
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
/*
* * * * * * * * * * * * * * * * * * * * * * *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| P P P P M M M M G G G G |+ *
* +| P P M M M M G G |+ *
* +| P P P p M M M M G |+ *
* +| P M M M G G G G |+ *
* +| P M M G G |+ *
* +| P ® M M ® G G G G |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + .----. @ @ |+ *
* + / .-"-.`. \v/ |+ *
* + | | '\ \ \_/ ) |+ *
* + ,-\ `-.' /.' / |+ *
* + '---`----'----' |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| Thesis Michael Galliakis 2016 |+ *
* +| Program m_g ; -) [email protected] |+ *
* +| TEI Athens - IT department. |+ *
* +| [email protected] |+ *
* +| https://github.com/michaelgalliakis |+ *
* +| (myThesis.git) |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* * * * * * * * * * * * * * * * * * * * * * *
*/ | michaelgalliakis/myThesis | UserClientV1/src/UserClientV1/BackgroundPanel.java |
1,520 | /**
* Κλάση που αναπαριστά έναν κύλινδρο. Η κλάση θα πρέπει να επεκτείνει την κλάση κύκλος.
* <p>
* Class that represents a cylinder. This class should extend the Circle class
*/
public class Cylinder extends Circle {
double h,r;
/**
* Κατασκευαστής/ Constructor
*
* @param r ακτίνα του κυλίνδρου / the cylinder's radius
* @param h ύψος του κυλίνδρου / the cylinder's height
*/
public Cylinder(double r, double h) {
super(r);
this.h=h;
}
/**
* Υπολογίζει τον όγκο του κυλίνδρου, ο οποίος ισούται με το εμβαδό μίας εκ των βάσεών του επί το ύψος του.
* <p>
* Computes the total volume of the cylinder which equals the total area of its base multiplied by its height.
*
* @return όγκος του κυλίνδρου / the volume of the cylinder
*/
public double getVolume() {
return super.getArea()*this.h;
}
/**
* Επιστρέφει τo εμβαδό του κυλίνδρου, το οποίο ισούται με το άθροισμα του εμβαδού των δύο βάσεων και του εμβαδού
* της παράπλευρης επιφάνειας, το οποίο ισούται με την περίμετρο της μίας βάσης επί το ύψος
* <p>
* Computer the total area of a cylinder, which equals the sum of the area of both bases and the lateral surface
* area. The lateral surface area equals the perimeter of the base multiplied by the height.
*
* @return Το εμβαδό του κυλίνδρου / The total surface area of the cylinder
*/
public double getArea() {
return super.getArea()*2+super.getPerimeter()*this.h;
}
}
| vtsipras/3rd-Semester---CSD-AUTH | Object-oriented programming/Labs/Lab6/src/Cylinder.java |
1,523 | package com.RapidPharma;
import java.util.*;
import java.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.swing.*;
import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.sql.*;
public class Aitima{
//fields
private static ObservableList<Aitima> aitimata;
public static void sendemail(int status,String id_aitimatos) {
try{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("select email,name from dromologitis inner join Αitima on id_dromologiti=ID_dromologiti where id_ait=id_aitimatos");
ResultSet myRs_1 = myStmt.executeQuery("select email,namefrom dimiourgos inner join Αitima on id_dimiourgos=ID_dromologiti where id_ait=id_aitimatos");
String to = myRs_1.getString("email"); // email αποδέκτη
String from = myRs.getString("email"); // email αποστολέα
String host = myRs.getString("name"); // Όνομα αποστολέα
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session session = Session.getDefaultInstance(properties);
try {
if (status==1) {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("To αίτημα με αριθμό " + id_aitimatos + " τροποποιήθηκε");
message.setText("Το αιτημά σας είναι σε διαδικασία δρομολόγησης απο τον " + myRs.getString("name")
+ " δρομολογητή μπορείτε να παρακολουθήσετε το αιτημά σας στην εφαρμογή μας, Ευχαριστούμε");
Transport.send(message);
System.out.println("Το μήνυμα στάλθηκε επιτυχώς....");
}
if (status==2) {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("To αίτημα με αριθμό " + id_aitimatos + " τροποποιήθηκε");
message.setText("Το αιτημά σας είναι σε διαδικασία διαχείρισης απο τον " + myRs.getString("name")
+ " ο οποίος είναι ο νέος δρομολογητής σας μπορείτε να παρακολουθήσετε το αιτημά σας στην εφαρμογή μας, Ευχαριστούμε");
Transport.send(message);
System.out.println("Το μήνυμα στάλθηκε επιτυχώς....");
}
if (status==3) {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("To αίτημα με αριθμό " + id_aitimatos + " τροποποιήθηκε");
message.setText("Το αιτημά σας ολοκληρώθηκε απο τον " + myRs.getString("name") +
" δρομολογητή μπορείτε να παρακολουθήσετε το αιτημά σας στα ολοκληρωμένα αιτήματα στην εφαρμογή μας, Ευχαριστούμε");
Transport.send(message);
System.out.println("Το μήνυμα στάλθηκε επιτυχώς....");
}
if (status==4) {
MimeMessage message = new MimeMessage(session);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject("To αίτημα με αριθμό " + id_aitimatos + " τροποποιήθηκε");
message.setText("Το αιτημά σας έγινε αποδεκτό απο τον " + myRs.getString("name") +
" δρομολογητή χωρίς όμως να έχει δρομολογηθεί λόγω κάποιας έλλειψης μπορείτε να παρακολουθήσετε το αιτημά σας στην " +
"εφαρμογή μας, Ευχαριστούμε");
Transport.send(message);
System.out.println("Το μήνυμα στάλθηκε επιτυχώς....");
}
} catch (MessagingException mex) {
mex.printStackTrace();
}
}
catch (Exception exc) {
exc.printStackTrace();
}
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {
int row = tableAitimata.getSelectedRow();
String aitimaId = tableAitimata.getModel().getValueAt(row, 0).toString();
Date imerominia = (Date) tableAitimata.getModel().getValueAt(row, 1);
String to = tableAitimata.getModel().getValueAt(row, 2).toString();
String from = tableAitimata.getModel().getValueAt(row, 3).toString();
String eidosMetaforas = tableAitimata.getModel().getValueAt(row, 4).toString();
String proteraiotita = tableAitimata.getModel().getValueAt(row, 5).toString();
String plithosPallets = tableAitimata.getModel().getValueAt(row, 6).toString();
boolean prosTropopoiisi = (boolean) tableAitimata.getModel().getValueAt(row, 7);
boolean prosAkirwsi = (boolean) tableAitimata.getModel().getValueAt(row, 8);
aitimaUpdate aitimaupdate = new aitimaUpdate();
aitimaupdate.setVisible(true);
aitimaupdate.pack();
aitimaupdate.setLocationRelativeTo(null);
aitimaupdate.aitimaidField.setText(aitimaId);
aitimaupdate.imerominiaField.setDate(imerominia);
aitimaupdate.toField.setText(to);
aitimaupdate.fromField.setText(from);
aitimaupdate.eidosmetaforasField.setText(eidosMetaforas);
aitimaupdate.proteraiotitaField.setText(proteraiotita);
aitimaupdate.plithospalletsField.setText(plithosPallets);
aitimaupdate.prostropopoiisiCheckBox.setSelected(prosTropopoiisi);
aitimaupdate.prosakirwsiCheckBox.setSelected(prosAkirwsi);
}
private void deleteAitimaButtonActionPerformed(java.awt.event.ActionEvent evt) {
for (int row : tableAitimata.getSelectedRows()) {
int aitimaID = Integer.parseInt(tableAitimata.getModel().getValueAt(row, 0).toString());
try{
PreparedStatement statement;
ResultSetImpl rs;
String query = "DELETE FROM `aitima` WHERE `aitimaid` = " +aitimaID;
statement = (PreparedStatement) DataConnection.getConnection().prepareStatement(query);
rs = (ResultSetImpl) statement.executeQuery();
tableAitimata.setModel(DbUtils.resultSetToTableModel(rs));
JOptionPane.showInternalMessageDialog(null, "Το αίτημα διαγράφηκε επιτυχώς!");
filltable();
}
catch(SQLException ex){
Logger.getLogger(tropopoiisiAitimatos.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public void filltable()){
try{
Date fromDate = fromDateField.getDate();
Date toDate = toDateField.getDate();
PreparedStatement statement;
ResultSetImpl rs;
String query = "SELECT * FROM `aitima`"
+ " (`fromdate` BETWEEN 'fromDate' AND 'toDate') OR \n"
+ " (`todate` BETWEEN 'fromDate' AND 'toDate') OR \n"
+ " (`fromdate` <= 'fromDate' AND `todate` >= 'toDate')";
statement = (PreparedStatement) DataConnection.getConnection().prepareStatement(query);
rs = (ResultSetImpl) statement.executeQuery();
tableAitimata.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException ex){
Logger.getLogger(tropopoiisiAitimatos.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void tropopoiisiButtonActionPerformed(java.awt.event.ActionEvent evt) {
try{
PreparedStatement statement;
ResultSetImpl rs;
Date Imerominia = imerominiaField.getDate();
String To = toField.getText();
String From = fromField.getText();
String EidosMetaforas = eidosmetaforasField.getText();
String Proteraiotita = proteraiotitaField.getText();
String PlithosPallets = plithospalletsField.getText();
boolean ProsTropopoiisi = Boolean.getBoolean(prostropopoiisiCheckBox.getText());
boolean ProsAkirwsi = Boolean.getBoolean(prosakirwsiCheckBox.getText());
String query = "UPDATE `aitima` SET"
+" `imerominia` = ?,"
+" `apo` = ?,"
+" `pros` = ?,"
+" `eidos_metaforas` = ?,"
+" `proteraiotita` = ?,"
+" `prostropopoiisi` = ?,"
+" `prosakirwsi` = ?,";
statement = (PreparedStatement) DataConnection.getConnection().prepareStatement(query);
statement.setDate(1, (java.sql.Date) Imerominia);
statement.setString(2, To);
statement.setString(3, From);
statement.setString(4, EidosMetaforas);
statement.setString(5, Proteraiotita);
statement.setString(6, PlithosPallets);
statement.setBoolean(7, ProsTropopoiisi);
statement.setBoolean(8, ProsAkirwsi);
rs = (ResultSetImpl) statement.executeQuery();
if(statement.executeUpdate()!=0){
JOptionPane.showInternalMessageDialog(null, "Οι πληροφορίες αποθηκεύτηκαν σωστά!");
this.dispose();
}
else{
JOptionPane.showMessageDialog(null, "Σφάλμα! Η τροποποίηση απέτυχε! ");
}
}
catch(SQLException ex){
Logger.getLogger(aitimaUpdate.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void kataxwrisiAitimatosButtonActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement statement1;
PreparedStatement statement2;
String query1 = "INSERT INTO `fortio`(`plithosIpostirigmatwn`,`mikos`, platos`, `varos`, `plithos`) VALUES (?,?,?,?,?)";
String query2 = "INSERT INTO `aitima`(`fortioid`,`imerominia`,`to`, from`, `eidosmetaforas`, `proteraiotita`) VALUES (SCOPE_IDENTITY(),?,?,?,?,?)";
String imerominia = imerominiaField.getText();
String apo = apoTopothesiaField.getText();
String pros = prosTopothesiaField.getText();
String eidosmetaforas = eidosMetaforasField.getSelectedItem().toString();
String proteraiotita = proteraiotitaField.getSelectedItem().toString();
int plithosIpostirigmatwn = Integer.valueOf(plithosIpostirigmatwnField.getText());
int mikos = Integer.valueOf(mikosField.getText());
int platos = Integer.valueOf(platosField.getText());
int varos = Integer.valueOf(varosField.getText());
int plithos = Integer.valueOf(plithosField.getText());
try{
statement1 = (PreparedStatement) DataConnection.getConnection().prepareStatement(query1);
statement2 = (PreparedStatement) DataConnection.getConnection().prepareStatement(query2);
statement1.setString(1, imerominia);
statement1.setString(2, apo);
statement1.setString(3, pros);
statement1.setString(4, eidosmetaforas);
statement1.setString(5, proteraiotita);
statement1.setNull(5, java.sql.Types.NULL);
statement2.setInt(1, plithosIpostirigmatwn);
statement2.setInt(2, mikos);
statement2.setInt(3, platos);
statement2.setInt(4, varos);
statement2.setInt(5, plithos);
statement2.setNull(5, java.sql.Types.NULL);
ResultSetImpl ts = (ResultSetImpl) statement1.executeQuery();
ResultSetImpl rs = (ResultSetImpl) statement2.executeQuery();
if(statement1.executeUpdate()!=0 && statement2.executeUpdate()!=0){
new ArxikiOthoni();
}
else{
JOptionPane.showMessageDialog(null, "Σφάλμα! Ελέγξτε τις πληροφορίες που εισάγατε!");
imerominiaField.setText("");
apoTopothesiaField.setText("");
prosTopothesiaField.setText("");
eidosMetaforasField.setSelectedItem(0);
proteraiotitaField.setSelectedItem(0);
plithosIpostirigmatwnField.setText("");
mikosField.setText("");
platosField.setText("");
varosField.setText("");
plithosField.setText("");
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void comboBoxFieldsFill(){
PreparedStatement statement1;
PreparedStatement statement2;
PreparedStatement statement3;
String query1 = "SELECT `eidos_metaforas` FROM `aitima`";
String query2 = "SELECT `proteraiotita` FROM `aitima`";
String query3 = "SELECT `tiposfortiou` FROM `fortio`";
try{
statement1 = (PreparedStatement) DataConnection.getConnection().prepareStatement(query1);
statement2 = (PreparedStatement) DataConnection.getConnection().prepareStatement(query2);
statement3 = (PreparedStatement) DataConnection.getConnection().prepareStatement(query3);
ResultSetImpl rs = (ResultSetImpl) statement1.executeQuery();
ResultSetImpl ts = (ResultSetImpl) statement2.executeQuery();
ResultSetImpl ps = (ResultSetImpl) statement3.executeQuery();
while(ts.next()){
proteraiotitaField.addItem(rs.getString("proteraiotita"));
}
while(ps.next()){
tiposFortiouField.addItem(rs.getString("tiposfortiou"));
}
while(rs.next()){
eidosMetaforasField.addItem(rs.getString("eidosmetaforas"));
}
}
catch(SQLException ex){
Logger.getLogger(dimiourgiaAitima.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void updateRouteDate(Date route_date, int id_aitimatos){
private static Statement statement;
try{
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet rs = statement.executeQuery("Update Aitimata Set imerominia_dromologiou = " + route_date + " WHERE ID = "+ id_aitimatos ";");
catch(Exception e){
e.printStackTrace();
}
}
}
//Επιστρέφονται όλα τα αιτήματα που αφορουν το χρήστη
public static ObservableList<Aitima> getaitimata(String id_xristi) {
aitimata = FXCollections.observableArrayList();
try {
myStmt = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet myRs = myStmt.executeQuery("select * from Aitima inner join xristis on ID_xristi=id_xristi where ID_xristi=" + id_xristi + ";");
if (myRs != null)
while (myRs.next()) {
Aitima aitima_1 = new Aitima();
aitima_1.setid(myRs.getInt(1));
aitima_1.setImerominia(myRs.getInt(2));
aitima_1.setApo_Topothesia(myRs.getString(3));
aitima_1.setPros_Topothesia(myRs.getString(4));
aitima_1.setEidos_Metaforas(myRs.getString(5));
aitima_1.setRequired_Europaletes(myRs.getInt(6));
aitima_1.setstatus(myRs.getInt(7));
aitimata.add(aitima_1);
}
} catch (Exception e) {
e.printStackTrace();
}
return aitimata;
}
//εδω αλλάζει η κατασταση του αιτηματος οταν το διαχειριζεται (π.χ δεν ειναι ανοιχτο πλεον αλλα δρομολογημενο)
public static void Update_status(String id_aitimatos,int status){
try{
Connection myConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root");
Statement myStmt = myConn.createStatement();
ResultSet myRs = myStmt.executeQuery("Update Aitima set status="+status+" where id_aitimatos="+id_aitimatos);
sendemail(status,id_aitimatos);
}
catch(Exception exc) {
exc.printStackTrace();
}
// int[] chkd τα επιλεγμένα αιτήματα, string[] router η επι΄λογη του νέου δρομολογητη απο τη λιστα για την ανακατευθυνση
public static void updateRouter(String kodikos, String id_aitimatos, String aitiologia ,int id_dromologiti){
private static Statement statement;
try {
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet myRs = statement.executeQuery("select * from Aitima inner join xristis a on id_xristi=a.id where a.id=" + id_dromologiti + ";");
if (myRs != null)
while (myRs.next()) {
Aitima aitima_1 = new Aitima();
aitima_1.setid(myRs.getInt(1));
aitima_1.setImerominia(myRs.getInt(2));
aitima_1.setApo_Topothesia(myRs.getString(3));
aitima_1.setPros_Topothesia(myRs.getString(4));
aitima_1.setEidos_Metaforas(myRs.getString(5));
aitima_1.setRequired_Europaletes(myRs.getInt(6));
aitima_1.setstatus(myRs.getInt(7));
int id = aitima_1.getID();
for(i=0; i<=chkd.length(); i++){
if ((aitima_1.setEidos_Metaforas == "ΑΠΟ ΦΑΡΜΑΚΑΠΟΘΗΚΗ" || aitima_1.setEidos_Metaforas == "ΠΡΟΣ ΚΑΤΑΣΤΗΜΑ" ) && id_aitimatos == id){
try {
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet Rs = statement.executeQuery("Update Aitimata Set apo = " + router + ", aitiologia = WHERE ID = "+ aitima_1.getID() ";");
}
catch (Exception e) {
e.printStackTrace();
}
}
else if (aitima_1.setEidos_Metaforas == "ΠΡΟΣ ΦΑΡΜΑΚΑΠΟΘΗΚΗ" || aitima_1.setEidos_Metaforas == "ΑΠΟ ΚΑΤΑΣΤΗΜΑ") && id_aitimatos == id) {
try {
statement = DataConnection.getConnection("jdbc:mysql://localhost:3306/RapidPharma", "root", "root").createStatement();
ResultSet myRs = statement.executeQuery("Update Aitimata Set pros = " + router + " WHERE ID = "+ aitima_1.getID() ";");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
| Asbaharoon/java-project | java_src/aitima.java |
1,525 | package thesis;
import java.util.ArrayList;
import java.util.List;
/**
* @author Nektarios Gkouvousis
* @author ice18390193
*
* Η κλάση Course αντιπροσωπεύει κάθε μάθημα του τμήματος. Περιλαμβάνει πληροφορίες
* όπως το όνομα του μαθήματος, τη συντομογραφία του, το εξάμηνο στο οποίο διδάσκεται,
* εάν βρίσκεται σε χειμερινό ή εαρινό εξάμηνο, καθώς και αν εξετάζεται. Αποθηκεύει
* επίσης τους εξεταστές του μαθήματος καθώς και τις αίθουσες διεξαγωγής της εξέτασης.
*/
public class Course{
private String courseName;
private String courseShort;
private String courseSem;
private String courseSeason;
private boolean isExamined;
private List<Professor> examiners;
private List<Classroom> classrooms;
private int approxStudents;
/**
* Κατασκευαστής για τη δημιουργία ενός νέου αντικειμένου Course.
*
* @param name Το όνομα του μαθήματος (String).
* @param nameShort Η συντομογραφία του μαθήματος (String).
* @param semester Το εξάμηνο διεξαγωγής του μαθήματος (String).
* @param season Περίοδος εξέστασης (String 'ΕΑΡΙΝΟ'/'ΧΕΙΜΕΡΙΝΟ').
* @param isExamined Εάν εξετάζεται το μάθημα ή όχι(boolean, true για '+', false για '-').
*/
public Course(String name, String nameShort, String semester, String season, boolean examined){
courseName = name;
courseShort = nameShort;
courseSem = semester;
courseSeason = season;
isExamined = examined;
examiners = new ArrayList<>();
classrooms = new ArrayList<>();
approxStudents = 0;
}
/**
* Ένας κατασκευαστής (copy-constrctor) ο οποίος δημιουργεί ένα νέο αντικείμενο
* τύπου Cousrse με τιμές από ένα άλλο αντικείμενο Course.
*
* @param course Αντικείμενο τύπου Course από το οποίο θα αντληθούν τα στοιχεία
* που θα θέσουμε στο νέο αντικείμενο Course.
*/
public Course(Course course){
courseName = course.getCourseName();
courseShort = course.getCourseShort();
courseSem = course.getCourseSem();
courseSeason = course.getCourseSeason();
isExamined = course.getIsExamined();
examiners = new ArrayList<>(course.getExaminers());
classrooms = new ArrayList<>();
approxStudents = course.getApproxStudents();
}
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseShort() {
return courseShort;
}
public void setCourseShort(String courseShort) {
this.courseShort = courseShort;
}
public String getCourseSem() {
return courseSem;
}
public void setCourseSem(String courseSem) {
this.courseSem = courseSem;
}
public boolean getIsExamined() {
return isExamined;
}
public void setIsExamined(boolean isExamined) {
this.isExamined = isExamined;
}
public List<Professor> getExaminers() {
return examiners;
}
public void setExaminers(List<Professor> examiners) {
this.examiners = examiners;
}
public void addExaminer(Professor prof){
examiners.add(prof);
}
public void setCourseSeason(String s) {
this.courseSeason = s;
}
public String getCourseSeason(){
return this.courseSeason;
}
public List<Classroom> getClassrooms() {
return classrooms;
}
public void setClassrooms(List<Classroom> classrooms) {
this.classrooms = classrooms;
}
public int getApproxStudents() {
return approxStudents;
}
public void setApproxStudents(int approxStudents) {
this.approxStudents = approxStudents;
}
public boolean checkIfProfessorsAreAvailable(String date, String timeslot){
boolean res = true;
for(Professor prf : examiners){
if (prf.isAvailable(date, timeslot) != 1){
res = false;
}
}
return res;
}
/**
* Εκτύπωση μαθήματος και εξεταστών.
*/
/*
public void printStatistics(){
int i = 0;
System.out.println("Course is:" + this.getCourseName() + examiners.size());
for (Professor prof : examiners){
System.out.println("Professor " + i + ": " + prof.getProfFirstname());
}
}*/
}
| Gouvo7/Exam-Schedule-Creator | src/thesis/Course.java |
1,527 | package highscoreTest;
import com.google.common.annotations.VisibleForTesting;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
/**
* <p>Λειτουργική κλάση για την εμφάνιση των top 10 scores μαζί με τα username αντίστοιχα.</p>
*
* @author Team Hack-You
* @version 1.0
* @see PlayerInfo
*/
public final class HighScore {
/**
* <code>playerInfo</code> Περιέχει τα στοιχεία των παικτών που έχουν καταχωρήσει highscore
*/
private final LinkedList<PlayerInfo> playerInfo = new LinkedList<>();
private final String name;
private final int score;
private static int playerInfoSize;
/**
* <p>Getter for <code>playerInfo.get(index)</code>.</p>
*
* @param index a int
* @return a {@link highscoreTest.PlayerInfo} object
*/
public PlayerInfo getPlayerInfoElement(int index) {
return playerInfo.get(index);
}
/**
* <p>Κατασκευαστής ο οποίος αρχικά κάνει writable το αρχείο των highscores και μετά την επεξεργασία <br>
* του αρχείου το κάνει read-only ώστε να μην επιτρέπεται η κακόβουλη αλλαγή του</p>
*
* @param name όνομα παίκτη
* @param score βαθμολογία παίκτη
*/
public HighScore(String name, int score) {
this.name = name;
this.score = score;
setFile(true);
load();
boolean checkForNewHigh = checkForNewRegister();
if (checkForNewHigh) {
//Αν δεν έγινε personal record
boolean flag = true;
sort();
int count = 0;
//Έλεγχος για το αν έγινε προσωπικό ρεκόρ
if (playerInfo.stream().anyMatch(p -> p.getName().equals(name))) {
for (PlayerInfo p : playerInfo) {
int check = new PlayerInfo(name, score).didGreater(p);
if (check == PlayerInfo.greater) {
//Για να μην υπάρξει interrupt στο Thread του WinFrame
SwingUtilities.invokeLater(() ->
JOptionPane.showMessageDialog(null,
"Ξεπέρασες το προσωπικό σου highscore!", "Congratulations",
JOptionPane.INFORMATION_MESSAGE));
flag = false;
break;
} else if (check == PlayerInfo.notGreater) {
count++;
//Αν συναντάται η ίδια καταχώρηση πάνω από μια φορά, η αναζήτηση σταματά
if (count == 2) {
break;
}
}
}
}
if (flag) {
//Για να μην υπάρξει interrupt στο Thread του WinFrame
SwingUtilities.invokeLater(() ->
JOptionPane.showMessageDialog(null,
"You managed to set a new Highscore to the highscore table", "Congratulations",
JOptionPane.INFORMATION_MESSAGE));
}
}
playerInfoSize = playerInfo.size();
setFile(false);
}
/**
* <p>Μέθοδος που μεταβάλει την κατάσταση του αρχείου σε writable/not-writable </p>
*
* @param status : true - writable , false - not-writable
*/
private void setFile(boolean status) {
File file = new File("./HighScore.txt");
//making the file as read/read-only using setWritable(status) method
file.setWritable(status);
}
/**
* <p>Έλεγχος για το αν το score που δίδεται είναι αρκετά μεγάλο <br>
* για να καταγραφεί στον πίνακα των top 10 ή όχι</p>
*
* @return true αν έγινε η καταχώρηση επιτυχώς,<br> false αν δεν έγινε νέα καταχώρηση
*/
private boolean checkForNewRegister() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("./HighScore.txt"), StandardCharsets.UTF_8))) {
int lines = 0;
while (reader.readLine() != null) {
lines++;
}
reader.close();
//Αν οι γραμμές είναι < 10 γίνεται καταχώρηση χωρίς έλεγχο
if (lines < 10) {
appendScore();
playerInfo.add(new PlayerInfo(name, score));
return true;
}
for (PlayerInfo player : playerInfo) {
if (score > player.getScore()) {
appendScore();
playerInfo.add(new PlayerInfo(name, score));
return true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* <p>Προσθήκη στοιχείων στο αρχείο txt των highscores </p>
*/
private void appendScore() {
try (BufferedWriter writer = new BufferedWriter
(new OutputStreamWriter(
new FileOutputStream("./HighScore.txt", true), StandardCharsets.UTF_8))) {
writer.write(String.format("%s %d", name, score));
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>Φόρτωση πληροφοριών αρχείου στη συνδεδεμένη λίστα <code>playerInfo</code></p>
*/
private void load() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(
new FileInputStream("./HighScore.txt"), StandardCharsets.UTF_8))) {
String currentLine = reader.readLine();
while (currentLine != null) {
String[] playerDetails = currentLine.split(" ");
String name = playerDetails[0];
int score = Integer.parseInt(playerDetails[1]);
//Creating PlayerInfo object for every record and adding it
playerInfo.add(new PlayerInfo(name, score));
currentLine = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>Ταξινόμηση playerInfo και αρχείου με φθίνουσα σειρά με βάση τα scores</p>
*/
private void sort() {
//Sorting ArrayList playerInfo based on scores
playerInfo.sort((p1, p2) -> p2.getScore() - p1.getScore());
try (BufferedWriter writer = new BufferedWriter
(new OutputStreamWriter(
new FileOutputStream("./HighScore.txt"), StandardCharsets.UTF_8))) {
int counter = 0;
//Ξαναδημιουργώ το αρχείο βάζοντας τα playerInfo σε σωστή σειρά και να είναι μέχρι 10
for (PlayerInfo player : playerInfo) {
if (counter == 10) {
playerInfo.remove(counter);
break;
}
writer.write(player.getName());
writer.write(" " + player.getScore());
writer.newLine();
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>Δημιουργία αρχείου καταγραφής HighScore την 1η φορά εκτέλεσης του παιχνιδιού.</p>
*/
public static void setup() {
try {
File file = new File("./HighScore.txt");
if (file.createNewFile()) {
SwingUtilities.invokeLater(() ->
JOptionPane.showMessageDialog(null, "Επιτυχής προετοιμασία αρχείου HighScore",
"Info", JOptionPane.INFORMATION_MESSAGE));
}
file.setWritable(false);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* <p>Έλεγχος για το αν υπάρχει μια συγκεκριμένη καταχώρηση.</p>
*
* @param name a {@link java.lang.String} object
* @param score an int
* @return a boolean
*/
@VisibleForTesting
public boolean isRegistered(String name, int score) {
return playerInfo.contains(new PlayerInfo(name, score));
}
/**
* <p>Getter for the field <code>playerInfoSize</code>.</p>
*
* @return an int
*/
public static int getPlayerInfoSize() {
return playerInfoSize;
}
}
| geoartop/Hack-You | Maven/src/main/java/highscoreTest/HighScore.java |
1,528 | package api;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Η κλάση αυτή περιέχει μεθόδους για τη διαχείριση των καταλυμάτων και την κεντρική λίστα που συγκεντρώνει όλα τα
* καταλύματα.
*/
public class ManageAccommodations implements Serializable {
private ArrayList<Accommodation> accommodations;
/**
* Κατασκευαστής της κλάσης ManageAccommodations. Αρχικοποιεί τη λίστα των καταλυμάτων.
*/
public ManageAccommodations() {
accommodations = new ArrayList<>();
}
/**
*Η μέθοδος αυτή αποθηκεύει το αντικείμενο τύπου ManageAccommodations στο αντίστοιχο αρχείο εξόδου.
*/
public void saveToOutputFiles() {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsManager.bin"))) {
out.writeObject(this);
//out.flush();
} catch (IOException e1) {
System.out.println("Δεν βρέθηκε αρχείο εξόδου");
}
}
/**
* Η μέθοδος αυτή ελέγχει εάν η λίστα των καταλυμάτων είναι άδεια και αν περιέχεται το κατάλυμα σε
* αυτήν. Εάν ισχύουν οι δύο αυτές προϋποθέσεις η μέθοδος επιστρέφει false διαφορετικά προσθέτει το
* κατάλυμα με τις παροχές που προσφέρει.
* @param name Το όνομα του καταλύματος.
* @param description Η περιγραφή του καταλύματος.
* @param stayType Ο τύπος του καταλύματος.
* @param address Η διεύθυνση του καταλύματος.
* @param town Η πόλη στην οποία βρίσκεται το κατάλυμα.
* @param postCode Ο ταχυδρομικός κώδικας της περιοχής που βρίσκεται το κατάλυμα.
* @param utilities Η λίστα με τις παροχές που προσφέρει το κατάλυμα.
* @param provider Ο πάροχος του καταλύματος.
* @return true αν γίνει επιτυχώς η προσθήκη του νέου καταλύματος και false διαφορετικά
*/
public boolean addAccommodation(String name, String description, String stayType, String address, String town, String postCode, ArrayList<Utility> utilities, Provider provider) {
Location location = new Location(address, town, postCode);
Accommodation accommodation = new Accommodation(name, description, stayType, location, provider);
if (!accommodations.isEmpty()) {
if (accommodations.contains(accommodation)) {
return false;
}
}
accommodation.setTypesOfUtilities(utilities);
accommodations.add(accommodation);
return true;
}
/**
* Η μέθοδος αυτή αφαιρεί ένα κατάλυμα απο τη λίστα καταλυμάτων εάν η λίστα δεν είναι αδεία και εάν αυτό περιέχεται
* στη λίστα καταλυμάτων, σε διαφορετική περίπτωση επιστρέφει false.
* @param accommodation Το κατάλυμα.
* @return true αν γίνει επιτυχώς η αφαίρεση του νέου καταλύματος και false διαφορετικά
*/
public boolean removeAccommodation(Accommodation accommodation) {
if (accommodations.isEmpty())
return false;
else if (!accommodations.contains(accommodation))
return false;
accommodations.remove(accommodation);
//Διαχείριση fallout των evaluations με εξτρα συνάρτηση στη ManageEvaluations
return true;
}
/**
* Η μέθοδος αυτή χρησιμοποιείται για την ανανέωση των πληροφοριών/χαρακτηριστικών ενός καταλύματος. Εάν η λίστα
* είναι άδεια επιστρέφει false διαφορετικά γίνεται μία αναζήτηση στη λίστα των καταλύμματων και όταν βρεθεί το
* κατάλυμα που αναζητείται γίνονται οι αλλαγές στις πληροφορίες/χαρακτηριστικά του.
*
* @param accommodation Το Κατάλυμα.
* @param name Το όνομα καταλύματος.
* @param description Η περιγραφή του καταλύματος.
* @param stayType Ο τύπος καταλύματος.
* @param address Η διεύθυνση καταλύματος.
* @param town Η πόλη του καταλύματος.
* @param postCode Ο ταχυδρομικός κώδικας του καταλύματος.
* @return True αν γίνει επιτυχώς η επεξεργασία του νέου καταλύματος και false διαφορετικά
*/
public boolean alterAccommodationDetails(Accommodation accommodation, String name, String description, String stayType, String address, String town, String postCode) {
Location location = new Location(address, town, postCode);
if (accommodations.isEmpty())
return false;
for (Accommodation accommodation1 : accommodations) {
if (accommodation.equals(accommodation1)) {
accommodations.remove(accommodation); // το accommodation υπάρχει οπότε η remove δεν επιστρέφει false
accommodation.setName(name);
accommodation.updateSingularId(); //απαραίτητο για να αποφευχθούν συγχύσεις
accommodation.setDescription(description);
accommodation.setStayType(stayType);
accommodation.setPlace(location);
accommodations.add(accommodation);
return true;
}
}
return false;
}
/**
* η Μέθοδος αυτή χρησιμοποιείται για την ανανέωση των παροχών ενός καταλύματος.
* @param accommodation Το κατάλυμα.
* @param utilities Οι νέες παροχές του καταλύμματος.
* @return True αν γίνει επιτυχώς η επεξεργασία των παροχών του καταλύματος και false διαφορετικά
*/
public boolean alterAccommodationUtilities(Accommodation accommodation , ArrayList<Utility> utilities) {
if (!accommodationExists(accommodation))
return false;
for (Accommodation accommodation1 : accommodations) {
if (accommodation.equals(accommodation1)) {
accommodations.remove(accommodation); // το accommodation υπάρχει οπότε η remove δεν επιστρέφει false
accommodation.setTypesOfUtilities(utilities);
accommodations.add(accommodation);
return true;
}
}
accommodation.setTypesOfUtilities(utilities);
return false;
}
/**
* Η μέθοδος αυτή χρησιμοποιείται για τη δημιουργία μιας λίστας για τα καταλύματα ενός παρόχου.
* @param provider Ο πάροχος
* @return Τα καταλύματα του παρόχου που δίνεται ως όρισμα.
*/
public ArrayList<Accommodation> getProvidersAccommodations(Provider provider) {
ArrayList<Accommodation> providersAccommodations = new ArrayList<>();
if (!accommodations.isEmpty()) {
for (Accommodation accommodation : accommodations) {
if (accommodation.getProvider().equals(provider))
providersAccommodations.add(accommodation);
}
}
return providersAccommodations;
}
/**
* Η μέθοδος αυτή ελέγχει εάν ένα κατάλυμα υπάρχει στη λίστα όλων των καταλυμάτων.
* @param accommodation το κατάλυμα που θέλουμε να ελέγξουμε αν υπάρχει
* @return True αν υπάρχε, false διαφορετικά
*/
public boolean accommodationExists(Accommodation accommodation) {
if (accommodations.isEmpty())
return false;
return accommodations.contains(accommodation);
}
/**
* Ελέγχει αν ένα κατάλυμα έχει προστεθεί απο τον χρήστη που δίνεται ως όρισμα
* @param user Πάροχος
* @param accommodation κατάλυμα που θέλουμε να δούμε αν έχει προστεθεί από τον πάροχο
* @return True αν το κατάλυμα έχει προστεθεί από τον πάροχο, false διαφορετικά
*/
public boolean isProvidersAccommodation(User user, Accommodation accommodation) {
return user.equals(accommodation.getProvider());
}
/**
*Η μέθοδος αυτή ενημερώνει τον μέσο όρο αξιολογήσεων όλων των καταλυμάτων.
* @param evaluations Οι αξιολογήσεις για όλα τα καταλύματα.
*/
public void updateAllAvgRatings(ArrayList<Evaluation> evaluations) {
if (evaluations.isEmpty())
return;
for (Accommodation accommodation : accommodations) {
accommodation.updateAvgRatingOfAccommodation(evaluations);
}
}
/**
* Η μέθοδος αυτή ελέγχει εάν τα πεδία για την καταχώρηση κάποιου καταλύματος έχουν συμπληρωθεί ορθά και επιστρέφει
* κατάλληλο μήνυμα. Η ορθότητα καταχώρησης κρίνεται από τις πληροφορίες του καταλύματος, των οποίων το μήκος της
* συμβολοσειράς πρέπει να υπερβαίνει του μηδενός χωρίς τους κενούς χαρακτήρες, του τύπου καταλύματος, το οποίο
* πρέπει να αντιστοιχείται σε κάποιο από τα τρία διαθέσιμα (Διαμέρισμα, Ξενοδοχείο, Μεζονέτα) και του ταχυδρομικού
* κώδικα ο οποίος πρέπει να είναι αριθμός μεγαλύτερος του μηδενός. Εάν πληρούνται αυτές οι προϋποθέσεις η μέθοδος
* επιστρέφει null, ενώ σε διαφορετική περίπτωση επιστρέφεται κατάλληλο μήνυμα λάθους.
* @param name Το όνομα καταλύματος.
* @param description Η περιγραφή του καταλύματος.
* @param stayType Ο τύπος καταλύματος.
* @param town Η πόλη του καταλύματος.
* @param address Η διεύθυνση καταλύματος.
* @param postCode Ο ταχυδρομικός κώδικας του καταλύματος.
* @return Κατάλληλο μήνυμα σε περίπτωση λανθασμένης καταχώρησης, διαφορετικά null.
* @param editing False αν πρόκειται για επεξεργασία καταλύματος για να μη χτυπήσει στη συνωνυμία με τον εαυτό του
*/
public String checkSubmissionInaccuracies(String name, String description, String stayType, String town, String address, String postCode, boolean editing) { //επιστρέφει null αν όλα καλά
if (name.trim().length() == 0 || stayType.trim().length() == 0 || description.trim().length() == 0 || town.trim().length() == 0 || postCode.trim().length() == 0 || address.trim().length() == 0) //Η μέθοδος trim() αφαιρεί όλα τα whitespaces ώστε να μην περνάει ως είσοδος το space
return "Τα πεδία κειμένου είναι υποχρεωτικά για να υποβάλετε επιτυχώς το νέο σας κατάλυμα.";
else if (!stayType.equals("Ξενοδοχείο") && !stayType.equals("Διαμέρισμα") && !stayType.equals("Μεζονέτα"))
return "Παρακαλώ δηλώστε τον τύπο του καταλύματος ως Ξενοδοχείο, Διαμέρισμα ή Μεζονέτα.";
else if (accommodationNameExists(name) && !editing)
return "Έχετε ήδη καταχωρήσει κατάλυμα με αυτό το όνομα παρακαλώ επιλέξτε άλλο";
float postC;
try {
postC = Float.parseFloat(postCode);
if (postC <= 0)
return "Εισάγετε έγκυρο ταχυδρομικό κώδικα";
} catch(NumberFormatException e1) {
return "Παρακαλώ εισάγετε αριθμό στο πεδίο του ταχυδρομικού κώδικα.";
}
return null; //περίπτωση του όλα καλά
}
/**
* Ελέγχει αν υπάρχει ήδη κατάλυμα με το όνομα που δίνεται ως όρισμα
* @param name όνομα προς αναζήτηση στη λίστα των καταλυμάτων
* @return True αν υπάρχει κατάλυμα με όνομα name, null διαφορετικά
*/
private boolean accommodationNameExists(String name) {
if (accommodations.isEmpty())
return false;
for (Accommodation accommodation : accommodations) {
if (accommodation.getName().equals(name))
return true;
}
return false;
}
/**
* Η μέθοδος αυτή χρησιμοποιείται για την αναζήτηση καταλυμάτων από τον χρήστη. Είναι έτσι υλοποιημένη ώστε αν
* κάποια πεδία είναι κενά να λειτουργεί κανονικά η αναζήτηση. Στο τέλος επιστρέφονται όσα καταλύματα ταυτίζονται
* με τις πληροφορίες των ορισμάτων.
* @param name Tο όνομα του καταλύματος.
* @param stayType Ο τύπος του καταλύματος.
* @param town Η πόλη του καταλύματος.
* @param utilities Οι παροχές του καταλύματος.
* @return Λίστα με τα καταλύματα.
*/
public ArrayList<Accommodation> searchAccommodations(String name, String stayType, String town, ArrayList<Utility> utilities) {
ArrayList<Accommodation> resultingAccommodations = new ArrayList<>();
if (accommodations.isEmpty())
return resultingAccommodations;
boolean fittingName;
boolean fittingStayType;
boolean fittingTown;
boolean fittingUtilities;
for (Accommodation accommodation : accommodations) {
fittingUtilities = true;
// Αν οι συμβολοσειρές είναι κενές ή έχουν μόνο whitespaces δεν οδηγείται στην απόρριψη του καταλύματος κατά την αναζήτηση
fittingName = name.trim().length() == 0 || name.equals(accommodation.getName());
fittingStayType = stayType.trim().length() == 0 || stayType.equals(accommodation.getStayType());
fittingTown = town.trim().length() ==0 || town.equals(accommodation.getLocation().getTown());
for (int i=0; i<utilities.size() && fittingUtilities; i++) {
if (!utilities.get(i).getSpecifics().isEmpty())
for (String specificUtility : utilities.get(i).getSpecifics()) {
if (!accommodation.getTypesOfUtilities().get(i).getSpecifics().contains(specificUtility)) {
fittingUtilities = false;
break;
}
}
}
if (fittingTown && fittingName && fittingUtilities && fittingStayType)
resultingAccommodations.add(accommodation);
}
return resultingAccommodations;
}
}
| patiosga/myreviews | src/api/ManageAccommodations.java |
1,529 | /*
Μέλη Ομάδας
Λόκκας Ιωάννης ΑΜ: 3120095
Μπούζας Βασίλειος ΑΜ: 3120124
Τασσιάς Παναγιώτης ΑΜ: 3120181
*/
package Logic_AI;
import CNF_Resolution.*;
import Horn_ForwardChaining.*;
import Horn_PKL.HornPKLClause;
import Horn_PKL.Relation;
import FileIO.ReadFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.InputMismatchException;
import java.util.Scanner;
/*
----------------------------------------------MAIN CLASS-----------------------------------------
Η κλάση αυτή είναι η Main κλάση για την εκτέλεση του προγράμματος.
Εμφανίζει στον χρήστη το μενού με τις διαθέσιμες επιλογές, δέχεται ως είσοδο την επιλογή του
και εκτελεί ανάλογα με την επιλογή του τον αντίστοιχο αλγόριθμο.
Συγκεκριμένα πατώντας:
1. Εκτελείται ο αλγόριθμος ανάλυσης
2. Εκτελείται ο αλγόριθμος εξαγωγής συμπεράσματος προς τα εμπρός για προτάσεις Horn Προτασιακής Λογικής
3. Εκτελείται ο αλγόριθμος εξαγωγής συμπεράσματος προς τα εμπρός για προτάσεις Horn ΠΚΛ
0. Τερματίζει το πρόγραμμα
Μετά την επιλογή του ο χρήστης καλέιται να εισάγει ένα αρχείο .txt το οποίο θα χρησιμοποιηθεί ως Βάση Γνώσης
για τον εκάστοτε αλγόριθμο και τον προς απόδειξη τύπο.
Τα παραπάνω θα χρησιμοποιηθούν από τον αλγόριθμο ο οποίος θα αποφανθεί αν ισχύει ή όχι ο προς απόδειξη τύπος
με βάση τους κανόνες που υπάρχουν στη Βάση Γνώσης του.
*/
public class Logic_AI_Main {
static Scanner input = new Scanner(System.in);
static int userChoice = -1;
// Κύριο Μενού
public static void showMenuItems() {
System.out.println("// 1. CNF Resolution");
System.out.println("// 2. Horn Forward Chaining");
System.out.println("// 3. Horn PKL");
System.out.println("// 0. Exit");
System.out.println("******************************");
System.out.print("\nType the number of your choice: ");
}
// Εκτέλεση αλγορίθμου ανάλογα με την επιλογή του χρήστη
public static void openMenuItem(int choice) {
switch (choice) {
case 1:
performCnfResolution();
break;
case 2:
performHornForwardChaining();
break;
case 3:
performHornPKL();
break;
case 0:
System.exit(0);
break;
default:
System.out.println("\n!!!!Please choose one of the available options!!!!!\n");
break;
}
}
public static void performCnfResolution() {
//local variables
String filepath;
String userExpression;
CNFClause KB = null;
Literal a = null;
System.out.print("\nType the path of KB (Knowledge Base) file for Resolution Algorithm: ");
filepath = input.next();
KB = ReadFile.CNFReadFile(filepath);
// Σε περίπτωση που κάτι πήγε στραβά με το άνοιγμα του αρχείου επέστρεψε στο αρχικό μενού
if (KB == null) {
return;
}
System.out.println("Type the expression you want to prove");
System.out.println("(use ^ for logical AND, | for logical OR and ~ for logical NOT)");
System.out.print("Your expression: ");
userExpression = input.next();
CNFSubClause cnfsub = new CNFSubClause();
// Χωρισμός της εισόδου του χρήστη στο χαρακτήρα '|' που αναπαριστά το Λογικό OR
String[] userExpOr = userExpression.split("\\|");
for (String orLit : userExpOr) {
if (orLit.startsWith("~")) {
a = new Literal(orLit.substring(1), true);
} else {
a = new Literal(orLit, false);
}
cnfsub.getLiterals().add(a);
}
// Επιλογή του χρήστη αν θέλει να εμφανιστούν ή όχι οι λεπτομέρειες εκτέλεησς του αλγορίθμου
System.out.print("Print details during execution? (y/n): ");
String details = input.next();
System.out.println("***Performing CNF Resolution Algorithm...***\n");
CNFMain cnf = new CNFMain(KB, cnfsub);
cnf.PL_Resolution(true ? details.startsWith("y") : false);
System.out.println();
}
private static void performHornForwardChaining() {
String filepath;
String userInferred;
HornClause KB = null;
Literal a = null;
System.out.print("\nType the path of Horn KB file: ");
filepath = input.next();
KB = ReadFile.HornForwardChaining(filepath);
// Σε περίπτωση που κάτι πήγε στραβά με το άνοιγμα του αρχείου επέστρεψε στο αρχικό μενού
if (KB == null) {
return;
}
System.out.print("Type the expression you want to prove: ");
userInferred = input.next();
if (userInferred.startsWith("~")) {
a = new Literal(userInferred.substring(1), true);
} else {
a = new Literal(userInferred, false);
}
// Επιλογή του χρήστη αν θέλει να εμφανιστούν ή όχι οι λεπτομέρειες εκτέλεησς του αλγορίθμου
System.out.print("Print details during execution? (y/n): ");
String details = input.next();
System.out.println("***Performing Horn Forward Chaining...***\n");
HornMain horn = new HornMain(KB, a);
horn.PL_FC_Entails(true ? details.startsWith("y") : false);
System.out.println();
}
public static void performHornPKL() {
String filepath;
String userType;
Relation a;
ArrayList<String> paramsArr = new ArrayList<String>();
System.out.print("\nType the path of Horn KB file: ");
filepath = input.next();
// Εισαγωγή Βάσης Γνώσης από αρχείο .txt
HornPKLClause hornClauses = ReadFile.HornPKL(filepath);
// Σε περίπτωση που κάτι πήγε στραβά με το άνοιγμα του αρχείου επέστρεψε στο αρχικό μενού
if (hornClauses == null) {
return;
}
System.out.println("Type the expression you want to prove");
System.out.println("You can type an expression like \"Criminal(West)\" to see if West is Criminal");
System.out.println("Use ~ for logical NOT");
System.out.print("Your type: ");
userType = input.next();
// Ορισμός της προς απόδειξη σχέσης ως αντκείμενο της κλάσης Relation
String[] paramsList = null;
String relName = null;
while (true) {
try {
int leftParIndex = userType.lastIndexOf("(");
relName = userType.substring(0, leftParIndex);
String params = userType.substring(leftParIndex+1, userType.length() - 1);
paramsList = params.split(",");
} catch (StringIndexOutOfBoundsException ex) {
System.err.println("Check your expression, only expression which follow the format Human(John) are allowed!");
System.out.print("Your expression: ");
userType = input.next();
continue;
}
break;
}
for (String param : paramsList) {
paramsArr.add(param);
}
if (relName.startsWith("~")) {
a = new Relation(relName.substring(1), paramsArr, true);
} else {
a = new Relation(relName, paramsArr, false);
}
hornClauses.setA(a);
// Επιλογή του χρήστη αν θέλει να εμφανιστούν ή όχι οι λεπτομέρειες εκτέλεησς του αλγορίθμου
System.out.print("Print details during execution? (y/n): ");
String details = input.next();
System.out.println("***Performing Horn fol-fc-ask Algorithm...***\n");
// Ο αλγόριθμος επιστρέφει ένα Map.Entry της μορφής {x -> West} σε περίπτωση που
// καταφέρει να κάνει την ενοποίηση με τον προς απόδειξη τύπο
HashMap<String, String> unifiedMap = hornClauses.fol_fc_ask(true ? details.startsWith("y") : false);
if (unifiedMap != null) {
System.out.println("Unify Done!");
for (String param : a.getParams()) {
System.out.print("x" + "->" + unifiedMap.get(param));
}
System.out.println();
} else {
System.out.println("Could not find unifier for your expression!");
}
System.out.println();
}
public static void main(String[] args) {
while (userChoice != 0) {
System.out.println("***********Main Menu**********");
showMenuItems();
while (true) {
try {
userChoice = input.nextInt();
} catch (InputMismatchException ex) {
System.err.print("Only numbers are allowed for your choice! Please type 1, 2 or 3 > ");
input.next();
continue;
}
openMenuItem(userChoice);
break;
}
}
}
}
| bouzasvas/Logic_AI | Logic_AI/src/Logic_AI/Logic_AI_Main.java |
1,533 | import java.util.concurrent.ThreadLocalRandom;
/**
* Η κλάση υλοποιεί ένα μεταδότη, ο οποίος δημιουργεί ένα τυχαίο μήνυμα μήκους k και εκτελείται ο αλγόριθμος εντοπισμού
* σφαλμάτων CRC.
*
* @author Δημήτριος Παντελεήμων Γιακάτος
* @version 1.0.0
*/
public class Transceiver {
private String key;
private String data;
private String dataForDivision;
private String dataWithCrc;
private int lenOfKey;
private long size;
/**
* Η μέθοδος είναι ο constructor.
*/
public Transceiver() {}
/**
* Η μέθοδος αποθηκεύει στη μεταβλητή key τον αριθμό P και αποθηκεύει στη μεταβλητή lenOf Key το μήλος του αριθμού P.
* @param key Μία συμβολοσειρά που περιλαμβάνει τον αριθμό P.
*/
public void setKey(String key) {
this.key = key;
lenOfKey = key.length();
}
/**
* Η μέθοδος αποθηκεύει στη μεταβλητή size το μήκος k για το μήνυμα που θέλουμε να δημιουργηθεί.
* @param size Ο αριθμός k δηλαδή το μήκος του μηνύματος.
*/
public void setSize(long size) {this.size = size;}
/**
* Η μέθοδος είναι ο εκκινητής της διαδικασίας μετάδοσης.
* @return Επιστρέφει μία συμβολοσειρά που περιλαμβάνει το μήνυμα T που θέλουμε να στείλουμε.
*/
public String start() {
generateData();
generateDataForDivision();
division();
return dataWithCrc;
}
/**
* Η μέθοδος δημιουργεί τυχαία ένα μήνυμα μήκους k.
*/
private void generateData() {
long randomData;
data = "";
for (long i=0; i<size; i++) {
randomData = ThreadLocalRandom.current().nextLong(0, 2);
data = data + Long.toBinaryString(randomData);
}
}
/**
* Η μέθοδος προσθέτει στο τέλος του μηνύματος Μ, n μηδενικά, όπου n είναι ο αριθμός των bits του P των n+1 bits,
* και προκύπτει ο αριθμός (2^n)M.
*/
private void generateDataForDivision() {
dataForDivision = data;
for (long i=0; i<lenOfKey-1; i++) {
dataForDivision = dataForDivision + "0";
}
}
/**
* Η μέθοδος υλοποιεί τη διαίρεση του αριθμού 2^n M με τον αριθμό P και από το υπόλοιπο της διαίρεσης προκύπτει ο
* αριθμός F. Μετά, ο αριθμός F προστίθεται στο τέλος του μηνύματος (2^n)M και προκύπτει ο αριθμός T.
*/
private void division() {
String value;
String result;
while (dataForDivision.length()>=lenOfKey) {
value = dataForDivision.substring(0, lenOfKey);
result = Long.toBinaryString(Long.parseLong(value, 2) ^ Long.parseLong(key, 2));
dataForDivision = result + dataForDivision.substring(lenOfKey);
}
if (dataForDivision.length()<lenOfKey-1) {
for (int i=dataForDivision.length(); i<lenOfKey-1; i++) {
dataForDivision = "0" + dataForDivision;
}
}
dataWithCrc = data + dataForDivision;
}
} | dpgiakatos/CRC | src/Transceiver.java |
1,535 | package GUI;
import accommodations.Accommodations;
import accommodations.HotelRooms;
import accommodations.PrivateAccommodation;
import accommodations.reservervations.Date;
import photo_characteristicsDisplay.Display;
import users.Providers;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.event.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.*;
public class Provider extends JDialog
{
private JTextField characteristicsHotelAdd;
private JTabbedPane tabbedPane1;
private JRadioButton privateRadioButton;
private JRadioButton hotelRoomsRadioButton;
private JTextField roomNumberText;
private JTextField roomFloorText;
private JTextField roomSquareText;
private JTextField roomPriceText;
private JTextField roomAddressText;
private JTextField privateAddressText;
private JTextField typeText;
private JTextField privateSquareText;
private JTextField privatePriceText;
private JButton AddRoom;
private JButton AddPrivateAccommodation;
private JPanel PrivateRadioButtonPanel;
private JPanel roomRadioButtonPanel;
private JPanel hotelRoomsPanel;
private JPanel Panel;
private JPanel panel1;
private JPanel ShowAccommodations;
private JTabbedPane tabbedPane2;
private JScrollPane HotelRoomsPane;
private JTable privateAccommodation;
private JTable HotelRooms;
private JButton LogOut;
private JPanel welcome;
private JPanel DeleteAccommodation;
private JButton MyAccommodations;
private JTextField deleteAccommodation;
private JButton deleteAccommodationButton;
private JButton MyAccommodation;
private JTextField AddID;
private JLabel HelloMsg;
private JButton myAccommodationsButton;
private JButton addNewAccommodationButton;
private JButton editAnAccommodationButton;
private JButton deleteAnAccommodationButton;
private JButton INBOXButton;
private JButton reservationsButton;
private JLabel numberOfAccomm;
private ButtonGroup G1;
private JSeparator Seperator;
private JLabel brandNameMSG;
private JPanel Reservations;
private JTabbedPane tabbedPane3;
private JScrollPane Active;
private JPanel hotelEdit;
private JPanel hotelRoomsc1;
private JPanel Privatec2;
private JButton editButton;
private JPanel emptyPanel;
private JScrollPane hoteledidscroll;
private JTextField roomSNumberTextField;
private JTextField roomSFloorTextField;
private JTextField squareMetresTextField;
private JTextField priceNight€TextField;
private JTextField capacityOfPeopleTextField;
private JPanel RoomsPanelEditTab;
private JPanel PrivatePanelEditTab;
private JButton saveChangesButton1;
private JButton saveChangesButton;
private JTextField typeTextField;
private JTextField editRoomCharacteristics;
private JTextField squareMetresTextField1;
private JTextField priceTextField;
private JTextField specialCharacteristicsTextField;
private JTextField capacityOfPeopleTextField1;
private JTable ActiveReservations;
private JTextField capacityHotels;
private JTextField privateCapacity;
private JTextField privateCharacteristics;
private JLabel editHotelName;
private JLabel editHotelAddress;
private JLabel editCompanys;
private JLabel editPrivateAddress;
private JPanel privateAddPanel;
private JScrollPane PrivateAccommodationPane;
private JButton browseButton;
private JButton browseButton1;
private JTextField textField2;
private String imagesPath = "";
public Provider(Providers prov, Login login)
{
setTitle("[Provider] " + prov.getUsername());
/*
ActionListener για το κουμπί editButton. Αναζητά στις λίστες με τα αποθηκευμένα καταλύματα το
ID που δόθηκε στο {@link #AddID}και ανοίγει το αντίστοιχο panel ανάλογα με το είδος του καταλύματος
αν και εφόσον βρέθηκε. Αν δε βρεθεί ή αν έχει δοθεί λάθος το ID εμφανίζεται αντίστοιχο μήνυμα
*/
editButton.addActionListener(e ->
{
int ID;
boolean found = false;
Scanner dump = new Scanner(AddID.getText());
if (dump.hasNextInt())
{
ID = dump.nextInt();
if (prov.getAccommodations().FindRoom(ID) != -1)
{
for (HotelRooms index : prov.getAccommodations().getRooms())
{
if (ID == index.getId() && index.getHotelName().equals(prov.getProvidersBrandName()))
{
RoomsPanelEditTab.setEnabled(true);
RoomsPanelEditTab.setVisible(true);
editHotelName.setText("Hotel name: " + index.getHotelName());
editHotelAddress.setText("Adress: " + index.getAddress());
found = true;
}
}
}
if (prov.getAccommodations().FindAccommodation(Integer.parseInt(AddID.getText())) != -1)
{
for (PrivateAccommodation index : prov.getAccommodations().getAirbnb())
{
if (ID == index.getId() && index.getCompanyName().equals(prov.getProvidersBrandName()))
{
PrivatePanelEditTab.setEnabled(true);
PrivatePanelEditTab.setVisible(true);
editCompanys.setText("Company's name: " + index.getCompanyName());
editPrivateAddress.setText("Adress: " + index.getAddress());
found = true;
}
}
}
if (!found)
JOptionPane.showMessageDialog(null, "You don't own an accommodation with ID: " + Integer.parseInt(AddID.getText()));
} else
JOptionPane.showMessageDialog(null, "Make sure you have given the ID correctly! ");
AddID.setText("");
});
/*
Απενεργοποίηση των JPanels στο EditAccommodation Tab
γιατί θέλουμε να εμφανίζονται μόνο όταν βρεθεί το κατάλυμα
*/
RoomsPanelEditTab.setEnabled(false);
RoomsPanelEditTab.setVisible(false);
PrivatePanelEditTab.setEnabled(false);
PrivatePanelEditTab.setVisible(false);
//Πρόσθεση των προσωπικών στοιχείων του Provider στο welcome Tab
brandNameMSG.setText("Your brand name is: " + prov.getProvidersBrandName());
HelloMsg.setText("Hello " + prov.getUsername());
numberOfAccomm.setText("You already own: " + prov.numberOfAccommodations(prov.getProvidersBrandName()) +
" accommodations!");
//Δημιουργία των JTables με τα HotelRooms,PrivateAccommodation,Reservations
createHotelRoomsTable();
createPrivateAccommodationTable();
createMyReservationsTable();
//Δημιουργία ButtonGroup των 2 radioButtons στο AddAccommodation tab ώστε να ανοίγει το αντίχτοιχο panel μόνο
G1 = new ButtonGroup();
G1.add(hotelRoomsRadioButton);
G1.add(privateRadioButton);
//Συναρτηση με το Action Listener του hotelRoomRadioButton
hotelRoomRadioButton();
//Συναρτηση με το Action Listener του PrivateRadioButton
PrivateRadioButton();
//Συνάρτηση με τον ActionListener του LogOut button
logOut(login);
myAccommodations();
DeleteAccommodationButton(prov);
addRoom(prov);
addPrivateAccommodation(prov);
roomTableMouseListener(prov);
privateAccommodationTableMouseListener(prov);
/*
-ActionListeners για τα κουμπιά που πατώντας τα θέλουμ να μεταφερθούμε
σε διαφορετικά Tab του tabbedPane1
*/
myAccommodationsButton.addActionListener(e -> tabbedPane1.setSelectedIndex(3));
addNewAccommodationButton.addActionListener(e -> tabbedPane1.setSelectedIndex(1));
editAnAccommodationButton.addActionListener(e -> tabbedPane1.setSelectedIndex(2));
deleteAnAccommodationButton.addActionListener(e -> tabbedPane1.setSelectedIndex(4));
INBOXButton.addActionListener(e -> JOptionPane.showMessageDialog(null, prov.getMessages()));
reservationsButton.addActionListener(e -> tabbedPane1.setSelectedIndex(5));
MyAccommodation.addActionListener(e -> tabbedPane1.setSelectedIndex(3));
/*
ActionListener για το κουμπί saveChangesButton που επιτρέπει την επεξεργασία καταλύματος τύπου HotelRooms
Αν έχουν δωθεί σωστά οι τιμές στα αντίστοιχα πεδία τότε γίνεται επιτυχής επεξεργασία του δωματίου και
εμφανίζεται το αντίστοιχο μήνυμα, διαφορετικά εμφανίζεται μήνυμα λάθους. Το μήνυμα αυτό εμφανίζεται κι όταν
ο πάροχος προσπαθήσει να ορίσει ως νέο αριθμό δωματίου έναν αριθμό ο οποίος αντιστοιχεί σε άλλο δωμάτιο στο
συγκεκριμένο ξενοδοχείο στην συγκεκριμένη διεύθυνση.Έπειτα απο την επιτυχημέμη ή αποτυχημένη επεξεργασία,
καθαρίζονται οι τιμές απο τα πεδία και κρύβεται το panel επεξεργασίας δωματίου.
Δημιουργείται ένα αντίγραφο του δωματίου το οποίο ο πάροχος θέλει να επεξεργαστεί και μέσω της EditRoom που βρίσκεται
στην κλάση Providers λαμβάνει νέες τιμές. Αν γίνει επιτυχημένη επεξεργασία στην EditRoom τότε διαγράφεται το δωμάτιο
με τις παλίες τιμές απο τη λίστα με τα δωμάτια (rooms) της κλάσης Accommodations και προσθέτεται το επεξεργασμένο δωμάτιο.
Το ίδιο συμβαίνει και στον πίνακα HotelRooms. Αφαιρείται το παλιό δωμάτιο και στη θέση του εισάγεται το επεξεργασμένο.
*/
saveChangesButton.addActionListener(e ->
{
accommodations.HotelRooms room = null;
int ID;
Scanner dump = new Scanner(AddID.getText());
if (dump.hasNextInt())
{
ID = dump.nextInt();
if (prov.getAccommodations().FindRoom(ID) != -1)
{
for (HotelRooms index : prov.getAccommodations().getRooms())
{
if (ID == index.getId() && index.getHotelName().equals(prov.getProvidersBrandName()))
{
room = index;
}
}
}
assert room != null;
HotelRooms newRoom = prov.EditRoom(roomSNumberTextField.getText(), roomSFloorTextField.getText(), squareMetresTextField.getText(),
priceNight€TextField.getText(), capacityOfPeopleTextField.getText(), editRoomCharacteristics.getText(), room);
if (newRoom == null)
{
JOptionPane.showMessageDialog(null, "There was an error trying to edit your room!");
RoomsPanelEditTab.setEnabled(false);
RoomsPanelEditTab.setVisible(false);
} else
{
prov.getAccommodations().getRooms().remove(room);
prov.getAccommodations().getRooms().add(newRoom);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hotelRooms.bin")))
{
out.writeObject(prov.getAccommodations().getRooms());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().identifierManager());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("imageIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().getImageIdentifier());
} catch (IOException err)
{
err.printStackTrace();
}
JOptionPane.showMessageDialog(null, "You have successfully edited your Hotel Room!");
int row = -1;
for (int i = 0; i < HotelRooms.getModel().getRowCount(); i++)
{
if (HotelRooms.getModel().getValueAt(i, 6).equals("" + AddID.getText()))
{
row = i;
break;
}
}
if (row != -1)
{
((DefaultTableModel) HotelRooms.getModel()).removeRow(row);
((DefaultTableModel) HotelRooms.getModel()).addRow(new Object[]{
"\uD83D\uDCBC " + newRoom.getHotelName(),
"\uD83D\uDCCD " + newRoom.getAddress(),
newRoom.getRoomNumber(),
newRoom.getFloor(),
newRoom.getSquareMetres() + "m²",
newRoom.getPrice() + "€",
"" + newRoom.getId(),
newRoom.getCapacity(),
"Click here!"
});
}
}
} else
JOptionPane.showMessageDialog(null,
"You don't own an accommodation with ID: " + AddID.getText());
roomSNumberTextField.setText("");
roomSFloorTextField.setText("");
squareMetresTextField.setText("");
priceNight€TextField.setText("");
capacityOfPeopleTextField.setText("");
editRoomCharacteristics.setText("");
RoomsPanelEditTab.setEnabled(false);
RoomsPanelEditTab.setVisible(false);
AddID.setText("");
});
/*
ActionListener για το κουμπί saveChangesButton1 που επιτρέπει την επεξεργασία καταλύματος τύπου PrivateAccommodations
Αν έχουν δωθεί σωστά οι τιμές στα αντίστοιχα πεδία τότε γίνεται επιτυχής επεξεργασία του καταλύματος και
εμφανίζεται το αντίστοιχο μήνυμα, διαφορετικά εμφανίζεται μήνυμα λάθους.
Έπειτα απο την επιτυχημέμη ή αποτυχημένη επεξεργασία,
καθαρίζονται οι τιμές απο τα πεδία και κρύβεται το panel επεξεργασίας ιδιωτικού καταλύματος.
Δημιουργείται ένα αντίγραφο του καταλύματος το οποίο ο πάροχος θέλει να επεξεργαστεί και μέσω της EditAccommodation
που βρίσκεται στην κλάση Providers λαμβάνει νέες τιμές. Αν γίνει επιτυχημένη επεξεργασία στην EditAccommodation
τότε διαγράφεται το κατάλυμα με τις παλίες τιμές απο τη λίστα με τα ιδιωτικά καταλύματα (airbnb)
της κλάσης Accommodations και προσθέτεται το επεξεργασμένο ιδιωτικό κατάλυμα.
Το ίδιο συμβαίνει και στον πίνακα privateAccommodation.
Αφαιρείται το παλιό κατάλυμα και στη θέση του εισάγεται το επεξεργασμένο
*/
saveChangesButton1.addActionListener(e ->
{
Scanner dump = new Scanner(AddID.getText());
int ID;
System.out.println(AddID.getText());
PrivateAccommodation accommodation = null;
System.out.println(dump.hasNextInt());
if (dump.hasNextInt())
{
ID = dump.nextInt();
if (prov.getAccommodations().FindAccommodation(ID) != -1)
{
for (PrivateAccommodation index : prov.getAccommodations().getAirbnb())
{
if (ID == index.getId() && index.getCompanyName().equals(prov.getProvidersBrandName()))
{
accommodation = index;
PrivatePanelEditTab.setEnabled(true);
PrivatePanelEditTab.setVisible(true);
}
}
}
assert accommodation != null;
PrivateAccommodation newAccommodation = prov.EditAccommodation(typeTextField.getText(),
squareMetresTextField1.getText(), priceTextField.getText(), capacityOfPeopleTextField1.getText(),
specialCharacteristicsTextField.getText(), accommodation);
if (newAccommodation == null)
JOptionPane.showMessageDialog(null, "There was an error trying to edit your Accommodation \n" +
"Move sensor to the fields to watch the proper insertion!");
else
{
int row = -1;
prov.getAccommodations().getAirbnb().remove(accommodation);
prov.getAccommodations().getAirbnb().add(newAccommodation);
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("privateAccommodation.bin")))
{
out.writeObject(prov.getAccommodations().getAirbnb());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().identifierManager());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("imageIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().getImageIdentifier());
} catch (IOException err)
{
err.printStackTrace();
}
for (int i = 0; i < privateAccommodation.getModel().getRowCount(); i++)
{
if (privateAccommodation.getModel().getValueAt(i, 7).equals(AddID.getText())) {
row = i;
break;
}
}
if (row != -1)
{
((DefaultTableModel) privateAccommodation.getModel()).removeRow(row);
((DefaultTableModel) privateAccommodation.getModel()).addRow(new Object[]{
"\uD83D\uDCBC " + newAccommodation.getCompanyName(),
"Type: " + newAccommodation.getType(),
"\uD83D\uDCCD " + newAccommodation.getAddress(),
newAccommodation.getSquareMetres() + "m²",
newAccommodation.getPrice() + "€",
newAccommodation.getCapacity(),
"Click here!",
"" + newAccommodation.getId()
});
}
JOptionPane.showMessageDialog(null, "You have successfully edited your private accommodation!");
}
} else
JOptionPane.showMessageDialog(null,
"You don't own an accommodation with ID: " + AddID.getText());
typeTextField.setText("");
squareMetresTextField1.setText("");
priceTextField.setText("");
editRoomCharacteristics.setText("");
PrivatePanelEditTab.setEnabled(false);
PrivatePanelEditTab.setVisible(false);
AddID.setText("");
});
/*
Κρύβονται τα panel παράθυρο επεξεργασίας καταλύματος ώστε να είναι ορατά μόνο
κατά το πάτημα του αντίστοιχου JRadioButton
*/
roomRadioButtonPanel.setVisible(false);
PrivateRadioButtonPanel.setVisible(false);
setContentPane(Panel);
setModal(true);
// call onCancel() when cross is clicked
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
// call onCancel() on ESCAPE
Panel.registerKeyboardAction(e -> System.exit(0), KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
tabbedPane1.setEnabled(true);
myAccommodationsButton.setEnabled(true);
addNewAccommodationButton.setEnabled(true);
editAnAccommodationButton.setEnabled(true);
deleteAnAccommodationButton.setEnabled(true);
reservationsButton.setEnabled(true);
INBOXButton.setEnabled(true);
//Αν ο πάροχος δεν έχει εγκριθεί από κάποιον διαχειριστή Τότε ακυρώνεται το login
if (!prov.accountStatus()) {
abortLogging();
}
//ACTION LISTENER GIA UPLOAD EIKONAS STA DWMATIA KSENODOXEIWN
browseButton.addActionListener(e -> {
if (e.getSource() == browseButton) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setCurrentDirectory(new File(".")); //sets current directory
fileChooser.addChoosableFileFilter(new ImageFilter());
fileChooser.setAcceptAllFileFilterUsed(false);
int response = fileChooser.showOpenDialog(null); //select file to open
//int response = fileChooser.showSaveDialog(null); //select file to save
if (response == JFileChooser.APPROVE_OPTION) {
imagesPath = fileChooser.getSelectedFile().getAbsolutePath();
} else
imagesPath = "";
}
});
//ACTION LISTENER GIA UPLOAD EIKONAS STA DWMATIA KSENODOXEIWN
browseButton1.addActionListener(e -> {
if (e.getSource() == browseButton1) {
JFileChooser fileChooser1 = new JFileChooser();
fileChooser1.setCurrentDirectory(new File(".")); //sets current directory
fileChooser1.addChoosableFileFilter(new ImageFilter());
fileChooser1.setAcceptAllFileFilterUsed(false);
int response = fileChooser1.showOpenDialog(null); //select file to open
//int response = fileChooser.showSaveDialog(null); //select file to save
if (response == JFileChooser.APPROVE_OPTION) {
imagesPath = fileChooser1.getSelectedFile().getAbsolutePath();
} else
imagesPath = "";
}
});
}
public void abortLogging()
{
JOptionPane.showMessageDialog(null,
"""
Your account is currently inactive.\s
Please contact the administrators at\s
[email protected] or [email protected]\s
if you have any more queries.\s
""");
tabbedPane1.setEnabled(false);
myAccommodationsButton.setEnabled(false);
addNewAccommodationButton.setEnabled(false);
editAnAccommodationButton.setEnabled(false);
deleteAnAccommodationButton.setEnabled(false);
reservationsButton.setEnabled(false);
INBOXButton.setEnabled(false);
}
/**
* Η μέθοδος αυτή δημιουργεί τον πίνακα με τα δωμάτια που έχει στην κατοχή του ο πάροχος
* στο tab {@link #ShowAccommodations}
*/
public void createHotelRoomsTable()
{
Object[][] data = {};
HotelRooms.setModel(new DefaultTableModel(
data,
new Object[]{"Hotel name", "Location", "Room's number", "Floor",
"Square metres", "Price", "ID", "Capacity", "Characteristics"}
));
}
/**
* Η μέθοδος αυτή προσθέτει τις ενεργές κρατήσεις για τα καταλύματα του παρόχου
* στον αντίστοιχο πίνακα του tab {@link #Reservations}
*/
public void addMyReservations(HashMap<PrivateAccommodation, ArrayList<Date>> allReservationsPrivate,
HashMap<HotelRooms, ArrayList<Date>> allReservationsRooms)
{
DefaultTableModel model = (DefaultTableModel) ActiveReservations.getModel();
if (allReservationsPrivate != null)
{
allReservationsPrivate.forEach((key, value) ->
{
for (Date date : value)
{
model.addRow(new Object[]{
"\uD83D\uDCBC " + key.getCompanyName() + "s",
key.getType(),
"\uD83D\uDCCD " + key.getAddress(),
"for " + key.getPrice() + "€",
"ID: " + key.getId(),
"\uD83D\uDCC6 " + date.toString()
});
}
});
}
if (allReservationsRooms != null)
{
allReservationsRooms.forEach((key, value) ->
{
for (Date date : value)
{
model.addRow(new Object[]{
"\uD83D\uDCBC " + key.getHotelName() + "'s",
"Room: " + key.getRoomNumber(),
"\uD83D\uDCCD " + key.getAddress(),
"for " + key.getPrice() + "€",
"ID: " + key.getId(),
"\uD83D\uDCC6 " + date.toString()
});
}
});
}
}
/**
* Η μέθοδος αυτή προσθέτει τα δωμάτια ξενοδοχείων που έχει
* στην κατοχή του ο πάροχος στον αντίστοιχο πίνακα του tab
* {@link #HotelRoomsPane}
*/
public void addHotelRoomsToTable(Providers provider)
{
DefaultTableModel model = (DefaultTableModel) HotelRooms.getModel();
if (provider.getAccommodations().getRooms() != null)
{
for (HotelRooms room : provider.getAccommodations().getRooms())
{
if (room.getHotelName().equals(provider.getProvidersBrandName()))
{
model.addRow(new Object[]{
"\uD83D\uDCBC " + room.getHotelName(),
"\uD83D\uDCCD " + room.getAddress(),
room.getRoomNumber(),
room.getFloor(),
room.getSquareMetres() + "m²",
room.getPrice() + "€",
"" + room.getId(),
room.getCapacity(),
"Click Here!"
});
}
}
}
}
/**
* Η μέθοδος αυτή δημιουργεί τον πίνακα με τις ενεργές κρατήσεις για τα καταλύματα
* του παρόχου στο tab {@link #Reservations}
*/
private void createMyReservationsTable()
{
Object[][] data = {};
ActiveReservations.setModel(new DefaultTableModel(
data,
new Object[]{"Company's name", "Type/Room Number", "Address",
"Price", "Accommodation's ID", "Reserved Dates"}
));
}
/**
* Η μέθοδος αυτή δημιουργεί τον πίνακα με τα ιδιωτικά καταλύματα
* που έχει στην κατοχή του ο πάροχος στο tab {@link #ShowAccommodations}
*/
public void createPrivateAccommodationTable()
{
Object[][] data = {};
privateAccommodation.setModel(new DefaultTableModel(
data,
new Object[]{"Company's name", "Type", "Location", "Square metres", "price", "Capacity", "Characteristics", "ID"}
));
}
/**
* Η μέθοδος αυτή προσθέτει τα ιδιωτικά καταλύματα που έχει στην κατοχή του ο πάροχος
* στον αντίστοιχο πίνακα στο tab {@link #PrivateAccommodationPane}.
*/
public void addPrivateAccommodationsToTable(Providers provider)
{
DefaultTableModel model = (DefaultTableModel) privateAccommodation.getModel();
if (provider.getAccommodations().getAirbnb() != null)
{
for (PrivateAccommodation accomm : provider.getAccommodations().getAirbnb())
{
if (provider.getProvidersBrandName().equals(accomm.getCompanyName()))
{
model.addRow(new Object[]{
"\uD83D\uDCBC " + accomm.getCompanyName(),
"Type: " + accomm.getType(),
"\uD83D\uDCCD " + accomm.getAddress(),
accomm.getSquareMetres() + "m²",
accomm.getPrice() + "€",
accomm.getCapacity(),
"Click here!",
"" + accomm.getId()
});
}
}
}
}
/**
* Στη μέθοδο αυτή υλοποιείται ο {@link ActionListener} για το κουμπί {@link #LogOut}
* όπου κατά το πάτημα του αποσυνδέεται ο πάροχος από την εφαρμογή
*/
public void logOut(Login login)
{
LogOut.addActionListener(e ->
{
dispose();
login.dispose();
});
}
/**
* Στη μέθοδο αυτή υλοποιείται ο {@link ActionListener} του {@link #hotelRoomsRadioButton}.
* Κατα το πάτημα του εμφανίζεται το πάνελ {@link #roomRadioButtonPanel}
* των δωματίων και κρύβεται το panel των ιδιωτικών καταλυμάτων {@link #PrivateRadioButtonPanel}
*/
public void hotelRoomRadioButton()
{
hotelRoomsRadioButton.addActionListener(e ->
{
hotelRoomsPanel.setVisible(true);
roomRadioButtonPanel.setVisible(true);
roomRadioButtonPanel.setVisible(true);
PrivateRadioButtonPanel.setEnabled(false);
PrivateRadioButtonPanel.setVisible(false);
});
}
/**
* Στη μέθοδο αυτή υλοποιείται ο {@link ActionListener} του {@link #privateRadioButton}.
* Κατα το πάτημα του εμφανίζεται το panel των ιδιωτικών καταλυμάτων {@link #PrivateRadioButtonPanel} και
* κρύβεται το panel των δωματίων {@link #hotelRoomsRadioButton}.
*/
public void PrivateRadioButton()
{
privateRadioButton.addActionListener(e ->
{
PrivateRadioButtonPanel.setVisible(true);
hotelRoomsPanel.setVisible(false);
roomRadioButtonPanel.setEnabled(false);
roomRadioButtonPanel.setVisible(false);
});
}
/**
* {@link ActionListener} για το κουμπί {@link #MyAccommodations}.
* Κατά το πάτημα του ανοίγει το tab {@link #ShowAccommodations}
*/
public void myAccommodations()
{
MyAccommodations.addActionListener(e -> tabbedPane1.setSelectedIndex(3));
}
/**
* Η μέθοδος αυτή υλοποιεί τον {@link ActionListener} του {@link #deleteAccommodationButton}
* με βάση το ID που δόθηκε στο πεδίο {@link #deleteAccommodation}. Καλείται η συνάρτηση
* {@link Providers#DeleteAccommodation(String)} όπου αν το κατάλυμα με το ID που δόθηκε ανήκει στον συγκεκριμένο
* πάροχο, διαγράφεται από την αντίστοιχη λίστα {@link Accommodations#getAirbnb()}.
* Αν έχει διαγραφεί επιτυχώς τότε ψάχνουμε στον αντίστοιχο
* πίνακα την γραμμή όπου εμφανίζεται το κατάλυμα με το δοθέν ID και την αφαιρούμε.
*/
public void DeleteAccommodationButton(Providers prov)
{
deleteAccommodationButton.addActionListener(e ->
{
//Αν το textField είναι κενό τότε τερματίζεται η διαδικασία
if (deleteAccommodation.getText().equals(""))
{
JOptionPane.showMessageDialog(null, "Make sure you've given the ID");
return;
}
Scanner dump = new Scanner(deleteAccommodation.getText());
//Αν το textField δεν είναι κενό και είναι συμπληρωμένο με ακέραιους τότε
//κάνει κανονικά την διαδικασία διαγραφής του καταλύματος
if (dump.hasNextInt())
{
int ID = dump.nextInt();
if (prov.DeleteAccommodation(deleteAccommodation.getText()))
{
JOptionPane.showMessageDialog(null, "Your accommodation was deleted successfully!");
numberOfAccomm.setText("You already own: "
+ prov.numberOfAccommodations(prov.getProvidersBrandName())
+ " accommodations!");
int row = -1;
DefaultTableModel model = (DefaultTableModel) HotelRooms.getModel();
for (int i = 0; i < model.getRowCount(); i++)
{
if (model.getValueAt(i, 6).equals("" + deleteAccommodation.getText()))
{
row = i;
break;
}
}
if (row != -1)
model.removeRow(row);//remove row
row = -1;
DefaultTableModel model1 = (DefaultTableModel) privateAccommodation.getModel();
for (int i = 0; i < model1.getRowCount(); i++)
{
if (model1.getValueAt(i, 5).equals("" + deleteAccommodation.getText())) {
row = i;
break;
}
}
if (row != -1)
model1.removeRow(row);//remove row
} else
JOptionPane.showMessageDialog(null, "You don't own an accommodation with ID:" + ID);
} else //Αν έχει συμβολοσειρές στην είσοδο του το textfield.
JOptionPane.showMessageDialog(null, "Make sure you have given the ID correctly!");
deleteAccommodation.setText("");
});
}
/**
* Η μέθοδος αυτή υλοποιεί τον {@link ActionListener} για το κουμπί
* {@link #AddRoom} . Καλείται η συνάρτηση {@link Providers#AddHotelRoom(String, String, String, String, String, String, List, String)}
* και η τιμή που επιστρέφει εισάγεται στη μεταβλητή room τύπου {@link HotelRooms}.
* Αν η τιμή αυτή είναι διάφορη του null
* δηλαδή είναι εφικτή η πρόσθεση δωματίου, τότε το δωμάτιο προστίθεται λίστα {@link Accommodations#getRooms()}
* και στον πίνακα {@link #HotelRooms}
*/
public void addRoom(Providers prov)
{
AddRoom.addActionListener(e ->
{
List<String> characteristics;
String[] temp = characteristicsHotelAdd.getText().split("/");
characteristics = Arrays.asList(temp);
HotelRooms room = prov.AddHotelRoom(roomNumberText.getText(), roomFloorText.getText(), roomSquareText.getText(),
roomPriceText.getText(), roomAddressText.getText(), capacityHotels.getText(), characteristics, imagesPath);
if (room != null)
{
prov.getAccommodations().getRooms().add(room);
//Εγγραφές στα αρχεία: δωμάτιο/αναγνωριστικός αριθμός δωματίου/αναγνωριστικός αριθμός ονόματος φωτογραφίας
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hotelRooms.bin")))
{
out.writeObject(prov.getAccommodations().getRooms());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().identifierManager());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("imageIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().getImageIdentifier());
} catch (IOException err)
{
err.printStackTrace();
}
DefaultTableModel model = (DefaultTableModel) HotelRooms.getModel();
model.addRow(new Object[]{
"\uD83D\uDCBC " + room.getHotelName(),
"\uD83D\uDCCD " + room.getAddress(),
room.getRoomNumber(),
room.getFloor(),
room.getSquareMetres() + "m²",
room.getPrice() + "€",
room.getId(),
room.getCapacity(),
"Click here!"
});
JOptionPane.showMessageDialog(null, "Your room has been added!");
numberOfAccomm.setText("You already have :"
+ prov.numberOfAccommodations(prov.getProvidersBrandName())
+ " accommodations! ");
} else
JOptionPane.showMessageDialog(null, "There was a problem trying to add your room!");
//TODO: πρέπει να μπούνε έλεγχοι σχετικά με την εγκυρότητα του τύπου του textField.
roomFloorText.setText("");
roomNumberText.setText("");
capacityHotels.setText("");
roomAddressText.setText("");
roomPriceText.setText("");
roomSquareText.setText("");
characteristicsHotelAdd.setText("");
roomRadioButtonPanel.setEnabled(false);
roomRadioButtonPanel.setVisible(false);
});
}
/**
* Η μέθοδος αυτή υλοποιεί τον {@link ActionListener} για το κουμπί {@link #AddPrivateAccommodation}.
* Καλείται η συνάρτηση {@link Providers#AddPrivateAccommodation(String, String, String, String, String, List, String)}
* και η τιμή που επιστρέφει εισάγεται στη μεταβλητή accommodation τύπου {@link PrivateAccommodation}.
* Αν η τιμή αυτή είναι διάφορη του null
* δηλαδή είναι εφικτή η πρόσθεση ιδιωτικού καταλύματος
* , τότε το κατάλυμα προστίθεται λίστα {@link Accommodations#getAirbnb()}
* και στον πίνακα {@link #privateAccommodation}
*/
public void addPrivateAccommodation(Providers prov)
{
AddPrivateAccommodation.addActionListener(e ->
{
List<String> characteristics;
String[] temp = privateCharacteristics.getText().split("/");
characteristics = Arrays.asList(temp);
PrivateAccommodation accommodation = prov.AddPrivateAccommodation(privateAddressText.getText(),
typeText.getText(), privateSquareText.getText(),
privatePriceText.getText(), privateCapacity.getText(), characteristics, imagesPath);
if (accommodation != null)
{
prov.getAccommodations().getAirbnb().add(accommodation);
//Εγγραφές στα αρχεία: ιδιωτικό κατάλυμα/αναγνωριστικός αριθμός καταλύματος
//αναγνωριστικός αριθμός ονόματος φωτογραφίας
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("privateAccommodation.bin")))
{
out.writeObject(prov.getAccommodations().getAirbnb());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().identifierManager());
} catch (IOException err)
{
err.printStackTrace();
}
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("imageIdentifier.bin")))
{
out.writeObject(prov.getAccommodations().getImageIdentifier());
} catch (IOException err)
{
err.printStackTrace();
}
DefaultTableModel model = (DefaultTableModel) privateAccommodation.getModel();
model.addRow(new Object[]{
"\uD83D\uDCBC " + accommodation.getCompanyName(),
"Type: " + accommodation.getType(),
"\uD83D\uDCCD " + accommodation.getAddress(),
accommodation.getSquareMetres() + "m²",
accommodation.getPrice() + "€",
accommodation.getCapacity(),
"Click here!",
accommodation.getId()
});
JOptionPane.showMessageDialog(null, "Your accommodation has been added!");
numberOfAccomm.setText("You already have :"
+ prov.numberOfAccommodations(prov.getProvidersBrandName())
+ " accommodations! ");
} else
JOptionPane.showMessageDialog(null, "There was a problem trying to add your accommodation!");
privateAddressText.setText("");
typeText.setText("");
privateSquareText.setText("");
privatePriceText.setText("");
privateCapacity.setText("");
privateCharacteristics.setText("");
PrivateRadioButtonPanel.setVisible(false);
PrivateRadioButtonPanel.setEnabled(false);
});
}
/**
* Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τον πίνακα
* {@link #privateAccommodation}.Στο κλικ του ποντικού στην στήλη που αποθηκεύει
* τα ειδικά χαρακτηριστικά του ιδιωτικού καταλύματος, εμφανίζει με την βοήθεια της
* κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά
* του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία
* του καταλύματος με όνομα {@link Accommodations#getImageName()}
*
* @param provider Ο πάροχος του οποίου το κατάλυμα θα χρησιμοποιηθεί για την εμφάνιση των χαρακτηριστικών του
*/
public void privateAccommodationTableMouseListener(Providers provider)
{
privateAccommodation.addMouseListener(new java.awt.event.MouseAdapter()
{
@Override
public void mouseClicked(java.awt.event.MouseEvent evt)
{
int row = privateAccommodation.rowAtPoint(evt.getPoint());
int col = privateAccommodation.columnAtPoint(evt.getPoint());
if (row >= 0 && col == 6)
{
Display temp = new Display(provider.getAccommodations().getProvidersPrivateAccommodations(provider).get(privateAccommodation.getSelectedRow()).getCharacteristics(),
provider.getAccommodations().getProvidersPrivateAccommodations(provider).get(privateAccommodation.getSelectedRow()).getImageName()
);
temp.pack();
temp.setVisible(true);
}
}
});
}
/**
* Η μέθοδος αυτή υλοποιεί {@link MouseListener} για τον πίνακα
* {@link #HotelRooms}.Στο κλικ του ποντικού στην στήλη που αποθηκεύει
* τα ειδικά χαρακτηριστικά του δωματίου, εμφανίζει με την βοήθεια της
* κλάσης {@link Display}την Λίστα με τα χαρακτηριστικά
* του καταλύματος {@link Accommodations#getCharacteristics()} και την φωτογραφία
* του καταλύματος με όνομα {@link Accommodations#getImageName()}
*
* @param provider Ο πάροχος του οποίου το κατάλυμα θα χρησιμοποιηθεί για την εμφάνιση των χαρακτηριστικών του
*/
public void roomTableMouseListener(Providers provider)
{
HotelRooms.addMouseListener(new java.awt.event.MouseAdapter()
{
@Override
public void mouseClicked(java.awt.event.MouseEvent evt)
{
int row = HotelRooms.rowAtPoint(evt.getPoint());
int col = HotelRooms.columnAtPoint(evt.getPoint());
if (row >= 0 && col == 8)
{
Display temp = new Display(provider.getAccommodations().getProvidersRooms(provider).get(HotelRooms.getSelectedRow()).getCharacteristics(),
provider.getAccommodations().getProvidersRooms(provider).get(HotelRooms.getSelectedRow()).getImageName()
);
temp.pack();
temp.setVisible(true);
}
}
});
}
}
| NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/GUI/Provider.java |
1,539 | package gui;
import api.GeneralUser;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
/**
* Κλάση για τη γραφική διεπαφή δημιουργίας νέου λογαριασμού.
*/
public class CreateAccountGUI extends JFrame {
private JTextField textFieldName;
private JTextField textFieldSiname;
private JPasswordField passwordField;
private JTextField textFieldUsername;
private JRadioButton πάροχοςRadioButton;
private JRadioButton απλόςΧρήστηςRadioButton;
private JButton createAccountButton;
private JButton goBackToLogButton;
private JPanel createAccount;
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο με τη φόρμα για την εγγραφή ενός χρήστη και αν τα στοιχεία γίνονται
* δεκτά προσθέτει τον χρήστη στο αρχείο με τη λίστα χρηστών.
*/
public CreateAccountGUI(){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(450,300);
setTitle("Create Account");
setContentPane(createAccount);
setLocationRelativeTo(null);
setVisible(true);
goBackToLogButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoginGUI l = new LoginGUI();
l.show();
dispose();
}
});
createAccountButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(textFieldName.getText().length()==0||textFieldSiname.getText().length()==0||textFieldUsername.getText().length()==0
||(new String(passwordField.getPassword())).length()==0
||(!πάροχοςRadioButton.isSelected() && !απλόςΧρήστηςRadioButton.isSelected())){
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Παρακαλώ συμπληρώστε όλα τα πεδία");
}
else{
if(πάροχοςRadioButton.isSelected()) {
if (GeneralUser.createAccount(textFieldName.getText(), textFieldSiname.getText(), textFieldUsername.getText(), new String(passwordField.getPassword()), "Provider")) {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Created account, go back to log in now.");
} else {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "User already exists with that username");
}
}
else{
if(GeneralUser.createAccount(textFieldName.getText(),textFieldSiname.getText(),textFieldUsername.getText(), new String(passwordField.getPassword()),"RegularUser")){
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"Created account, go back to log in now.");
}
else{
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),"User already exists with that username");
}
}
}
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/CreateAccountGUI.java |
1,540 | package gui;
import api.Accommodation;
import api.Provider;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Κλάση για τη γραφική διεπαφή των λειτουργιών ενός παρόχου.
*/
public class ProviderGUI extends JFrame{
private JButton addAccommodation;
private JPanel providerFrame;
private JLabel avgReviewsValue;
private JLabel totalReviews;
private JLabel noListings;
private JPanel listings;
private JButton button1;
private JLabel totNumOfRev;
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο το οποίο πληρεί και τις βασικές λειτουργίες αλλά και το dashboard
* του παρόχου
* @param p ο πάροχος για τον οποίο θα ανοίξει το αντίστοιχο παράθυρο
*/
public ProviderGUI(Provider p) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(950,700);
setTitle("Provider");
setLocationRelativeTo(null);
button1.setText("Log out from user: "+p.getUsername());
avgReviewsValue.setText(String.valueOf(p.averageRating()));
totalReviews.setText(String.valueOf(p.numberOfTotalReviews()));
if(p.getListOfAccommodations().size()!=0){
noListings.setVisible(false);
}
listings.setLayout(new GridLayout(0,1));
int index=0;
for(Accommodation a : p.getListOfAccommodations()){
index+=1;
GridLayout layout = new GridLayout(0,3);
layout.setHgap(15);
layout.setVgap(20);
JPanel listing_i=new JPanel(layout);
listing_i.setBorder(new EmptyBorder(5, 2, 10, 5)); //padding
if(index%2==0){
listing_i.setBackground(Color.lightGray);
}
else{
listing_i.setBackground(Color.white);
}
JLabel accomNamei=new JLabel();
JLabel accomAvgRatingi=new JLabel();
JLabel accomAdressi=new JLabel();
JLabel accomIconi = new JLabel(new ImageIcon("src/gui/icons/"+a.getType()+".png"));
JButton accomViewi=new JButton("Προβολή Καταλύματος");
JButton accomDeletei=new JButton("Διαγραφή Καταλύματος");
JButton accomEditi=new JButton("Επεξεργασία Καταλύματος");
JLabel accomType = new JLabel();
accomNamei.setText(a.getName());
accomAvgRatingi.setText("Μέση αξιολόγηση: "+String.valueOf(a.getAverageRating()));
String labelText = String.format("<html><div WIDTH=%d>%s</div></html>", 50, a.getAddress()+" " + a.getCity() + " " + a.getPostalCode());
accomAdressi.setText(labelText);
accomType.setText("Τύπος καταλύματος: "+a.getType());
listing_i.add(accomIconi);
listing_i.add(accomNamei);
listing_i.add(new JLabel());
listing_i.add(accomAvgRatingi);
listing_i.add(accomType);
listing_i.add(accomAdressi);
listing_i.add(accomViewi);
listing_i.add(accomDeletei);
listing_i.add(accomEditi);
listing_i.setSize(950,200);
listing_i.setVisible(true);
accomViewi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAccommodationGUI f = new showAccommodationGUI(a,p);
f.show();
dispose();
}
} );
accomDeletei.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
a.delete();
ProviderGUI f = new ProviderGUI(p);
f.show();
dispose();
}
} );
accomEditi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addAccommodationGUI f = new addAccommodationGUI(a,p);
f.show();
dispose();
}
} );
listings.add(listing_i);
}
setContentPane(providerFrame);
setVisible(true);
addAccommodation.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addAccommodationGUI f = new addAccommodationGUI(p);
f.show();
dispose();
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoginGUI f = new LoginGUI();
f.show();
dispose();
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/ProviderGUI.java |
1,541 | package gui;
import api.Accommodation;
import api.RegularUser;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* Κλάση για τη γραφική διεπαφή των λειτουργιών απλού χρήστη
*/
public class RegularUserGUI extends JFrame {
private JPanel regUserShow;
private JTextField textField1;
private JRadioButton όνομαRadioButton;
private JRadioButton τύποςRadioButton;
private JRadioButton τοποθεσίαRadioButton;
private JRadioButton παροχέςRadioButton;
private JButton αναζήτησηButton;
private JButton dasboardButton;
private JScrollPane showResults;
private JPanel listings;
private JLabel noResults;
private JButton button1;
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο με τις λειτουργίες απλού χρήστη
* @param g ο απλός χρήστης για τον οποίο εμφανίζεται το παράθυρο
*/
public RegularUserGUI(RegularUser g) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(regUserShow);
setResizable(false);
setSize(950,700);
setTitle("Regular User");
setLocationRelativeTo(null);
button1.setText("Log out from user: "+g.getUsername());
noResults.setVisible(true);
dasboardButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RegularUserDashboard f = new RegularUserDashboard(g);
f.show();
dispose();
}
});
αναζήτησηButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ArrayList<Integer> criteria = new ArrayList<>();
if (παροχέςRadioButton.isSelected()) {
criteria.add(4);
}
if (όνομαRadioButton.isSelected()) {
criteria.add(1);
}
if (τύποςRadioButton.isSelected()) {
criteria.add(2);
}
if (τοποθεσίαRadioButton.isSelected()) {
criteria.add(3);
}
if (criteria.size() == 0) {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "Επιλέξτε κριτήρια αναζήτησης");
}
else {
ArrayList<Accommodation> results = g.searchAccommodations(criteria, textField1.getText());
listings.removeAll();
if (results.size() == 0) noResults.setVisible(true);
else {
noResults.setVisible(false);
listings.setLayout(new GridLayout(0, 1));
int index = 0;
for (Accommodation a : results) {
index += 1;
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(15);
layout.setVgap(20);
JPanel listing_i = new JPanel(layout);
listing_i.setBorder(new EmptyBorder(5, 2, 10, 5)); //padding
if (index % 2 == 0) {
listing_i.setBackground(Color.lightGray);
} else {
listing_i.setBackground(Color.white);
}
JLabel accomNamei = new JLabel();
JLabel accomAvgRatingi = new JLabel();
JLabel accomAdressi = new JLabel();
JLabel accomIconi = new JLabel(new ImageIcon("src/gui/icons/" + a.getType() + ".png"));
JButton accomViewi = new JButton("Προβολή Καταλύματος");
JLabel accomType = new JLabel();
accomNamei.setText(a.getName());
accomAvgRatingi.setText("Μέση αξιολόγηση: " + String.valueOf(a.getAverageRating()));
String labelText = String.format("<html><div WIDTH=%d>%s</div></html>", 50, a.getAddress()+" " + a.getCity() + " " + a.getPostalCode());
accomAdressi.setText(labelText);
accomType.setText("Τύπος καταλύματος: " + a.getType());
listing_i.add(accomIconi);
listing_i.add(accomNamei);
listing_i.add(new JLabel());
listing_i.add(accomAvgRatingi);
listing_i.add(accomType);
listing_i.add(accomAdressi);
listing_i.add(accomViewi);
listing_i.setSize(950, 200);
listing_i.setVisible(true);
listings.add(listing_i);
accomViewi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAccommodationGUI f = new showAccommodationGUI(a, g);
f.show();
dispose();
}
});
}
}
}
}
});
button1.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
LoginGUI f = new LoginGUI();
f.show();
dispose();
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/RegularUserGUI.java |
1,542 | package gui;
import api.Accommodation;
import api.RegularUser;
import api.Review;
import jdk.jfr.consumer.RecordedThreadGroup;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Κλάση για την γραφική διεπαφή Dashboard του απλού χρήστη
*/
public class RegularUserDashboard extends JFrame {
private JLabel avgStarsGiven;
private JScrollPane showReviews;
private JPanel listings;
private JButton πίσωΣτηνΑρχικήΣελίδαButton;
private JPanel showRegUser;
/**
* κατασκευαστής ο οποίος εμφανίζει το dashboard του απλού χρήστη r
* @param r ο απλός χρήστης για τον οποίο εμφανίζεται το παράθυρο
*/
public RegularUserDashboard(RegularUser r) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setContentPane(showRegUser);
setResizable(false);
setSize(950,700);
setTitle("Dashboard");
setLocationRelativeTo(null);
avgStarsGiven.setText("Μέσος όρος βαθμολογίας αξιολογήσεων: "+String.valueOf(r.getAverageRating()));
listings.setLayout(new GridLayout(0,1));
int index=0;
for(Review rev: r.getListOfReviews()) {
index += 1;
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(15);
layout.setVgap(20);
JPanel listing_i = new JPanel(layout);
listing_i.setBorder(new EmptyBorder(5, 2, 10, 5)); //padding
if (index % 2 == 0) {
listing_i.setBackground(Color.lightGray);
} else {
listing_i.setBackground(Color.white);
}
JLabel AccomNamei=new JLabel(rev.getAccommodationReviewed().getName());
JLabel accomAdressi= new JLabel("Τοποθεσία: "+rev.getAccommodationReviewed().getAddress()+" " +
rev.getAccommodationReviewed().getCity() + " " + rev.getAccommodationReviewed().getPostalCode());
JLabel accomTypei = new JLabel("Τύπος καταλύματος: "+rev.getAccommodationReviewed().getType());
JLabel accomIconi = new JLabel(new ImageIcon("src/gui/icons/"+rev.getAccommodationReviewed().getType()+".png"));
JLabel accomReviewStars = new JLabel("Βαθμός αξιολόγησης: "+String.valueOf(rev.getReviewStars()));
JButton showReviewi = new JButton("Προβολή καταχώρησης");
JButton editReviewi = new JButton("Επεξεργασία αξιολόγησης");
JButton deleteReviewi = new JButton("Διαγραφή αξιολόγησης");
listing_i.add(accomIconi);
listing_i.add(AccomNamei);
listing_i.add(accomTypei);
listing_i.add(accomAdressi);
listing_i.add(accomReviewStars);
listing_i.add(new JLabel());
listing_i.add(showReviewi);
listing_i.add(editReviewi);
listing_i.add(deleteReviewi);
listing_i.setSize(950,200);
listing_i.setVisible(true);
listings.add(listing_i);
showReviewi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
showAccommodationGUI f = new showAccommodationGUI(rev.getAccommodationReviewed(), r);
f.show();
dispose();
}
});
editReviewi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addReviewGUI f = new addReviewGUI(r,rev.getAccommodationReviewed(), rev);
rev.delete();
f.show();
dispose();
}
});
deleteReviewi.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
rev.delete();
RegularUserGUI f = new RegularUserGUI(r);
f.show();
dispose();
}
});
}
πίσωΣτηνΑρχικήΣελίδαButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
RegularUserGUI f = new RegularUserGUI(r);
f.show();
dispose();
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/RegularUserDashboard.java |
1,543 | package gui;
import api.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Κλάση για τη γραφική διεπαφή προβολής ενός καταλύματος
*/
public class showAccommodationGUI extends JFrame{
private JPanel showAccom;
private JLabel description;
private JLabel adress;
private JLabel name;
private JLabel type;
private JPanel listings;
private JScrollPane showReviews;
private JLabel numOfReviews;
private JLabel avgRatingOfReviews;
private JTextArea amenityList;
private JButton DeleteButton;
private JButton editButton;
private JButton addReviewButton;
private JButton backButton;
private JLabel noReviews;
private JLabel amenityListLabel;
/**
* Κατασκευαστής που ανοίγει ένα παράθυρο για την προβολή ενός καταλύματος
* @param a το κατάλυμα το οποίο προβάλλεται
* @param g ο χρήστης ο οποίος ανοίγει το κατάλυμα για προβολή
*/
public showAccommodationGUI(Accommodation a,GeneralUser g) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(950,700);
setTitle("Show Accommodation");
setLocationRelativeTo(null);
setContentPane(showAccom);
if(g.getUserType().equals("Provider")){
addReviewButton.setVisible(false);
}
else if(g.getUserType().equals("RegularUser")){
DeleteButton.setVisible(false);
editButton.setVisible(false);
}
name.setText("Όνομα: "+a.getName());
type.setText("Τύπος: "+a.getType());
adress.setText("Τοποθεσία: "+a.getCity()+" "+a.getAddress()+" "+String.valueOf(a.getPostalCode()));
description.setText(a.getDescription());
numOfReviews.setText("Αριθμός Αξιολογήσεων: "+ String.valueOf(a.getNumberOfReviews()));
avgRatingOfReviews.setText("Μέσος όρος Αξιολογήσεων: "+ String.valueOf(a.getAverageRating()));
amenityList.setText(""+a.getListOfAmenities());
amenityList.setEditable(false);
amenityList.setOpaque(false);
if(a.getListOfReviews().size()==0){
noReviews.setVisible(true);
}
else {
noReviews.setVisible(false);
listings.setLayout(new GridLayout(0, 1));
int index = 0;
for (Review r : a.getListOfReviews()) {
index += 1;
GridLayout layout = new GridLayout(0, 3);
layout.setHgap(15);
layout.setVgap(20);
JPanel listing_i = new JPanel(layout);
listing_i.setBorder(new EmptyBorder(5, 2, 10, 5)); //padding
if (index % 2 == 0) {
listing_i.setBackground(Color.lightGray);
} else {
listing_i.setBackground(Color.white);
}
JLabel reviewStars=new JLabel("Αστέρια:"+ String.valueOf(r.getReviewStars()));
JLabel reviewDate = new JLabel(r.getCurrentDate());
JLabel reviewAuthor = new JLabel("Συγγραφέας: "+r.getAuthor().getName());
JTextArea reviewTextArea = new JTextArea();
reviewTextArea.setEditable(false);
reviewTextArea.setLineWrap(true);
reviewTextArea.setSize(100,0);
reviewTextArea.setText(r.getReviewText());
reviewTextArea.setOpaque(false);
listing_i.add(reviewStars);
listing_i.add(new JLabel());
listing_i.add(reviewDate);
listing_i.add(reviewAuthor);
listing_i.add(reviewTextArea);
listing_i.setSize(950,200);
listing_i.setVisible(true);
listings.add(listing_i);
}
}
setContentPane(showAccom);
DeleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
a.delete();
ProviderGUI l = new ProviderGUI((Provider) g);
l.show();
dispose();
}
});
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addAccommodationGUI l = new addAccommodationGUI(a,(Provider) g);
l.show();
dispose();
}
});
addReviewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
addReviewGUI l = new addReviewGUI((RegularUser)g, a);
l.show();
dispose();
}
});
backButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(g.getUserType().equals("Provider")){
ProviderGUI l = new ProviderGUI((Provider)g);
l.show();
dispose();
}
else if(g.getUserType().equals("RegularUser")){
RegularUserGUI l = new RegularUserGUI((RegularUser)g);
l.show();
dispose();
}
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/showAccommodationGUI.java |
1,544 | package gr.aueb.cf.ch10;
/*
* Αναπτύξτε ένα πρόγραμμα σε Java που να διαβάζει από ένα αρχείο ακέραιους
αριθμούς μέχρι να βρει την τιμή -1 (το αρχείο πρέπει να περιέχει περισσότερους από
6 αριθμούς και το πολύ 49 αριθμούς) με τιμές από 1 έως 49. Τους αριθμούς αυτούς
τους εισάγει σε ένα πίνακα, τον οποίο ταξινομεί (π.χ. με την Arrays.sort()). Στη
συνέχεια, το πρόγραμμα παράγει όλες τις δυνατές εξάδες (συνδυασμούς 6 αριθμών).
Ταυτόχρονα και αμέσως μετά την παραγωγή κάθε εξάδας ‘φιλτράρει’ κάθε εξάδα
ώστε να πληροί τα παρακάτω κριτήρια: 1) Να περιέχει το πολύ 4 άρτιους, 2) να
περιέχει το πολύ 4 περιττούς, 3) να περιέχει το πολύ 2 συνεχόμενους, 4) να περιέχει
το πολύ 3 ίδιους λήγοντες, 5) να περιέχει το πολύ 3 αριθμούς στην ίδια δεκάδα.
Τέλος, εκτυπώνει τις τελικές εξάδες σε ένα αρχείο με όνομα της επιλογής σας και
κατάληξη.txt.*/
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Scanner;
/*
*Hint. Ακολουθήστε τη διαδικασία που είχαμε δει για την παραγωγή 4άδων. Κάθε
παραγόμενη εξάδα μπορεί να αποθηκεύεται σε ένα πίνακα ο οποίος στη συνέχεια να
ελέγχεται από κάθε μία από τις αναφερόμενες μεθόδους (φίλτρα). Αν για
παράδειγμα μία εξάδα έχει αποθηκευτεί στον πίνακα arr, τότε για να ‘περάσει’ τα
φίλτρα που είναι ταυτόχρονα περιορισμοί, θα πρέπει να ελεγχθεί. Π.χ.
if (!isEven(arr)) && (!isOfdd(arr)) && (!isContiguous(arr)) && (!isSameEnding(arr)) &&
(!isSameTen), γράψε την εξάδα στο αρχείο εξόδου.
* */
public class MiniProject01 {
public static void main(String[] args) {
try (Scanner in = new Scanner(new File("C:\\Users\\Dell\\whatever\\lotto5in.txt"));
PrintStream ps = new PrintStream("C:\\Users\\Dell\\whatever\\lotto5out.txt", StandardCharsets.UTF_8)) {
final int LOTTO_SIZE = 6;
int[] inputNumbers = new int[49];
int pivot = 0; //επειδής μπορεί να μην είναι και οι 49 γεμάτες θα δείχνει στην τελευταία θέση των πραγματικών στοιχείων που έχει μέσα (στην πρώτη ελεύθερη)
int[] result = new int[6];
int num;
int window; // οι θέσεις που μετακινούνται
while ((num = in.nextInt()) != -1 && pivot <= 48) {
inputNumbers[pivot++] = num;
//pivot++;
}
int[] numbers = Arrays.copyOfRange(inputNumbers, 0, pivot);
Arrays.sort(numbers);
window = pivot - LOTTO_SIZE;
for (int i = 0; i <= window; i++) {
for (int j = i + 1; j <= window + 1; j++) {
for (int k = j + 1; k <= window + 2; k++) {
for (int l = k + 1; l <= window + 3; l++) {
for (int m = l + 1; m <= window + 4; m++) {
for (int n = m + 1; n <= window +5; n++){
result[0] = numbers[i];
result[1] = numbers[j];
result[2] = numbers[k];
result[3] = numbers[l];
result[4] = numbers[m];
result[5] = numbers[n];
if (!isEvenGE(result, 4) && !isOddGE(result, 4) && !isContiguous(result, 2) && !isSameEnding(result, 3)) {
// εδώ δεν είχα το if πριν γράψω τη λούπα και δεν είχα ps.print αλλά souf.
System.out.printf("%d, %d, %d, %d,%d\n",
result[0], result[1], result[2], result[3], result[4], result[5]);
}
}
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean isEvenGE(int[] arr, int threshold) {
int even = 0;
for (int num : arr) {
if (num % 2 == 0)
even++;
}
return even > threshold;
}
public static boolean isOddGE(int[] arr, int threshold) {
int odd = 0;
for (int num : arr) {
if (num % 2 != 0)
odd++;
}
return odd > threshold;
}
public static boolean isContiguous(int[] arr, int threshold){
//need to find position
int contiguous = 0;
for (int numPosition = 0; numPosition < arr.length -1; numPosition++){
for (int num : arr) {
if (arr[numPosition] == num && arr[numPosition + 1] == num)
contiguous++;
}
}
return contiguous > threshold;
}
public static boolean isSameEnding(int[] arr, int threshold){
boolean sameNumber = false;
int same = 0;
for (int num :arr) {
if ((arr[num] - 10 == num )) {
same++;
}
}
return same > threshold;
}
// public static boolean isSameTen(int[] arr, int threshold) {
// int plusTen = 0;
// for (int num : arr) {
// if (num += 10)
// plusTen++;
// }
// return plusTen > threshold;
// }
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/MiniProject01.java |
1,545 | package gui;
import api.Accommodation;
import api.RegularUser;
import api.Review;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/**
* Kλάση για τη γραφική διεπαφή προσθήκης και επεξεργασίας αξιολόγησης
*/
public class addReviewGUI extends JFrame{
private JTextField textField1;
private JButton addReviewButton;
private JTextField textField2;
private JPanel addReview;
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο για την επεξεργασία αξιολόγησης
* @param r ο χρήστης ο οποίος επεξεργάζεται την αξιολόγηση
* @param a το κατάλυμα το οποίο αξιολογείται
* @param rev η προηγούμενη αξιολόγηση
*/
public addReviewGUI(RegularUser r, Accommodation a, Review rev){
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(950,700);
setTitle("Edit Review");
setLocationRelativeTo(null);
setContentPane(addReview);
textField2.setText(rev.getReviewText());
textField1.setText(String.valueOf(rev.getReviewStars()));
addReviewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if((textField1.getText().matches("[0-9]+") && textField1.getText().length() >=1)) {
if (!r.AddReview(a, textField2.getText(), Integer.parseInt(textField1.getText()))) {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "H βαθμολογία πρέπει να είναι ακαριαίος απο το 1 μέχρι το 5 και το κείμενο αξιολόγησης εώς 500 χαρακτήρες. Ξαναπροσπάθησε.");
}
else {
RegularUserGUI f = new RegularUserGUI(r);
f.show();
dispose();
}
}
else {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "H βαθμολογία πρέπει να είναι ακαριαίος απο το 1 μέχρι το 5 και το κείμενο αξιολόγησης εώς 500 χαρακτήρες. Ξαναπροσπάθησε.");
}
}
});
}
/**
* Κατασκευαστής ο οποίος εμφανίζει ένα παράθυρο για την προσθήκη νέας αξιολόγησης
* @param r ο χρήστης ο οποίος κάνει την αξιολόγηση
* @param a το κατάλυμα το οποίο αξιολογείται
**/
public addReviewGUI(RegularUser r, Accommodation a) {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setResizable(false);
setSize(950,700);
setTitle("Add Review");
setLocationRelativeTo(null);
setContentPane(addReview);
addReviewButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if((textField1.getText().matches("[0-9]+") && textField1.getText().length() >=1)) {
if (!r.AddReview(a, textField2.getText(), Integer.parseInt(textField1.getText()))) {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "H βαθμολογία πρέπει να είναι ακαριαίος απο το 1 μέχρι το 5 και το κείμενο αξιολόγησης εώς 500 χαρακτήρες. Ξαναπροσπάθησε.");
}
else {
RegularUserGUI f = new RegularUserGUI(r);
f.show();
dispose();
}
}
else {
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(), "H βαθμολογία πρέπει να είναι ακαριαίος απο το 1 μέχρι το 5 και το κείμενο αξιολόγησης εώς 500 χαρακτήρες. Ξαναπροσπάθησε.");
}
}
});
}
}
| dallasGeorge/reviewsApp | src/gui/addReviewGUI.java |
1,546 | package logic;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
*
* Αυτή η κλάση χειρίζεται το σύνολο των παιχτών που συμμετέχουν στο παιχνίδι.
* Περιέχει μία λίστα από αντικείμενα τύπου Player και μεθόδους που επιτρέπουν
* την προσθήκη νέου παίχτη, την αλλαγή του σκορ του, καθώς και μεθόδους
* πρόσβασης στα στοιχεία του όπως το όνομα, τα πλήκτρα και το σκορ. *
*
* @author thanasis
* @author tasosxak
* @since 9/11/16
* @version 1.0
*/
public class PlayerList implements Serializable {
private final Map<Integer, Player> players;
private int num = 0;
public PlayerList() {
players = new HashMap<>();
}
/**
*
* Αυτή η μέθοδος προσθέτει έναν παίχτη στην λίστα των παιχτών με όνομα και
* πλήκτρα αυτά που θα πάρει ως παραμέτρους, αφού ελέγξει αν το όνομα
* περιέχει χαρακτήρες (δεν είναι η κενή συμβολοσειρά), αν τα πλήκτρα είναι
* ακριβώς 4 και αν δεν υπάρχει άλλος παίχτης με το ίδιο όνομα ή με κάποιο
* κοινό πλήκτρο.
*
* @param name Το όνομα του νέου παίκτη.
* @param keys Τα πλήκτρα που αντιστοιχούν στον παίχτη (πχ "asdf").
* @return Επιστρέφει true αν έγινε εισαγωγή του παίχτη, αλλιώς false.
*/
public boolean addPlayer(String name, String keys) {
if (keys.length() == 4 && name.length() > 0) {
for (Player player : players.values()) {
// Έλλεγχος αν υπάρχει άλλος παίχτης με όνομα name.
if (player.getName().equals(name)) {
return false;
}
/* Έλλεγχος αν υπάρχει κάποιο πλήκτρο από αυτά που
δόθηκαν (keys), χρησιμοποιείται ήδη από άλλο παίχτη. */
for (int i = 0; i < 4; i++) {
if (player.getAllKeys().contains(Character.toString(keys.charAt(i)))) {
return false;
}
}
}
// Εισαγωγή του παίχτη στο HashMap.
Player player = new Player(name, keys);
players.put(++num, player);
return true;
}
return false;
}
/**
*
* @param points Οι πόντοι που θα προστεθούν στον παίκτη.
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) του οποίου
* το σκορ μεταβάλλεται.
*/
public void addPointsToPlayer(int points, int player_id) {
if (players.containsKey(player_id)) {
players.get(player_id).addPoints(points);
}
}
/**
*
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) του οποίου
* το σκορ ζητείται.
* @return Επιστρέφει το σκορ του παίκτη αν ο παίκτης υπάρχει, αλλιώς null.
*/
public Integer getScoreOfPlayer(int player_id) {
if (players.containsKey(player_id)) {
Integer score = players.get(player_id).getScore();
if (score != null) {
return score;
} else {
return 0;
}
} else {
return null;
}
}
/**
*
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) του οποίου
* το όνομα ζητείται.
* @return Επιστρέφει το όνομα του παίκτη αν ο παίκτης υπάρχει, αλλιώς null
*/
public String getNameOfPlayer(int player_id) {
if (players.containsKey(player_id)) {
return players.get(player_id).getName();
} else {
return null;
}
}
public int getNumOfPlayers() {
return num;
}
/**
*
* @param key Συμβολοσειρά με έναν χαρακτήρα ο οποίος είναι το πλήκτρο του
* οποίου η θέση ζητείται.
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) για τον
* οποίο ζητούμε το id του πλήκτρου.
* @return Επιστρέφει το id του key για αυτόν τον παίκτη (πχ αν ο παίκτης
* έχει τα πλήκτρα "asdf" τότε το id του 'a' είναι το 0, το id του 's' είναι
* το 1 κτλ) αν υπάρχει παίκτης που έχει τέτοιο πλήκτρο, αλλιώς επιστρέφει
* -1.
*/
public int getKeyIdOfPlayer(String key, int player_id) {
if (players.containsKey(player_id) && players.get(player_id).isMyKey(key)) {
return players.get(player_id).getKeyId(key);
} else {
return -1;
}
}
/**
*
* @param key Συμβολοσειρά με έναν χαρακτήρα ο οποίος είναι το πλήκτρο που
* θέλουμε να δούμε αν αντιστοιχεί σε κάποιον παίχτη.
* @return Επιστρέφει true αν το πλήκτρο (key) ανήκει σε κάποιον παίχτη,
* αλλιώς false.
*/
public boolean isSomeonesKey(String key) {
for (Player player : players.values()) {
if (player.isMyKey(key)) {
return true;
}
}
return false;
}
/**
*
* @return Επιστρέφει μία συμβολοσειρά με όλα τα πλήκτρα όλων των παιχτών
* (πχ "asdfhjkl").
*/
public String getAllKeys() {
String keys = "";
for (Player player : players.values()) {
keys += player.getAllKeys();
}
return keys;
}
/**
*
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) του οποίου
* τα πλήκτρα ζητούνται.
* @return Επιστρέφει μια συμβολοσειρά με τα πλήκτρα του παίχτη που έχει το
* id που δόθηκε ως παράμετρος (πχ "asdf") ή null αν ο παίχτης δεν υπάρχει.
*/
public String getKeysOfPlayer(int player_id) {
if (players.containsKey(player_id)) {
return players.get(player_id).getAllKeys();
} else {
return null;
}
}
/**
*
* @param key Συμβολοσειρά με έναν χαρακτήρα ο οποίος είναι το πλήκτρο που
* θέλουμε να δούμε σε ποιόν παίχτη αντιστοιχεί.
* @return Επιστρέφει το id του παίχτη στον οποίο αντιστοιχεί το πλήκτρο
* (key) αν υπάρχει, αλλιώς επιστρέφει -1.
*/
public int whoseKeyIs(String key) {
if (isSomeonesKey(key)) {
for (Integer player_id : players.keySet()) {
if (players.get(player_id).isMyKey(key)) {
return player_id;
}
}
}
return -1;
}
/**
*
* @param key Συμβολοσειρά με έναν χαρακτήρα ο οποίος είναι το πλήκτρο που
* θέλουμε να δούμε αν ανήκει στον παίκτη με id ίσο με player_id.
* @param player_id Το id του παίκτη (Ποιος παίκτης είναι: 1 ή 2) για τον
* οποίο ζητούμε το id του πλήκτρου.
* @return Επιστρέφει true αν το πλήκτρο (key) ανήκει στον παίκτη με id ίσο
* με player_id.
*/
public boolean isKeyOfPlayer(String key, int player_id) {
return players.containsKey(player_id) && players.get(player_id).isMyKey(key);
}
/**
*
* @return Επιστρέφει το id του παίχτη που νίκησε, ή 0 αν έληξε με ισοπαλία.
*/
public int getWinnersId() {
if (getNumOfPlayers() > 1) {
int[] scores = getScoreTableScores();
String[] names = getScoreTableNames();
if (scores[0] != scores[1]) {
return getIdByPlayerName(names[0]);
}
}
return 0;
}
/**
*
* @param name Το όνομα του χρήστη του οποίο το id ζητείται.
* @return Επιστρέφει το id του παίχτη με όνομα name, ή 0 αν δεν υπάρχει τέτοιος παίχτης.
*/
public int getIdByPlayerName(String name) {
for (int id : players.keySet()) {
if (players.get(id).getName().equals(name)) {
return id;
}
}
return 0;
}
/**
*
* @return Επιστρέφει έναν πίνακα με τα ονόματα των παιχτών που έπαιξαν,
* σε φθήνουσα σειρά με βάση το σκορ.
*/
public String[] getScoreTableNames() {
HighScoresList highScores = new HighScoresList();
for (Player player : players.values()) {
String name = player.getName();
int score = 0;
if (player.getScore() != null) {
score = player.getScore();
}
highScores.addPlayer(name);
highScores.setScoreOfPlayer(score, name);
}
return highScores.getNamesForHighScores(num);
}
/**
*
* @return Επιστρέφει έναν πίνακα με τα σκορ των παιχτών που έπαιξαν,
* σε φθήνουσα σειρά με βάση το σκορ.
*/
public int[] getScoreTableScores() {
HighScoresList highScores = new HighScoresList();
for (Player player : players.values()) {
String name = player.getName();
int score = 0;
if (player.getScore() != null) {
score = player.getScore();
}
highScores.addPlayer(name);
highScores.setScoreOfPlayer(score, name);
}
// Μετατροπή των null σε 0
Integer[] scores = highScores.getHighScores(num);
int[] results = new int[num];
for (int i = 0; i < num; i++) {
if (scores[i] == null) {
results[i] = 0;
} else {
results[i] = scores[i];
}
}
return results;
}
/**
*
* @return Επιστρέφει το όνομα και το σκορ από κάθε παίχτη στην μορφή
* "Παίχτης1: Σκορ1 Παίχτης2: Σκορ2"
*/
@Override
public String toString() {
String result = "";
for (Player player : players.values()) {
result += player + "\n"; // εδώ καλείται η toString της player
}
return result;
}
}
| TeamLS/Buzz | src/logic/PlayerList.java |
1,550 | package gr.aueb.cf.ch10;
import java.util.Scanner;
/*
* Iteratively presents a multi-choice menu.
* The users select a choice and get feedback.
* Q/q is quit
* */
public class ProjectCh3 {
static Scanner in = new Scanner (System.in);
public static void main(String[] args) {
boolean quit = false;
String response = "";
do {
printMenu();
response = getChoice();
try{
if (response.matches("[Qq]")) {
//μεσα στα [] μπορώ να βάλω τους χαρακτήρες που θέλω να συμπεριλάβω στις πιθανές απαντήσεις
quit = true;
} else {
printOnChoice(response);
}
} catch (IllegalArgumentException e) {
System.out.println("invalid Choice");
}
} while (!quit);
}
public static void printMenu() {
System.out.println("Please select one of the following: ");
System.out.println("1. Insert");
System.out.println("2. Update");
System.out.println("3. Delete");
System.out.println("4. Select");
System.out.println("Q or q to Quit");
}
public static String getChoice() {
return in.nextLine().trim();
}
public static void printOnChoice(String s){
int choice = -1;
try{
if (s== null) throw new IllegalArgumentException();
choice = Integer.parseInt(s);
switch (choice) {
case 1:
System.out.println("Inserted");
break;
case 2:
System.out.println("Updated");
break;
case 3:
System.out.println("Deleted");
break;
default:
throw new IllegalArgumentException();
}
} catch (IllegalArgumentException e) {
// e.printStackTrace();
throw e;
}
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/ProjectCh3.java |
1,554 | /** Primitive types pass by value, collections and objects "seem to be passed by reference".
* In fact, everything in Java is passed by value because they are pointers.
* We also have the unmodifiable collections */
package gr.hua.dit.oopii.lec3.lists;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import gr.hua.dit.oopii.lec2.inheritance.Human;
//slide 7
public class ReferenceValue {
int obj_value;
public final static List<String> public_final_strings = new ArrayList<String>();
public static final Human human = new Human();
ReferenceValue(){
this.obj_value=5;
}
ReferenceValue(ReferenceValue in_obj){//Easy way to duplicate an object with a constructor that copies (duplicates) all elements.
this.obj_value=in_obj.obj_value;
System.out.println("Argument-object hashcode is: " + in_obj.hashCode());
System.out.println("The new-created object hashcode is: " + this.hashCode());
}
public static void passPrimitiveTypes(int number) { //The changes of the primitive types inside the class do not take effect outside the class.
number=1000;
}
public static void passObject( ReferenceValue obj , int number) {
obj.obj_value=number;
}
public static void passObject_withNew( ReferenceValue obj) {
ReferenceValue object2 = new ReferenceValue();
object2.obj_value=100;
obj=object2; //The parameter object pointer will not change.
}
public static void passArray( int[] in_array) {
in_array[0]=100;
in_array[1]=100;
in_array[2]=100;
}
public static void passObject_withfinal(final ReferenceValue obj , final int number) {
//number=50;
obj.obj_value=number;
}
public static void main(String[] args) {
int number=5;
System.out.println("1. Before call the func: Primitive types passed by value: "+number);
passPrimitiveTypes(number); //It adds 10 to the primitive type argument but no changes take place.
System.out.println("1. After call the func: Primitive types passed by value: "+number +"\n"); //Primitive type passed by Value.
ReferenceValue object = new ReferenceValue();
System.out.println("2."+object.hashCode() + " Before call the func: Objects seems to be passed by \"reference\" "+object.obj_value); //the object's hash code, which is the object's memory address in hexadecimal.
passObject(object,200);
System.out.println("2."+object.hashCode() + " After call the func: Objects seems to be passed by \"reference\": "+object.obj_value +"\n"); //Objects seems passed by "Reference". The changes took place.
int[] in_array = {11,12,13,14,15};
System.out.println("3."+in_array.hashCode() + " Before call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]);
passArray(in_array);
System.out.println("3."+in_array.hashCode() + " After call the func: Arrays also seem to be passed by \"reference\": "+in_array[0 ] +" "+ in_array[1] +" "+ in_array[2] +" "+ in_array[3] +" "+ in_array[4]+"\n"); //Objects passed by "Reference".
ReferenceValue object3 = new ReferenceValue(); //Reference to the values of the object. But passed with value thepointer to the object. We cannot change the object that we point.
System.out.println("4."+object3.hashCode() + " Before call the func: On the left we have the object's hash code, which is the object's memory address: " +object3.obj_value);
passObject_withNew(object3); //But we can change the variables of the object that we pass in. Δεν μπορώ να δειξω σε άλλο αντικείμενο. O pointer θα δείχνει πάντα στο ιδιο object.
System.out.println("4."+object3.hashCode() + " But, we cannot change the reference (pointer) of the object: On the left we have again the hash hashcode: "+object3.obj_value); //So if we re-think our statement everything is passed by value!!! you cannot change where that pointer points.
System.out.println("4.In fact everything in Java is PASSED BY VALUE!");
final ReferenceValue object4 = new ReferenceValue();
//object4 = object; //Final declaration of objects cannot change objects. But object4 = object; is acceptable.
System.out.println("\n\n\n5.How can we define that some collections or objects should not be modified?\n");
ReferenceValue object5 = new ReferenceValue(); //We have overloaded the constructor.
passObject(new ReferenceValue(object5), 200); //we really make a new object that duplicate the status of object5 and pass it as argument into the function.
System.out.println("5."+object5.hashCode() + " With the new object as argument and constructor that makes a deep copy, we can pass the object: "+object5.obj_value); //Objects passed by "Reference".
System.out.println("\n\n");
System.out.println("with unmodified collecction");
unmodifiedcollection(); //Unmodifiable collections!
System.out.println("Old name: "+human.getName()); // human is public static final. We cannot change the pointer, but we can change the state of the object.
human.setName("Theodoros");
System.out.println("New name: "+human.getName());
//human= new Human(); We cannot because the pointer cannot point a different object.
}
public static void unmodifiedcollection() { // We can explicitly declare a collection as unmodifiable and we will not be able to modify this collection.
List<String> strings = new ArrayList<String>();
List<String> unmodifiable = Collections.unmodifiableList(strings); //Now the collection cannot be modified. We cannot add or remove items from the list.
//unmodifiable.add("New string"); // will fail at runtime
strings.add("Aha!"); // will succeed
System.out.println(unmodifiable);
public_final_strings.add("word1"); //In the public final list we can add or remove elements.
public_final_strings.add("word2");
public_final_strings.add("word3");
public_final_strings.remove(1);
System.out.println(public_final_strings);
//public_final_strings = strings; //When the pointer is final, it cannot point another object (even if it is the same class).
List<Human> list_data_obj = new ArrayList<Human>();
Human x1 = new Human();
x1.setName("\nDimitris");
list_data_obj.add(x1);
List<Human> unmodifiable_list_data_obj = Collections.unmodifiableList(list_data_obj);
System.out.println(unmodifiable_list_data_obj.get(0).getName());
x1.setName("Peter");
System.out.println(unmodifiable_list_data_obj.get(0).getName());
}
public class ImmutableClass { //Immutable class has a constructor to initialize the objects. It has getters to return the values but it does not have setters.
private int var1;
private int var2;
ImmutableClass(int in_var1, int in_var2){
this.var1=in_var1;
this.var2=in_var2;
}
public int getVar1() {
return var1;
}
public int getVar2() {
return var2;
}
}
}
| johnviolos/OOPII | src/gr/hua/dit/oopii/lec3/lists/ReferenceValue.java |
1,557 | package gui;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumnModel;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import api.*;
public class App {
private static JPanel searchPanel = new JPanel();
private static api.User userOfApp ;
private JPanel p2 = new JPanel();
private static JTable table;
private static int rowSelected=-999;
private static JButton addButton;
private static JButton editButton;
private static JButton deleteButton;
private static JButton showButton;
private static JPanel panelForButtons = new JPanel();
private static DefaultTableModel tableModel;
private static JFrame AppFrame;
private static ArrayList<Slave> frames = new ArrayList<>();
private static int indexForClose;
private static ProviderFrame providerFrame;
private static JTabbedPane tp;
private static ArrayList<AccommodationItem> accItems = new ArrayList<AccommodationItem>();
public static ArrayList<Accommodation> getAccToShow() {
return accToShow;
}
private static ArrayList<Accommodation> accToShow = new ArrayList<>(Accommodation.getAccommodations());
public static void setIndexForClose(int indexForClose1)
{
indexForClose=indexForClose1;
}
public static AccommodationItem getAccItemByData(Accommodation a) {
for (int i = 0; i < accItems.size(); i++) {
if (a.equals(accItems.get(i).getAccommodationInfo())) {
return accItems.get(i);
}
}
return null;
}
public static ArrayList<AccommodationItem> getAccItems() {
return accItems;
}
// App Index
public App(User connectedUser, JFrame loginFrame) {
// Frame
userOfApp=connectedUser;
accToShow = Accommodation.getAccommodations();
addButton = new JButton("Add");
editButton = new JButton("Edit");
deleteButton = new JButton("Delete");
showButton = new JButton("Show Statistics");
AppFrame = new JFrame();
AppFrame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
AppFrame.setTitle("Καταλύματα App");
// Tabbed Pane
tp = new JTabbedPane();
createTab(tp,connectedUser);
tp.add("Dashboard", p2);
createDashBoard(p2);
// Έξοδος
JPanel p3 = new JPanel();
tp.add("Έξοδος", p3);
tp.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if(tp.getSelectedIndex()==indexForClose)
{
AppFrame.dispose();
loginFrame.setVisible(true);
}
else if(tp.getSelectedIndex()==1)
{
ProviderFrame providerFrame = new ProviderFrame(AppFrame);
accToShow = SearchTab.createSearchTab(providerFrame,AppFrame);
createTab(tp, connectedUser);
}
}
});
AppFrame.setSize(1300,800);
AppFrame.setResizable(false);
AppFrame.setLayout(null);
AppFrame.add(tp);
tp.setSize(780,450);//780 είναι το αθροίσμα των μεγεθών των column του JTable;
AppFrame.setVisible(true);
}
protected static void createDashBoard(JPanel panelToFill) {
String columnHeaders[] = {"'Ονομα","Τύπος","Πόλη","Διεύθυνση","Ταχυδρομικός Κώδικας","Βαθμός Αξιολόγησης"};
Object[][] data = userOfApp.setDataForTable();//Φέρνω τα data!
tableModel = new DefaultTableModel(data, columnHeaders) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
table = new JTable(tableModel);
table.getTableHeader().setReorderingAllowed(false);
setSizeOfColumns();
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)//Για να εμφανίζεται το JInternalFrame
{
rowSelected=table.getSelectedRow();
Accommodation acc=Accommodation.findAccommodation((String)table.getValueAt(rowSelected,0),(String)table.getValueAt(rowSelected,3), (String)table.getValueAt(rowSelected, 2));
if(frames.size()!=0)
{
frames.get(0).internalFrame.dispose();
frames.clear();
}
frames.add(new Slave(AppFrame,acc,userOfApp));
}
});
JScrollPane scrollPane = new JScrollPane(table);
panelToFill.setLayout(new BorderLayout());
panelToFill.add(scrollPane,BorderLayout.CENTER);
panelForButtons = new JPanel();
if (userOfApp instanceof Provider) {
providerFrame = new ProviderFrame(AppFrame);
panelForButtons.setLayout(new GridLayout(1,4));
panelForButtons.add(addButton);
addButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
providerFrame.createAddFrame((Provider)userOfApp);
}
});
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
if(rowSelected!=-999)
{
Accommodation temp=Accommodation.findAccommodation(table.getValueAt(rowSelected,0)+"",table.getValueAt(rowSelected,3)+"",(String)table.getValueAt(rowSelected,2));//Βρίσκω το acc με βάση το όνομα και την διευθυνσή
providerFrame.createEditFrame(temp);
table.setValueAt(temp.getName(),rowSelected,0);//Ενημέρωση του JTable για να μπορώ να το βρω με την findAccommodation
table.setValueAt(temp.getType(),rowSelected,1);
table.setValueAt(temp.getCity(),rowSelected, 2
);
table.setValueAt(temp.getRoad(),rowSelected,3);
table.setValueAt(temp.getAverage() == -1 ? "Καμία αξιολόγηση." : temp.getAverage() + "",rowSelected,5);
rowSelected=-999;
Slave.updateTextArea();
}
}
});
showButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews() + "\n"
+ "Πλήθος αξιολογήσεων σε όλα τα κατάλυματα σας: " + ((Provider)userOfApp).countReviews());
}
});
} else {
panelForButtons.setLayout(new GridLayout(1,3));
editButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if(rowSelected!=-999)
{
userOfApp.editAction(rowSelected,table);
rowSelected=-999;
Slave.updateTextArea();
}
}
});
showButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "Μέσος όρος αξιολογήσεων: " + userOfApp.countAverageReviews());
}
});
}
panelForButtons.add(editButton);
panelForButtons.add(deleteButton);
panelForButtons.add(showButton);
panelToFill.add(panelForButtons,BorderLayout.PAGE_END);
deleteButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
if(rowSelected!=-999)
{
userOfApp.deleteAction(rowSelected,table);
tableModel.removeRow(rowSelected);//Αφαιρώ απο το table to review
rowSelected=-999;
Slave.updateTextArea();
} //Αν rowSelected==-999 δεν έχει κάνει κάπου κλικ ο χρήστης
}
});
}
protected static void addRowToTable(String name,String type,String city,String address,String postalCode,String rating) {
tableModel.addRow(new String[]{name, type, city, address, postalCode, rating});
}
public void createTab(JTabbedPane tabbedPane, User connectedUser) {
if (connectedUser instanceof Customer) {
JPanel p1 = new JPanel();
AccommodationItem temp;
accItems = new ArrayList<>();
GridLayout accommodationLayout = new GridLayout(1,2);
if (accToShow.size() == Accommodation.getAccommodations().size()) {
accToShow = Provider.randomAcc();
}
for (int i = 0; i < accToShow.size(); i++) {
double review_avg = accToShow.get(i).calculateAverage();
String t = review_avg == -1 ? "Καμία Αξιολόγηση." : String.valueOf(review_avg);
temp = new AccommodationItem(accToShow.get(i), accToShow.get(i).getName(), t);
AccommodationItem finalTemp = temp;
temp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() instanceof AccommodationItem) {
AccommodationItem t = (AccommodationItem) e.getSource();
if(frames.size()!=0)
{
frames.get(0).internalFrame.dispose();
frames.clear();
}
frames.add(new Slave(AppFrame, finalTemp.getAccommodationInfo(),userOfApp));
}
}
});
temp.setLayout(accommodationLayout);
accItems.add(temp);
p1.add(temp);
}
GridLayout accommodationsLayout = new GridLayout(10,1);
p1.setLayout(accommodationsLayout);
if (tabbedPane.getTabCount() == 0) {
tabbedPane.add("Καταλύματα", p1);
tabbedPane.add("Αναζήτηση", searchPanel);
} else if (tabbedPane.getTabCount() > 2) {
tabbedPane.remove(0);
tabbedPane.insertTab("Καταλύματα", null, p1, null, 0);
}
}
}
private static void setSizeOfColumns() {
TableColumnModel columnModel = table.getColumnModel();
for(int i=0;i<table.getColumnCount();i++)
{
columnModel.getColumn(i).setPreferredWidth(130);
columnModel.getColumn(i).setMaxWidth(130);
}
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
}
} | StylianosBairamis/oop-myreviews-project | src/gui/App.java |
1,560 | package com.example.androidergasia;
import android.content.ContentValues;
import android.content.Context;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.LocaleList;
import android.util.Pair;
import androidx.annotation.Nullable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class DBhandler extends SQLiteOpenHelper
{
public static int DATABASE_VERSION = 1;
private static int NEW_VERSION;
public static final String DATABASE_NAME = "myAPP.db";
public static final String DATABASE_TABLE_PLACES = "places";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_TYPE_OF_PLACE = "type_of_place";
public static final String COLUMN_NAME = "placeName";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_RATING = "rating";
public static final String COLUMN_IMAGE ="image"; //Εδω αποθηκέυω path της αντίστοιχης εικόνας!
public static final String COLUMN_LONGITUDE = "longitude";
public static final String COLUMN_LATITUDE = "latitude";
//Για το Table που κρατάει τις Κρατήσεις.
public static final String DATABASE_TABLE_RESERVATIONS = "reservations";
public static final String COLUMN_RESERVATION_DATE = "reservation_date";
public static final String COLUMN_RESERVATION_TIME = "reservation_time";
public static final String COLUMN_TRACK_PLACE = "id_of_place";
public static final String COLUMN_NUMBER_OF_PEOPLE = "number_of_people";
private static Context context ;
//Για table που κρατάει τα favourite places
private static final String COLUMN_FAVOURITE_PLACE_ID="id_of_place";
private static final String DATABASE_TABLE_FAVORITE = "favorite";
private final String DB_PATH = "/data/data/com.example.androidergasia/databases/";
private final String DB_NAME = "myAPP.db";
private SQLiteDatabase db = null;
public DBhandler(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, version);
this.context = context;
copyTable();
Controller.setDBhandler(this);//Θέτω τον DBhandler στον Controller.
NEW_VERSION = version ;
db = getWritableDatabase();
}
/**
* Μέθοδος που αντιγράφει την ΒΔ που υπάρχει στο φάκελο assets, αν δεν υπάρχει το αντίστοιχο αρχείο.
* Το table places περιέχει πληροφορίες για τα μαγαζία του app.
*/
private void copyTable()
{
try {
String myPath = DB_PATH + DB_NAME; //Path που αποθηκέυεται η ΒΔ της εφαρμογής.
File file = new File(myPath);
if(file.exists())//Αν υπάρχει ήδη ο φάκελος επιστρέφω
{
return;
}
//Αλλίως γράφω στο παραπάνω path την ΒΔ που υπάρχει στο φάκελο assets.
InputStream inputStream = context.getAssets().open("myAPP.db");
File outputFile = context.getDatabasePath("myAPP.db");
OutputStream outputStream = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0)
{
outputStream.write(buffer, 0, length); //Γράφω σταδιακά το αρχείο.
}
outputStream.flush();//Κλείσιμο πόρων
outputStream.close();
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase db)
{
}
/**
* Δημιουργώ ακόμα 2 tables, 1 για που θα αποθηκεύω τις κρατήσεις και 1
* για την αποθήκευση των αγαπημένων μαγαζιών.
* Καλείται η onUpgrade καθώς η ΒΔ προυπαρχεί καθώς περιέχει το table places
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
if(oldVersion < newVersion)
{
String CREATE_FAVORITE_TABLE = " CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_FAVORITE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_FAVOURITE_PLACE_ID + " INTEGER NOT NULL, " +
" FOREIGN KEY(" + COLUMN_FAVOURITE_PLACE_ID + ") REFERENCES places(_id)" +
")";
String CREATE_RESERVATIONS_TABLE = "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_RESERVATIONS + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_RESERVATION_DATE + " TEXT NOT NULL," +
COLUMN_RESERVATION_TIME + " TEXT NOT NULL," +
COLUMN_NUMBER_OF_PEOPLE + " INTEGER NOT NULL," +
COLUMN_TRACK_PLACE + " INTEGER," +
" FOREIGN KEY(id_of_place) REFERENCES places(_id)" +
")";
db.execSQL(CREATE_RESERVATIONS_TABLE);
db.execSQL(CREATE_FAVORITE_TABLE);
this.db = db;
}
}
/**
* Το PRIMARY KEY EXΕΙ ΑUTOINCREMENT DEN BAZW ID!
* @param placeToAdd
*/
// public void addPlace(Place placeToAdd)
// {
// ContentValues contentValues = new ContentValues();//KEY-VALUE ΔΟΜΗ
//
// contentValues.put(COLUMN_NAME, placeToAdd.getName());
// contentValues.put(COLUMN_TYPE_OF_PLACE,placeToAdd.getTypeOfPlace());
// contentValues.put(COLUMN_DESCRIPTION,placeToAdd.getDescription());
// contentValues.put(COLUMN_RATING,placeToAdd.getRating());
//
// contentValues.put(COLUMN_CHAIRS_AVAILABLE, placeToAdd.getNumberOfChairs());
// contentValues.put(COLUMN_LATITUDE, placeToAdd.getLatitude());
// contentValues.put(COLUMN_LONGITUDE,placeToAdd.getLongitude());
//
// String pathToFile = "/"+placeToAdd.getTypeOfPlace() + "/" + freeFromSpaces(placeToAdd.getName()) + ".jpg";
//
// contentValues.put(COLUMN_IMAGE, pathToFile);//Περίεχει το Path για την εικόνα του Place
//
// SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
// sqLiteDatabase.insert(DATABASE_TABLE_PLACES,null, contentValues);
// sqLiteDatabase.close();
// }
/**
* Query που επιστρέφει places με βάση το type_of_place
* @param typeOfPlaceToSearch
* @return
*/
public Cursor findPlaces(String typeOfPlaceToSearch)
{
Resources resources = context.getResources();
//Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app
Configuration configuration = resources.getConfiguration();
LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes
String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό.
String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί.
String query = "SELECT " + COLUMN_NAME + "," + COLUMN_TYPE_OF_PLACE + "," +
description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + ","
+ COLUMN_IMAGE +
" FROM " + DATABASE_TABLE_PLACES +
" WHERE " + COLUMN_TYPE_OF_PLACE + " = '" + typeOfPlaceToSearch + "' ";
Cursor cursorForReturn = db.rawQuery(query, null);
return cursorForReturn;
}
// /**
// * Αφαιρώ τα κένα απο το String, δεν μπορώ να εχώ κενά στο fileSystem
// * Επίσης το androidFileSystem δεν δέχεται UpperCase γράμματα, επιστρέφω lowerCase String
// * @param toFree
// * @return
// */
// private String freeFromSpaces(String toFree)
// {
// if(!toFree.contains(" "))
// {
// return toFree;
// }
//
// String[] arrayOfWords = toFree.split(" ");
// String spaceFree = "";
// for(int i = 0 ;i < arrayOfWords.length;i++)
// {
// spaceFree += arrayOfWords[i];
// }
// return spaceFree.toLowerCase();
// }
/**
* @param nameForSearch Όνομα του Place που θα επιστρέψω τα coordinates
* @return ενα αντικείμενο τύπου Pair με το latitude, longitude
*/
public Pair<Float,Float> getCoordinates(String nameForSearch)
{
String query = "SELECT " + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE +
" FROM " + DATABASE_TABLE_PLACES +
" WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' ";
// SQLiteDatabase db = getReadableDatabase();
Cursor cursor = db.rawQuery(query, null);
cursor.moveToFirst(); //Ενα μόνο αντικείμενο επιστρέφεται
Pair<Float, Float> tempPair = new Pair<>(cursor.getFloat(0),cursor.getFloat(1));
cursor.close(); //απελευθερωση πόρων
return tempPair;
}
/**
* @param nameForSearch Όνομα του Place που θα προσθέσω στο table favorite
*/
public void addPlaceToFavorite(String nameForSearch)
{
int id = getPlaceID(nameForSearch); // Παίρνω το id απο την μέθοδο getPlaceID
ContentValues contentValues = new ContentValues();// key,value δομή
contentValues.put(COLUMN_FAVOURITE_PLACE_ID, id);
db.insert(DATABASE_TABLE_FAVORITE,null, contentValues);//Προσθήκη στον πίνακα.
}
/**
* Μέθοδος για την αφαίρεση place απο το table favorite, ενημερώνω τον adapter αν βρίσκομαι στο
* FavoritesActivity.
* @param nameForDelete όνομα του place προς αφαίρεση.
*/
public void removePlaceFromFavorite(String nameForDelete)
{
int idOfPlace = getPlaceID(nameForDelete); // Παίρνω το id απο την μέθοδο getPlaceID
String condition = COLUMN_FAVOURITE_PLACE_ID + " = " + "?";
String[] conditionArgs = {idOfPlace+""};
db.delete(DATABASE_TABLE_FAVORITE,condition,conditionArgs);
if(Controller.isTypeOfAdapter())//Αν είναι το recyclerAdapter του FavoritesActivity.
{
Controller.getAdapter().removeItem(nameForDelete);
//Ενημέρωση του adapter ώστε να αφαιρέσει το αντίστοιχο Place απο το recyclerViewer.
}
}
/**
* Μέθοδος που επιστρέφει όλα τα places που έχει επιλέξει ο χρήστης ως favorite
* Πραγματοποιείται inner join μεταξύ του πίνακα favorite table και του places table.
* Τable favorite έχει ως foreign key το primary key των places.
* @return
*/
public Cursor getFavoritePlaces()
{
Resources resources = context.getResources();
//Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app
Configuration configuration = resources.getConfiguration();
LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes
String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό.
String description = currentLanguage.equals("el")?"description_gr" : COLUMN_DESCRIPTION; //Ποία απο τις δυο στήλες θα επιστραφεί.
String query ="SELECT "+ COLUMN_NAME + "," +COLUMN_TYPE_OF_PLACE + ","+
description + "," + COLUMN_RATING + "," + COLUMN_LATITUDE + "," + COLUMN_LONGITUDE + ","
+ COLUMN_IMAGE +
" FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_FAVORITE +
" ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_FAVORITE + ".id_of_place";
return db.rawQuery(query,null);
}
/**
* Μέθοδος που ελέγχει αν place υπάρχει ως record στον πίνακα των favorite.
* @param nameOfPlace όνομα του place
* @return 0 αν δεν βρίσκεται αλλιώς επιστρέφει 1
*/
public int isInFavoriteTable(String nameOfPlace)
{
String query = "SELECT " + "_id" +
" FROM " + "places " +
" WHERE " + "placeName" + " = '" + nameOfPlace + "' ";
Cursor cursor = db.rawQuery(query,null);
cursor.moveToFirst();
int id = cursor.getInt(0);
query = "SELECT " + " * " +
" FROM " + " favorite " +
" WHERE " + "id_of_place = " + id ;
cursor = db.rawQuery(query, null);
int toReturnCount = cursor.getCount();
cursor.close();
return toReturnCount;
}
/**
* Μέθοδος για προσθήκη Reservation στο table reservations
* @param reservation προς εισαγωγή
*/
public void addReservation(Reservation reservation)
{
ContentValues values = new ContentValues(); //key,value δομή.
values.put(COLUMN_TRACK_PLACE, reservation.getPlaceId());
values.put(COLUMN_RESERVATION_DATE, reservation.getDate());
values.put(COLUMN_RESERVATION_TIME, reservation.getDateTime());
values.put(COLUMN_NUMBER_OF_PEOPLE, reservation.getNumberOfPeople());
db.insert(DATABASE_TABLE_RESERVATIONS, null, values);
}
/**
* Μέθοδος για την αφαίρεση reservation απο το table
* @param idToDelete id του reservation
*/
public void removeReservation(int idToDelete)
{
String condition = COLUMN_ID + " = " + "?";
String[] conditionArgs = {idToDelete+""};
db.delete(DATABASE_TABLE_RESERVATIONS, condition, conditionArgs) ;
}
/**
* Μεθοδος που επιστρέφει όλα τα Reservations που υπάρχουν στο table
* @return ArrayList με Reservations.
*/
public ArrayList<Reservation> findReservations()
{
// SQLiteDatabase db = this.getReadableDatabase();
String query ="SELECT "+ "places."+COLUMN_NAME + "," +"reservations." + COLUMN_RESERVATION_TIME + "," +
"reservations." + COLUMN_RESERVATION_DATE + "," + "reservations." + COLUMN_NUMBER_OF_PEOPLE
+ "," + "reservations." + COLUMN_ID +
" FROM " + DATABASE_TABLE_PLACES + " INNER JOIN " + DATABASE_TABLE_RESERVATIONS +
" ON "+ DATABASE_TABLE_PLACES+"._id" + "=" + DATABASE_TABLE_RESERVATIONS + ".id_of_place";
return fromCursorToArrayList(db.rawQuery(query, null));
}
/**
* @param cursor απο το query της μέθοδου findReservations.
* @return ArrayList με Reservations.
*/
private ArrayList<Reservation> fromCursorToArrayList(Cursor cursor)
{
ArrayList<Reservation> toReturn = new ArrayList<>();
Reservation tempReservation;
for(int i = 0 ; i < cursor.getCount(); i++)
{
cursor.moveToFirst();
cursor.move(i);
String nameOfPlace = cursor.getString(0);
String time = cursor.getString(1);
String date = cursor.getString(2);
int numberOfPeople = cursor.getInt(3);
int reservationID = cursor.getInt(4);
//Δημιουργεία reservation με τα στοιχεία του query.
tempReservation = new Reservation(date, time, nameOfPlace, numberOfPeople, reservationID);
toReturn.add((tempReservation));//προσθήκη στο arrayList.
}
return toReturn;
}
/**
* Μέθοδος που δέχεται ώς όρισμα το όνομα ενος Place, επιστρέφει το id του
*/
public int getPlaceID(String nameForSearch)
{
String query = "SELECT " + COLUMN_ID +
" FROM " + DATABASE_TABLE_PLACES +
" WHERE " + COLUMN_NAME + " = '" + nameForSearch + "' ";
Cursor cursor = db.rawQuery(query,null); //Εκτέλεση του query.
cursor.moveToFirst();
int toReturn = cursor.getInt(0);
return toReturn;
}
}
| StylianosBairamis/ReserveIT | app/src/main/java/com/example/androidergasia/DBhandler.java |
1,567 | package com.example.androidergasia;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Paint;
import android.icu.text.SimpleDateFormat;
import android.icu.util.Calendar;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.text.format.DateFormat;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Locale;
public class BlankFragment extends Fragment
{
private Button submit;
private Button pickTime;
private TextView numOfPersons;
private ImageView favorite;
private static String nameOfPlace;
private String timePicked; //ώρα της κράτησης
private String datePicked; //μέρα της κράτησης
private boolean[] validRequest; // πίνακας για boolean τιμές, χρησιμοποιείται για τον έλεγχο εγκυρότητας της κράτησης.
//στην πρώτη θέση είναι ο αριθμός των ατόμων, στην δεύτερη η ημερομηνία και στην τρίτη η ώρα.
private boolean isSameDate = false; // πεδίο που χρησιμοποιείται για τον έλεγχο της εγκυρότητας της κράτησης.
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
public BlankFragment() {}
public BlankFragment(String nameOfPlace)
{
this.nameOfPlace = nameOfPlace;
}
@SuppressLint("MissingInflatedId")
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
validRequest = new boolean[3];
submit = view.findViewById(R.id.button);
pickTime = view.findViewById(R.id.timeButton);
submit.setOnClickListener(this::submit);
submit.setEnabled(false);
// pickTime.setEnabled(false); //περιμένω πρώτα να βάλει ημερομηνια.
numOfPersons = view.findViewById(R.id.numOfPersons);
ImageButton incrementButton = view.findViewById(R.id.increment);
ImageButton decrementButton = view.findViewById(R.id.decrement);
Button showLocation = view.findViewById(R.id.locationShow);
favorite = view.findViewById(R.id.favoriteIcon);
CalendarView calendarView = view.findViewById(R.id.calendarView);
calendarView.getDate();
calendarView.setDate(System.currentTimeMillis(), false, true);
TextView nameView = view.findViewById(R.id.placeName);
nameView.setText(nameOfPlace);
nameView.setPaintFlags(nameView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG); // underline του ονόματος.
validRequest[1] = true; // θέτω ως true για να αναγνωρίζει κατευθείαν την τρέχουσα μέρα.
//Listener για το button που αυξάνει τον αριθμό των ατόμων.
incrementButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view)
{
int num = Integer.parseInt(numOfPersons.getText().toString());
num++;
numOfPersons.setText(num + "");
validRequest[0] = true; //έχει επιλέξει άτομα
checkValidness(); //Ελέγχος εγκυρότητας.
}
});
//Listener για το button που μείωνει τον αριθμό των ατόμων.
decrementButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
int num = Integer.parseInt(numOfPersons.getText().toString());
if(num != 0)
{
num--;
numOfPersons.setText(num +"");
if(num == 0)
{
validRequest[0] = false; //δεν έχει επιλέξει άτομα
}
}
checkValidness(); //Ελέγχος εγκυρότητας.
}
});
pickTime.setOnClickListener(this::pickTime);
calendarView.setOnDateChangeListener(new CalendarView.OnDateChangeListener()
{
@Override
public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int dayOfMonth)
{
Calendar selectedDate = Calendar.getInstance(); //Δημιουργώ object τύπου Calendar
Calendar currentDate = Calendar.getInstance();
// μέθοδος .get της Calendar δέχεται int, επιστρέφει πληροφορία που αντιστοιχεί η σταθερά
int currentYear = currentDate.get(Calendar.YEAR);
int currentMonth = currentDate.get(Calendar.MONTH);
int currentDay = currentDate.get(Calendar.DAY_OF_MONTH);
currentDate.set(currentYear,currentMonth,currentDay); // Τρέχουσα ημερομηνια.
selectedDate.set(year, month, dayOfMonth); // Ημερομηνια που επιλέχθηκε.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
datePicked = dateFormat.format(selectedDate.getTime());
String dateCurrent = dateFormat.format(currentDate.getTime());
//'Ελεγχος για το αν η ημερομηνια που επιλέχθηκε είναι πριν απο την τρέχουσα
// δεν έχει επιλέξει εγκυρη ημερομηνια
validRequest[1] = !selectedDate.before(currentDate); // έχει επιλέξει εγκυρη ημερομηνία.
pickTime.setEnabled(validRequest[1]); // αν μπορώ να διαλέξω ώρα
isSameDate = dateCurrent.equals(datePicked);
checkValidness();
}
});
showLocation.setOnClickListener(this::startMapActivity);
setFavoriteIcon();
setTempDate();
return view;
}
/**
* Μέθοδος που εκτελείται όταν ο user κάνει click το location button.
* @param view
*/
private void startMapActivity(View view)
{
Intent intent = new Intent(getContext(), MapsActivity.class);
intent.putExtra("name", nameOfPlace);//Παιρνάω το όνομα του Place στο MapsActivity.
startActivity(intent); //Ξεκινάω το mapActivity
}
/**
* Μέθοδος για την αρχικοποίηση της εικόνας, ανάλογα με το αν η εικόνα βρίσκεται
* στα favorite του user.
*/
private void setFavoriteIcon()
{
int value = Controller.isInFavoriteTable(nameOfPlace);
if(value == 0)
{
favorite.setImageResource(R.mipmap.favorite_empty);
}
else
{
favorite.setImageResource(R.mipmap.favorite_filled);
}
favorite.setOnClickListener(this::addToFavorite);
}
/**
* Μέθοδος που εκτελείται όταν ο user κάνει click το submit button.
*/
private void submit(View view)
{
Resources resources = getResources();
//Configurations της συσκευής που μπορεί να επηρεάσουν τα resources του app
Configuration configuration = resources.getConfiguration();
LocaleList localeList = configuration.getLocales(); //επιστρέφει λίστα με two-letter lowercase language codes
String currentLanguage = localeList.get(0).getLanguage(); //γλώσσα που χρησιμοποιείται απο το κινητό.
ProgressDialog progressDialog = new ProgressDialog(getActivity());//Δημιουργεία του progressDialog.
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
String negativeButtonText;
if(currentLanguage.equals("el"))
{
progressDialog.setTitle("Καταχωρείται η κράτηση");
progressDialog.setMessage("Περιμένετε...");
negativeButtonText = "Ακύρωση";
}
else
{
progressDialog.setTitle("Making a reservation");
progressDialog.setMessage("please wait...");
negativeButtonText = "Cancel";
}
progressDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, negativeButtonText, new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i)
{
dialogInterface.cancel();
}
});
progressDialog.show();
new Handler().postDelayed(new Runnable() {
@Override
public void run()
{
String message;
progressDialog.dismiss(); //Φεύγει το progressDialog απο το UI
AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
if(currentLanguage.equals("el"))
{
alertDialog.setTitle("Επιτυχία");
message = "Η κράτηση σας καταχωρήθηκε!" + "\n" +
"Ημερομηνία κράτησης: " + datePicked + "\n" + "Ώρα κράτησης: "
+timePicked;
}
else
{
alertDialog.setTitle("Success");
message = "Your reservation has been made!" + "\n" +
"Date of reservation: " + datePicked + "\n" + "Time of reservation: "
+timePicked;
}
alertDialog.setMessage(message);
int placeID = Controller.getDBhandler().getPlaceID(nameOfPlace);
Reservation reservation = new Reservation(placeID, datePicked, timePicked, Integer.parseInt(numOfPersons.getText().toString()));
Controller.addReservation(reservation);
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
getActivity().finish();//Κλείνω το activity
}
});
alertDialog.show();
}
}, 2000);
// Βάζω καθυστέρηση 2 second για να φαίνεται αληθοφανές το progressDialog και να έχει χρόνο ο user να ακυρώσει την κράτηση.
}
private void pickTime(View view)
{
Calendar currentTime = Calendar.getInstance();
TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute)
{
Calendar selectedTime = Calendar.getInstance();
if(!isSameDate)
{
selectedTime.set(Calendar.HOUR_OF_DAY, selectedHour);
selectedTime.set(Calendar.MINUTE, selectedMinute);
@SuppressLint("SimpleDateFormat")
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
timePicked = (format.format(selectedTime.getTime()));
validRequest[2] = true;
checkValidness();
return;
}
selectedTime.set(Calendar.HOUR_OF_DAY, selectedHour);
selectedTime.set(Calendar.MINUTE, selectedMinute);
int currentHour = currentTime.get(Calendar.HOUR_OF_DAY);
int currentMinute = currentTime.get(Calendar.MINUTE);
currentTime.set(Calendar.HOUR_OF_DAY,currentHour);
currentTime.set(Calendar.MINUTE,currentMinute);
int result = selectedTime.compareTo(currentTime);
validRequest[2] = result >= 0 ;
@SuppressLint("SimpleDateFormat")
SimpleDateFormat format = new SimpleDateFormat("hh:mm a");
timePicked = (format.format(selectedTime.getTime()));
checkValidness();
}
}
,currentTime.get(Calendar.HOUR_OF_DAY),currentTime.get(Calendar.MINUTE), DateFormat.is24HourFormat(getActivity()));
timePickerDialog.show();
}
private void addToFavorite(View view)
{
int value = Controller.isInFavoriteTable(nameOfPlace);
if(value == 0)
{
favorite.setImageResource(R.mipmap.favorite_filled);
Controller.getDBhandler().addPlaceToFavorite(nameOfPlace);
}
else
{
favorite.setImageResource(R.mipmap.favorite_empty);
Controller.getDBhandler().removePlaceFromFavorite(nameOfPlace);
//Controller.notifyRecyclerAdapter();
}
}
/**
* Μέθοδος που θέτει την ημερομηνία, εκτελείται όταν ξεκινάει το activity.
*/
private void setTempDate()
{
Calendar currentDate = Calendar.getInstance();
// μέθοδος .get της Calendar δέχεται int, επιστρέφει πληροφορία που αντιστοιχεί η σταθερά
int currentYear = currentDate.get(Calendar.YEAR);
int currentMonth = currentDate.get(Calendar.MONTH);
int currentDay = currentDate.get(Calendar.DAY_OF_MONTH);
currentDate.set(currentYear,currentMonth,currentDay); // Τρέχουσα ημερομηνια.
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.getDefault());
datePicked = dateFormat.format(currentDate.getTime());
}
/**
* Μέθοδος που ελέγχει αν η πληροφορίες που έχει καταχωρήσει ο user είναι έγκυρες
* Δήλαδη η ώρα, αριθμός των ατόμων και η ημερομηνία.
*/
private void checkValidness()
{
boolean allValid = true;
for (boolean isValid : validRequest)
{
if (!isValid) // Αν έστω και ένα απο τα απαιτόυμενα είναι false δεν είναι εγκυρή η κράτηση
{
allValid = false;
break;
}
}
submit.setEnabled(allValid);
if (allValid) // Ανάλογα με την κατάσταση αλλάζω και το χρώμα του button
{
submit.setBackgroundColor(Color.parseColor("#9C27B0"));
}
else
{
submit.setBackgroundColor(Color.rgb(227, 227, 227));
}
}
} | StylianosBairamis/ReserveIT | app/src/main/java/com/example/androidergasia/BlankFragment.java |
1,568 | import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame {
private Board board;
public GUI() {
board = new Board();
this.setContentPane(board);
//Ακροατής σε συμβάντα τύπου 'κλικ' στο ποντίκι
//MouseClickListener listener = new MouseClickListener();
//board.addMouseListener(listener);
//Ακροατής σε συμβάντα τύπου 'drag & drop' στο ποντίκι
MouseMoveListener listener = new MouseMoveListener();
board.addMouseMotionListener(listener);
this.setVisible(true);
this.setSize(400, 400);
}
//Χειρισμός συμβάντων κλικ ποντικιού
// Βιβλιοθήκη MouseListener
// Εσωτερική της GUI για να μπορώ να βλέπω το board
class MouseClickListener implements MouseListener {
// Αφηριμένες μεθόδους
@Override
public void mouseClicked(MouseEvent event) {
// Παίρνω συντεταγμένες που ο χρήστης έκανε κλικ με το ποντίκι
int x = event.getX();
int y = event.getY();
board.setXYCoordinates(x, y); // Θέτει τις συντεταγμένες στην σκακιέρα
board.repaint(); //Ξανασχεδιάζει τον εαυτό της
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
class MouseMoveListener implements MouseMotionListener {
// Αφηριμένες μεθόδους
@Override
public void mouseDragged(MouseEvent event) {
// Παίρνω συντεταγμένες που ο χρήστης έκανε κλικ με το ποντίκι
int x = event.getX();
int y = event.getY();
board.setXYCoordinates(x, y); // Θέτει τις συντεταγμένες στην σκακιέρα
board.repaint(); //Ξανασχεδιάζει τον εαυτό της
}
@Override
public void mouseMoved(MouseEvent arg0) {
// TODO Auto-generated method stub
}
}
}
class Board extends JPanel {
// Συντεταγμένες που θα βγαίνει στο πιόνι
private int xCoord = 0;
private int yCoord = 0;
// Θέτει τις τιμές που θα σχεδιαστεί ο δίσκος (μέθοδος set)
//μέθοδος που θέτει συντεταγμένες στο 'πιόνι' που θα σχεδιαστεί
public void setXYCoordinates(int x, int y) {
xCoord = x;
yCoord = y;
}
//Επικάλυψη του painComponent και ζωγραφίζουμε σκακιέρα
public void paintComponent(Graphics g) {
super.paintComponent(g);
int sqSize1 = this.getWidth() / 8;
int sqSize2 = this.getHeight() / 8;
int sqSize = sqSize1;
if(sqSize2 < sqSize1)
sqSize = sqSize2;
for(int i=0; i<8; i++) {
for(int j=0; j<8; j++) {
int x = j * sqSize;
int y = i * sqSize;
//g.drawRect(x, y, sqSize, sqSize);
if( (i+j)%2 != 0) {
g.setColor(Color.BLUE);
g.fillRect(x, y, sqSize, sqSize);
}
else {
g.setColor(Color.RED);
g.fillRect(x, y, sqSize, sqSize);
}
}
}
//Σχεδίαση πιονιού. Αλλάζω το χρώμα της γραφίδας
//προκειται για οβάλ (κύκλος) που σχεδιάζεται εντός ορθογωνίου (τετραγώνου)
g.setColor(Color.GREEN);
// Ζωγραφίζω ένα οβάλ x,y εκεί που ξεκινάει και έχει μέγεθος ίσο με το μέγεθος του τετραγωνιδίου
// (sqSize/2 για να μην βγαίνει από σκακιέρα).
// η μετατόπιση κατά sqSize/2 γινεται ώστε το κλίκ να αντιστοιχεί στο κέντρο του κύκλου
g.fillOval(xCoord-sqSize/2, yCoord-sqSize/2, sqSize, sqSize);
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/Chess/src/GUI.java |
1,569 | import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
public class GUI extends JFrame{
private JPanel panel = new JPanel();
private JTextField input = new JTextField("add a name here");
private JButton addButton = new JButton("Add");
private JButton shuffleButton = new JButton("Shuffle");
// Δημιουργία λίστας
private JList list = new JList();
// Τροφοδοτεί την λίστα
private DefaultListModel<String> model = new DefaultListModel<>();
// Προσθήκη μπάρας κύλισης
private JScrollPane scrollPane;
public GUI(){
list.setModel(model); // Προσθέτω την δομή πάνω στην λίστα
scrollPane = new JScrollPane(list); // Περιτυλίγει το γραφικό συστατικό list
// Προσθέτω τα συστατικά στο panel
panel.add(input);
panel.add(addButton);
panel.add(scrollPane); // Βάζω την λίστα+την μπάρα κύλισης στο panel
panel.add(shuffleButton);
// Προσθέτω το panel στο παράθυρο
this.setContentPane(panel);
panel.setBackground(Color.GREEN); //Χρώμα παραθύρου
// Σύμπτυξη όλων των ενεργειών του Button
// Δημιουργία ButtonListener
// Συγγραφή actionPerformed
// Κατασκευή listener
// Σύνδεση listener με button
addButton.addActionListener(new ActionListener () {
@Override
public void actionPerformed(ActionEvent arg0) {
model.addElement(input.getText()); // Παίρνω ότι έχει πληκτρολογήσει ο χρήστης και το βάζει στην λίστα
}
});
// Ανώμνυμη κλάση ActionListener και πρέπει να φτιάξω την actionPerformed
shuffleButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
//Θέλω να ταξινομίσω την δομή λίστα (models) που δεν είναι τύπου λίστας
//Η μέθοδος elements επιστρέφει ένα enumeration interface και η .list μου κάνει το μοντέλο τύπο λίστας
//Πάντρεμα δομής σε μια άλλη
ArrayList<String> namesList = Collections.list(model.elements());
Collections.shuffle(namesList); // Αφού έγινε λίστα, μπορώ να εφαρμόσω μια μέθοδο shuffle
model.clear(); //καθαρισμός μοντέλου
// Ξαναβάζω τα στοιχεία ανακατεμένα
for(String name: namesList)
model.addElement(name);
}
});
this.setVisible(true);
this.setSize(400,400);
this.setTitle("Algorithms");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/DataStructures10_GUI/src/GUI.java |
1,570 |
public class Main {
public static void main(String[] args) {
// Εκκίνηση του παραθύρου. Δημιουργώ ανώνυμο αντικείμενο
new StudentFrame();
// Εναλλακτικά μπορώ να το δηλώσω και ως StudentFrame sf = new StudentFrame();
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/Students_7_12/src/Main.java |
1,571 | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class Main {
public static void main(String[] args) {
// Θα διαβάσουμε ένα αντικείμενο από ένα αρχείο, οπότε πρέπει να το δημιουργήσω αρχικά.
Employee e = null;
// Ανάγνωση αντικειμένου υπάλληλος από αρχείο
// Εμφανίζει exception οπότε try/catch
File file = new File("employee.ser"); // Αναπαράσταση του αρχείου δίσκου
try {
FileInputStream inputStream = new FileInputStream(file); // Το στέλνω για να το διαβάσει επειδή δεν μπορώ να το διαβάσω κατευθείαν
ObjectInputStream in = new ObjectInputStream(inputStream); // Επειδή δεν μπορώ να το διαβάσω bytε προς byte ο στέλνω για να διαβάσει ολόκληρα αντικείμενα
// Αναθέτω το αντικείμενο που διάβασα σε ένα αντικείμενο e (ΡΗΤΗ ΜΕΤΑΤΡΟΠΗ ΕΔΩ γιατί θεωρητικά δεν ξέρω τι επιστρέφει)
// Εμφανίζει exception (δεν μπορεί να καταλάβει την κλάση)
e = (Employee)in.readObject();
System.out.println("Object has been deserialized");
// Εκτυπώνω το όνομα
System.out.println("The retrieved employee object has name: " + e.getName());
// Κλείνω ρεύματα
in.close();
inputStream.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/BinaryFiles_v2/src/Main.java |
1,572 | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Φτιάψνω μια κενή λίστα που θα αποθηκεύσω την λίστα που θα διαβάσω από το αρχείο
ArrayList<Employee> employees = null;
// Ανάγνωση αντικειμένου υπάλληλος από αρχείο
// Εμφανίζει exception οπότε try/catch
File file = new File("Employees.ser"); // Αναπαράσταση του αρχείου δίσκου
try {
FileInputStream inputStream = new FileInputStream(file); // Το στέλνω για να το διαβάσει επειδή δεν μπορώ να το διαβάσω κατευθείαν
ObjectInputStream in = new ObjectInputStream(inputStream); // Επειδή δεν μπορώ να το διαβάσω bytε προς byte ο στέλνω για να διαβάσει ολόκληρα αντικείμενα
// Αναθέτω το αντικείμενο που διάβασα σε ένα αντικείμενο e (ΡΗΤΗ ΜΕΤΑΤΡΟΠΗ ΕΔΩ γιατί θεωρητικά δεν ξέρω τι επιστρέφει)
// Εμφανίζει exception (δεν μπορεί να καταλάβει την κλάση)
employees = (ArrayList<Employee>)in.readObject();
System.out.println("Object has been deserialized");
// Εκτυπώνω το όνομα
for(Employee e: employees){
System.out.println("The retrieved employee object has name: " + e.getName());
System.out.println("has the following car: ");
System.out.println(e.getCar().getDetails());
}
// Κλείνω ρεύματα
in.close();
inputStream.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/BinaryFiles_v6/src/Main.java |
1,573 | import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// Φτιάχνω μια κενή λίστα για να μπορεί να δεχτεί την ArrayList που θα διαβάσει από το αρχείο
ArrayList<Employee> employees = null;
// Ανάγνωση αντικειμένου υπάλληλος από αρχείο
// Εμφανίζει exception οπότε try/catch
File file = new File("Employees.ser"); // Αναπαράσταση του αρχείου δίσκου
try {
FileInputStream inputStream = new FileInputStream(file); // Το στέλνω για να το διαβάσει επειδή δεν μπορώ να το διαβάσω κατευθείαν
ObjectInputStream in = new ObjectInputStream(inputStream); // Επειδή δεν μπορώ να το διαβάσω bytε προς byte ο στέλνω για να διαβάσει ολόκληρα αντικείμενα
// Αναθέτω το αντικείμενο που διάβασα σε ένα αντικείμενο employees (ΡΗΤΗ ΜΕΤΑΤΡΟΠΗ ΕΔΩ γιατί θεωρητικά δεν ξέρω τι επιστρέφει)
// Εμφανίζει exception η readObject (δεν μπορεί να καταλάβει την κλάση)
employees = (ArrayList<Employee>)in.readObject();
System.out.println("Object has been deserialized");
// Εκτυπώνω το όνομα
for(Employee e: employees)
System.out.println("The retrieved employee object has name: " + e.getName());
// Κλείνω ρεύματα
in.close();
inputStream.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/BinaryFiles_v4/src/Main.java |
1,574 | // Φοιτητής: Ευστάθιος Ιωσηφίδης
// ΑΜ: iis21027
public class Main {
public static void main(String[] args){
// Μπορώ να πάρω τις τιμές από το πληκτρολόγιο
// Scanner in = new Scanner(System.in);
// System.out.println("Enter a Name: ");
// String name = in.nextLine();
// System.out.println("Enter some id: ");
// String id = in.nextLine();
// Student s1 = new Student(name,id);
// χρήση διαφορετικών κατασκευαστών
Student s1 = new Student("Babis", "ics20155");
Student s2 = new Student("Maria");
Student s3 = new Student();
// εκτύπωση αντικειμένων
s1.printInfo();
s2.printInfo();
s3.printInfo();
// Θέτω το όνομα σε ένα αντικείμενο Student
s3.setName("Takis");
s3.printInfo();
// Εκτυπώνω ΜΟΝΟ το όνομα του φοιτητή s1 λαμβάνοντάς το με την μέθοδο get
System.out.println(s1.getName());
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/University_2_11/src/Main.java |
1,576 |
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// 2η εργασία (Λόγω αρχής υποκατάστασης, βάζω στο ArrayList μόνο αναφορές Student)
ArrayList<Student> students = new ArrayList<>();
//Εισαγωγή φοιτητή με αλληλεπίδραση με τον χρήστη
boolean more = true;
while(more){
//Μέθοδος που εμφανίζει παράθυρο για εισαγωγή δεδομένων
//Η μέθοδο είναι static οπότε δεν χρειάστηκε να φτιάξω κλάση.
String name = JOptionPane.showInputDialog("Enter name: ");
String id = JOptionPane.showInputDialog("Enter id: ");
String answer = JOptionPane.showInputDialog("Type of Student: stud, grad, phd ");
//Αρχή της υποκατάστασης. Δηλώνω μια μεταβλητή, ώστε να βάλω μια student.add στο τέλος
Student student = null;
//Τι θα γίνει αν δεν δηλώσει ο χρήστης και δεν μπεί μέσα στις if; Δηλώνω null για αρχικοποίηση.
//Με else, τότε θα έμπαινε στην τελευταία οπότε δεν θα χρειαζόταν αρχικοποίηση
//Όταν συγκρίνω αντικείμενα κλάσεων, δεν μπορώ να χρησιμοποιήσω ==. Βλέπει μόνο αν είναι ίσες οι διευθύνσεις. Το == ΜΟΝΟ σε String
// Τι θα είναι ίσα στα αντικείμενα; Τα αντικείμενα έχουν πολλές μεταβλητές μέσα
//equalsIgnoreCase = ανεξάρτητα με το αν είναι κεφαλαία ή μικρά
//Εισάγω UnderGradStudent την νέα κλάση
if(answer.equals("stud")){
String yearText = JOptionPane.showInputDialog("Enter year: ");
//Μετατρέπω ένα κείμενο που έχει ακέραιο αριθμό και τον μετατρέπει ως μεταβλητή τύπου ακέραιο
int year = Integer.parseInt(yearText);
student = new UnderGradStudent(name, id, year);
}
if(answer.equals("grad")){
String supervisor = JOptionPane.showInputDialog("Supervisor: ");
student = new GraduateStudent(name, id, supervisor);
}
if(answer.equals("phd")){
String thesis = JOptionPane.showInputDialog("Thesis: ");
student = new PhDStudent(name, id, thesis);
}
students.add(student);
String another = JOptionPane.showInputDialog("Another student: yes, no");
if(another.equals("no")){
more = false;
}
}
//students = όνομα δομής δεδομένων που θέλω να τυπώσω.
//Student = τύπος δεδομενων μέσα στην δομή δεδομένων
//s = είναι αυθαίρετο όνομα. Είναι σαν το students.get(i)
for(Student s: students){
s.printInfo(); //** ΠΟΛΥΜΟΡΦΙΚΗ ΚΛΗΣΗ **//
}
for(Student s: students){
s.printType();
}
// //Καταχωρώ φοιτητές (δημιουργώ τα αντικείμενα και θέτω την αναφορά της ArrayList στο αντικείμενο φοιτητή)
// //OCP -> Εισάγω κλάσεις αλλά δεν πειράζω το πρόγραμμα της main πχ σε if ή for (ανοικτή κλειστή σχεδίαση)
// students.add(new Student("John", "ics19047"));
// students.add(new GraduateStudent("Mary", "mai20012", "Roberts"));
// students.add(new Student("Babis", "iis20113"));
// students.add(new PhDStudent("Helen", "phd123", "Software Quality"));
// for(int i=0 ; i<students.size(); i++){
// //ΔΥΝΑΜΙΚΗ ΔΙΑΣΥΝΔΕΣΗ. Ποιά printInfo είναι; --> ΠΟΛΥΜΟΡΦΙΣΜΟΣ (ανάλογα με τι είναι ο αποδέκτης, επιλέγεται το printInfo του και αποκρίνεται ανάλογα)
// students.get(i).printInfo();
// }
// //students = όνομα δομής δεδομένων που θέλω να τυπώσω.
// //Student = τύπος δεδομενων μέσα στην δομή δεδομένων
// //student = είναι αυθαίρετο όνομα. Είναι σαν το students.get(i)
// for(Student student: students){
// student.printInfo();
// }
//
// Student s1 = new Student("John", "ics20132");
//
// //Βάζω έναν GraduateStudent ως Student λόγω αρχής υποκατάστασης
// Student s2 = new GraduateStudent("Mary", "mai20098", "Nikolaou");
//
// // Στατική διασύνδεση με τον printInfo
// s1.printInfo();
//
// // ΔΥΝΑΜΙΚΗ ΔΙΑΣΥΝΔΕΣΗ ή ΚΑΘΥΣΤΕΡΗΜΕΝΗ ΔΙΑΣΥΝΔΕΣΗ. Την ώρα που διαβάζει, δεν ξέρει ποια μέθοδος θα κληθεί, την ώρα που τρέχει τον κώδικα αποφασίζει ποια μέθοδος θα κληθεί.
// s2.printInfo();
//
// //GraduateStudent gs1 = new GraduateStudent("Mary", "mai20098", "Nikolaou");
// //gs1.printInfo();
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/University_23_11/src/Main.java |
1,577 | package com.example.carpicker;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends AppCompatActivity {
// το ορίζουμε εδώ για να το δούν όλες οι μέθοδοι.
RadioGroup rg;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Δημιουργείται το radiogroup
rg = findViewById(R.id.modelPicker);
}
// Γράφουμε την μέθοδο για το τι θα κάνει το κουμπί όταν πατηθεί. Στα Attributes στο xml βάζω στο onClick αυτή τη μέθοδο
public void onClickPickBrand(View v){
// Δημιουργώ ένα νέο αντικείμενο που θέλω να γεμίσω με μοντέλα
CarPickerSelector cps = new CarPickerSelector();
// Φτιάχνω ένα αντικείμενο spinner. Επιλεγμένο αντικείμενο από την λίστα
Spinner sp = findViewById(R.id.brandList);
// Από το spinner παίρνω το επιλεγμένο αντικείμενο και το αποθηκεύω στο brand
String brand = sp.getSelectedItem().toString();
// Σύνδεση του GUI με την κλάση πρέπει να γίνει μέσα στην παρένθεση
List<String> mList = cps.getCars(brand);
// Πρέπει να περάσουμε τα μοντέλα στο GUI στο radiogroup
rg.removeAllViews(); // το αδειάζουμε
// κάνουμε έλεγχο αν είναι μια άδεια λίστα
if (mList.size() == 0){
// Αν είναι άδεια η λίστα να εμφανίζει ένα toast
Toast myToast = Toast.makeText(
getApplicationContext(),
"There are no models for this brand!",
Toast.LENGTH_LONG
);
myToast.show();
}
else{
// Μέθοδος που δέχεται το radiobutton και την λίστα που θέλουμε να προσθέσουμε. Την φτιάχνουμε στο main actiiviti
createRadioButtons(rg, mList);
// Φτιάχνω έναν Listener που θα τον υλοποιήσω εδώ μέσα
rg.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup radioGroup, int checkedID) {
// Φτιάχνω ένα αντικείμενο Radio button για να βρεί τι επέλεξα
RadioButton rb = findViewById(checkedID);
// εμφανίζει ένα toast με το μοντέλο που επιλέχθηκε
Toast myToast = Toast.makeText(
getApplicationContext(),
"The selected model is " + brand + " " + rb.getText(),
Toast.LENGTH_LONG
);
myToast.show();
}
}
);
}
}
// Μέθοδος που θα χρησιμοποιήσω παραπάνω. Δέχεται το radiobutton και την λίστα που θέλουμε να προσθέσουμε
private void createRadioButtons(RadioGroup rg, List<String> mList) {
int count = mList.size(); // Παίρνω το μέγεθος της λίστας. Αυτό μπορεί να μπει και κατευθείαν στην κάτω σειρά στις αγγύλες.
RadioButton rb[] = new RadioButton[count]; // Δημιουργώ ένα radio button (μέσα στην αγγύλη μπορώ να βάλω κατευθείαν το μέγεθος
// Κατασκευή του radiobutton
for (int i=0 ; i<mList.size(); i++){
rb[i] = new RadioButton(this); // Φτιάχνω ένα radio button ανάλογα με τι μέγεθος θα έχει η λίστα
rb[i].setText(mList.get(i)); // Προσθέτων το κείμενο που πήρα από την λίστα ως κείμενο σε radiobutton
rb[i].setId(i+100); // Βάζω ένα id γιατί πιθανό να το ψάξω με το id
rg.addView(rb[i]); // Το προσθέτω στο radiogroup
}
}
} | iosifidis/UoM-Applied-Informatics | s6/Mobile Application Developement/Java-XML-files/04 CarPicker_noOOP/MainActivity.java |
1,583 | 404: Not Found | io7m-com/smfj | com.io7m.smfj.tests/src/main/java/com/io7m/smfj/tests/core/SMFSchemaNameTest.java |
1,584 | 404: Not Found | io7m-com/smfj | com.io7m.smfj.tests/src/main/java/com/io7m/smfj/tests/core/SMFAttributeNameTest.java |
1,585 | /*
* Copyright (C) 2015 Google Inc.
*
* 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 benchmarks.regression;
import java.net.IDN;
public class IdnBenchmark {
public void timeToUnicode(int reps) {
for (int i = 0; i < reps; i++) {
IDN.toASCII("fass.de");
IDN.toASCII("faß.de");
IDN.toASCII("fäß.de");
IDN.toASCII("a\u200Cb");
IDN.toASCII("öbb.at");
IDN.toASCII("abc・日本.co.jp");
IDN.toASCII("日本.co.jp");
IDN.toASCII("x\u0327\u0301.de");
IDN.toASCII("σόλοσ.gr");
}
}
public void timeToAscii(int reps) {
for (int i = 0; i < reps; i++) {
IDN.toUnicode("xn--fss-qla.de");
IDN.toUnicode("xn--n00d.com");
IDN.toUnicode("xn--bb-eka.at");
IDN.toUnicode("xn--og-09a.de");
IDN.toUnicode("xn--53h.de");
IDN.toUnicode("xn--iny-zx5a.de");
IDN.toUnicode("xn--abc-rs4b422ycvb.co.jp");
IDN.toUnicode("xn--wgv71a.co.jp");
IDN.toUnicode("xn--x-xbb7i.de");
IDN.toUnicode("xn--wxaikc6b.gr");
IDN.toUnicode("xn--wxaikc6b.xn--gr-gtd9a1b0g.de");
}
}
}
| Reginer/aosp-android-jar | android-31/src/benchmarks/regression/IdnBenchmark.java |
1,586 | package UserClientV1;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Insets;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Path2D;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import javax.swing.event.PopupMenuEvent;
import javax.swing.event.PopupMenuListener;
import UserClientV1.Device.Unit;
/**
* Κλάση η οποία έχει κληρονομήσει ένα JPanel και που πρακτικά είναι υπεύθυνη
* να αναπαραστήσει με γραφικό τρόπο μια μονάδα .
* Δηλαδή με ένα μικρό σχετικά panel μπορεί ο χρήστης να δει όλες τις βασικές
* πληροφορίες μιας μονάδας όπως επίσης μπορεί να αλλάζει(ανάλογα βέβαια την κάθε
* περίπτωση) την τιμή και το mode της με απλό και γραφικό τρόπο με τη χρήση του ποντικιού.
* Επίσης μας επιτρέπει να υπάρχουν ομαδοποιημένα όλα αυτά που πρέπει για την
* απεικόνηση της κάθε μονάδας και έτσι να έχουμε καλύτερη διαχείρηση της .
* @author Michael Galliakis
*/
public class UnitControl extends javax.swing.JPanel {
private Double value ;
public boolean locked = false;
private boolean selected =false ;
public int mode ;
Point initPoint ;
boolean isSwitch ;
private Double dbLimit ;
private boolean isReadOnly ;
ImageIcon imIcOn ;
ImageIcon imIcOff ;
public Unit unit ;
/**
* Κατασκευαστής που προετοιμάζει κατάλληλα την κλάση μας ούτως ώστε να είναι
* έτοιμη να διαχειριστεί πλήρως τη γραφική αναπαράσταση της εκάστοτε μονάδας .
* @param u Ένα αντικείμενο τύπου {@link Unit} με το οποίο θα συσχετιστεί η κλάση μας.
* Δηλαδή η κλάση μας θα αφορά την ίδια μονάδα που αφορά και το αντικείμενο u .
*/
public UnitControl(Unit u) {
initComponents();
unit = u ;
if (Tools.isNumeric(u.getMode()))
setMode((int)Math.round(correctNum(u.getMode()))) ;
else
setMode(2) ;
if (unit.device.devAccess.equals("R"))
{
isReadOnly= true ;
bMode.setEnabled(false);
lAccess.setIcon(Globals.imNoHand);
}
else
{
if (this.mode ==0)
{
isReadOnly = true ;
lAccess.setIcon(Globals.imNoHand);
}
else
{
isReadOnly = false ;
lAccess.setIcon(Globals.imHand);
}
}
if (u.limit.contains("SW"))
{
isSwitch = true ;
lValue.setIcon(Globals.imSwitch);
lValue.setText("");
dbLimit = (Tools.isNumeric(u.limit.replace("SW", "")))?Double.parseDouble(u.limit.replace("SW", "")):null ;
}
else if (u.limit.contains("TB"))
{
isSwitch = false ;
dbLimit = (Tools.isNumeric(u.limit.replace("TB", "")))?Double.parseDouble(u.limit.replace("TB", "")):null ;
}
else
{
isSwitch = false ;
dbLimit = null ;
}
setDescription(unit.getFullID()) ;
setID(u.getFullID()) ;
setType(u.getType()) ; // Έχει σημασία να είναι πρώτο!
setValue(u.getValue()) ;
lAccess.setText("");
initPoint = new Point(this.getLocation());
PopClickListener pcl = new PopClickListener() ;
this.addMouseListener(pcl);
lID.addMouseListener(pcl);
lValue.addMouseListener(pcl);
lImage.addMouseListener(pcl);
setOpaque(false);
}
/**
* Μέθοδος που αλλάζει το description της μονάδας τόσο στην μεταβλητή της κλάσης
* όσο και στα toolTip που εμφανίζονται αν είναι λίγη ώρα το ποντίκι
* του χρήστη πάνω στο {@link UnitControl} μας .
* @param description Το νέο Description .
*/
public void setDescription(String description) {
lValue.setToolTipText(description);
lAccess.setToolTipText(description);
lID.setToolTipText(description);
lImage.setToolTipText(description);
}
/**
* Απλή get μέθοδος που επιστρέφει το mode της μονάδας .
* @return Το mode που έχει η μονάδα .
*/
public int getMode() {
return mode;
}
/**
* Μέθοδος που απλά αλλάζει το τύπο του {@link UnitControl} μας .
* Όπως βέβαια συγχρόνως και την εικόνα τύπου που έχει το panel μας.
* @param type Ένα λεκτικό που πρακτικά είναι ένας αριθμός που αναπαριστά το τύπο της μονάδας.
*/
public void setType(String type) {
fillTypeImage(type);
}
/**
* Static μέθοδος που απλά απο-επιλέγει όλα τα εικονίδια των μονάδων (παύουν
* δηλαδή να είναι πορτοκαλί)
* @param allPanels Μια λίστα με όλα τα {@link UnitControl} που θα απο-επιλεχθούν.
*/
public static void clearSelection(ArrayList<UnitControl> allPanels)
{
for (UnitControl p : allPanels)
{
p.setSelected(false);
p.setLocked(p.locked);
}
}
/**
* Ανάλογα την παράμετρο κάνει το εκάστοτε εικονίδιο μονάδας να είναι
* κλειδωμένο(γκρι) ή όχι(πράσινο) .
* @param locked Αν είναι True τότε "κλειδώνεται" αλλιώς αν False "ξεκλειδώνεται" .
*/
public void setLocked(boolean locked) {
this.locked = locked;
if (locked)
{
//this.setBorder(BorderFactory.createLoweredBevelBorder());
if (!selected)
this.setBackground(Globals.lockColor);
}
else
{
//this.setBorder(BorderFactory.createLineBorder(Color.black));
if (!selected)
this.setBackground(Globals.unLockColor);
}
}
/**
* Μέθοδος που αναλαμβάνει να φορτώνει την ανάλογη εικόνα-εικόνες(αν έχει 2 καταστάσεις
* ο τύπος) με βάση το τύπο .
* @param t Ένα λεκτικό που πρακτικά είναι ο αριθμός του τύπου της μονάδας .
*/
private void fillTypeImage(String t)
{
if (dbLimit!=null)
{
imIcOff = Globals.hmUnitImages.get("0" + t) ;
imIcOn = Globals.hmUnitImages.get("1" + t) ;
}
else
{
imIcOff = Globals.hmUnitImages.get("0" + t) ;
imIcOn = null ;
}
if (imIcOff!=null && imIcOn==null)
imIcOn = imIcOff ;
else if (imIcOff==null)
{
imIcOff = Globals.hmUnitImages.get("00") ;
dbLimit =null;
//imIcOn = Globals.hmUnitImages.get("00") ;
}
}
/**
* Μέθοδος που αναλαμβάνει να αλλάζει κατάλληλα το Mode με βάση τη τιμή της παράμετρου.
* Δηλαδή πέρα από την τιμή του mode που αλλάζει στην κλάση , αλλάζει και
* το κουμπί του mode πάνω στο {@link UnitControl} όπως επίσης και το λεκτικό
* του αντίστοιχου "φύλλου" που υπάρχει στο "δέντρο" αριστερά της καρτέλας της συσκευής .
* @param mode ένας αριθμός (από 0-4) για το νέο mode της μονάδας .
*/
public void setMode(int mode) {
this.mode = mode;
switch (mode)
{
case 0 :
bMode.setText("A"); //only Auto
bMode.setEnabled(false);
break ;
case 1 :
bMode.setText("R"); //only Remote
bMode.setEnabled(false);
break ;
case 2 :
bMode.setText("B"); //Both
bMode.setEnabled(false);
break ;
case 3 :
bMode.setText("A"); //Auto by User
bMode.setEnabled(!isReadOnly);
break ;
case 4 :
bMode.setText("R"); //Remote by User
bMode.setEnabled(!isReadOnly);
break ;
default :
bMode.setText("B"); //Both
bMode.setEnabled(false);
}
}
/**
* Μέθοδος που αναλαμβάνει να αλλάζει κατάλληλα το value με βάση τη τιμή της παραμέτρου.
* Δηλαδή πέρα από την τιμή του value που αλλάζει στην κλάση , αλλάζει και
* τη τιμή που φαίνεται πάνω στο {@link UnitControl} ή αν δεν είναι είδος switch .
* Επίσης αλλάζει και το λεκτικό του αντίστοιχου "φύλλου" που υπάρχει στο "δέντρο"
* αριστερά της καρτέλας της συσκευής .
* Ακόμη αν η μονάδα έχει limit και ο τύπος της είναι 2 καταστάσεων,
* αλλάζει και το εικονίδιο του τύπου (Πχ από ανοιχτή σε κλειστή λάμπα)
* @param val Ένα λεκτικό που θα μετατραπεί σε αριθμό για να αποδοθεί στο νέο Value
*/
public void setValue(String val) {
this.value = correctNum(val) ;
if (!isSwitch)
lValue.setText(String.valueOf(Math.round(value)));
if (dbLimit==null)
lImage.setIcon(imIcOff);
else
{
if (value>dbLimit)
lImage.setIcon(imIcOn);
else
lImage.setIcon(imIcOff);
}
}
/**
* Μέθοδος που απλά βρίσκει αν ένα λεκτικό είναι αριθμός ή όχι .
* @param sNum Ένα λεκτικό που θα ελεγχθεί αν είναι αριθμός.
* @return Τον ίδιο αριθμό αν το λεκτικό είναι έγκυρος αριθμός
* ή 0 αν δεν είναι έγκυρος αριθμός .
*/
private static double correctNum(String sNum)
{
double res ;
try {
res = Double.parseDouble(sNum);
}
catch (Exception ex)
{
//Nothing
return 0 ;
}
return res ;
}
/**
* Απλή set μέθοδος που εκτός από το να καταχωρεί το ID στην κλάση αλλάζει
* ανάλογα και το κείμενο στο label του ID .
* @param ID Συμβολοσειρά του νέου ID .
*/
public void setID(String ID) {
lID.setText(ID);
}
/**
* Μέθοδος που κάνει να είναι επιλεγμένο ή όχι το εκάστοτε {@link UnitControl}
* ανάλογα με τη τιμή στην παράμετρο .
* @param selected Αν True γίνεται το {@link UnitControl} μας επιλεγμένο αλλιώς
* αν False γίνεται το ανάποδο .
*/
public void setSelected(boolean selected) {
this.selected = selected;
if (selected)
{
this.setBackground(Globals.selectedColor);
}
else
this.setBackground((locked)?Globals.lockColor:Globals.unLockColor);
}
/**
* Απλά επιστρέφει το {@link Unit} με το οποίο είναι συσχετισμένο .
* @return Το {@link Unit} με το οποίο είναι συσχετισμένο .
*/
public Unit getUnit() {
return unit;
}
/**
* Συσχετίζεται το συγκεκριμένο {@link UnitControl} με το {@link BackgroundPanel} στο οποίο βρίσκεται .
* @param backPanel Το {@link BackgroundPanel} στο οποίο βρίσκεται το
* συγκεκριμένο {@link UnitControl} .
*/
public void setBackPanel(BackgroundPanel backPanel) {
unit.device.backPanel = backPanel;
}
/**
* Μέθοδος που απλά γίνεται override για να επιστρέφει διαφορετικό
* Insets από το Default .
* @return Insets με 10 απόσταση προς όλες τις πλευρές .
*/
@Override
public Insets getInsets() {
return new Insets(10, 10, 10,10);
}
/**
* Μέθοδος που εκτελείτε κάθε φορά που επαναζωγραφίζεται το panel.
* Όλος ο κώδικας που υπάρχει μέσα στο σώμα της μεθόδου απλά δίνει αυτό το
* ιδιαίτερο σχήμα στο {@link UnitControl}. Δηλαδή αυτή την πολύγωνη μορφή
* αντί της κλασικής τετράγωνης .
* @param g Το Default Graphics αντικείμενο που έχει το συγκεκριμένο event το οποίο
* χρησιμοποιούμε για να αλλάξουμε το πίσω σχήμα του panel μας .
*/
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
int width = getWidth() - 1;
int height = getHeight() - 1;
int radius = Math.min(width, height) / 10;
Path2D p = new Path2D.Float();
p.moveTo(0, radius / 2);
p.curveTo(0, 0, 0, 0, radius / 2, 0);
p.curveTo(width / 4, radius, width / 4, radius, (width / 2) - radius, radius / 2);
p.curveTo(width / 2, 0, width / 2, 0, (width / 2) + radius, radius / 2);
p.curveTo(width - (width / 4), radius, width - (width / 4), radius, width - (radius / 2), 0);
p.curveTo(width, 0, width, 0, width, radius / 2);
p.curveTo(width - radius, height / 4, width - radius, height / 4, width - (radius / 2), (height / 2) - radius);
p.curveTo(width, height / 2, width, height / 2, width - (radius / 2), (height / 2) + radius);
p.curveTo(width - radius, height - (height / 4), width - radius, height - (height / 4), width, height - (radius / 2));
p.curveTo(width, height, width, height, width - (radius / 2), height);
p.curveTo(width - (width / 4), height - radius, width - (width / 4), height - radius, (width / 2) + radius, height - (radius / 2));
p.curveTo(width / 2, height, width / 2, height, (width / 2) - radius, height - (radius / 2));
p.curveTo((width / 4), height - radius, (width / 4), height - radius, (radius / 2), height);
p.curveTo(0, height, 0, height, 0, height - (radius / 2));
p.curveTo(radius, height - (height / 4), radius, height - (height / 4), (radius / 2), (height / 2) + radius);
p.curveTo(0, height / 2, 0, height / 2, (radius / 2), (height / 2) - radius);
p.curveTo(radius, (height / 4), radius, (height / 4), 0, (radius / 2));
p.closePath();
Graphics2D g2d = (Graphics2D) g.create();
g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
g2d.setColor(getBackground());
g2d.fill(p);
g2d.dispose();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
lID = new javax.swing.JLabel();
lImage = new javax.swing.JLabel();
lValue = new javax.swing.JLabel();
lAccess = new javax.swing.JLabel();
bMode = new javax.swing.JButton();
setName(""); // NOI18N
setPreferredSize(new java.awt.Dimension(74, 88));
addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseMoved(java.awt.event.MouseEvent evt) {
formMouseMoved(evt);
}
public void mouseDragged(java.awt.event.MouseEvent evt) {
formMouseDragged(evt);
}
});
addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
formMouseClicked(evt);
}
});
lID.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
lID.setText("1/2/0");
lID.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
lIDMouseDragged(evt);
}
});
lID.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lIDMouseClicked(evt);
}
});
lImage.setText(" ");
lImage.setToolTipText("");
lImage.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
lImageMouseDragged(evt);
}
});
lImage.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lImageMouseClicked(evt);
}
});
lValue.setText("52%");
lValue.setToolTipText("");
lValue.addMouseMotionListener(new java.awt.event.MouseMotionAdapter() {
public void mouseDragged(java.awt.event.MouseEvent evt) {
lValueMouseDragged(evt);
}
});
lValue.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
lValueMouseClicked(evt);
}
});
lAccess.setText("A");
lAccess.setToolTipText("");
bMode.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
bMode.setText("R");
bMode.setFocusPainted(false);
bMode.setFocusable(false);
bMode.setMargin(new java.awt.Insets(0, 0, 0, 0));
bMode.setMaximumSize(new java.awt.Dimension(18, 18));
bMode.setMinimumSize(new java.awt.Dimension(18, 18));
bMode.setPreferredSize(new java.awt.Dimension(18, 18));
bMode.setVerifyInputWhenFocusTarget(false);
bMode.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bModeMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lAccess)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lValue)
.addContainerGap())
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(3, 3, 3)
.addComponent(lID)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(lImage, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(0, 0, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lID)
.addComponent(bMode, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lImage, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lValue, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lAccess))
.addContainerGap())
);
getAccessibleContext().setAccessibleDescription("");
}// </editor-fold>//GEN-END:initComponents
/**
* Μέθοδος που αναλαμβάνει να κάνει όλη την απαραίτητη διαδικασία
* όταν ο χρήστης "κλικάρει" ένα "εικονίδιο" μονάδας .
* Στο ένα μόνο συνεχόμενο "κλικ" επιλέγεται(γίνεται πορτοκαλί) το εικονίδιο
* μονάδας .
* Αν κάνει ο χρήστης 2 συνεχόμενα "κλικ" τότε αν ο χρήστης έχει δικαίωμα
* να αλλάξει την τιμή της μονάδας (Και βέβαια είναι ενεργή η εποπτεία στην συσκευή)
* αλλάζει την τιμή της μονάδας .
* Η αλλαγή μπορεί να γίνει είτε άμεσα αν η μονάδα είναι ρυθμισμένη να είναι
* τύπου "switch" ή αλλιώς ανοίγει το {@link DfChangeValue} .
* @param evt Default MouseEvent αντικείμενο το οποίο το χρησιμοποιούμε
* για να βρούμε πόσα "κλικ" έχει πατήσει ο χρήστης .
*/
private void clickedProcess(java.awt.event.MouseEvent evt)
{
if (evt.getClickCount()==1)
{
clearSelection(unit.device.getAllControls()) ;
unit.setSelectedNode();
if (!selected)
setSelected(true) ;
}
else
{
if (!isReadOnly && unit.device.myPTab.isConnected)
{
if (dbLimit==null)
{
new DfChangeValue( true, value, this).setVisible(true); ;
}
else
{
if (isSwitch)
{
if (value>dbLimit)
setValue(String.valueOf(unit.min));
else
setValue(String.valueOf(unit.max));
if (mode == 3)
{
setMode(4) ;
unit.setMode(String.valueOf(mode));
unit.device.changeRemoteMode(unit.getFullMode());
}
unit.setValue(String.valueOf(value));
unit.device.changeRemoteValue(unit.getFullValue());
}
else
new DfChangeValue( true, value, this).setVisible(true);
}
}
}
}
/**
* Μέθοδος που αναλαμβάνει να κάνει όλη την απαραίτητη διαδικασία
* όταν ο χρήστης αρπάξει ένα "εικονίδιο" μονάδας και αρχίσει να το
* μεταφέρει .
* Αρχικά κάνει επιλεγμένο-πορτοκαλί το εικονίδιο μονάδας και στην συνέχεια
* αν δεν είναι "κλειδωμένο" το {@link UnitControl} το μεταφέρει μέσα στο
* χώρο ανάλογα με την κίνηση του ποντικιού .
* @param evt Default MouseEvent αντικείμενο το οποίο το χρησιμοποιούμε
* για να βρούμε αν ο χρήστης έχει πατήσει το αριστερό κλικ .
*/
private void draggedProcess(java.awt.event.MouseEvent evt)
{
if (!selected)
{
clearSelection(unit.device.getAllControls()) ;
unit.setSelectedNode();
setSelected(true) ;
}
if (!locked)
{
if (SwingUtilities.isLeftMouseButton(evt))
{
Point p = MouseInfo.getPointerInfo().getLocation() ;
p.x -= unit.device.backPanel.getLocationOnScreen().x + (this.size().getWidth()/2);
p.y -= unit.device.backPanel.getLocationOnScreen().y+ (this.size().getHeight()/2);
if (p.x<0) p.x = 0 ;
if (p.y<0) p.y = 0 ;
if (p.y> unit.device.backPanel.size().height-this.size().height) p.y = unit.device.backPanel.size().height-this.size().height ;
if (p.x> unit.device.backPanel.size().width-this.size().width) p.x = unit.device.backPanel.size().width-this.size().width ;
this.setLocation(p);
}
}
}
/**
* Μέθοδος που μεταφέρει ένα {@link UnitControl} μέσα στο οπτικό πεδίο του
* χρήστη αν για κάποιο λόγο δεν του εμφανίζεται το εικονίδιο μονάδας , πχ μετά
* από κάποιο resize του κεντρικού παραθύρου του User Client .
*/
public void fixToResize()
{
Point p = this.getLocation() ;
if (p.x<0) p.x = 0 ;
if (p.y<0) p.y = 0 ;
if (p.y> unit.device.backPanel.size().height-this.size().height) p.y = unit.device.backPanel.size().height-this.size().height ;
if (p.x> unit.device.backPanel.size().width-this.size().width) p.x = unit.device.backPanel.size().width-this.size().width ;
this.setLocation(p);
}
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το panel μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο clickedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην clickedProcess.
*/
private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
clickedProcess(evt) ;
}//GEN-LAST:event_formMouseClicked
/**
* Μέθοδος που εκτελείτε όταν τραβήξει-αρπάξει ο χρήστης το panel μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο draggedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην draggedProcess.
*/
private void formMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseDragged
draggedProcess(evt) ;
}//GEN-LAST:event_formMouseDragged
private void formMouseMoved(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseMoved
}//GEN-LAST:event_formMouseMoved
/**
* Μέθοδος που εκτελείτε όταν τραβήξει-αρπάξει ο χρήστης το label της εικόνας μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο draggedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην draggedProcess.
*/
private void lImageMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lImageMouseDragged
draggedProcess(evt) ;
}//GEN-LAST:event_lImageMouseDragged
/**
* Μέθοδος που εκτελείτε όταν τραβήξει-αρπάξει ο χρήστης το label του value μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο draggedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην draggedProcess.
*/
private void lValueMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lValueMouseDragged
draggedProcess(evt) ;
}//GEN-LAST:event_lValueMouseDragged
/**
* Μέθοδος που εκτελείτε όταν τραβήξει-αρπάξει ο χρήστης το label του ID μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο draggedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην draggedProcess.
*/
private void lIDMouseDragged(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lIDMouseDragged
draggedProcess(evt) ;
}//GEN-LAST:event_lIDMouseDragged
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το label του ID μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο clickedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην clickedProcess.
*/
private void lIDMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lIDMouseClicked
clickedProcess(evt) ;
}//GEN-LAST:event_lIDMouseClicked
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το label της εικόνας μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο clickedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην clickedProcess.
*/
private void lImageMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lImageMouseClicked
clickedProcess(evt) ;
}//GEN-LAST:event_lImageMouseClicked
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το label του Value μας
* Ο σκοπός του είναι να εκτελεί την μέθοδο clickedProcess .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην clickedProcess.
*/
private void lValueMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lValueMouseClicked
clickedProcess(evt) ;
}//GEN-LAST:event_lValueMouseClicked
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί του Mode μας
* Ο σκοπός του είναι να αλλάζει το mode με το αντίθετο του , δηλαδή από Remote
* σε Auto και το αντίστροφο , αν βέβαια το επιτρέπει η αρχική ρύθμιση της μονάδας .
* Αλλάζει το mode τόσο στο πρόγραμμα μας όσο και στην ίδια την συσκευή όπως επίσης
* και σε όλους τους απομακρυσμένους UserClints που μπορεί να έχουν και αυτοί την ίδια
* στιγμή εποπτεία πραγματικού χρόνου (μέσω του Server).
* @param evt Το Default MouseEvent αντικείμενο το οποίο στην περίπτωση μας
* δεν χρησιμοποιείται .
*/
private void bModeMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bModeMouseClicked
if (unit.device.myPTab.isConnected)
{
if (bMode.isEnabled())
{
if (mode==3)
setMode(4);
else if (mode ==4)
setMode(3);
unit.setMode(String.valueOf(mode));
unit.device.changeRemoteMode(unit.getFullMode());
}
}
}//GEN-LAST:event_bModeMouseClicked
/**
* Κλάση η οποία έχει κληρονομήσει την MouseAdapter και που πρακτικά
* την φτιάξαμε με απώτερο σκοπό να έχουμε στο panel (και σε όλα τα αντικείμενα
* που είναι πάνω του) μενού αν πατήσουμε δεξί "κλικ" .
* Και πιο συγκεκριμένα για να μπορούμε να κλειδώνουμε σε κάποια θέση το
* εκάστοτε {@link UnitControl} ή αντίστοιχα να το ξεκλειδώνουμε .
*/
class PopClickListener extends MouseAdapter {
/**
* Μέθοδος που εκτελείται αν πατήσει ο χρήστης κάποιο πλήκτρο του ποντικιού.
* @param e Default MouseEvent αντικείμενο που το χρησιμοποιούμε
* για να δούμε αν είναι Popup ο trigger .
*/
@Override
public void mousePressed(MouseEvent e){
if (e.isPopupTrigger())
doPop(e);
}
/**
* Μέθοδος που εκτελείται αν σταματήσει να πατάει ο χρήστης κάποιο πλήκτρο του ποντικιού.
* @param e Default MouseEvent αντικείμενο που το χρησιμοποιούμε
* για να δούμε αν είναι Popup ο trigger .
*/
@Override
public void mouseReleased(MouseEvent e){
if (e.isPopupTrigger())
doPop(e);
}
/**
* Μέθοδος που φτιάχνει ένα custom JPopupMenu ({@link MyPopUpMenu}) και το εμφανίζει.
* @param e Default MouseEvent αντικείμενο που το χρησιμοποιούμε
* με σκοπό να αξιοποιήσουμε το Component του όπως και τη Χ και Y θέση του.
*/
private void doPop(MouseEvent e){
MyPopUpMenu menu = new MyPopUpMenu();
menu.show(e.getComponent(), e.getX(), e.getY());
}
}
/**
* Κλάση η οποία έχει κληρονομήσει την JPopupMenu και σκοπό έχει
* να φτιάξουμε κατάλληλα ένα δικό μας popup menu που θα εμφανίζεται όταν
* ο χρήστης κάνει δεξί "κλικ" πάνω στο {@link UnitControl} και ουσιαστικά
* για να μπορεί ο χρήστης να "κλειδώνει" ή να "ξεκλειδώνει" το "εικονίδιο" μονάδας.
*/
class MyPopUpMenu extends JPopupMenu {
JMenuItem anItem,anItem2;
/**
* Κατασκευαστής που απλά κάνει όλες τις απαραίτητες ενέργειες για να
* αρχικοποιήσει το αντικείμενο στην ώρα εκτέλεσης .
*/
public MyPopUpMenu(){
anItem = new JMenuItem("Unlocked!");
anItem2 = new JMenuItem("Locked!");
add(anItem);
add(anItem2);
anItem.addMouseListener(new customMousePopUpListener());
anItem2.addMouseListener(new customMousePopUpListener());
/**
* Άμεση δημιουργία προγραμματιστικά ενός PopupMenuListener
*/
this.addPopupMenuListener(new PopupMenuListener() {
/**
* Μέθοδος που εκτελείτε λίγο πριν πάει να εμφανιστεί το μενού.
* Πρακτικά κρύβει την επιλογή να ξεκλειδωθεί το {@link UnitControl}
* αν είναι ξεκλείδωτο και το ανάποδο .
* @param e Ένα Default PopupMenuEvent αντικείμενο το οποίο δεν
* το χρησιμοποιούμε .
*/
@Override
public void popupMenuWillBecomeVisible(PopupMenuEvent pme) {
if (locked)
{
anItem.setVisible(true);
anItem2.setVisible(false);
}
else
{
anItem.setVisible(false);
anItem2.setVisible(true);
}
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param pme Ένα Default PopupMenuEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void popupMenuWillBecomeInvisible(PopupMenuEvent pme) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param pme Ένα Default PopupMenuEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void popupMenuCanceled(PopupMenuEvent pme) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
}
}
class customMousePopUpListener implements MouseListener
{
/**
* Μέθοδος που εκτελείτε όταν ο χρήστης αφήσει κάποιο κουμπί του
* ποντικιού που είχε πατημένο .
* Ουσιαστικά αλλάζει την κατάσταση του "κλειδώματος" με το ανάποδο
* δηλαδή αν είναι κλειδωμένο το {@link UnitControl} το ξεκλειδώνει και το ανάποδο .
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν
* το χρησιμοποιούμε .
*/
@Override
public void mouseReleased(MouseEvent me) {
setLocked(!locked);
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseEntered(MouseEvent me) {
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseExited(MouseEvent me) {
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mousePressed(MouseEvent me) {
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseClicked(MouseEvent me) {
}
}
/*
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null); // see javadoc for more info on the parameters
}
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bMode;
private javax.swing.JLabel lAccess;
private javax.swing.JLabel lID;
private javax.swing.JLabel lImage;
private javax.swing.JLabel lValue;
// End of variables declaration//GEN-END:variables
}
/*
* * * * * * * * * * * * * * * * * * * * * * *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| P P P P M M M M G G G G |+ *
* +| P P M M M M G G |+ *
* +| P P P p M M M M G |+ *
* +| P M M M G G G G |+ *
* +| P M M G G |+ *
* +| P ® M M ® G G G G |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + .----. @ @ |+ *
* + / .-"-.`. \v/ |+ *
* + | | '\ \ \_/ ) |+ *
* + ,-\ `-.' /.' / |+ *
* + '---`----'----' |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| Thesis Michael Galliakis 2016 |+ *
* +| Program m_g ; -) [email protected] |+ *
* +| TEI Athens - IT department. |+ *
* +| [email protected] |+ *
* +| https://github.com/michaelgalliakis |+ *
* +| (myThesis.git) |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* * * * * * * * * * * * * * * * * * * * * * *
*/ | michaelgalliakis/myThesis | UserClientV1/src/UserClientV1/UnitControl.java |
1,587 | package org.unicode.jsp;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
import org.unicode.text.utility.Settings;
import org.unicode.text.utility.Settings.ReleasePhase;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result =
result.replaceAll("⇑⇑", "<u>")
.replaceAll("⇓⇓", "</u>")
.replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
*
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
// String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat).addRules("$root=" + regex + ";").complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line"))
b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence"))
b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start, decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
// piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece =
piece.replaceAll("
", "<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString();
}
public static void showProperties(
int cp, String history, boolean showDevProperties, Appendable out) throws IOException {
showDevProperties = Settings.latestVersionPhase == ReleasePhase.BETA || showDevProperties;
UnicodeUtilities.showProperties(cp, history, showDevProperties, out);
}
static String defaultIdnaInput =
""
+ "fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+ "\nöbb.at ÖBB.at ÖBB.at"
+ "\nȡog.de ☕.de I♥NY.de"
+ "\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+ "\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+ "\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+ "\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(
String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
// setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(
String grouping,
String info,
UnicodeSet a,
boolean showDevProperties,
boolean abbreviate,
boolean ucdFormat,
boolean collate,
Appendable out)
throws IOException {
showDevProperties = Settings.latestVersionPhase == ReleasePhase.BETA || showDevProperties;
CodePointShower codePointShower =
new CodePointShower(
grouping, info, showDevProperties, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, showDevProperties, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink)
throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(
String setA,
String setB,
boolean abbreviate,
String[] abResults,
int[] abSizes,
String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int[] parseCode(String text, String nextButton, String previousButton) {
// text = fromHTML.transliterate(text);
String trimmed = text.trim();
// Accept U+ notation and standalone hexadecimal digits, as well as a variety
// of hexadecimal character escape and numeric literal syntaxes.
Matcher matcher =
Pattern.compile(
"(?:U\\+|\\\\[ux]\\{?|&#x|0x|16#|&H)?([0-9a-f'_]+)[\\};#]?",
Pattern.CASE_INSENSITIVE)
.matcher(trimmed);
String digits = matcher.matches() ? matcher.group(1).replaceAll("['_]", "") : null;
if (digits != null && digits.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(digits, 16));
} catch (Exception e) {
}
}
int[] result = text.codePoints().toArray();
int cp = result[0];
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
return new int[] {cp};
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
return new int[] {cp};
}
return result;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(
new UnicodeSet(Uts46.SINGLETON.validSet_transitional)
.retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(
String test,
boolean nfkcCheck,
boolean scriptCheck,
boolean idCheck,
boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100 / max) + "%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append(
"<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append("<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append(
"<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script, boolean showDevProperties) {
showDevProperties = Settings.latestVersionPhase == ReleasePhase.BETA || showDevProperties;
return UnicodeUtilities.getIdentifier(script, showDevProperties);
}
static final String VERSIONS =
"Version 3.9; "
+ "ICU version: "
+ VersionInfo.ICU_VERSION.getVersionString(2, 2)
+ "; "
+ "Unicode/Emoji version: "
+ Settings.lastVersion
+ "; "
+ (Settings.latestVersionPhase == ReleasePhase.BETA
? "Unicodeβ version: " + Settings.latestVersion + "; "
: "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD =
Settings.latestVersionPhase == ReleasePhase.BETA
? "<p style='border: 1pt solid red;'>Unmarked properties are from Unicode V"
+ Settings.lastVersion
+ "; the beta properties are from Unicode V"
+ Settings.latestVersion
+ "β. "
+ "For more information, see <a target='help' href='https://unicode-org.github.io/unicodetools/help/changes'>Unicode Utilities Beta</a>.</p>"
: "";
public static String getSubtitle() {
return SUBHEAD;
}
}
| unicode-org/unicodetools | UnicodeJsps/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,590 | package ontology;
import utils.HelperMethods;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDFS;
/**
* @author G. Razis
*/
public class OntologyInitialization {
HelperMethods hm = new HelperMethods();
/**
* Add the necessary prefixes to the model we are currently
* working with.
*
* @param Model the model we are currently working with
*/
public void setPrefixes(Model model) {
model.setNsPrefix("elod", Ontology.eLodPrefix);
model.setNsPrefix("elodGeo", Ontology.elodGeoPrefix);
model.setNsPrefix("pc", Ontology.publicContractsPrefix);
model.setNsPrefix("skos", Ontology.skosPrefix);
model.setNsPrefix("gr", Ontology.goodRelationsPrefix);
model.setNsPrefix("rov", Ontology.regOrgPrefix);
model.setNsPrefix("org", Ontology.orgPrefix);
model.setNsPrefix("foaf", Ontology.foafPrefix);
model.setNsPrefix("xsd", Ontology.xsdPrefix);
model.setNsPrefix("dcterms", Ontology.dctermsPrefix);
model.setNsPrefix("dc", Ontology.dcPrefix);
model.setNsPrefix("pcdt", Ontology.pcdtPrefix);
model.setNsPrefix("vcard", Ontology.vcardPrefix);
}
/**
* Create the basic hierarchies of the OWL classes and their labels
* to the model we are currently working with.
*
* @param Model the model we are currently working with
*/
public void createHierarchies(Model model) {
//Agent
model.add(Ontology.agentResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.agentResource, RDFS.label, model.createLiteral("Agent", "en"));
model.add(Ontology.agentResource, RDFS.label, model.createLiteral("Πράκτορας", "el"));
//Concept
model.add(Ontology.conceptResource, RDFS.subClassOf, OWL.Thing);
//Concept Scheme
model.add(Ontology.conceptSchemeResource, RDFS.subClassOf, OWL.Thing);
//Concept - Vat Type
model.add(Ontology.vatTypeResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.vatTypeResource, RDFS.label, model.createLiteral("VAT Type", "en"));
model.add(Ontology.vatTypeResource, RDFS.label, model.createLiteral("Τύπος ΑΦΜ", "el"));
//Concept - Thematic Category
model.add(Ontology.thematicCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.thematicCategoryResource, RDFS.label, model.createLiteral("Thematic Category Type", "en"));
model.add(Ontology.thematicCategoryResource, RDFS.label, model.createLiteral("Τύπος Θεματικής Κατηγορίας", "el"));
//Concept - Role
model.add(Ontology.roleResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.roleResource, RDFS.label, model.createLiteral("Role", "en"));
model.add(Ontology.roleResource, RDFS.label, model.createLiteral("Ρόλος", "el"));
//Concept - Country
model.add(Ontology.countryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.countryResource, RDFS.label, model.createLiteral("Country", "en"));
model.add(Ontology.countryResource, RDFS.label, model.createLiteral("Χώρα", "el"));
//Concept - Currency
model.add(Ontology.currencyResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.currencyResource, RDFS.label, model.createLiteral("Currency", "en"));
model.add(Ontology.currencyResource, RDFS.label, model.createLiteral("Νόμισμα", "el"));
//Concept - Organizational Unit Category
model.add(Ontology.orgUnitCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.orgUnitCategoryResource, RDFS.label, model.createLiteral("Organizational Unit Category", "en"));
model.add(Ontology.orgUnitCategoryResource, RDFS.label, model.createLiteral("Τύποι Οργανωτικών Μονάδων", "el"));
//Concept - Organization Domain
model.add(Ontology.organizationDomainResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationDomainResource, RDFS.label, model.createLiteral("Organization Domain", "en"));
model.add(Ontology.organizationDomainResource, RDFS.label, model.createLiteral("Πεδίο Αρμοδιότητας Φορέων", "el"));
//Concept - Organization Status
model.add(Ontology.organizationStatusResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationStatusResource, RDFS.label, model.createLiteral("Organization Status", "en"));
model.add(Ontology.organizationStatusResource, RDFS.label, model.createLiteral("Κατάσταση Οργανισμού", "el"));
//Concept - Organization Category
model.add(Ontology.organizationCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationCategoryResource, RDFS.label, model.createLiteral("Organization Category", "en"));
model.add(Ontology.organizationCategoryResource, RDFS.label, model.createLiteral("Κατηγορίες Φορέων", "el"));
//Concept - Decision Status
model.add(Ontology.decisionStatusResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.decisionStatusResource, RDFS.label, model.createLiteral("Decision Status", "en"));
model.add(Ontology.decisionStatusResource, RDFS.label, model.createLiteral("Κατάσταση Πράξης", "el"));
//Concept - Selection Criterion
model.add(Ontology.selectionCriterionResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.selectionCriterionResource, RDFS.label, model.createLiteral("Selection Criterion", "en"));
model.add(Ontology.selectionCriterionResource, RDFS.label, model.createLiteral("Κριτήριο Επιλογής", "el"));
//Concept - Budget Category
model.add(Ontology.budgetCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.budgetCategoryResource, RDFS.label, model.createLiteral("Budget Category", "en"));
model.add(Ontology.budgetCategoryResource, RDFS.label, model.createLiteral("Κατηγορία Προϋπολογισμού", "el"));
//Fek Type
model.add(Ontology.fekTypeResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.fekTypeResource, RDFS.label, model.createLiteral("Greek Government Gazzette Issue Type ", "en"));
model.add(Ontology.fekTypeResource, RDFS.label, model.createLiteral("Τύπος Τεύχους Φύλλου Εφημερίδος Κυβερνήσεως", "el"));
//Agent - Business Entity
model.add(Ontology.businessEntityResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.businessEntityResource, RDFS.label, model.createLiteral("Business Entity", "en"));
model.add(Ontology.businessEntityResource, RDFS.label, model.createLiteral("Επιχειρηματική Οντότητα", "el"));
//Agent - Registered Organization
model.add(Ontology.registeredOrganizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.registeredOrganizationResource, RDFS.label, model.createLiteral("Registered Organization", "en"));
model.add(Ontology.registeredOrganizationResource, RDFS.label, model.createLiteral("Καταχωρημένος Οργανισμός", "el"));
//Agent - Organization (FOAF)
model.add(Ontology.organizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
//Agent - Organization (org)
model.add(Ontology.orgOrganizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.orgOrganizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.orgOrganizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
//Orgs equivalence
/*model.add(Ontology.businessEntityResource, OWL.equivalentClass, Ontology.registeredOrganizationResource);
model.add(Ontology.businessEntityResource, OWL.equivalentClass, Ontology.organizationResource);
model.add(Ontology.businessEntityResource, OWL.equivalentClass, Ontology.orgOrganizationResource);
model.add(Ontology.registeredOrganizationResource, OWL.equivalentClass, Ontology.organizationResource);
model.add(Ontology.registeredOrganizationResource, OWL.equivalentClass, Ontology.orgOrganizationResource);
model.add(Ontology.organizationResource, OWL.equivalentClass, Ontology.orgOrganizationResource);*/
//Agent - Person
model.add(Ontology.personResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.personResource, RDFS.label, model.createLiteral("Person", "en"));
model.add(Ontology.personResource, RDFS.label, model.createLiteral("Πρόσωπο", "el"));
//Agent - Organization
model.add(Ontology.organizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
//Agent - Organizational Unit
model.add(Ontology.organizationalUnitResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationalUnitResource, RDFS.label, model.createLiteral("Organizational Unit", "en"));
model.add(Ontology.organizationalUnitResource, RDFS.label, model.createLiteral("Μονάδα Οργανισμού", "el"));
//Spending Item
model.add(Ontology.spendingItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.spendingItemResource, RDFS.label, model.createLiteral("Spending Item", "en"));
model.add(Ontology.spendingItemResource, RDFS.label, model.createLiteral("Αντικείμενο Δαπάνης", "el"));
//Award Criteria Combination
model.add(Ontology.awardCriteriaCombinationResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.awardCriteriaCombinationResource, RDFS.label, model.createLiteral("Combination of Contract Award Criteria", "en"));
model.add(Ontology.awardCriteriaCombinationResource, RDFS.label, model.createLiteral("Συνδυασμός των Κριτηρίων Ανάθεσης της Σύμβασης", "el"));
//Criterion Weighting
model.add(Ontology.criterionWeightingResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.criterionWeightingResource, RDFS.label, model.createLiteral("Award Criterion", "en"));
model.add(Ontology.criterionWeightingResource, RDFS.label, model.createLiteral("Κριτήριο Ανάθεσης", "el"));
//Contract
model.add(Ontology.contractResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.contractResource, RDFS.label, model.createLiteral("Public Contract", "en"));
model.add(Ontology.contractResource, RDFS.label, model.createLiteral("Δημόσια Σύμβαση", "el"));
//CPV
model.add(Ontology.cpvResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.cpvResource, RDFS.label, model.createLiteral("Common Procurement Vocabulary", "en"));
model.add(Ontology.cpvResource, RDFS.label, model.createLiteral("Κοινό Λεξιλόγιο Προμηθειών", "el"));
//Attachment
model.add(Ontology.attachmentResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.attachmentResource, RDFS.label, model.createLiteral("Attachments", "en"));
model.add(Ontology.attachmentResource, RDFS.label, model.createLiteral("Συνημμένα Έγγραφα", "el"));
//Decision
model.add(Ontology.decisionResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.decisionResource, RDFS.label, model.createLiteral("Decision", "en"));
model.add(Ontology.decisionResource, RDFS.label, model.createLiteral("Πράξη", "el"));
//Committed Amount
model.add(Ontology.committedItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.committedItemResource, RDFS.label, model.createLiteral("Committed Item", "en"));
model.add(Ontology.committedItemResource, RDFS.label, model.createLiteral("Δεσμευθέν Αντικείμενο", "el"));
//Expenditure Line
model.add(Ontology.expenditureLineResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.expenditureLineResource, RDFS.label, model.createLiteral("Expenditure Line", "en"));
model.add(Ontology.expenditureLineResource, RDFS.label, model.createLiteral("Τμήμα Δαπάνης", "el"));
//Expense Approval Item
model.add(Ontology.expenseApprovalItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.expenseApprovalItemResource, RDFS.label, model.createLiteral("Expense Approval", "en"));
model.add(Ontology.expenseApprovalItemResource, RDFS.label, model.createLiteral("Έγκριση Δαπάνης", "el"));
//FEK
model.add(Ontology.fekResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.fekResource, RDFS.label, model.createLiteral("Greek Government Gazzette", "en"));
model.add(Ontology.fekResource, RDFS.label, model.createLiteral("Φύλλο Εφημερίδος Κυβερνήσεως", "el"));
//KAE
model.add(Ontology.kaeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.kaeResource, RDFS.label, model.createLiteral("Code Number of Revenues/Expenses", "en"));
model.add(Ontology.kaeResource, RDFS.label, model.createLiteral("Κωδικός Αριθμού Εσόδων/Εξόδων", "el"));
//Unit Price Specification
model.add(Ontology.unitPriceSpecificationResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.unitPriceSpecificationResource, RDFS.label, model.createLiteral("Unit Price Specification", "en"));
model.add(Ontology.unitPriceSpecificationResource, RDFS.label, model.createLiteral("Προδιαγραφή τιμής ανά μονάδα", "el"));
//Membership
model.add(Ontology.membershipResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.membershipResource, RDFS.label, model.createLiteral("Membership", "en"));
model.add(Ontology.membershipResource, RDFS.label, model.createLiteral("Μέλος", "el"));
//Address
model.add(Ontology.addressResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.addressResource, RDFS.label, model.createLiteral("Adress", "en"));
model.add(Ontology.addressResource, RDFS.label, model.createLiteral("Διεύθυνση", "el"));
}
/**
* Create the SKOS Concepts and Concept Schemes to the
* model we are currently working with.
*
* @param Model the model we are currently working with
*/
public void addConceptSchemesToModel(Model model) {
/** Concepts **/
/* regarding KindScheme */
Resource conceptServicesResource = model.createResource(Ontology.publicContractsPrefix + "Services", Ontology.conceptResource);
Resource conceptWorksResource = model.createResource(Ontology.publicContractsPrefix + "Works", Ontology.conceptResource);
Resource conceptSuppliesResource = model.createResource(Ontology.publicContractsPrefix + "Supplies", Ontology.conceptResource);
Resource conceptStudiesResource = model.createResource(Ontology.eLodPrefix + "Studies", Ontology.conceptResource);
/* regarding ProcedureTypeScheme */
Resource conceptOpenResource = model.createResource(Ontology.publicContractsPrefix + "Open", Ontology.conceptResource);
Resource conceptRestrictedResource = model.createResource(Ontology.publicContractsPrefix + "Restricted", Ontology.conceptResource);
Resource conceptProxeirosDiagonismosResource = model.createResource(Ontology.eLodPrefix + "LowValue", Ontology.conceptResource);
/** Concept Schemes **/
Resource kindSchemeResource = model.createResource(Ontology.publicContractsPrefix + "KindScheme", Ontology.conceptSchemeResource);
Resource procedureTypeSchemeResource = model.createResource(Ontology.publicContractsPrefix + "ProcedureTypeScheme", Ontology.conceptSchemeResource);
/** configure StatusSchemes **/
/* regarding KindScheme */
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptServicesResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptWorksResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptSuppliesResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptStudiesResource);
conceptServicesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptWorksResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptSuppliesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptStudiesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptServicesResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptWorksResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptSuppliesResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptStudiesResource.addProperty(Ontology.inScheme, kindSchemeResource);
/* regarding ProcedureTypeScheme */
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptOpenResource);
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptRestrictedResource);
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptProxeirosDiagonismosResource);
conceptOpenResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptRestrictedResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptProxeirosDiagonismosResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptOpenResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
conceptRestrictedResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
conceptProxeirosDiagonismosResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
/** configure prefLabels **/
/* regarding KindScheme */
conceptServicesResource.addProperty(Ontology.prefLabel, model.createLiteral("Υπηρεσίες", "el"));
conceptWorksResource.addProperty(Ontology.prefLabel, model.createLiteral("Έργα", "el"));
conceptSuppliesResource.addProperty(Ontology.prefLabel, model.createLiteral("Προμήθειες", "el"));
conceptStudiesResource.addProperty(Ontology.prefLabel, model.createLiteral("Μελέτες", "el"));
conceptServicesResource.addProperty(Ontology.prefLabel, model.createLiteral("Services", "en"));
conceptWorksResource.addProperty(Ontology.prefLabel, model.createLiteral("Works", "en"));
conceptSuppliesResource.addProperty(Ontology.prefLabel, model.createLiteral("Supplies", "en"));
conceptStudiesResource.addProperty(Ontology.prefLabel, model.createLiteral("Researches", "en"));
/* regarding ProcedureTypeScheme */
conceptOpenResource.addProperty(Ontology.prefLabel, model.createLiteral("Ανοικτός Διαγωνισμός", "el"));
conceptRestrictedResource.addProperty(Ontology.prefLabel, model.createLiteral("Κλειστός Διαγωνισμός", "el"));
conceptProxeirosDiagonismosResource.addProperty(Ontology.prefLabel, model.createLiteral("Πρόχειρος Διαγωνισμός", "el"));
conceptOpenResource.addProperty(Ontology.prefLabel, model.createLiteral("Open", "en"));
conceptRestrictedResource.addProperty(Ontology.prefLabel, model.createLiteral("Restricted", "en"));
conceptProxeirosDiagonismosResource.addProperty(Ontology.prefLabel, model.createLiteral("Low Value", "en"));
}
} | YourDataStories/harvesters | DiavgeiaGeneralHarvester/src/ontology/OntologyInitialization.java |
1,591 | /*
* copyright 2013-2020
* codebb.gr
* ProtoERP - Open source invocing program
* [email protected]
*/
/*
* Changelog
* =========
* 17/11/2020 (georgemoralis) - Validation works
* 16/11/2020 (georgemoralis) - Editing now working ok as well
* 16/11/2020 (georgemoralis) - More progress in loading/saving
* 15/11/2020 (georgemoralis) - Progress in loading/saving form
* 12/11/2020 (georgemoralis) - Initial work
*/
package gr.codebb.protoerp.userManagement;
import gr.codebb.ctl.CbbClearableTextField;
import gr.codebb.dlg.AlertDlg;
import gr.codebb.lib.database.GenericDao;
import gr.codebb.lib.database.PersistenceManager;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.stage.Modality;
import javafx.util.StringConverter;
import net.synedra.validatorfx.Validator;
import org.controlsfx.control.CheckListView;
public class RolesDetailView implements Initializable {
@FXML private TextField textId;
@FXML private CbbClearableTextField textRoleΝame;
@FXML private CheckListView<PermissionsEntity> permCheckList;
private Validator validator = new Validator();
/** Initializes the controller class. */
@Override
public void initialize(URL url, ResourceBundle rb) {
permCheckList.getItems().addAll(PersimssionsQueries.getPermissions());
permCheckList.setCellFactory(
(ListView<PermissionsEntity> listView) ->
new CheckBoxListCell<PermissionsEntity>(
item -> permCheckList.getItemBooleanProperty(item),
new StringConverter<PermissionsEntity>() {
@Override
public PermissionsEntity fromString(String arg0) {
return null;
}
@Override
public String toString(PermissionsEntity per) {
return per.getPermissionDisplayName();
}
}));
validator
.createCheck()
.dependsOn("rolename", textRoleΝame.textProperty())
.withMethod(
c -> {
String rolename = c.get("rolename");
if (rolename.isEmpty()) {
c.error("Το όνομα του ρόλου δεν μπορεί να είναι κενό");
}
})
.decorates(textRoleΝame)
.immediate();
validator
.createCheck()
.dependsOn("rolename", textRoleΝame.textProperty())
.withMethod(
c -> {
String rolename = c.get("rolename");
RolesEntity rolef = RolesQueries.findRoleName(rolename);
if (rolef != null) // if exists
{
if (!textId.getText().isEmpty()) { // if it is not a new entry
if (rolef.getId()
!= Long.parseLong(textId.getText())) // check if found id is the same
{
c.error("Υπάρχει ήδη ρόλος με όνομα " + rolename);
}
} else {
c.error("Υπάρχει ήδη ρόλος με όνομα " + rolename);
}
}
})
.decorates(textRoleΝame);
/*permCheckList
.getCheckModel()
.getCheckedItems()
.addListener(
new ListChangeListener<PermissionsEntity>() {
@Override
public void onChanged(ListChangeListener.Change<? extends PermissionsEntity> change) {
while (change.next()) {
if (change.wasAdded()) {
for (PermissionsEntity perm : change.getAddedSubList()) {
System.out.println(perm.getPermissionName());
}
}
if (change.wasRemoved()) {
for (PermissionsEntity perm : change.getRemoved()) {
System.out.println(perm.getPermissionName());
}
}
}
}
});*/
}
public void fillData(RolesEntity role) {
textId.setText(role.getId().toString());
textRoleΝame.setText(role.getRoleName());
for (PermissionsEntity perm : permCheckList.getItems()) {
for (PermissionsEntity permExist : role.getPermissionList()) {
if (permExist.getPermissionName().matches(perm.getPermissionName())) {
permCheckList.getCheckModel().check(perm);
}
}
}
}
public boolean save() {
GenericDao gdao = new GenericDao(RolesEntity.class, PersistenceManager.getEmf());
RolesEntity role = new RolesEntity();
role.setRoleName(textRoleΝame.getText());
for (PermissionsEntity perm : permCheckList.getCheckModel().getCheckedItems()) {
role.getPermissionList().add(perm);
}
gdao.createEntity(role);
return true;
}
public boolean validateControls() {
validator.validate();
if (validator.containsErrors()) {
AlertDlg.create()
.type(AlertDlg.Type.ERROR)
.message("Ελέξτε την φόρμα για λάθη")
.title("Πρόβλημα")
.owner(textRoleΝame.getScene().getWindow())
.modality(Modality.APPLICATION_MODAL)
.showAndWait();
return false;
}
return true;
}
public boolean saveEdit() {
GenericDao gdao = new GenericDao(RolesEntity.class, PersistenceManager.getEmf());
RolesEntity role = (RolesEntity) gdao.findEntity(Long.valueOf(textId.getText()));
role.setRoleName(textRoleΝame.getText());
role.getPermissionList().clear();
for (PermissionsEntity perm : permCheckList.getCheckModel().getCheckedItems()) {
role.getPermissionList().add(perm);
}
gdao.updateEntity(role);
return true;
}
}
| boost-entropy-repos-org/protoERP | src/main/java/gr/codebb/protoerp/userManagement/RolesDetailView.java |
1,593 | package org.unicode.jsptest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.cldr.util.props.UnicodeProperty;
import org.unicode.idna.Idna;
import org.unicode.idna.Idna.IdnaType;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.IdnaTypes;
import org.unicode.idna.Uts46;
import org.unicode.jsp.Common;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.XPropertyFactory;
import org.unicode.text.UCD.Default;
import org.unicode.text.UCD.ToolUnicodePropertySource;
import com.ibm.icu.dev.test.TestFmwk;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.text.UnicodeSetIterator;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
public class TestJsp extends TestFmwk {
private static final String enSample = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 = new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE = new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
public static void main(String[] args) throws Exception {
// int cp = ' ';
// if (BREAKING_WHITESPACE.contains(cp)) {
// System.out.println("found");
// }
// System.out.println(BREAKING_WHITESPACE);
// UnicodeUtilities.StringPair foo = null;
new TestJsp().run(args);
}
static UnicodeSet IPA = new UnicodeSet("[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]").freeze();
static String IPA_SAMPLE = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {language, script, region, mixed, fail}
static UnicodeSetPrettyPrinter pretty = new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0,max) + "...";
}
return prettySet;
}
public void TestLanguage() {
final String foo = UnicodeJsp.getLanguageOptions("de");
final String fii = UnicodeJsp.validateLanguageID("en", "fr");
}
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
final boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")", !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")", !expectedUni, error[0]);
}
public void Test2003vsUts46() {
final ToolUnicodePropertySource properties = ToolUnicodePropertySource.make(Default.ucdVersion());
final UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
for (final UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
final int i = it.codepoint;
final String map2003 = Idna2003.SINGLETON.mappings.get(i);
final String map46 = Uts46.SINGLETON.mappings.get(i);
final IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
if (type46 == IdnaType.ignored) {
assertNotNull("tr46ignored U+" + codeAndName(i), map46);
} else if (type46 == IdnaType.deviation) {
type46 = map46 == null || map46.length() == 0
? IdnaType.ignored
: IdnaType.mapped;
}
if (type2003 == IdnaType.ignored) {
assertNotNull("2003ignored", map2003);
}
if (type46 != type2003 || !org.unicode.cldr.util.props.UnicodeProperty.equals(map46, map2003)) {
final String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
final String nfcf = nfkc_cfMap.get(i);
if (!map2.equals(nfcf)) {
continue;
}
final String typeDiff = type46 + "\tvs 2003\t" + type2003;
final String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
errln((codeAndName(i)) + "\tdifference:"
+ (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
+ (!org.unicode.cldr.util.props.UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
+ "\tNFKCCF:\t" + codeAndName(nfcf));
}
}
}
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null ? null : (Utility.hex(i, 4, ",", true, new StringBuilder()) + " ( " + i + " ) " + UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void TestIdnaAndIcu() {
final StringBuffer inbuffer = new StringBuffer();
final TypeAndMap typeAndMapIcu = new TypeAndMap();
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
final IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
final String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type || !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
final String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
final String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
+ (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ? "\tmap:\t" + mapDiff : ""));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
final StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
final StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (final StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (final Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer) throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (final StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
final IDNA icuIdna = IDNA.getUTS46Instance(0);
final IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
final StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
final StringBuilder outbuffer = icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (final StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (final Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna) throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (final RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
final String map2003 = Idna2003.SINGLETON.mappings.get(i);
final String map46 = Uts46.SINGLETON.mappings.get(i);
final String map2008 = Idna2008.SINGLETON.mappings.get(i);
final IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
final IdnaType type46 = Uts46.SINGLETON.types.get(i);
final IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) {
return;
}
if (t1 == IdnaType.valid && t2 == IdnaType.valid) {
return;
}
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) {
return;
}
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
//showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
final String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (final Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop); i <= UCharacter.getIntPropertyMaxValue(prop); ++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t"+ nameChoice + "\t" + propertyValueName);
} catch (final Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (final Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
final Set<String> languages = new TreeSet<String>();
final Set<String> scripts = new TreeSet<String>();
final Set<String> countries = new TreeSet<String>();
for (final ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
final Map<ULocale,Counter<Subtag>> canDisplay = new TreeMap<ULocale,Counter<Subtag>>(new Comparator<ULocale>() {
@Override
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toLanguageTag());
}
});
for (final ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
final Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet = new UnicodeSet()
.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars = new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]").addAll(exemplarSet).freeze();
final Set<String> mixedSamples = new TreeSet<String>();
for (final String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (final String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (final String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
final UnicodeSet missing = new UnicodeSet();
for (final String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total = counter.getTotal() - counter.getCount(Subtag.mixed) - counter.getCount(Subtag.fail);
final String missingDisplay = mixedSamples.size() == 0 ? "" : "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(displayLanguage + "\t" + displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t" + (total/(double)counter.getTotal())
+ "\t" + total
+ "\t" + counter.getCount(Subtag.language)
+ "\t" + counter.getCount(Subtag.script)
+ "\t" + counter.getCount(Subtag.region)
+ "\t" + counter.getCount(Subtag.mixed)
+ "\t" + counter.getCount(Subtag.fail)
+ missingDisplay
);
}
}
private void add(ULocale displayLanguage, Subtag subtag, String code, Counter<Subtag> counter, UnicodeSet okChars, Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {code, localized, badLocalization}
private Display canDisplay(ULocale displayLanguage, Subtag subtag, String code, UnicodeSet okChars, Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default: throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
final UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
public void TestLanguageTag() {
final String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(null, "invalid\\sextlang\\scode", UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), false, actual);
}
// return handleAssert(expected == actual, message, stringFor(expected), stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
//logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
//logln(sample);
final String deva = "कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(String testString, String transId, UnicodeSet exceptionsAllowed) {
final String pieces[] = testString.split(",\\s*");
final UnicodeSet shouldNotBeLeftOver = new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
final UnicodeSet allProblems = new UnicodeSet();
for (final String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
//logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing = new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
errln("Leftover from " + transId + ": " + missing.toPattern(false));
final Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
//Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
//Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
errln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
public void TestGrouping() throws IOException {
final StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet("subhead", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, printWriter);
assertContains(printWriter.toString(), "a=A595");
}
public void TestStuff() throws IOException {
//int script = UScript.getScript(0xA6E6);
//int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
final String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
//logln(propValue);
//logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
final Appendable printWriter = getLogPrintWriter();
//if (true) return;
UnicodeJsp.showSet("sc gc", new UnicodeSet("[[:ascii:]{123}{ab}{456}]"), true, true, printWriter);
UnicodeJsp.showSet("", new UnicodeSet("[\\u0080\\U0010FFFF]"), true, true, printWriter);
UnicodeJsp.showSet("", new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"), true, true, printWriter);
UnicodeJsp.showSet("", new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"), true, true, printWriter);
final String[] abResults = new String[3];
final String[] abLinks = new String[3];
final int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\n\t" + abResults[i] + "\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", unicodeSet, true, true, printWriter);
// String archaic = "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
//"";
UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false, false, printWriter);
UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"), false, false, printWriter);
}
public void TestShowProperties() throws IOException {
final StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
//logln(out);
}
public void TestIdentifiers() throws IOException {
final String out = UnicodeUtilities.getIdentifier("Latin");
assertTrue("identifier info", out.toString().contains("Line_Break"));
logln(out.toString());
//logln(out);
}
public void TestShowSet() throws IOException {
final StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet("sc", UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"), false, true, out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
public void TestParameters() {
final UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals("", "<u>abcc</u> <u>abxyzc</u> ab$c", UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
public void TestIdna() {
final boolean[] error = new boolean[1];
final String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkInvalidIdna(Uts46.SINGLETON, "≠");
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
//checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertFalse("uts46 not equals", Uts46.SINGLETON.isValid("≠"));
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
//showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue("contains hyphen", UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
final boolean[] error = new boolean[1];
final String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
final String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
final boolean[] error = new boolean[1];
final String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
final String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (final IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
public void TestBnf() {
final UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{
"c = a* wq;\n" +
"a = xyz;\n" +
"b = a{2} c;\n"
},
{
"c = a* b;\n" +
"a = xyz;\n" +
"b = a{2} c;\n",
"Exception"
},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n" +
"scheme = reserved+;\n" +
"host = \\/\\/ reserved+;\n" +
"query = [\\=reserved]+;\n" +
"fragment = reserved+;\n" +
"reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"},
// {
// org.unicode.text.utility.Utility.WORKSPACE_DIRECTORY + "cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (final String[] test2 : tests) {
final String test = test2[0];
final boolean expectException = test2.length < 2 ? false : test2[1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
final List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
final String result2 = result.replaceAll("[0-9]+%", ""); // just so we can use the language subtag stuff
final String resolved = regex.transform(result2);
//logln(resolved);
final Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < test2.length; ++j) {
final String check = test2[j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
//logln("Result: " + result + "\n" + checks + "\n" + test);
final String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
//logln(randomBnf);
} catch (final Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
public void TestBnfMax() {
final BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10)
.addRules("$root=[0-9]+;")
.complete();
for (int i = 0; i < 100; ++i) {
final String s = bnf.next();
assertTrue("Max too large? " + i + ", " + s.length() + ", " + s, 1 <= s.length() && s.length() < 11);
}
}
public void TestBnfGen() {
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
final String bnf = "item = word | number;\n" +
"word = $alpha+;\n" +
"number = (digits (separator digits)?);\n" +
"digits = [:Pd:]+;\n" +
"separator = [[:WB=MB:][:WB=MN:]];\n" +
"$alpha = [:alphabetic:];";
final String fixedbnf = new UnicodeRegex().compileBnf(bnf);
final String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
//String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
final String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
assertContains(random, "\\U0002A089");
}
private void assertContains(String stuff, String string) {
if (!stuff.contains(string)) {
errln(string + " not contained in " + stuff);
}
}
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
final UnicodeSet actual = new UnicodeSet();
final UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
TestUnicodeSet.assertEquals(this, test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
final UnicodeSet actual = new UnicodeSet();
final UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
TestUnicodeSet.assertContains(this, test, expectedSubset, actual);
}
}
| MylesBorins/unicodetools | unicodetools/org/unicode/jsptest/TestJsp.java |
1,594 | package org.unicode.jsp;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result =
result.replaceAll("⇑⇑", "<u>")
.replaceAll("⇓⇓", "</u>")
.replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
*
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
// String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat).addRules("$root=" + regex + ";").complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line"))
b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence"))
b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start, decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
// piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece =
piece.replaceAll("
", "<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString();
}
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput =
""
+ "fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+ "\nöbb.at ÖBB.at ÖBB.at"
+ "\nȡog.de ☕.de I♥NY.de"
+ "\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+ "\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+ "\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+ "\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(
String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
// setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(
String grouping,
String info,
UnicodeSet a,
boolean abbreviate,
boolean ucdFormat,
boolean collate,
Appendable out)
throws IOException {
CodePointShower codePointShower =
new CodePointShower(grouping, info, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink)
throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(
String setA,
String setB,
boolean abbreviate,
String[] abResults,
int[] abSizes,
String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int parseCode(String text, String nextButton, String previousButton) {
// text = fromHTML.transliterate(text);
String trimmed = text.trim();
if (trimmed.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(trimmed, 16));
} catch (Exception e) {
}
}
int cp = UTF16.charAt(text, 0);
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
}
return cp;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(
new UnicodeSet(Uts46.SINGLETON.validSet_transitional)
.retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(
String test,
boolean nfkcCheck,
boolean scriptCheck,
boolean idCheck,
boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100 / max) + "%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append(
"<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append("<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append(
"<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
static final String VERSIONS =
"Version 3.9; "
+ "ICU version: "
+ VersionInfo.ICU_VERSION.getVersionString(2, 2)
+ "; "
+ "Unicode/Emoji version: "
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; "
+ (CachedProps.IS_BETA
? "Unicodeβ version: "
+ CachedProps.CACHED_PROPS.version.getVersionString(2, 2)
+ "; "
: "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD =
!CachedProps.IS_BETA
? ""
: "<p style='border: 1pt solid red;'>Properties use ICU for Unicode V"
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; the beta properties support Unicode V"
+ CachedProps.CACHED_PROPS.version.getVersionString(2, 2)
+ "β. "
+ "For more information, see <a target='help' href='https://unicode-org.github.io/unicodetools/help/changes'>Unicode Utilities Beta</a>.</p>";
public static String getSubtitle() {
return SUBHEAD;
}
}
| acidburn0zzz/unicodetools | UnicodeJsps/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,596 | package dit.hua.distributedSystems.project.demo.entity;
import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import java.util.List;
import java.util.Optional;
@Entity
public class Role {
//Δήλωση των attributes της οντότητας Role. Δήλωση των setters και getters και των αντίστοιχων constructor.
@Id
@Column(name="id")
private Integer id;
@Column(name="role")
private String role;
//Ένας χρήστης έχει έναν ρόλο, ένας ρόλος ανήκει σε πολλούς χρήστες.
@JsonIgnore
@OneToMany(mappedBy = "role", cascade = CascadeType.ALL)
private List<MUser> users;
public Role(Integer id, String role, List<MUser> users) {
this.id = id;
this.role = role;
this.users = users;
}
public Role() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public List<MUser> getUsers() {
return users;
}
public void setUsers(List<MUser> users) {
this.users = users;
}
@Override
public String toString() {
return "Role{" +
"id=" + id +
", role='" + role + '\'' +
'}';
}
}
| VasileiosKokki/FarmerCompensation_University | Distributed-Systems-Project-backend/Farmer Compensation System/src/main/java/dit/hua/distributedSystems/project/demo/entity/Role.java |
1,597 | package org.unicode.jsp;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result =
result.replaceAll("⇑⇑", "<u>")
.replaceAll("⇓⇓", "</u>")
.replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
*
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
// String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat).addRules("$root=" + regex + ";").complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line"))
b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence"))
b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start, decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
// piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece =
piece.replaceAll("
", "<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString();
}
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput =
""
+ "fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+ "\nöbb.at ÖBB.at ÖBB.at"
+ "\nȡog.de ☕.de I♥NY.de"
+ "\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+ "\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+ "\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+ "\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(
String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
// setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(
String grouping,
String info,
UnicodeSet a,
boolean abbreviate,
boolean ucdFormat,
boolean collate,
Appendable out)
throws IOException {
CodePointShower codePointShower =
new CodePointShower(grouping, info, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink)
throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(
String setA,
String setB,
boolean abbreviate,
String[] abResults,
int[] abSizes,
String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int[] parseCode(String text, String nextButton, String previousButton) {
// text = fromHTML.transliterate(text);
String trimmed = text.trim();
// Accept U+ notation and standalone hexadecimal digits, as well as a variety
// of hexadecimal character escape and numeric literal syntaxes.
Matcher matcher =
Pattern.compile(
"(?:U\\+|\\\\[ux]\\{?|&#x|0x|16#|&H)?([0-9a-f'_]+)[\\};#]?",
Pattern.CASE_INSENSITIVE)
.matcher(trimmed);
String digits = matcher.matches() ? matcher.group(1).replaceAll("['_]", "") : null;
if (digits != null && digits.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(digits, 16));
} catch (Exception e) {
}
}
int[] result = text.codePoints().toArray();
int cp = result[0];
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
return new int[] {cp};
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
return new int[] {cp};
}
return result;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(
new UnicodeSet(Uts46.SINGLETON.validSet_transitional)
.retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(
String test,
boolean nfkcCheck,
boolean scriptCheck,
boolean idCheck,
boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100 / max) + "%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append(
"<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append("<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append(
"<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
static final String VERSIONS =
"Version 3.9; "
+ "ICU version: "
+ VersionInfo.ICU_VERSION.getVersionString(2, 2)
+ "; "
+ "Unicode/Emoji version: "
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; "
+ (CachedProps.IS_BETA
? "Unicodeβ version: "
+ CachedProps.CACHED_PROPS.version.getVersionString(2, 2)
+ "; "
: "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD =
!CachedProps.IS_BETA
? ""
: "<p style='border: 1pt solid red;'>Properties use ICU for Unicode V"
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; the beta properties support Unicode V"
+ CachedProps.CACHED_PROPS.version.getVersionString(2, 2)
+ "β. "
+ "For more information, see <a target='help' href='https://unicode-org.github.io/unicodetools/help/changes'>Unicode Utilities Beta</a>.</p>";
public static String getSubtitle() {
return SUBHEAD;
}
}
| josh-hadley/unicodetools | UnicodeJsps/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,598 | package org.unicode.jsptest;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.jsp.Common;
import org.unicode.jsp.Idna;
import org.unicode.jsp.Idna.IdnaType;
import org.unicode.jsp.Idna2003;
import org.unicode.jsp.Idna2008;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeProperty;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.Uts46;
import org.unicode.jsp.XPropertyFactory;
import com.ibm.icu.dev.test.TestFmwk;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
public class TestJsp extends TestFmwk {
private static final String enSample = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 = new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE = new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
public static void main(String[] args) throws Exception {
// int cp = ' ';
// if (BREAKING_WHITESPACE.contains(cp)) {
// System.out.println("found");
// }
// System.out.println(BREAKING_WHITESPACE);
// UnicodeUtilities.StringPair foo = null;
new TestJsp().run(args);
}
static UnicodeSet IPA = new UnicodeSet("[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]").freeze();
static String IPA_SAMPLE = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {language, script, region, mixed, fail}
static UnicodeSetPrettyPrinter pretty = new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0,max) + "...";
}
return prettySet;
}
public void TestLanguage() {
String foo = UnicodeJsp.getLanguageOptions("de");
String fii = UnicodeJsp.validateLanguageID("en", "fr");
}
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")", !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")", !expectedUni, error[0]);
}
// public void Test2003vsUts46() {
//
// ToolUnicodePropertySource properties = ToolUnicodePropertySource.make("6.0");
// UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
//
// for (UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
// int i = it.codepoint;
// String map2003 = Idna2003.SINGLETON.mappings.get(i);
// String map46 = Uts46.SINGLETON.mappings.get(i);
// IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
// IdnaType type46 = Uts46.SINGLETON.types.get(i);
// if (type46 == IdnaType.ignored) {
// assertNotNull("tr46ignored U+" + codeAndName(i), map46);
// } else if (type46 == IdnaType.deviation) {
// type46 = map46 == null || map46.length() == 0
// ? IdnaType.ignored
// : IdnaType.mapped;
// }
// if (type2003 == IdnaType.ignored) {
// assertNotNull("2003ignored", map2003);
// }
// if (type46 != type2003 || !UnicodeProperty.equals(map46, map2003)) {
// String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
// String nfcf = nfkc_cfMap.get(i);
// if (!map2.equals(nfcf)) continue;
// String typeDiff = type46 + "\tvs 2003\t" + type2003;
// String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
// errln((codeAndName(i)) + "\tdifference:"
// + (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
// + "\tNFKCCF:\t" + codeAndName(nfcf));
// }
// }
// }
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null ? null : (Utility.hex(i, 4, ",", true, new StringBuilder()) + " ( " + i + " ) " + UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void oldTestIdnaAndIcu() {
StringBuffer inbuffer = new StringBuffer();
TypeAndMap typeAndMapIcu = new TypeAndMap();
UnicodeMap<String> errors = new UnicodeMap<String>();
int count = 0;
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type || !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errors.put(cp, (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ? "\tmap:\t" + mapDiff : ""));
// errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
// + (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ? "\tmap:\t" + mapDiff : ""));
if (++count > 50) {
break;
}
}
}
if (errors.size() != 0) {
for (String value : errors.values()) {
UnicodeSet s = errors.getSet(value);
errln(value + "\t" + s.toPattern(false));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer) throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
IDNA icuIdna = IDNA.getUTS46Instance(0);
IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuilder outbuffer = icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna) throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
String map2003 = Idna2003.SINGLETON.mappings.get(i);
String map46 = Uts46.SINGLETON.mappings.get(i);
String map2008 = Idna2008.SINGLETON.mappings.get(i);
IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) return;
if (t1 == IdnaType.valid && t2 == IdnaType.valid) return;
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) return;
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
//showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop); i <= UCharacter.getIntPropertyMaxValue(prop); ++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t"+ nameChoice + "\t" + propertyValueName);
} catch (Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
Set<String> languages = new TreeSet<String>();
Set<String> scripts = new TreeSet<String>();
Set<String> countries = new TreeSet<String>();
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
Map<ULocale,Counter<Subtag>> canDisplay = new TreeMap<ULocale,Counter<Subtag>>(new Comparator<ULocale>() {
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toString());
}
});
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet = new UnicodeSet()
.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars = (UnicodeSet) new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]").addAll(exemplarSet).freeze();
Set<String> mixedSamples = new TreeSet<String>();
for (String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
UnicodeSet missing = new UnicodeSet();
for (String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total = counter.getTotal() - counter.getCount(Subtag.mixed) - counter.getCount(Subtag.fail);
final String missingDisplay = mixedSamples.size() == 0 ? "" : "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(displayLanguage + "\t" + displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t" + (total/(double)counter.getTotal())
+ "\t" + total
+ "\t" + counter.getCount(Subtag.language)
+ "\t" + counter.getCount(Subtag.script)
+ "\t" + counter.getCount(Subtag.region)
+ "\t" + counter.getCount(Subtag.mixed)
+ "\t" + counter.getCount(Subtag.fail)
+ missingDisplay
);
}
}
private void add(ULocale displayLanguage, Subtag subtag, String code, Counter<Subtag> counter, UnicodeSet okChars, Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {code, localized, badLocalization}
private Display canDisplay(ULocale displayLanguage, Subtag subtag, String code, UnicodeSet okChars, Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default: throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
public void TestLanguageTag() {
String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(null, "invalid\\sextlang\\scode", UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), false, actual);
}
// return handleAssert(expected == actual, message, stringFor(expected), stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
//logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
//logln(sample);
String deva = "कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(String testString, String transId, UnicodeSet exceptionsAllowed) {
String pieces[] = testString.split(",\\s*");
UnicodeSet shouldNotBeLeftOver = new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
UnicodeSet allProblems = new UnicodeSet();
for (String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
//logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing = new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
warnln("Leftover from " + transId + ": " + missing.toPattern(false));
Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
//Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
//Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
warnln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
public void TestGrouping() throws IOException {
StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet("sc gc", "", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, true, printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet("subhead", "", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, true, printWriter);
assertContains(printWriter.toString(), "a=A595");
}
public void TestStuff() throws IOException {
//int script = UScript.getScript(0xA6E6);
//int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
//logln(propValue);
//logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
Appendable printWriter = getLogPrintWriter();
//if (true) return;
UnicodeJsp.showSet("sc gc", "", new UnicodeSet("[[:ascii:]{123}{ab}{456}]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080\\U0010FFFF]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"), true, true, true, printWriter);
String[] abResults = new String[3];
String[] abLinks = new String[3];
int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\r\n\t" + abResults[i] + "\r\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", "", unicodeSet, true, true, true, printWriter);
// String archaic = "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
//"";
//UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false, false, printWriter);
UnicodeJsp.showSet("","", UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"), false, false, true, printWriter);
}
public void TestShowProperties() throws IOException {
StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
//logln(out);
}
public void TestIdentifiers() throws IOException {
String out = UnicodeUtilities.getIdentifier("Latin");
assertTrue("identifier info", out.toString().contains("U+016F"));
logln(out.toString());
//logln(out);
}
public void TestShowSet() throws IOException {
StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet("sc", "", UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"), false, true,true, out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
public void TestParameters() {
UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals("", "<u>abcc</u> <u>abxyzc</u> ab$c", UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
public void TestIdna() {
boolean[] error = new boolean[1];
String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkInvalidIdna(Uts46.SINGLETON, "≠");
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
//checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertFalse("uts46 not equals", Uts46.SINGLETON.isValid("≠"));
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
//showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue("contains hyphen", UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
public void TestBnf() {
UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{
"c = a* wq;\n" +
"a = xyz;\n" +
"b = a{2} c;\n"
},
{
"c = a* b;\n" +
"a = xyz;\n" +
"b = a{2} c;\n",
"Exception"
},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n" +
"scheme = reserved+;\n" +
"host = \\/\\/ reserved+;\n" +
"query = [\\=reserved]+;\n" +
"fragment = reserved+;\n" +
"reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"},
// {
// "/Users/markdavis/Documents/workspace/cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (int i = 0; i < tests.length; ++i) {
String test = tests[i][0];
final boolean expectException = tests[i].length < 2 ? false : tests[i][1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
String result2 = result.replaceAll("[0-9]+%", ""); // just so we can use the language subtag stuff
String resolved = regex.transform(result2);
//logln(resolved);
Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < tests[i].length; ++j) {
String check = tests[i][j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
//logln("Result: " + result + "\n" + checks + "\n" + test);
String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
//logln(randomBnf);
} catch (Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
public void TestBnfMax() {
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10)
.addRules("$root=[0-9]+;")
.complete();
for (int i = 0; i < 100; ++i) {
String s = bnf.next();
assertTrue("Max too large? " + i + ", " + s.length() + ", " + s, 1 <= s.length() && s.length() < 11);
}
}
public void TestBnfGen() {
if (logKnownIssue("x", "old test disabling for now")) {
return;
}
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
String bnf = "item = word | number;\n" +
"word = $alpha+;\n" +
"number = (digits (separator digits)?);\n" +
"digits = [:Pd:]+;\n" +
"separator = [[:WB=MB:][:WB=MN:]];\n" +
"$alpha = [:alphabetic:];";
String fixedbnf = new UnicodeRegex().compileBnf(bnf);
String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
//String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
//assertContains(random, "\\U0002A089");
}
private void assertContains(String stuff, String string) {
if (!stuff.contains(string)) {
errln(string + " not contained in " + stuff);
}
}
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
TestUnicodeSet.assertEquals(this, test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
TestUnicodeSet.assertContains(this, test, expectedSubset, actual);
}
public void TestConfusable() {
String test = "l l l l o̸ ä O O v v";
String string = UnicodeJsp.showTransform("confusable", test);
assertEquals(null, test, string);
string = UnicodeJsp.showTransform("confusableLower", test);
assertEquals(null, test, string);
String listedTransforms = UnicodeJsp.listTransforms();
if (!listedTransforms.contains("confusable")) {
errln("Missing 'confusable' " + listedTransforms);
}
}
}
| Manishearth/unicodetools | UnicodeJspsTest/src/org/unicode/jsptest/TestJsp.java |
1,599 | /*
* copyright 2013-2020
* codebb.gr
* ProtoERP - Open source invocing program
* [email protected]
*/
/*
* Changelog
* =========
* 17/11/2020 (georgemoralis) - Validation works
* 16/11/2020 (georgemoralis) - Editing now working ok as well
* 16/11/2020 (georgemoralis) - More progress in loading/saving
* 15/11/2020 (georgemoralis) - Progress in loading/saving form
* 12/11/2020 (georgemoralis) - Initial work
*/
package eu.taxofficer.protoerp.auth.views;
import eu.taxofficer.protoerp.auth.entities.PermissionEntity;
import eu.taxofficer.protoerp.auth.entities.RoleEntity;
import eu.taxofficer.protoerp.auth.queries.PermissionQueries;
import eu.taxofficer.protoerp.auth.queries.RoleQueries;
import gr.codebb.codebblib.validatorfx.Validator;
import gr.codebb.ctl.CbbClearableTextField;
import gr.codebb.dlg.AlertDlg;
import gr.codebb.lib.database.GenericDao;
import gr.codebb.lib.database.PersistenceManager;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ListView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.CheckBoxListCell;
import javafx.stage.Modality;
import javafx.util.StringConverter;
import org.controlsfx.control.CheckListView;
public class RolesDetailView implements Initializable {
@FXML private TextField textId;
@FXML private CbbClearableTextField textRoleΝame;
@FXML private CheckListView<PermissionEntity> permCheckList;
@FXML private CheckBox checkActive;
private Validator validator = new Validator();
/** Initializes the controller class. */
@Override
public void initialize(URL url, ResourceBundle rb) {
permCheckList.getItems().addAll(PermissionQueries.getPermissions());
permCheckList.setCellFactory(
(ListView<PermissionEntity> listView) ->
new CheckBoxListCell<PermissionEntity>(
item -> permCheckList.getItemBooleanProperty(item),
new StringConverter<PermissionEntity>() {
@Override
public PermissionEntity fromString(String arg0) {
return null;
}
@Override
public String toString(PermissionEntity per) {
return per.getPermissionDisplayName();
}
}));
validator
.createCheck()
.dependsOn("rolename", textRoleΝame.textProperty())
.withMethod(
c -> {
String rolename = c.get("rolename");
if (rolename.isEmpty()) {
c.error("Το όνομα του ρόλου δεν μπορεί να είναι κενό");
}
})
.decorates(textRoleΝame)
.immediate();
validator
.createCheck()
.dependsOn("rolename", textRoleΝame.textProperty())
.withMethod(
c -> {
String rolename = c.get("rolename");
RoleEntity rolef = RoleQueries.findRoleName(rolename);
if (rolef != null) // if exists
{
if (!textId.getText().isEmpty()) { // if it is not a new entry
if (rolef.getId()
!= Long.parseLong(textId.getText())) // check if found id is the same
{
c.error("Υπάρχει ήδη ρόλος με όνομα " + rolename);
}
} else {
c.error("Υπάρχει ήδη ρόλος με όνομα " + rolename);
}
}
})
.decorates(textRoleΝame);
/*permCheckList
.getCheckModel()
.getCheckedItems()
.addListener(
new ListChangeListener<PermissionsEntity>() {
@Override
public void onChanged(ListChangeListener.Change<? extends PermissionsEntity> change) {
while (change.next()) {
if (change.wasAdded()) {
for (PermissionsEntity perm : change.getAddedSubList()) {
System.out.println(perm.getPermissionName());
}
}
if (change.wasRemoved()) {
for (PermissionsEntity perm : change.getRemoved()) {
System.out.println(perm.getPermissionName());
}
}
}
}
});*/
checkActive.setSelected(true);
}
public void fillData(RoleEntity role) {
textId.setText(role.getId().toString());
textRoleΝame.setText(role.getName());
checkActive.setSelected(role.getActive());
for (PermissionEntity perm : permCheckList.getItems()) {
for (PermissionEntity permExist : role.getPermissions()) {
if (permExist.getPermissionName().matches(perm.getPermissionName())) {
permCheckList.getCheckModel().check(perm);
}
}
}
}
public boolean save() {
GenericDao gdao = new GenericDao(RoleEntity.class, PersistenceManager.getEmf());
RoleEntity role = new RoleEntity();
role.setName(textRoleΝame.getText());
role.setActive(checkActive.isSelected());
for (PermissionEntity perm : permCheckList.getCheckModel().getCheckedItems()) {
role.getPermissions().add(perm);
}
gdao.createEntity(role);
return true;
}
public boolean validateControls() {
validator.validate();
if (validator.containsErrors()) {
AlertDlg.create()
.type(AlertDlg.Type.ERROR)
.message("Ελέξτε την φόρμα για λάθη")
.title("Πρόβλημα")
.owner(textRoleΝame.getScene().getWindow())
.modality(Modality.APPLICATION_MODAL)
.showAndWait();
return false;
}
return true;
}
public boolean saveEdit() {
GenericDao gdao = new GenericDao(RoleEntity.class, PersistenceManager.getEmf());
RoleEntity role = (RoleEntity) gdao.findEntity(Long.valueOf(textId.getText()));
role.setName(textRoleΝame.getText());
role.setActive(checkActive.isSelected());
role.getPermissions().clear();
for (PermissionEntity perm : permCheckList.getCheckModel().getCheckedItems()) {
role.getPermissions().add(perm);
}
gdao.updateEntity(role);
return true;
}
}
| georgemoralis/protoERP | src/main/java/eu/taxofficer/protoerp/auth/views/RolesDetailView.java |
1,600 | /*
* Copyright (C) 2022 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 android.libcore.regression;
import android.perftests.utils.BenchmarkState;
import android.perftests.utils.PerfStatusReporter;
import android.test.suitebuilder.annotation.LargeTest;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.net.IDN;
@RunWith(AndroidJUnit4.class)
@LargeTest
public class IdnPerfTest {
@Rule public PerfStatusReporter mPerfStatusReporter = new PerfStatusReporter();
@Test
public void timeToUnicode() {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
IDN.toASCII("fass.de");
IDN.toASCII("faß.de");
IDN.toASCII("fäß.de");
IDN.toASCII("a\u200Cb");
IDN.toASCII("öbb.at");
IDN.toASCII("abc・日本.co.jp");
IDN.toASCII("日本.co.jp");
IDN.toASCII("x\u0327\u0301.de");
IDN.toASCII("σόλοσ.gr");
}
}
@Test
public void timeToAscii() {
BenchmarkState state = mPerfStatusReporter.getBenchmarkState();
while (state.keepRunning()) {
IDN.toUnicode("xn--fss-qla.de");
IDN.toUnicode("xn--n00d.com");
IDN.toUnicode("xn--bb-eka.at");
IDN.toUnicode("xn--og-09a.de");
IDN.toUnicode("xn--53h.de");
IDN.toUnicode("xn--iny-zx5a.de");
IDN.toUnicode("xn--abc-rs4b422ycvb.co.jp");
IDN.toUnicode("xn--wgv71a.co.jp");
IDN.toUnicode("xn--x-xbb7i.de");
IDN.toUnicode("xn--wxaikc6b.gr");
IDN.toUnicode("xn--wxaikc6b.xn--gr-gtd9a1b0g.de");
}
}
}
| Reginer/aosp-android-jar | android-34/src/android/libcore/regression/IdnPerfTest.java |
1,601 | /*
* Copyright (C) 2015 Google Inc.
*
* 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 benchmarks.regression;
import java.net.IDN;
public class IdnBenchmark {
public void timeToUnicode(int reps) {
for (int i = 0; i < reps; i++) {
IDN.toASCII("fass.de");
IDN.toASCII("faß.de");
IDN.toASCII("fäß.de");
IDN.toASCII("a\u200Cb");
IDN.toASCII("öbb.at");
IDN.toASCII("abc・日本.co.jp");
IDN.toASCII("日本.co.jp");
IDN.toASCII("x\u0327\u0301.de");
IDN.toASCII("σόλοσ.gr");
}
}
public void timeToAscii(int reps) {
for (int i = 0; i < reps; i++) {
IDN.toUnicode("xn--fss-qla.de");
IDN.toUnicode("xn--n00d.com");
IDN.toUnicode("xn--bb-eka.at");
IDN.toUnicode("xn--og-09a.de");
IDN.toUnicode("xn--53h.de");
IDN.toUnicode("xn--iny-zx5a.de");
IDN.toUnicode("xn--abc-rs4b422ycvb.co.jp");
IDN.toUnicode("xn--wgv71a.co.jp");
IDN.toUnicode("xn--x-xbb7i.de");
IDN.toUnicode("xn--wxaikc6b.gr");
IDN.toUnicode("xn--wxaikc6b.xn--gr-gtd9a1b0g.de");
}
}
}
| multi-os-engine/libcore | benchmarks/src/benchmarks/regression/IdnBenchmark.java |
1,602 | /*
* copyright 2013-2020
* codebb.gr
* ProtoERP - Open source invocing program
* [email protected]
*/
/*
* Changelog
* =========
* 19/02/2021 (georgemoralis) - Added userData for use with saveTableSettings
* 17/11/2020 (georgemoralis) - Added delete action
* 17/11/2020 (georgemoralis) - Validation works
* 16/11/2020 (georgemoralis) - More in saving
* 15/11/2020 (georgemoralis) - Added edit action
* 12/11/2020 (georgemoralis) - Initial work in Add detail view
* 09/11/2020 (georgemoralis) - More work on listview
* 06/11/2020 (georgemoralis) - Initial
*/
package gr.codebb.protoerp.userManagement;
import gr.codebb.ctl.cbbTableView.CbbTableView;
import gr.codebb.ctl.cbbTableView.columns.CbbLongTableColumn;
import gr.codebb.ctl.cbbTableView.columns.CbbStringTableColumn;
import gr.codebb.ctl.cbbTableView.columns.CbbTableColumn;
import gr.codebb.dlg.AlertDlg;
import gr.codebb.lib.crud.AbstractListView;
import gr.codebb.lib.crud.annotation.ColumnProperty;
import gr.codebb.lib.database.GenericDao;
import gr.codebb.lib.database.PersistenceManager;
import gr.codebb.lib.util.AlertDlgHelper;
import gr.codebb.lib.util.FxmlUtil;
import java.net.URL;
import java.util.List;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.StackPane;
import javafx.stage.Modality;
public class RolesView extends AbstractListView implements Initializable {
@FXML private StackPane mainStackPane;
@FXML private Button refreshButton;
@FXML private Button newButton;
@FXML private Button openButton;
@FXML private Button deleteButton;
@FXML private CbbTableView<RolesEntity> rolesTable;
@ColumnProperty(prefWidth = "100.0d")
CbbTableColumn<RolesEntity, Long> columnId;
@ColumnProperty(prefWidth = "150.0d")
CbbTableColumn<RolesEntity, String> columnRoleName;
@Override
public void initialize(URL url, ResourceBundle rb) {
columnId = new CbbLongTableColumn<>("Id");
columnId.setCellValueFactory(new PropertyValueFactory<>("id"));
columnRoleName = new CbbStringTableColumn<>("Ρόλος");
columnRoleName.setCellValueFactory(new PropertyValueFactory<>("roleName"));
rolesTable.getColumns().addAll(columnId, columnRoleName);
init(this);
selectWithService();
rolesTable.setUserData("rolesTable"); // for use with savesettings
}
@FXML
private void deleteAction(ActionEvent event) {
int row = rolesTable.getSelectionModel().getSelectedIndex();
rolesTable.getSelectionModel().select(row);
ButtonType response =
AlertDlg.create()
.message(
"Είστε σιγουροι ότι θέλετε να διαγράψετε τον ρόλο : "
+ rolesTable.getSelectionModel().getSelectedItem().getRoleName())
.title("Διαγραφή")
.modality(Modality.APPLICATION_MODAL)
.owner(rolesTable.getScene().getWindow())
.showAndWaitConfirm();
if (response == ButtonType.OK) {
GenericDao gdao = new GenericDao(RolesEntity.class, PersistenceManager.getEmf());
try {
gdao.deleteEntity(rolesTable.getSelectionModel().getSelectedItem().getId());
} catch (Exception e) {
e.printStackTrace();
}
selectWithService();
}
}
@FXML
private void refreshAction(ActionEvent event) {
selectWithService();
}
@FXML
private void newAction(ActionEvent event) {
FxmlUtil.LoadResult<RolesDetailView> getDetailView =
FxmlUtil.load("/fxml/userManagement/RolesDetail.fxml");
Alert alert =
AlertDlgHelper.saveDialog(
"Προσθήκη ρόλου - δικαιωμάτων",
getDetailView.getParent(),
mainStackPane.getScene().getWindow());
Button okbutton = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
okbutton.addEventFilter(
ActionEvent.ACTION,
(event1) -> {
if (!getDetailView.getController().validateControls()) {
event1.consume();
}
});
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if (getDetailView.getController() != null) {
getDetailView.getController().save();
selectWithService();
}
}
}
@FXML
protected void openAction(ActionEvent event) {
FxmlUtil.LoadResult<RolesDetailView> getDetailView =
FxmlUtil.load("/fxml/userManagement/RolesDetail.fxml");
Alert alert =
AlertDlgHelper.editDialog(
"Άνοιγμα/Επεξεργασία ρόλου - δικαιωμάτων",
getDetailView.getParent(),
mainStackPane.getScene().getWindow());
getDetailView.getController().fillData(rolesTable.getSelectionModel().getSelectedItem());
Button okbutton = (Button) alert.getDialogPane().lookupButton(ButtonType.OK);
okbutton.addEventFilter(
ActionEvent.ACTION,
(event1) -> {
if (!getDetailView.getController().validateControls()) {
event1.consume();
}
});
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.OK) {
if (getDetailView.getController() != null) {
getDetailView.getController().saveEdit();
selectWithService();
}
}
}
@Override
protected CbbTableView getTableView() {
return rolesTable;
}
@Override
protected List getMainQuery() {
return RolesQueries.getRoles();
}
@Override
protected StackPane getMainStackPane() {
return mainStackPane;
}
@Override
protected Button getDeleteButton() {
return deleteButton;
}
@Override
protected Button getOpenButton() {
return openButton;
}
}
| boost-entropy-repos-org/protoERP | src/main/java/gr/codebb/protoerp/userManagement/RolesView.java |
1,603 | package ontology;
import utils.HelperMethods;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.vocabulary.OWL;
import com.hp.hpl.jena.vocabulary.RDFS;
/**
* @author G. Razis
*/
public class OntologyInitialization {
HelperMethods hm = new HelperMethods();
/**
* Add the necessary prefixes to the model we are currently working with.
*
* @param Model
* the model we are currently working with
*/
public void setPrefixes(Model model) {
model.setNsPrefix("elod", Ontology.eLodPrefix);
model.setNsPrefix("elodGeo", Ontology.elodGeoPrefix);
model.setNsPrefix("pc", Ontology.publicContractsPrefix);
model.setNsPrefix("skos", Ontology.skosPrefix);
model.setNsPrefix("gr", Ontology.goodRelationsPrefix);
model.setNsPrefix("rov", Ontology.regOrgPrefix);
model.setNsPrefix("org", Ontology.orgPrefix);
model.setNsPrefix("foaf", Ontology.foafPrefix);
model.setNsPrefix("xsd", Ontology.xsdPrefix);
model.setNsPrefix("dcterms", Ontology.dctermsPrefix);
model.setNsPrefix("dc", Ontology.dcPrefix);
model.setNsPrefix("pcdt", Ontology.pcdtPrefix);
model.setNsPrefix("vcard", Ontology.vcardPrefix);
}
/**
* Create the basic hierarchies of the OWL classes and their labels to the
* model we are currently working with.
*
* @param Model
* the model we are currently working with
*/
public void createHierarchies(Model model) {
// Agent
model.add(Ontology.agentResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.agentResource, RDFS.label, model.createLiteral("Agent", "en"));
model.add(Ontology.agentResource, RDFS.label, model.createLiteral("Πράκτορας", "el"));
// Concept
model.add(Ontology.conceptResource, RDFS.subClassOf, OWL.Thing);
// Concept Scheme
model.add(Ontology.conceptSchemeResource, RDFS.subClassOf, OWL.Thing);
// Concept - Vat Type
model.add(Ontology.vatTypeResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.vatTypeResource, RDFS.label, model.createLiteral("VAT Type", "en"));
model.add(Ontology.vatTypeResource, RDFS.label, model.createLiteral("Τύπος ΑΦΜ", "el"));
// Concept - Thematic Category
model.add(Ontology.thematicCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.thematicCategoryResource, RDFS.label, model.createLiteral("Thematic Category Type", "en"));
model.add(Ontology.thematicCategoryResource, RDFS.label,
model.createLiteral("Τύπος Θεματικής Κατηγορίας", "el"));
// Concept - Role
model.add(Ontology.roleResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.roleResource, RDFS.label, model.createLiteral("Role", "en"));
model.add(Ontology.roleResource, RDFS.label, model.createLiteral("Ρόλος", "el"));
// Concept - Country
model.add(Ontology.countryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.countryResource, RDFS.label, model.createLiteral("Country", "en"));
model.add(Ontology.countryResource, RDFS.label, model.createLiteral("Χώρα", "el"));
// Concept - Currency
model.add(Ontology.currencyResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.currencyResource, RDFS.label, model.createLiteral("Currency", "en"));
model.add(Ontology.currencyResource, RDFS.label, model.createLiteral("Νόμισμα", "el"));
// Concept - Organizational Unit Category
model.add(Ontology.orgUnitCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.orgUnitCategoryResource, RDFS.label,
model.createLiteral("Organizational Unit Category", "en"));
model.add(Ontology.orgUnitCategoryResource, RDFS.label, model.createLiteral("Τύποι Οργανωτικών Μονάδων", "el"));
// Concept - Organization Domain
model.add(Ontology.organizationDomainResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationDomainResource, RDFS.label, model.createLiteral("Organization Domain", "en"));
model.add(Ontology.organizationDomainResource, RDFS.label,
model.createLiteral("Πεδίο Αρμοδιότητας Φορέων", "el"));
// Concept - Organization Status
model.add(Ontology.organizationStatusResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationStatusResource, RDFS.label, model.createLiteral("Organization Status", "en"));
model.add(Ontology.organizationStatusResource, RDFS.label, model.createLiteral("Κατάσταση Οργανισμού", "el"));
// Concept - Organization Category
model.add(Ontology.organizationCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.organizationCategoryResource, RDFS.label,
model.createLiteral("Organization Category", "en"));
model.add(Ontology.organizationCategoryResource, RDFS.label, model.createLiteral("Κατηγορίες Φορέων", "el"));
// Concept - Decision Status
model.add(Ontology.decisionStatusResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.decisionStatusResource, RDFS.label, model.createLiteral("Decision Status", "en"));
model.add(Ontology.decisionStatusResource, RDFS.label, model.createLiteral("Κατάσταση Πράξης", "el"));
// Concept - Selection Criterion
model.add(Ontology.selectionCriterionResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.selectionCriterionResource, RDFS.label, model.createLiteral("Selection Criterion", "en"));
model.add(Ontology.selectionCriterionResource, RDFS.label, model.createLiteral("Κριτήριο Επιλογής", "el"));
// Concept - Budget Category
model.add(Ontology.budgetCategoryResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.budgetCategoryResource, RDFS.label, model.createLiteral("Budget Category", "en"));
model.add(Ontology.budgetCategoryResource, RDFS.label, model.createLiteral("Κατηγορία Προϋπολογισμού", "el"));
// Fek Type
model.add(Ontology.fekTypeResource, RDFS.subClassOf, Ontology.conceptResource);
model.add(Ontology.fekTypeResource, RDFS.label,
model.createLiteral("Greek Government Gazzette Issue Type ", "en"));
model.add(Ontology.fekTypeResource, RDFS.label,
model.createLiteral("Τύπος Τεύχους Φύλλου Εφημερίδος Κυβερνήσεως", "el"));
// Agent - Business Entity
model.add(Ontology.businessEntityResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.businessEntityResource, RDFS.label, model.createLiteral("Business Entity", "en"));
model.add(Ontology.businessEntityResource, RDFS.label, model.createLiteral("Επιχειρηματική Οντότητα", "el"));
// Agent - Registered Organization
model.add(Ontology.registeredOrganizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.registeredOrganizationResource, RDFS.label,
model.createLiteral("Registered Organization", "en"));
model.add(Ontology.registeredOrganizationResource, RDFS.label,
model.createLiteral("Καταχωρημένος Οργανισμός", "el"));
// Agent - Organization (FOAF)
model.add(Ontology.organizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
// Agent - Organization (org)
model.add(Ontology.orgOrganizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.orgOrganizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.orgOrganizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
// Orgs equivalence
/*
* model.add(Ontology.businessEntityResource, OWL.equivalentClass,
* Ontology.registeredOrganizationResource);
* model.add(Ontology.businessEntityResource, OWL.equivalentClass,
* Ontology.organizationResource);
* model.add(Ontology.businessEntityResource, OWL.equivalentClass,
* Ontology.orgOrganizationResource);
* model.add(Ontology.registeredOrganizationResource,
* OWL.equivalentClass, Ontology.organizationResource);
* model.add(Ontology.registeredOrganizationResource,
* OWL.equivalentClass, Ontology.orgOrganizationResource);
* model.add(Ontology.organizationResource, OWL.equivalentClass,
* Ontology.orgOrganizationResource);
*/
// Agent - Person
model.add(Ontology.personResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.personResource, RDFS.label, model.createLiteral("Person", "en"));
model.add(Ontology.personResource, RDFS.label, model.createLiteral("Πρόσωπο", "el"));
// Agent - Organization
model.add(Ontology.organizationResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Organization", "en"));
model.add(Ontology.organizationResource, RDFS.label, model.createLiteral("Οργανισμός", "el"));
// Agent - Organizational Unit
model.add(Ontology.organizationalUnitResource, RDFS.subClassOf, Ontology.agentResource);
model.add(Ontology.organizationalUnitResource, RDFS.label, model.createLiteral("Organizational Unit", "en"));
model.add(Ontology.organizationalUnitResource, RDFS.label, model.createLiteral("Μονάδα Οργανισμού", "el"));
// Spending Item
model.add(Ontology.spendingItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.spendingItemResource, RDFS.label, model.createLiteral("Spending Item", "en"));
model.add(Ontology.spendingItemResource, RDFS.label, model.createLiteral("Αντικείμενο Δαπάνης", "el"));
// Award Criteria Combination
model.add(Ontology.awardCriteriaCombinationResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.awardCriteriaCombinationResource, RDFS.label,
model.createLiteral("Combination of Contract Award Criteria", "en"));
model.add(Ontology.awardCriteriaCombinationResource, RDFS.label,
model.createLiteral("Συνδυασμός των Κριτηρίων Ανάθεσης της Σύμβασης", "el"));
// Criterion Weighting
model.add(Ontology.criterionWeightingResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.criterionWeightingResource, RDFS.label, model.createLiteral("Award Criterion", "en"));
model.add(Ontology.criterionWeightingResource, RDFS.label, model.createLiteral("Κριτήριο Ανάθεσης", "el"));
// Contract
model.add(Ontology.contractResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.contractResource, RDFS.label, model.createLiteral("Public Contract", "en"));
model.add(Ontology.contractResource, RDFS.label, model.createLiteral("Δημόσια Σύμβαση", "el"));
// CPV
model.add(Ontology.cpvResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.cpvResource, RDFS.label, model.createLiteral("Common Procurement Vocabulary", "en"));
model.add(Ontology.cpvResource, RDFS.label, model.createLiteral("Κοινό Λεξιλόγιο Προμηθειών", "el"));
// Attachment
model.add(Ontology.attachmentResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.attachmentResource, RDFS.label, model.createLiteral("Attachments", "en"));
model.add(Ontology.attachmentResource, RDFS.label, model.createLiteral("Συνημμένα Έγγραφα", "el"));
// Decision
model.add(Ontology.decisionResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.decisionResource, RDFS.label, model.createLiteral("Decision", "en"));
model.add(Ontology.decisionResource, RDFS.label, model.createLiteral("Πράξη", "el"));
// Committed Amount
model.add(Ontology.committedItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.committedItemResource, RDFS.label, model.createLiteral("Committed Item", "en"));
model.add(Ontology.committedItemResource, RDFS.label, model.createLiteral("Δεσμευθέν Αντικείμενο", "el"));
// Expenditure Line
model.add(Ontology.expenditureLineResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.expenditureLineResource, RDFS.label, model.createLiteral("Expenditure Line", "en"));
model.add(Ontology.expenditureLineResource, RDFS.label, model.createLiteral("Τμήμα Δαπάνης", "el"));
// Expense Approval Item
model.add(Ontology.expenseApprovalItemResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.expenseApprovalItemResource, RDFS.label, model.createLiteral("Expense Approval", "en"));
model.add(Ontology.expenseApprovalItemResource, RDFS.label, model.createLiteral("Έγκριση Δαπάνης", "el"));
// FEK
model.add(Ontology.fekResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.fekResource, RDFS.label, model.createLiteral("Greek Government Gazzette", "en"));
model.add(Ontology.fekResource, RDFS.label, model.createLiteral("Φύλλο Εφημερίδος Κυβερνήσεως", "el"));
// KAE
model.add(Ontology.kaeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.kaeResource, RDFS.label, model.createLiteral("Code Number of Revenues/Expenses", "en"));
model.add(Ontology.kaeResource, RDFS.label, model.createLiteral("Κωδικός Αριθμού Εσόδων/Εξόδων", "el"));
// Unit Price Specification
model.add(Ontology.unitPriceSpecificationResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.unitPriceSpecificationResource, RDFS.label,
model.createLiteral("Unit Price Specification", "en"));
model.add(Ontology.unitPriceSpecificationResource, RDFS.label,
model.createLiteral("Προδιαγραφή τιμής ανά μονάδα", "el"));
// Membership
model.add(Ontology.membershipResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.membershipResource, RDFS.label, model.createLiteral("Membership", "en"));
model.add(Ontology.membershipResource, RDFS.label, model.createLiteral("Μέλος", "el"));
// Address
model.add(Ontology.addressResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.addressResource, RDFS.label, model.createLiteral("Adress", "en"));
model.add(Ontology.addressResource, RDFS.label, model.createLiteral("Διεύθυνση", "el"));
// Regulatory Act
model.add(Ontology.regulatoryActResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.regulatoryActResource, RDFS.label, model.createLiteral("Regulatory Act", "en"));
model.add(Ontology.regulatoryActResource, RDFS.label, model.createLiteral("Κανονιστική Πράξη", "el"));
// Position Type
model.add(Ontology.positionResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.positionResource, RDFS.label, model.createLiteral("Position Type", "en"));
model.add(Ontology.positionResource, RDFS.label, model.createLiteral("Τύπος Θέσης", "el"));
// Collective Body Type
model.add(Ontology.collectiveTypeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.collectiveTypeResource, RDFS.label, model.createLiteral("Collective Body Type", "en"));
model.add(Ontology.collectiveTypeResource, RDFS.label, model.createLiteral("Τύπος Συλλογικού Οργάνου", "el"));
// Collective Body Kind
model.add(Ontology.collectiveKindResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.collectiveKindResource, RDFS.label, model.createLiteral("Είδος Συλλογικού Οργάνου", "en"));
model.add(Ontology.collectiveKindResource, RDFS.label, model.createLiteral("", "el"));
// Opinion Org Type
model.add(Ontology.opinionResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.opinionResource, RDFS.label, model.createLiteral("Opinion Organization Type", "en"));
model.add(Ontology.opinionResource, RDFS.label, model.createLiteral("Τύπος Οργανισμού Γνωμοδότησης", "el"));
// Budget Kind
model.add(Ontology.budgetKindResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.budgetKindResource, RDFS.label, model.createLiteral("Budget Kind", "en"));
model.add(Ontology.budgetKindResource, RDFS.label, model.createLiteral("Είδος Προϋπολογισμού", "el"));
// Account Type
model.add(Ontology.accountResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.accountResource, RDFS.label, model.createLiteral("Account Type", "en"));
model.add(Ontology.accountResource, RDFS.label, model.createLiteral("Τύπος Λογαριασμού", "el"));
// Time Period
model.add(Ontology.timeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.timeResource, RDFS.label, model.createLiteral("Time Period", "en"));
model.add(Ontology.timeResource, RDFS.label, model.createLiteral("Χρονική Περίοδος", "el"));
// Vacancy Type
model.add(Ontology.vacancyTypeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.vacancyTypeResource, RDFS.label, model.createLiteral("Vacancy Type", "en"));
model.add(Ontology.vacancyTypeResource, RDFS.label, model.createLiteral("Είδος Κενής Θέσης", "el"));
// Official Administrative Change
model.add(Ontology.adminChangeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.adminChangeResource, RDFS.label,
model.createLiteral("Official Administrative Change", "en"));
model.add(Ontology.adminChangeResource, RDFS.label, model.createLiteral("Επίσημη Διοικητική Αλλαγή", "el"));
// -------------------------------------------Overall Specification of
// OWL file-------------------------------------------------//
// Subclasses of OWL.Thing
model.add(Ontology.addressResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.attachmentResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.cpvResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.kaeResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.expenditureLineResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.fekResource, RDFS.subClassOf, OWL.Thing);
model.add(Ontology.unitPriceSpecificationResource, RDFS.subClassOf, OWL.Thing);
// Object Properties Domain and Ranges
// mainObject
model.add(Ontology.mainObject, RDFS.domain, Ontology.contractResource);
model.add(Ontology.mainObject, RDFS.range, Ontology.cpvResource);
// hasAttachment
model.add(Ontology.hasAttachment, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasAttachment, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasAttachment, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.hasAttachment, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasAttachment, RDFS.domain, Ontology.contractResource);
model.add(Ontology.hasAttachment, RDFS.range, Ontology.attachmentResource);
// assetGrantee
model.add(Ontology.assetGrantee, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.assetGrantee, RDFS.range, Ontology.agentResource);
// budgetRefersTo
model.add(Ontology.budgetRefersTo, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.budgetRefersTo, RDFS.range, Ontology.organizationResource);
model.add(Ontology.budgetRefersTo, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.budgetRefersTo, RDFS.range, Ontology.registeredOrganizationResource);
// accountRefersTo
model.add(Ontology.accountRefersTo, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.accountRefersTo, RDFS.range, Ontology.organizationResource);
model.add(Ontology.accountRefersTo, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.accountRefersTo, RDFS.range, Ontology.registeredOrganizationResource);
// accountType
model.add(Ontology.accountType, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.accountType, RDFS.range, Ontology.accountResource);
// agreedPrice
model.add(Ontology.agreedPrice, RDFS.domain, Ontology.contractResource);
model.add(Ontology.agreedPrice, RDFS.range, Ontology.unitPriceSpecificationResource);
// amount
model.add(Ontology.amount, RDFS.domain, Ontology.expenditureLineResource);
model.add(Ontology.amount, RDFS.range, Ontology.unitPriceSpecificationResource);
// assetGrantor
model.add(Ontology.assetGrantor, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.assetGrantor, RDFS.range, Ontology.organizationResource);
model.add(Ontology.assetGrantor, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.assetGrantor, RDFS.range, Ontology.registeredOrganizationResource);
model.add(Ontology.assetGrantor, RDFS.range, Ontology.personResource);
// broader
model.add(Ontology.broader, RDFS.domain, Ontology.conceptResource);
model.add(Ontology.broader, RDFS.range, Ontology.conceptResource);
model.add(Ontology.broader, OWL.inverseOf, Ontology.narrower);
// buyer
model.add(Ontology.buyer, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.buyer, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.buyer, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.buyer, RDFS.domain, Ontology.contractResource);
model.add(Ontology.buyer, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.buyer, RDFS.range, Ontology.agentResource);
// collectiveBodyKind
model.add(Ontology.collectiveBodyKind, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.collectiveBodyKind, RDFS.range, Ontology.collectiveKindResource);
// collectiveBodyType
model.add(Ontology.collectiveBodyType, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.collectiveBodyType, RDFS.range, Ontology.collectiveTypeResource);
// competentMinistry
model.add(Ontology.competentMinistry, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.competentMinistry, RDFS.range, Ontology.organizationResource);
model.add(Ontology.competentMinistry, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.competentMinistry, RDFS.range, Ontology.registeredOrganizationResource);
model.add(Ontology.competentMinistry, RDFS.range, Ontology.organizationalUnitResource);
// competentUnit
model.add(Ontology.competentUnit, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.competentUnit, RDFS.range, Ontology.organizationalUnitResource);
// decisionStatus
model.add(Ontology.decisionStatus, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.decisionStatus, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.decisionStatus, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.decisionStatus, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.decisionStatus, RDFS.domain, Ontology.contractResource);
model.add(Ontology.decisionStatus, RDFS.range, Ontology.decisionStatusResource);
// documentsPrice
model.add(Ontology.documentsPrice, RDFS.domain, Ontology.contractResource);
model.add(Ontology.documentsPrice, RDFS.range, Ontology.unitPriceSpecificationResource);
// donationGiver
model.add(Ontology.donationGiver, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.donationGiver, RDFS.range, Ontology.agentResource);
// donationReceiver
model.add(Ontology.donationReceiver, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.donationReceiver, RDFS.range, Ontology.agentResource);
// employerOrg
model.add(Ontology.employerOrg, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.employerOrg, RDFS.range, Ontology.organizationResource);
model.add(Ontology.employerOrg, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.employerOrg, RDFS.range, Ontology.registeredOrganizationResource);
// fekIssue
model.add(Ontology.fekIssue, RDFS.domain, Ontology.fekResource);
model.add(Ontology.fekIssue, RDFS.range, Ontology.fekTypeResource);
// hasAddress
model.add(Ontology.hasAddress, RDFS.domain, Ontology.agentResource);
model.add(Ontology.hasAddress, RDFS.range, Ontology.addressResource);
// hasBudgetCategory
model.add(Ontology.hasBudgetCategory, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasBudgetCategory, RDFS.range, Ontology.budgetCategoryResource);
// hasBudgetKind
model.add(Ontology.hasBudgetKind, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasBudgetKind, RDFS.range, Ontology.budgetKindResource);
// hasExpenditureLine
model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.contractResource);
model.add(Ontology.hasExpenditureLine, RDFS.range, Ontology.expenditureLineResource);
// hasCorrectedDecision
model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.contractResource);
model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.decisionResource);
model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.committedItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.spendingItemResource);
model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.contractResource);
// hasCpv
model.add(Ontology.hasCpv, RDFS.domain, Ontology.expenditureLineResource);
model.add(Ontology.hasCpv, RDFS.range, Ontology.cpvResource);
// hasCurrency
model.add(Ontology.hasCurrency, RDFS.domain, Ontology.unitPriceSpecificationResource);
model.add(Ontology.hasCurrency, RDFS.range, Ontology.currencyResource);
// hasKae
model.add(Ontology.hasKae, RDFS.domain, Ontology.expenditureLineResource);
model.add(Ontology.hasKae, RDFS.range, Ontology.kaeResource);
// hasOfficialAdministrativeChange
model.add(Ontology.hasOfficialAdministrativeChange, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasOfficialAdministrativeChange, RDFS.range, Ontology.adminChangeResource);
// hasOpinionOrgType
model.add(Ontology.hasOpinionOrgType, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasOpinionOrgType, RDFS.range, Ontology.opinionResource);
// // hasPositionType
// model.add(Ontology.hasPositionType, RDFS.domain, Ontology.decisionResource);
// model.add(Ontology.hasPositionType, RDFS.range, Ontology.positionResource);
// hasRelatedAdministrativeDecision
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.domain, Ontology.projectResource);
// model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.domain, Ontology.subprojectResource);
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.decisionResource);
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.committedItemResource);
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.spendingItemResource);
model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.contractResource);
// hasRelatedDecision
model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.contractResource);
model.add(Ontology.hasRelatedDecision, RDFS.range, Ontology.decisionResource);
// hasThematicCategory
model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.contractResource);
model.add(Ontology.hasThematicCategory, RDFS.range, Ontology.thematicCategoryResource);
// hasTopConcept
model.add(Ontology.hasTopConcept, RDFS.domain, Ontology.conceptSchemeResource);
model.add(Ontology.hasTopConcept, RDFS.range, Ontology.conceptResource);
// hasVacancyType
model.add(Ontology.hasVacancyType, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.hasVacancyType, RDFS.range, Ontology.vacancyTypeResource);
// hasVatType
model.add(Ontology.hasVatType, RDFS.domain, Ontology.agentResource);
model.add(Ontology.hasVatType, RDFS.range, Ontology.vatTypeResource);
// inScheme
model.add(Ontology.inScheme, RDFS.domain, Ontology.conceptResource);
model.add(Ontology.inScheme, RDFS.range, Ontology.conceptSchemeResource);
// topConceptOf
model.add(Ontology.topConceptOf, RDFS.domain, Ontology.conceptResource);
model.add(Ontology.topConceptOf, RDFS.range, Ontology.conceptSchemeResource);
// isRegisteredAt
model.add(Ontology.isRegisteredAt, RDFS.domain, Ontology.agentResource);
model.add(Ontology.isRegisteredAt, RDFS.range, Ontology.addressResource);
// kind
model.add(Ontology.kind, RDFS.domain, Ontology.contractResource);
model.add(Ontology.kind, RDFS.range, Ontology.conceptResource);
// narrower
model.add(Ontology.narrower, RDFS.domain, Ontology.conceptResource);
model.add(Ontology.narrower, RDFS.range, Ontology.conceptResource);
// orgCategory
model.add(Ontology.orgCategory, RDFS.domain, Ontology.organizationResource);
model.add(Ontology.orgCategory, RDFS.domain, Ontology.businessEntityResource);
model.add(Ontology.orgCategory, RDFS.domain, Ontology.registeredOrganizationResource);
model.add(Ontology.orgCategory, RDFS.range, Ontology.organizationCategoryResource);
// orgStatus
model.add(Ontology.orgStatus, RDFS.domain, Ontology.organizationResource);
model.add(Ontology.orgStatus, RDFS.domain, Ontology.businessEntityResource);
model.add(Ontology.orgStatus, RDFS.domain, Ontology.registeredOrganizationResource);
model.add(Ontology.orgStatus, RDFS.range, Ontology.organizationStatusResource);
// // price
// model.add(Ontology.price, RDFS.domain, Ontology.Thing);
// model.add(Ontology.price, RDFS.range, Ontology.Thing);
// publisher
model.add(Ontology.publisher, RDFS.domain, Ontology.contractResource);
model.add(Ontology.publisher, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.publisher, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.publisher, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.publisher, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.publisher, RDFS.range, Ontology.businessEntityResource);
model.add(Ontology.publisher, RDFS.range, Ontology.registeredOrganizationResource);
model.add(Ontology.publisher, RDFS.range, Ontology.organizationalUnitResource);
model.add(Ontology.publisher, RDFS.range, Ontology.organizationStatusResource);
// regulatoryAct
model.add(Ontology.regulatoryAct, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.regulatoryAct, RDFS.range, Ontology.regulatoryAct);
// relatedFek
model.add(Ontology.relatedFek, RDFS.domain, Ontology.businessEntityResource);
model.add(Ontology.relatedFek, RDFS.domain, Ontology.registeredOrganizationResource);
model.add(Ontology.relatedFek, RDFS.domain, Ontology.organizationalUnitResource);
model.add(Ontology.relatedFek, RDFS.domain, Ontology.organizationStatusResource);
model.add(Ontology.relatedFek, RDFS.range, Ontology.fekResource);
// // relatedLaw
// model.add(Ontology.relatedLaw, RDFS.domain, Ontology.decisionResource);
// model.add(Ontology.relatedLaw, RDFS.range, Ontology);
// seller
model.add(Ontology.seller, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.seller, RDFS.domain, Ontology.expenditureLineResource);
// model.add(Ontology.seller, RDFS.domain, Ontology.subprojectResource);
model.add(Ontology.seller, RDFS.range, Ontology.agentResource);
// signer
model.add(Ontology.signer, RDFS.domain, Ontology.decisionResource);
model.add(Ontology.signer, RDFS.domain, Ontology.committedItemResource);
model.add(Ontology.signer, RDFS.domain, Ontology.expenseApprovalItemResource);
model.add(Ontology.signer, RDFS.domain, Ontology.contractResource);
model.add(Ontology.signer, RDFS.domain, Ontology.spendingItemResource);
model.add(Ontology.signer, RDFS.range, Ontology.personResource);
// // timePeriod
// model.add(Ontology.timePeriod, RDFS.domain, Ontology.decisionResource);
// model.add(Ontology.timePeriod, RDFS.range, Ontology);
// Datatype Properties Domain and Ranges
// // mainObject
// model.add(Ontology.mainObject, RDFS.domain, Ontology.countryResource);
// model.add(Ontology.mainObject, RDFS.domain, xsdString);
// // hasAttachment
// model.add(Ontology.hasAttachment, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasAttachment, RDFS.range, Ontology.Thing);
// // assetGrantee
// model.add(Ontology.assetGrantee, RDFS.domain, Ontology.Thing);
// model.add(Ontology.assetGrantee, RDFS.range, Ontology.Thing);
// // budgetRefersTo
// model.add(Ontology.budgetRefersTo, RDFS.domain, Ontology.Thing);
// model.add(Ontology.budgetRefersTo, RDFS.range, Ontology.Thing);
// // accountRefersTo
// model.add(Ontology.accountRefersTo, RDFS.domain, Ontology.Thing);
// model.add(Ontology.accountRefersTo, RDFS.range, Ontology.Thing);
// // accountType
// model.add(Ontology.accountType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.accountType, RDFS.range, Ontology.Thing);
// // agreedPrice
// model.add(Ontology.agreedPrice, RDFS.domain, Ontology.Thing);
// model.add(Ontology.agreedPrice, RDFS.range, Ontology.Thing);
// // amount
// model.add(Ontology.amount, RDFS.domain, Ontology.Thing);
// model.add(Ontology.amount, RDFS.range, Ontology.Thing);
// // assetGrantor
// model.add(Ontology.assetGrantor, RDFS.domain, Ontology.Thing);
// model.add(Ontology.assetGrantor, RDFS.range, Ontology.Thing);
// // broader
// model.add(Ontology.broader, RDFS.domain, Ontology.Thing);
// model.add(Ontology.broader, RDFS.range, Ontology.Thing);
// // buyer
// model.add(Ontology.buyer, RDFS.domain, Ontology.Thing);
// model.add(Ontology.buyer, RDFS.range, Ontology.Thing);
// // collectiveBodyKind
// model.add(Ontology.collectiveBodyKind, RDFS.subClassOf, Ontology.Thing);
// model.add(Ontology.collectiveBodyKind, RDFS.range, Ontology.Thing);
// // collectiveBodyType
// model.add(Ontology.collectiveBodyType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.collectiveBodyType, RDFS.range, Ontology.Thing);
// // competentMinistry
// model.add(Ontology.competentMinistry, RDFS.domain, Ontology.Thing);
// model.add(Ontology.competentMinistry, RDFS.range, Ontology.Thing);
// // competentUnit
// model.add(Ontology.competentUnit, RDFS.domain, Ontology.Thing);
// model.add(Ontology.competentUnit, RDFS.range, Ontology.Thing);
// // decisionStatus
// model.add(Ontology.decisionStatus, RDFS.domain, Ontology.Thing);
// model.add(Ontology.decisionStatus, RDFS.range, Ontology.Thing);
// // documentsPrice
// model.add(Ontology.documentsPrice, RDFS.domain, Ontology.Thing);
// model.add(Ontology.documentsPrice, RDFS.range, Ontology.Thing);
// // donationGiver
// model.add(Ontology.donationGiver, RDFS.domain, Ontology.Thing);
// model.add(Ontology.donationGiver, RDFS.range, Ontology.Thing);
// // donationReceiver
// model.add(Ontology.donationReceiver, RDFS.domain, Ontology.Thing);
// model.add(Ontology.donationReceiver, RDFS.range, Ontology.Thing);
// // employerOrg
// model.add(Ontology.employerOrg, RDFS.domain, Ontology.Thing);
// model.add(Ontology.employerOrg, RDFS.range, Ontology.Thing);
// // fekIssue
// model.add(Ontology.fekIssue, RDFS.domain, Ontology.Thing);
// model.add(Ontology.fekIssue, RDFS.range, Ontology.Thing);
// // hasAddress
// model.add(Ontology.hasAddress, RDFS.domain, Ontology.contractResource);
// model.add(Ontology.hasAddress, RDFS.range, Ontology.cpvResource);
// // hasBudgetCategory
// model.add(Ontology.hasBudgetCategory, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasBudgetCategory, RDFS.range, Ontology.Thing);
// // hasBudgetKind
// model.add(Ontology.hasBudgetKind, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasBudgetKind, RDFS.range, Ontology.Thing);
// // hasExpenditureLine
// model.add(Ontology.hasExpenditureLine, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasExpenditureLine, RDFS.range, Ontology.Thing);
// // hasCorrectedDecision
// model.add(Ontology.hasCorrectedDecision, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasCorrectedDecision, RDFS.range, Ontology.Thing);
// // hasCpv
// model.add(Ontology.hasCpv, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasCpv, RDFS.range, Ontology.Thing);
// // hasCurrency
// model.add(Ontology.hasCurrency, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasCurrency, RDFS.range, Ontology.Thing);
// // hasKae
// model.add(Ontology.hasKae, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasKae, RDFS.range, Ontology.Thing);
// // hasOfficialAdministrativeChange
// model.add(Ontology.hasOfficialAdministrativeChange, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasOfficialAdministrativeChange, RDFS.range, Ontology.Thing);
// // hasOpinionOrgType
// model.add(Ontology.hasOpinionOrgType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasOpinionOrgType, RDFS.range, Ontology.Thing);
// // hasPositionType
// model.add(Ontology.hasPositionType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasPositionType, RDFS.range, Ontology.Thing);
// // hasRelatedAdministrativeDecision
// model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.subClassOf, Ontology.Thing);
// model.add(Ontology.hasRelatedAdministrativeDecision, RDFS.range, Ontology.Thing);
// // hasRelatedDecision
// model.add(Ontology.hasRelatedDecision, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasRelatedDecision, RDFS.range, Ontology.Thing);
// // hasThematicCategory
// model.add(Ontology.hasThematicCategory, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasThematicCategory, RDFS.range, Ontology.Thing);
// // hasTopConcept
// model.add(Ontology.hasTopConcept, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasTopConcept, RDFS.range, Ontology.Thing);
// // hasVacancyType
// model.add(Ontology.hasVacancyType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasVacancyType, RDFS.range, Ontology.Thing);
// // hasVatType
// model.add(Ontology.hasVatType, RDFS.domain, Ontology.Thing);
// model.add(Ontology.hasVatType, RDFS.range, Ontology.Thing);
// // inScheme
// model.add(Ontology.inScheme, RDFS.domain, Ontology.Thing);
// model.add(Ontology.inScheme, RDFS.range, Ontology.Thing);
// // topConceptOf
// model.add(Ontology.topConceptOf, RDFS.domain, Ontology.Thing);
// model.add(Ontology.topConceptOf, RDFS.range, Ontology.Thing);
// // isRegisteredAt
// model.add(Ontology.isRegisteredAt, RDFS.domain, Ontology.Thing);
// model.add(Ontology.isRegisteredAt, RDFS.range, Ontology.Thing);
// // kind
// model.add(Ontology.kind, RDFS.domain, Ontology.Thing);
// model.add(Ontology.kind, RDFS.range, Ontology.Thing);
// // narrower
// model.add(Ontology.narrower, RDFS.domain, Ontology.Thing);
// model.add(Ontology.narrower, RDFS.range, Ontology.Thing);
// // orgCategory
// model.add(Ontology.orgCategory, RDFS.domain, Ontology.Thing);
// model.add(Ontology.orgCategory, RDFS.range, Ontology.Thing);
// // orgStatus
// model.add(Ontology.orgStatus, RDFS.domain, Ontology.Thing);
// model.add(Ontology.orgStatus, RDFS.range, Ontology.Thing);
// // price
// model.add(Ontology.price, RDFS.domain, Ontology.Thing);
// model.add(Ontology.price, RDFS.range, Ontology.Thing);
// // publisher
// model.add(Ontology.publisher, RDFS.domain, Ontology.Thing);
// model.add(Ontology.publisher, RDFS.range, Ontology.Thing);
// // regulatoryAct
// model.add(Ontology.regulatoryAct, RDFS.domain, Ontology.Thing);
// model.add(Ontology.regulatoryAct, RDFS.range, Ontology.Thing);
// // relatedFek
// model.add(Ontology.relatedFek, RDFS.domain, Ontology.Thing);
// model.add(Ontology.relatedFek, RDFS.range, Ontology.Thing);
// // relatedLaw
// model.add(Ontology.relatedLaw, RDFS.domain, Ontology.Thing);
// model.add(Ontology.relatedLaw, RDFS.range, Ontology.Thing);
// // seller
// model.add(Ontology.seller, RDFS.domain, Ontology.Thing);
// model.add(Ontology.seller, RDFS.range, Ontology.Thing);
// // signer
// model.add(Ontology.signer, RDFS.domain, Ontology.Thing);
// model.add(Ontology.signer, RDFS.range, Ontology.Thing);
// // timePeriod
// model.add(Ontology.timePeriod, RDFS.domain, Ontology.Thing);
// model.add(Ontology.timePeriod, RDFS.range, Ontology.Thing);
}
/**
* Create the SKOS Concepts and Concept Schemes to the model we are
* currently working with.
*
* @param Model
* the model we are currently working with
*/
public void addConceptSchemesToModel(Model model) {
/** Concepts **/
/* regarding KindScheme */
Resource conceptServicesResource = model.createResource(Ontology.kindPrefix + "Services",
Ontology.conceptResource);
Resource conceptWorksResource = model.createResource(Ontology.kindPrefix + "Works", Ontology.conceptResource);
Resource conceptSuppliesResource = model.createResource(Ontology.kindPrefix + "Supplies",
Ontology.conceptResource);
Resource conceptStudiesResource = model.createResource(Ontology.eLodPrefix + "Studies",
Ontology.conceptResource);
/* regarding ProcedureTypeScheme */
Resource conceptOpenResource = model.createResource(Ontology.procTypesPrefix + "Open",
Ontology.conceptResource);
Resource conceptRestrictedResource = model.createResource(Ontology.procTypesPrefix + "Restricted",
Ontology.conceptResource);
Resource conceptProxeirosDiagonismosResource = model.createResource(Ontology.eLodPrefix + "LowValue",
Ontology.conceptResource);
/** Concept Schemes **/
Resource kindSchemeResource = model.createResource(Ontology.kindPrefix + "KindScheme",
Ontology.conceptSchemeResource);
Resource procedureTypeSchemeResource = model.createResource(Ontology.kindPrefix + "ProcedureTypeScheme",
Ontology.conceptSchemeResource);
/** configure StatusSchemes **/
/* regarding KindScheme */
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptServicesResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptWorksResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptSuppliesResource);
kindSchemeResource.addProperty(Ontology.hasTopConcept, conceptStudiesResource);
conceptServicesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptWorksResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptSuppliesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptStudiesResource.addProperty(Ontology.topConceptOf, kindSchemeResource);
conceptServicesResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptWorksResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptSuppliesResource.addProperty(Ontology.inScheme, kindSchemeResource);
conceptStudiesResource.addProperty(Ontology.inScheme, kindSchemeResource);
/* regarding ProcedureTypeScheme */
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptOpenResource);
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptRestrictedResource);
procedureTypeSchemeResource.addProperty(Ontology.hasTopConcept, conceptProxeirosDiagonismosResource);
conceptOpenResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptRestrictedResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptProxeirosDiagonismosResource.addProperty(Ontology.topConceptOf, procedureTypeSchemeResource);
conceptOpenResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
conceptRestrictedResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
conceptProxeirosDiagonismosResource.addProperty(Ontology.inScheme, procedureTypeSchemeResource);
/** configure prefLabels **/
/* regarding KindScheme */
conceptServicesResource.addProperty(Ontology.prefLabel, model.createLiteral("Υπηρεσίες", "el"));
conceptWorksResource.addProperty(Ontology.prefLabel, model.createLiteral("Έργα", "el"));
conceptSuppliesResource.addProperty(Ontology.prefLabel, model.createLiteral("Προμήθειες", "el"));
conceptStudiesResource.addProperty(Ontology.prefLabel, model.createLiteral("Μελέτες", "el"));
conceptServicesResource.addProperty(Ontology.prefLabel, model.createLiteral("Services", "en"));
conceptWorksResource.addProperty(Ontology.prefLabel, model.createLiteral("Works", "en"));
conceptSuppliesResource.addProperty(Ontology.prefLabel, model.createLiteral("Supplies", "en"));
conceptStudiesResource.addProperty(Ontology.prefLabel, model.createLiteral("Researches", "en"));
/* regarding ProcedureTypeScheme */
conceptOpenResource.addProperty(Ontology.prefLabel, model.createLiteral("Ανοικτός Διαγωνισμός", "el"));
conceptRestrictedResource.addProperty(Ontology.prefLabel, model.createLiteral("Κλειστός Διαγωνισμός", "el"));
conceptProxeirosDiagonismosResource.addProperty(Ontology.prefLabel,
model.createLiteral("Πρόχειρος Διαγωνισμός", "el"));
conceptOpenResource.addProperty(Ontology.prefLabel, model.createLiteral("Open", "en"));
conceptRestrictedResource.addProperty(Ontology.prefLabel, model.createLiteral("Restricted", "en"));
conceptProxeirosDiagonismosResource.addProperty(Ontology.prefLabel, model.createLiteral("Low Value", "en"));
}
} | YourDataStories/harvesters | DiavgeiaProjectHarvester/src/ontology/OntologyInitialization.java |
1,605 |
package gui.Authentication;
import api.Customer;
import api.Error;
import api.Host;
import api.User;
import gui.Dashboard.DashboardScreen;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Struct;
import java.util.ArrayList;
public class Register extends JPanel {
private JRadioButton customerRadioButton;
private JLabel existingMemberLabel;
private JRadioButton hostRadioButton;
private JTextField nameField;
private JLabel nameLabel;
private JPasswordField passwordField;
private JLabel passwordLabel;
private JButton registerButton;
private JLabel repeatPasswordErrorLabel;
private JPasswordField repeatPasswordField;
private JLabel repeatPasswordLabel;
private JLabel roleLabel;
private JTextField surnameField;
private JLabel surnameLabel;
private JLabel titleLabel;
private JLabel usernameErrorLabel;
private JTextField usernameField;
private JLabel usernameLabel;
private JLabel emptyFieldErrorLabel;
private ButtonGroup groupRoles;
Login logPanel;
AuthenticationScreen auth;
private api.Register registerApi;
public Register() {
initComponents();
myActionListeners();
//customerRadioButton.setSelected(true);
}
public void setLoginPanel(Login logPanel){
this.logPanel = logPanel;
}
public void setAuthenticationScreen(AuthenticationScreen auth) {
this.auth = auth;
}
private void initComponents() {
titleLabel = new JLabel();
nameLabel = new JLabel();
nameField = new JTextField();
passwordLabel = new JLabel();
passwordField = new JPasswordField();
registerButton = new JButton();
existingMemberLabel = new JLabel();
surnameLabel = new JLabel();
surnameField = new JTextField();
usernameLabel = new JLabel();
usernameField = new JTextField();
roleLabel = new JLabel();
hostRadioButton = new JRadioButton();
customerRadioButton = new JRadioButton();
repeatPasswordLabel = new JLabel();
repeatPasswordField = new JPasswordField();
repeatPasswordErrorLabel = new JLabel();
usernameErrorLabel = new JLabel();
emptyFieldErrorLabel = new JLabel();
groupRoles = new ButtonGroup();
emptyFieldErrorLabel.setPreferredSize(new Dimension(50, 20));
emptyFieldErrorLabel.setVisible(false);
usernameErrorLabel.setPreferredSize(new Dimension(50, 20));
usernameErrorLabel.setVisible(false);
repeatPasswordErrorLabel.setPreferredSize(new Dimension(50, 20));
repeatPasswordErrorLabel.setVisible(false);
setBackground(new Color(255, 255, 255));
setPreferredSize(new Dimension(350, 540));
titleLabel.setFont(new Font("Verdana", 1, 24));
titleLabel.setHorizontalAlignment(SwingConstants.CENTER);
titleLabel.setText("Εγγραφή");
nameLabel.setFont(new Font("Verdana", 0, 12));
nameLabel.setText("Όνομα");
nameField.setFont(new Font("Verdana", 0, 12));
passwordLabel.setFont(new Font("Verdana", 0, 12));
passwordLabel.setText("Κωδικός Πρόσβασης");
passwordField.setFont(new Font("Verdana", 0, 12));
registerButton.setBackground(new Color(204, 204, 204));
registerButton.setFont(new Font("Verdana", 0, 12));
registerButton.setText("Εγγραφή");
existingMemberLabel.setFont(new Font("Verdana", 0, 12));
existingMemberLabel.setForeground(new Color(0, 51, 255));
existingMemberLabel.setHorizontalAlignment(SwingConstants.CENTER);
existingMemberLabel.setText("Είστε μέλος; Κάντε σύνδεση εδώ!");
existingMemberLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));
existingMemberLabel.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
existingMemberLabelMouseClicked(evt);
}
});
surnameLabel.setFont(new Font("Verdana", 0, 12));
surnameLabel.setText("Επίθετο");
surnameField.setFont(new Font("Verdana", 0, 12));
usernameLabel.setFont(new Font("Verdana", 0, 12));
usernameLabel.setText("Όνομα χρήστη");
usernameField.setFont(new Font("Verdana", 0, 12));
roleLabel.setFont(new Font("Verdana", 0, 12));
roleLabel.setText("Ρόλος");
hostRadioButton.setFont(new Font("Verdana", 0, 12));
hostRadioButton.setText("Ιδιοκτήτης");
customerRadioButton.setFont(new Font("Verdana", 0, 12));
customerRadioButton.setText("Επισκέπτης");
groupRoles.add(hostRadioButton);
groupRoles.add(customerRadioButton);
repeatPasswordLabel.setFont(new Font("Verdana", 0, 12));
repeatPasswordLabel.setText("Επανάληψη Κωδικού Πρόσβασης");
repeatPasswordField.setFont(new Font("Verdana", 0, 12));
repeatPasswordErrorLabel.setForeground(new Color(255, 0, 51));
repeatPasswordErrorLabel.setText("repeatPasswordError");
usernameErrorLabel.setForeground(new Color(255, 0, 51));
usernameErrorLabel.setText("usernameExistsError");
emptyFieldErrorLabel.setFont(new Font("Verdana", 0, 12)); // NOI18N
emptyFieldErrorLabel.setForeground(new Color(255, 0, 0));
emptyFieldErrorLabel.setText("emptyFieldError");
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(titleLabel, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(emptyFieldErrorLabel)
.addComponent(usernameErrorLabel)
.addComponent(repeatPasswordErrorLabel)
.addComponent(registerButton)
.addGroup(layout.createSequentialGroup()
.addComponent(hostRadioButton)
.addGap(18, 18, 18)
.addComponent(customerRadioButton))
.addComponent(roleLabel)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING, false)
.addComponent(usernameLabel)
.addComponent(surnameLabel)
.addComponent(passwordLabel)
.addComponent(nameLabel)
.addComponent(nameField)
.addComponent(passwordField, GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
.addComponent(surnameField)
.addComponent(usernameField))
.addComponent(repeatPasswordLabel)
.addComponent(repeatPasswordField, GroupLayout.PREFERRED_SIZE, 246, GroupLayout.PREFERRED_SIZE))
.addContainerGap(51, Short.MAX_VALUE))
.addComponent(existingMemberLabel, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap(2, 60)
.addComponent(titleLabel)
.addGap(1, 1, 1)
.addComponent(emptyFieldErrorLabel)
.addGap(1, 1, 1)
.addComponent(nameLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(surnameLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(surnameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(usernameLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(usernameField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(usernameErrorLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(roleLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(hostRadioButton)
.addComponent(customerRadioButton))
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(passwordLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(passwordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(repeatPasswordLabel)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(repeatPasswordField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(repeatPasswordErrorLabel)
.addGap(3, 3, 3)
.addComponent(registerButton)
.addGap(18, 18, 18)
.addComponent(existingMemberLabel)
.addGap(32, 32, 32))
);
}
private void existingMemberLabelMouseClicked(java.awt.event.MouseEvent evt) {
logPanel.setVisible(true);
setVisible(false);
}
private User registered;
private ArrayList<Error> errors;
private void myActionListeners() {
registerButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (hostRadioButton.isSelected()){
registerApi = new api.Register(new Host(
nameField.getText(),
surnameField.getText(),
usernameField.getText(),
String.valueOf(passwordField.getPassword())
), String.valueOf(repeatPasswordField.getPassword()));
} else if (customerRadioButton.isSelected()) {
registerApi = new api.Register(new Customer(
nameField.getText(),
surnameField.getText(),
usernameField.getText(),
String.valueOf(passwordField.getPassword())
), String.valueOf(repeatPasswordField.getPassword()));
} else {
// ΤΙΠΟΤΑ ΔΕΝ ΕΙΝΑΙ ΕΠΙΛΕΓΜΕΝΟ.
}
registered = registerApi.addUser();
if (registered == null) {
errors = registerApi.getErrors();
for (Error error : errors) {
error.checkError(0, repeatPasswordErrorLabel);
error.checkError(1, emptyFieldErrorLabel);
error.checkError(2, usernameErrorLabel);
}
} else {
// κάνε σύνδεση
//System.out.println("Έγινε εγγραφή");
auth.setCurrentUser(registered);
auth.dispose();
DashboardScreen d = new DashboardScreen(registered);
}
}
});
}
}
| ThodorisAnninos/appartments-management-system-java | src/gui/Authentication/Register.java |
1,606 | package org.unicode.jsp;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result = result.replaceAll("⇑⇑", "<u>").replaceAll("⇓⇓", "</u>").replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
//String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat)
.addRules("$root=" + regex + ";")
.complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line")) b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence")) b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start,decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
//piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece = piece.replaceAll("
","<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString(); }
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput = ""
+"fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+"\nöbb.at ÖBB.at ÖBB.at"
+"\nȡog.de ☕.de I♥NY.de"
+"\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+"\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+"\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+"\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
//setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(String grouping, String info, UnicodeSet a, boolean abbreviate, boolean ucdFormat, boolean collate, Appendable out) throws IOException {
CodePointShower codePointShower = new CodePointShower(grouping, info, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink) throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(String setA, String setB,
boolean abbreviate, String[] abResults, int[] abSizes, String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int parseCode(String text, String nextButton, String previousButton) {
//text = fromHTML.transliterate(text);
String trimmed = text.trim();
if (trimmed.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(trimmed,16));
} catch (Exception e) {}
}
int cp = UTF16.charAt(text, 0);
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
}
return cp;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(new UnicodeSet(Uts46.SINGLETON.validSet_transitional).retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(String test, boolean nfkcCheck, boolean scriptCheck, boolean idCheck, boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100/max) +
"%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append("<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append( "<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append("<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
static final String VERSIONS = "Version 3.9; "
+ "ICU version: " + VersionInfo.ICU_VERSION.getVersionString(2, 2) + "; "
+ "Unicode/Emoji version: " + UCharacter.getUnicodeVersion().getVersionString(2, 2) + "; "
+ (CachedProps.IS_BETA ? "Unicodeβ version: " + CachedProps.CACHED_PROPS.version.getVersionString(2, 2) + "; " : "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD = !CachedProps.IS_BETA ? ""
: "<p style='border: 1pt solid red;'>Properties use ICU for Unicode V" + UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; the beta properties support Unicode V" + CachedProps.CACHED_PROPS.version.getVersionString(2, 2) + "β. "
+ "For more information, see <a target='help' href='https://unicode-org.github.io/unicodetools/help/changes'>Unicode Utilities Beta</a>.</p>"
;
public static String getSubtitle() {
return SUBHEAD;
}
}
| Manishearth/unicodetools | UnicodeJsps/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,607 | package dit.hua.distributedSystems.project.demo.rest;
import dit.hua.distributedSystems.project.demo.entity.Role;
import dit.hua.distributedSystems.project.demo.entity.MUser;
import dit.hua.distributedSystems.project.demo.service.RoleService;
import dit.hua.distributedSystems.project.demo.service.UserDetailsServiceImpl;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/user")
public class UserRestController {
@Autowired
private UserDetailsServiceImpl userService;
@Autowired
private RoleService roleService;
private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
//Δήλωση μιας μεθόδου setup όπου θα κληθεί μόλις ξεκινήσει η εφαρμογή για την προσθήκη του admin και την προσθήκη των ρόλων στην βάση.
@PostConstruct
public void setup() {
if (roleService.getRoles().isEmpty()) {
Role role = new Role();
role.setId(1);
role.setRole("ROLE_FARMER");
roleService.saveRole(role);
Role role1 = new Role();
role1.setId(2);
role1.setRole("ROLE_INSPECTOR");
roleService.saveRole(role1);
Role role2 = new Role();
role2.setId(3);
role2.setRole("ROLE_ADMIN");
roleService.saveRole(role2);
MUser adminUser = new MUser();
adminUser.setUsername("admin");
adminUser.setPassword("pavlosnikolopoulos44");
String passencode=passwordEncoder.encode(adminUser.getPassword());
adminUser.setPassword(passencode);
adminUser.setFirstName("Pavlos");
adminUser.setLastName("Nikolopoulos");
adminUser.setEmail("[email protected]");
adminUser.setPhone("6942553328");
adminUser.setAddress("Kipon 44");
adminUser.setRole(role2);
userService.saveUser(adminUser);
}
}
//Μέθοδος για την προβολή των στοιχείων όλων των χρηστών.
@GetMapping("")
public List<MUser> showUsers(){
return userService.getUsers();
}
//Μέθοδος για την αποθήκευση ενός χρήστη στην βάση.
@PostMapping("/new")
public ResponseEntity<String> saveUser(@RequestBody MUser user) {
String passencode=passwordEncoder.encode(user.getPassword());
user.setPassword(passencode);
String usrnm=user.getUsername();
String email=user.getEmail();
if (userService.findByUsername(usrnm)) { //Αν ο χρήστης υπάρχει ήδη ελέγχοντας το email και το username τότε ο χρήστης δεν μπορεί να
//αποθηκευτεί στην βάση αλλιώς αποθηκεύεται.
return new ResponseEntity<>("User already exists! Change Username", HttpStatus.BAD_REQUEST);
} else if (userService.findByEmail(email)) {
return new ResponseEntity<>("User already exists! Change Email", HttpStatus.BAD_REQUEST);
}
else{
userService.saveUser(user);
return new ResponseEntity<>("User has been saved successfully!", HttpStatus.OK);
}
}
//Μέθοδος για την διαγραφή ενός χρήστη από την βάση.
@DeleteMapping("{user_id}")
public List<MUser> deleteUser(@PathVariable Integer user_id){
userService.deleteUser(user_id);
return userService.getUsers();
}
@PutMapping("{user_id}")
public ResponseEntity<String> editUser(@PathVariable Integer user_id, @RequestBody MUser modifiedUser){
MUser user = userService.getUser(user_id);
if(user==null){
return new ResponseEntity<>("User not found", HttpStatus.NOT_FOUND);
}
//Τροποποίηση στοιχείων ενός χρήστη. Μόνο τα πεδία address,phone και email μπορούν να τροποποιηθούν τα υπόλοιπα όχι. Σε περίπτωση που ένα πεδίο δεν μπορεί να
//τροποποιηθεί εμφανίζεται κατάλληλο μήνυμα.
if(modifiedUser.getAddress()!=null){
user.setAddress(modifiedUser.getAddress());
userService.saveUser(user);
}
if(modifiedUser.getPhone()!=null){
user.setPhone(modifiedUser.getPhone());
userService.saveUser(user);
}
if(modifiedUser.getEmail()!=null && !modifiedUser.getEmail().equals(user.getEmail())){
// Check if the new email already exists
if (userService.findByEmail(modifiedUser.getEmail())) {
return new ResponseEntity<>("Email already exists", HttpStatus.BAD_REQUEST);
}
user.setEmail(modifiedUser.getEmail());
userService.saveUser(user);
}
if(modifiedUser.getUsername()!=null){
return new ResponseEntity<>("Cannot update username", HttpStatus.BAD_REQUEST);
}
if(modifiedUser.getPassword()!=null){
return new ResponseEntity<>("Cannot update password", HttpStatus.BAD_REQUEST);
}
if(modifiedUser.getFirstName()!=null){
return new ResponseEntity<>("Cannot update first name", HttpStatus.BAD_REQUEST);
}
if(modifiedUser.getLastName()!=null){
return new ResponseEntity<>("Cannot update last name", HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>("User updated successfully", HttpStatus.OK);
}
//Μέθοδος για την ανάθεση ενός ρόλου σε έναν χρήστη.
@PostMapping("/role/{user_id}/{role_id}")
public String assignRole(@PathVariable Integer user_id, @PathVariable Integer role_id) {
MUser user = userService.getUser(user_id);
Role role = roleService.getRole(role_id);
user.setRole(role); //Κλήση της μεθόδου setRole στην κλάση Muser και αποθήκευση του τροποποιημένου(αφού προστέθηκε σε αυτόν ρόλος) χρήστη.
userService.saveUser(user);
return "Role: " + role.getRole() + " has been given to user: " + user.getEmail(); //Εμφάνιση κατάλληλου μηνύματος.
}
}
| VasileiosKokki/FarmerCompensation_University | Distributed-Systems-Project-backend/Farmer Compensation System/src/main/java/dit/hua/distributedSystems/project/demo/rest/UserRestController.java |
1,608 | package org.unicode.jsp;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
import org.unicode.text.utility.Settings;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result =
result.replaceAll("⇑⇑", "<u>")
.replaceAll("⇓⇓", "</u>")
.replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
*
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
// String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat).addRules("$root=" + regex + ";").complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line"))
b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence"))
b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start, decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
// piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece =
piece.replaceAll("
", "<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString();
}
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput =
""
+ "fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+ "\nöbb.at ÖBB.at ÖBB.at"
+ "\nȡog.de ☕.de I♥NY.de"
+ "\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+ "\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+ "\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+ "\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(
String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
// setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(
String grouping,
String info,
UnicodeSet a,
boolean abbreviate,
boolean ucdFormat,
boolean collate,
Appendable out)
throws IOException {
CodePointShower codePointShower =
new CodePointShower(grouping, info, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink)
throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(
String setA,
String setB,
boolean abbreviate,
String[] abResults,
int[] abSizes,
String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int[] parseCode(String text, String nextButton, String previousButton) {
// text = fromHTML.transliterate(text);
String trimmed = text.trim();
// Accept U+ notation and standalone hexadecimal digits, as well as a variety
// of hexadecimal character escape and numeric literal syntaxes.
Matcher matcher =
Pattern.compile(
"(?:U\\+|\\\\[ux]\\{?|&#x|0x|16#|&H)?([0-9a-f'_]+)[\\};#]?",
Pattern.CASE_INSENSITIVE)
.matcher(trimmed);
String digits = matcher.matches() ? matcher.group(1).replaceAll("['_]", "") : null;
if (digits != null && digits.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(digits, 16));
} catch (Exception e) {
}
}
int[] result = text.codePoints().toArray();
int cp = result[0];
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
return new int[] {cp};
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
return new int[] {cp};
}
return result;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(
new UnicodeSet(Uts46.SINGLETON.validSet_transitional)
.retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(
String test,
boolean nfkcCheck,
boolean scriptCheck,
boolean idCheck,
boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100 / max) + "%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append(
"<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append("<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append(
"<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
static final String VERSIONS =
"Version 3.9; "
+ "ICU version: "
+ VersionInfo.ICU_VERSION.getVersionString(2, 2)
+ "; "
+ "Unicode/Emoji version: "
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; "
+ (CachedProps.IS_BETA
? "Unicodeβ version: "
+ CachedProps.CACHED_PROPS.version.getVersionString(2, 2)
+ "; "
: "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD =
!CachedProps.IS_BETA
? ""
: "<p style='border: 1pt solid red;'>Properties use ICU for Unicode V"
+ UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; the beta properties support Unicode V"
+ VersionInfo.getInstance(Settings.latestVersion).getVersionString(2, 2)
+ "β. "
+ "For more information, see <a target='help' href='https://unicode-org.github.io/unicodetools/help/changes'>Unicode Utilities Beta</a>.</p>";
public static String getSubtitle() {
return SUBHEAD;
}
}
| eggrobin/unicodetools | UnicodeJsps/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,609 | package org.unicode.jsp;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
import com.ibm.icu.util.VersionInfo;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result = result.replaceAll("⇑⇑", "<u>").replaceAll("⇓⇓", "</u>").replaceAll("\r?\n", "<br>");
return result;
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
//String regex = new UnicodeRegex().compileBnf(rules);
String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat)
.addRules("$root=" + regex + ";")
.complete();
StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
else if (choice.equals("Line")) b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
else if (choice.equals("Sentence")) b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
else b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
int radix = 10;
int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start,decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = UNESCAPER.transform(result2.toString());
int lastBreak = 0;
StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
//piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece = piece.replaceAll("
","<br>")
.replaceAll("\r\n", "<br>")
.replaceAll("\n", "<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString(); }
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput = ""
+"fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+"\nöbb.at ÖBB.at ÖBB.at"
+"\nȡog.de ☕.de I♥NY.de"
+"\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+"\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+"\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+"\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
//setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(String grouping, String info, UnicodeSet a, boolean abbreviate, boolean ucdFormat, boolean collate, Appendable out) throws IOException {
CodePointShower codePointShower = new CodePointShower(grouping, info, abbreviate, ucdFormat, collate);
UnicodeUtilities.showSetMain(a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink) throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(String setA, String setB,
boolean abbreviate, String[] abResults, int[] abSizes, String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int parseCode(String text, String nextButton, String previousButton) {
//text = fromHTML.transliterate(text);
String trimmed = text.trim();
if (trimmed.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(trimmed,16));
} catch (Exception e) {}
}
int cp = UTF16.charAt(text, 0);
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
}
return cp;
}
public static String getConfusables(String test, int choice) {
try {
Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(new UnicodeSet(Uts46.SINGLETON.validSet_transitional).retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
StringWriter s = new StringWriter();
PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(String test, boolean nfkcCheck, boolean scriptCheck, boolean idCheck, boolean xidCheck) {
try {
Confusables confusables = new Confusables(test);
if (nfkcCheck) confusables.setNormalizationCheck(Normalizer.NFKC);
if (scriptCheck) confusables.setScriptCheck(Confusables.ScriptCheck.same);
if (idCheck) confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
if (xidCheck) confusables.setAllowedCharacters(XIDModifications.getAllowed());
return getConfusablesCore(test, confusables);
} catch (Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\r\n\t]", " ").trim();
StringBuilder result = new StringBuilder();
double maxSize = confusables.getMaxSize();
List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (Collection<String> items : alternates) {
int size = items.size();
if (size > max) {
max = size;
}
}
String topCell = "<td class='smc' align='center' width='" + (100/max) +
"%'>";
String underStart = " <span class='chb'>";
String underEnd = "</span> ";
UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append("<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (Collection<String> items : alternates) {
result.append("<tr>");
for (String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append( "<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append("<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
static final String VERSIONS = "Version 3.9; "
+ "ICU version: " + VersionInfo.ICU_VERSION.getVersionString(2, 2) + "; "
+ "Unicode version: " + UCharacter.getUnicodeVersion().getVersionString(2, 2) + "; "
+ (CachedProps.IS_BETA ? "Unicodeβ version: " + CachedProps.CACHED_PROPS.version.getVersionString(2, 2) + "; " : "");
public static String getVersions() {
return VERSIONS;
}
static final String SUBHEAD = !CachedProps.IS_BETA ? ""
: "<p style='border: 1pt solid red;'>Properties use ICU for Unicode V" + UCharacter.getUnicodeVersion().getVersionString(2, 2)
+ "; the beta properties support Unicode V" + CachedProps.CACHED_PROPS.version.getVersionString(2, 2) + "β. "
+ "For more information, see <a target='help' href='http://cldr.unicode.org/unicode-utilities/changes'>Unicode Utilities Beta</a>.</p>"
;
public static String getSubtitle() {
return SUBHEAD;
}
}
| MylesBorins/unicodetools | UnicodeJsps/src/org/unicode/jsp/UnicodeJsp.java |
1,611 | package org.unicode.jsp;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Quoter;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.UnicodeUtilities.CodePointShower;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.text.BreakIterator;
import com.ibm.icu.text.Normalizer;
import com.ibm.icu.text.NumberFormat;
import com.ibm.icu.text.RuleBasedBreakIterator;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.ULocale;
public class UnicodeJsp {
public static NumberFormat nf = NumberFormat.getInstance(ULocale.ENGLISH);
static {
nf.setGroupingUsed(true);
nf.setMaximumFractionDigits(0);
}
public static String showBidi(String str, int baseDirection, boolean asciiHack) {
return UnicodeUtilities.showBidi(str, baseDirection, asciiHack);
}
public static String validateLanguageID(String input, String locale) {
final String result = LanguageCode.validate(input, new ULocale(locale));
return result;
}
public static String showRegexFind(String regex, String test) {
try {
final Matcher matcher = Pattern.compile(regex, Pattern.COMMENTS).matcher(test);
String result = UnicodeUtilities.toHTML.transform(matcher.replaceAll("⇑⇑$0⇓⇓"));
result = result.replaceAll("⇑⇑", "<u>").replaceAll("⇓⇓", "</u>");
return result;
} catch (final Exception e) {
return "Error: " + e.getMessage();
}
}
/**
* The regex doesn't have to have the UnicodeSets resolved.
* @param regex
* @param count
* @param maxRepeat
* @return
*/
public static String getBnf(String regexSource, int count, int maxRepeat) {
//String regex = new UnicodeRegex().compileBnf(rules);
final String regex = regexSource.replace("(?:", "(").replace("(?i)", "");
final BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
if (maxRepeat > 20) {
maxRepeat = 20;
}
bnf.setMaxRepeat(maxRepeat)
.addRules("$root=" + regex + ";")
.complete();
final StringBuffer output = new StringBuffer();
for (int i = 0; i < count; ++i) {
final String line = bnf.next();
output.append("<p>").append(UnicodeUtilities.toHTML(line)).append("</p>");
}
return output.toString();
}
public static String showBreaks(String text, String choice) {
RuleBasedBreakIterator b;
if (choice.equals("Word")) {
b = (RuleBasedBreakIterator) BreakIterator.getWordInstance();
} else if (choice.equals("Line")) {
b = (RuleBasedBreakIterator) BreakIterator.getLineInstance();
} else if (choice.equals("Sentence")) {
b = (RuleBasedBreakIterator) BreakIterator.getSentenceInstance();
} else {
b = (RuleBasedBreakIterator) BreakIterator.getCharacterInstance();
}
final Matcher decimalEscapes = Pattern.compile("&#(x)?([0-9]+);").matcher(text);
// quick hack, since hex-any doesn't do decimal escapes
int start = 0;
final StringBuffer result2 = new StringBuffer();
while (decimalEscapes.find(start)) {
final int radix = 10;
final int code = Integer.parseInt(decimalEscapes.group(2), radix);
result2.append(text.substring(start,decimalEscapes.start()) + UTF16.valueOf(code));
start = decimalEscapes.end();
}
result2.append(text.substring(start));
text = result2.toString();
int lastBreak = 0;
final StringBuffer result = new StringBuffer();
b.setText(text);
b.first();
for (int nextBreak = b.next(); nextBreak != BreakIterator.DONE; nextBreak = b.next()) {
final int status = b.getRuleStatus();
String piece = text.substring(lastBreak, nextBreak);
//piece = toHTML.transliterate(piece);
piece = UnicodeUtilities.toHTML(piece);
piece = piece.replaceAll("
","<br>");
result.append("<span class='break'>").append(piece).append("</span>");
lastBreak = nextBreak;
}
return result.toString(); }
public static void showProperties(int cp, Appendable out) throws IOException {
UnicodeUtilities.showProperties(cp, out);
}
static String defaultIdnaInput = ""
+"fass.de faß.de fäß.de xn--fa-hia.de"
+ "\n₹.com 𑀓.com"
+ "\n\u0080.com xn--a.com a\u200cb xn--ab-j1t"
+"\nöbb.at ÖBB.at ÖBB.at"
+"\nȡog.de ☕.de I♥NY.de"
+"\nABC・日本.co.jp 日本。co。jp 日本。co.jp 日本⒈co.jp"
+"\nx\\u0327\\u0301.de x\\u0301\\u0327.de"
+"\nσόλος.gr Σόλος.gr ΣΌΛΟΣ.gr"
+"\nﻋﺮﺑﻲ.de عربي.de نامهای.de نامه\\u200Cای.de".trim();
public static String getDefaultIdnaInput() {
return defaultIdnaInput;
}
public static final Transliterator UNESCAPER = Transliterator.getInstance("hex-any");
public static String getLanguageOptions(String locale) {
return LanguageCode.getLanguageOptions(new ULocale(locale));
}
public static String getTrace(Exception e) {
return Arrays.asList(e.getStackTrace()).toString().replace("\n", "<\br>");
}
public static String getSimpleSet(String setA, UnicodeSet a, boolean abbreviate, boolean escape) {
String a_out;
a.clear();
try {
//setA = UnicodeSetUtilities.MyNormalize(setA, Normalizer.NFC);
setA = setA.replace("..U+", "-\\u");
setA = setA.replace("U+", "\\u");
a.addAll(UnicodeSetUtilities.parseUnicodeSet(setA));
a_out = UnicodeUtilities.getPrettySet(a, abbreviate, escape);
} catch (final Exception e) {
a_out = e.getMessage();
}
return a_out;
}
public static void showSet(String grouping, UnicodeSet a, boolean abbreviate, boolean ucdFormat, Appendable out) throws IOException {
final CodePointShower codePointShower = new CodePointShower(abbreviate, ucdFormat, false);
UnicodeUtilities.showSet(grouping, a, codePointShower, out);
}
public static void showPropsTable(Appendable out, String propForValues, String myLink) throws IOException {
UnicodeUtilities.showPropsTable(out, propForValues, myLink);
}
public static String showTransform(String transform, String sample) {
return UnicodeUtilities.showTransform(transform, sample);
}
public static String listTransforms() {
return UnicodeUtilities.listTransforms();
}
public static void getDifferences(String setA, String setB,
boolean abbreviate, String[] abResults, int[] abSizes, String[] abLinks) {
UnicodeUtilities.getDifferences(setA, setB, abbreviate, abResults, abSizes, abLinks);
}
public static int parseCode(String text, String nextButton, String previousButton) {
//text = fromHTML.transliterate(text);
final String trimmed = text.trim();
if (trimmed.length() > 1) {
try {
text = UTF16.valueOf(Integer.parseInt(trimmed,16));
} catch (final Exception e) {}
}
int cp = UTF16.charAt(text, 0);
if (nextButton != null) {
cp += 1;
if (cp > 0x10FFFF) {
cp = 0;
}
} else if (previousButton != null) {
cp -= 1;
if (cp < 0) {
cp = 0x10FFFF;
}
}
return cp;
}
public static String getConfusables(String test, int choice) {
try {
final Confusables confusables = new Confusables(test);
switch (choice) {
case 0: // none
break;
case 1: // IDNA2008
confusables.setAllowedCharacters(Idna2003.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 2: // IDNA2008
confusables.setAllowedCharacters(Idna2008.SINGLETON.validSet_transitional);
confusables.setNormalizationCheck(Normalizer.NFC);
break;
case 3: // UTS46/39
confusables.setAllowedCharacters(new UnicodeSet(Uts46.SINGLETON.validSet_transitional).retainAll(XIDModifications.getAllowed()));
confusables.setNormalizationCheck(Normalizer.NFC);
confusables.setScriptCheck(Confusables.ScriptCheck.same);
break;
}
return getConfusablesCore(test, confusables);
} catch (final Exception e) {
return returnStackTrace(e);
}
}
private static String returnStackTrace(Exception e) {
final StringWriter s = new StringWriter();
final PrintWriter p = new PrintWriter(s);
e.printStackTrace(p);
String str = UnicodeUtilities.toHTML(s.toString());
str = str.replace("\n", "<br>");
return str;
}
public static String getConfusables(String test, boolean nfkcCheck, boolean scriptCheck, boolean idCheck, boolean xidCheck) {
try {
final Confusables confusables = new Confusables(test);
if (nfkcCheck) {
confusables.setNormalizationCheck(Normalizer.NFKC);
}
if (scriptCheck) {
confusables.setScriptCheck(Confusables.ScriptCheck.same);
}
if (idCheck) {
confusables.setAllowedCharacters(new UnicodeSet("[\\-[:L:][:M:][:N:]]"));
}
if (xidCheck) {
confusables.setAllowedCharacters(XIDModifications.getAllowed());
}
return getConfusablesCore(test, confusables);
} catch (final Exception e) {
return returnStackTrace(e);
}
}
private static String getConfusablesCore(String test, Confusables confusables) {
test = test.replaceAll("[\n\t]", " ").trim();
final StringBuilder result = new StringBuilder();
final double maxSize = confusables.getMaxSize();
final List<Collection<String>> alternates = confusables.getAlternates();
if (alternates.size() > 0) {
int max = 0;
for (final Collection<String> items : alternates) {
final int size = items.size();
if (size > max) {
max = size;
}
}
final String topCell = "<td class='smc' align='center' width='" + (100/max) +
"%'>";
final String underStart = " <span class='chb'>";
final String underEnd = "</span> ";
final UnicodeSet nsm = new UnicodeSet("[[:Mn:][:Me:]]");
result.append("<table><caption style='text-align:left'><h3>Confusable Characters</h3></caption>\n");
for (final Collection<String> items : alternates) {
result.append("<tr>");
for (final String item : items) {
result.append(topCell);
String htmlItem = UnicodeUtilities.toHTML(item);
if (nsm.containsAll(item)) {
htmlItem = " " + htmlItem + " ";
}
result.append(underStart).append(htmlItem).append(underEnd);
result.append("</td>");
}
for (int i = max - items.size(); i > 0; --i) {
result.append("<td class='smb' rowSpan='3'> </td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (final String item : items) {
result.append("<td class='smh' align='center'>");
result.append(com.ibm.icu.impl.Utility.hex(item));
result.append("</td>");
}
result.append("</tr>\n");
result.append("<tr>");
for (final String item : items) {
result.append("<td class='smn' align='center'>");
result.append(UCharacter.getName(item, " + "));
result.append("</td>");
}
result.append("</tr>\n");
}
result.append("</table>\n");
}
result.append("<p>Total raw values: " + nf.format(maxSize) + "</p>\n");
if (maxSize > 1000000) {
result.append( "<p><i>Too many raw items to process.<i></p>\n");
return result.toString();
}
result.append("<h3>Confusable Results</h3>");
int count = 0;
result.append("<div style='border: 1px solid blue'>");
for (final String item : confusables) {
++count;
if (count > 1000) {
continue;
}
if (count != 1) {
result.append("\n");
}
result.append(UnicodeUtilities.toHTML(item));
}
if (count > 1000) {
result.append(" ...\n");
}
result.append("</div>\n");
result.append("<p>Total filtered values: " + nf.format(count) + "</p>\n");
if (count > 1000) {
result.append("<p><i>Too many filtered items to display; truncating to 1,000.<i></p>\n");
}
return result.toString();
}
public static String testIdnaLines(String lines, String filter) {
return UnicodeUtilities.testIdnaLines(lines, filter);
}
public static String getIdentifier(String script) {
return UnicodeUtilities.getIdentifier(script);
}
}
| Manishearth/unicodetools | unicodetools/src/main/java/org/unicode/jsp/UnicodeJsp.java |
1,612 | package users;
import accommodations.HotelRooms;
import accommodations.PrivateAccommodation;
import accommodations.reservervations.Date;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
* Η κλάση Customers υλοποιεί τον τύπο χρήστη του πελάτη.
* Λειτουργίες: <p>
* <p>
* Κράτηση καταλύματος: {@link #TabBookAccommodation(int, String, String, Customers)},
* Αναζήτηση καταλύματος με κριτήρια: για ξενοδοχειακα δωμάτια -> {@link #TabSearchRoom(String, int, ArrayList, List)},
* για ιδιωτικά καταλύματα -> {@link #TabSearchAccommodation(String, int, ArrayList, List)}
* ακύρωση κράτησης: {@link #CancelReservation(int)}
*/
public class Customers extends Users {
private boolean activated;
/**
* Ορίζει, με βάση τις παραμέτρους του κατασκευαστή, αρχικές
* τιμές στο προφίλ του πελάτη που καλείται να δημιουργηθεί.
*
* @param username (Μοναδικό) Όνομα χρήστη.
* @param password Κωδικός χρήστη.
* @param role Ρόλος χρήστη.
* @param gender Γένος χρήστη.
*/
public Customers(String username, String password, String role, String gender)
{
super(username, password, role, gender);
this.activated = false;
}
/**
* Μέθοδος ακύρωση κράτησης.
* @param reservationID Αναγνωριστικός αριθμός κράτησης
* @return true/false ανάλογα με το αν η κράτηση ακυρώθηκε επιτυχώς ή όχι
*/
public boolean CancelReservation(int reservationID) {
if (this.getAccommodations().CancelReservationPrivateAccommodation(reservationID, this)) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("privateAccommodation.bin"))) {
out.writeObject(this.getAccommodations().getAirbnb());
} catch (IOException err) {
err.printStackTrace();
}
return true;
}
if (this.getAccommodations().CancelReservationHotelRoom(reservationID, this)) {
try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hotelRooms.bin"))) {
out.writeObject(this.getAccommodations().getRooms());
} catch (IOException err) {
err.printStackTrace();
}
return true;
}
return false;
}
/**
* Μέθοδος που επιτρέπει την αναζήτηση ιδιωτικού καταλύματος με βάση τα κριτήρια που δέχεται η μέθοδος
* ως παραμέτρους. Καλείται η μέθοδος {@link accommodations.Accommodations#SearchHotelRooms(String, int, ArrayList, List)}
* Και η λίστα που επιστρέφει επιστρέφεται και απο αυτήν την συνάρτηση.
* @param address Διεύθυνση ξενοδοχείου. Υπορεωτικό για την αναζήτηση δωματίου
* @param capacity Χωρητικότητα ατόμων
* @param ranges Λίστα με το εύρος τετραγωνικών/τιμής
* @param characteristics Λίστα με τα χαρακτηριστικά
* @return Λίστα με όλα τα δωμάτια που βρέθηκαν με τα δοθέντα χαρακτηριστικά
* null αν δεν βρεθούν δωμάτια.
*/
public ArrayList<HotelRooms> TabSearchRoom(
String address, int capacity,
ArrayList<ArrayList<Integer>> ranges, List<String> characteristics) {
ArrayList<HotelRooms> allHotelRoomsFound = this.getAccommodations().SearchHotelRooms(
address, capacity,
ranges, characteristics);
if (allHotelRoomsFound != null) {
if (allHotelRoomsFound.size() == 0) {
return null;
}
}
return allHotelRoomsFound;
}
/**
* Μέθοδος που επιτρέπει την αναζήτηση ιδιωτικού καταλύματος με βάση τα κριτήρια που δέχεται η μέθοδος
* ως παραμέτρους. Καλείται η μέθοδος {@link accommodations.Accommodations#SearchPrivateAccommodations(String, int, ArrayList, List)}
* Και η λίστα που επιστρέφει επιστρέφεται και απο αυτήν την συνάρτηση.
*
* @param address Διεύθυνση ιδιωτικού καταλύματος. Υποχρεωτικό πεδίο για την αναζήτηση
* @param capacity Χωρητικότητα δωματίου
* @param ranges Λίστα με το εύρος αναζήτησης τετραγωνικών και τιμής
* @param characteristics Λίστα με τα χαρακτηριστικά
* @return Λίστα με όλα τα καταλύματα που βρέθηκαν με τα δοθέντα χαρακτηριστικά
* null αν δεν βρεθούν καταλύματα με τα συγκεκριμένα χαρακτηριστικά
*/
public ArrayList<PrivateAccommodation> TabSearchAccommodation(
String address, int capacity,
ArrayList<ArrayList<Integer>> ranges, List<String> characteristics) {
ArrayList<PrivateAccommodation> allAccommodationsFound = this.getAccommodations().SearchPrivateAccommodations(
address, capacity,
ranges, characteristics);
if (allAccommodationsFound != null) {
if (allAccommodationsFound.size() == 0) {
return null;
}
}
return allAccommodationsFound;
}
/**
* Μέθοδος κράτησης καταλύματος.
* Η κράτηση πραγματοποιείται με την επιτυχή καταχώρηση του αναγνωριστικού αριθμού και σε περίπτωση που για
* τις επιθυμητές ημερομηνίες δεν έχει κάνει κάποιος άλλος πελάτης κράτηση στο κατάλυμα αυτό
* @param ID Αναγνωριστικός αριθμός δωματίου για το οποίο ο χρήστης επιθυμεί να κάνει κράτηση
* @param startDate Ημερομηνία "από"
* @param toDate Ημερομηνία "εως"
* @param customer Πελάτης που επιθυμεί να κάνει κράτηση
* @return true/false Ανάλογα με το αν έγινε επιτυχημένη κράτηση ή όχι
*/
public boolean TabBookAccommodation(int ID, String startDate, String toDate, Customers customer/*int temp*/) {
Date tempDate = new Date();
int preferredRoomPosition = this.getAccommodations().FindRoom(ID);
if (preferredRoomPosition != -1) {
HotelRooms preferredRoom = this.getAccommodations().getRooms().get(preferredRoomPosition);
return preferredRoom.Reserve(customer, tempDate.intermediateDates(tempDate.dateGenerator(startDate), tempDate.dateGenerator(toDate)));
}
int preferredAccommodationPosition = this.getAccommodations().FindAccommodation(ID);
if (preferredAccommodationPosition != -1) {
PrivateAccommodation preferredAccommodation = this.getAccommodations().getAirbnb().get(preferredAccommodationPosition);
return preferredAccommodation.Reserve(customer, tempDate.intermediateDates(tempDate.dateGenerator(startDate), tempDate.dateGenerator(toDate)));
}
return false;
}
public void activate() {
this.activated = true;
}
}
| NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/users/Customers.java |
1,613 | package org.unicode.jsptest;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.idna.Idna;
import org.unicode.idna.Idna.IdnaType;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.Common;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.XPropertyFactory;
import org.unicode.props.UnicodeProperty;
import org.unicode.unittest.TestFmwkMinusMinus;
public class TestJsp extends TestFmwkMinusMinus {
private static final String enSample =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 =
new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE =
new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
static UnicodeSet IPA =
new UnicodeSet(
"[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]")
.freeze();
static String IPA_SAMPLE =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {
language,
script,
region,
mixed,
fail
}
static UnicodeSetPrettyPrinter pretty =
new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0, max) + "...";
}
return prettySet;
}
@Test
public void TestLanguage() {
String foo = UnicodeJsp.getLanguageOptions("de");
assertContains(foo, "<option value='de' selected>Deutsch / German</option>");
String fii = UnicodeJsp.validateLanguageID("en", "fr");
assertContains(fii, "draft-ietf-ltru-4646bis");
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")=" + fii, !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")=" + fii, !expectedUni, error[0]);
}
// public void Test2003vsUts46() {
//
// ToolUnicodePropertySource properties = ToolUnicodePropertySource.make("6.0");
// UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
//
// for (UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
// int i = it.codepoint;
// String map2003 = Idna2003.SINGLETON.mappings.get(i);
// String map46 = Uts46.SINGLETON.mappings.get(i);
// IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
// IdnaType type46 = Uts46.SINGLETON.types.get(i);
// if (type46 == IdnaType.ignored) {
// assertNotNull("tr46ignored U+" + codeAndName(i), map46);
// } else if (type46 == IdnaType.deviation) {
// type46 = map46 == null || map46.length() == 0
// ? IdnaType.ignored
// : IdnaType.mapped;
// }
// if (type2003 == IdnaType.ignored) {
// assertNotNull("2003ignored", map2003);
// }
// if (type46 != type2003 || !UnicodeProperty.equals(map46, map2003)) {
// String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
// String nfcf = nfkc_cfMap.get(i);
// if (!map2.equals(nfcf)) continue;
// String typeDiff = type46 + "\tvs 2003\t" + type2003;
// String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
// errln((codeAndName(i)) + "\tdifference:"
// + (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
// + "\tNFKCCF:\t" + codeAndName(nfcf));
// }
// }
// }
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null
? null
: (Utility.hex(i, 4, ",", true, new StringBuilder())
+ " ( "
+ i
+ " ) "
+ UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void oldTestIdnaAndIcu() {
StringBuffer inbuffer = new StringBuffer();
TypeAndMap typeAndMapIcu = new TypeAndMap();
UnicodeMap<String> errors = new UnicodeMap<String>();
int count = 0;
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type
|| !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errors.put(
cp,
(type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)
? "\tmap:\t" + mapDiff
: ""));
// errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
// + (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ?
// "\tmap:\t" + mapDiff : ""));
if (++count > 50) {
break;
}
}
}
if (errors.size() != 0) {
for (String value : errors.values()) {
UnicodeSet s = errors.getSet(value);
errln(value + "\t" + s.toPattern(false));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer)
throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
IDNA icuIdna = IDNA.getUTS46Instance(0);
IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuilder outbuffer =
icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna)
throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
String map2003 = Idna2003.SINGLETON.mappings.get(i);
String map46 = Uts46.SINGLETON.mappings.get(i);
String map2008 = Idna2008.SINGLETON.mappings.get(i);
IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(
String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) return;
if (t1 == IdnaType.valid && t2 == IdnaType.valid) return;
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) return;
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
@Test
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
// showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop);
i <= UCharacter.getIntPropertyMaxValue(prop);
++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t" + nameChoice + "\t" + propertyValueName);
} catch (Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
Set<String> languages = new TreeSet<String>();
Set<String> scripts = new TreeSet<String>();
Set<String> countries = new TreeSet<String>();
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
Map<ULocale, Counter<Subtag>> canDisplay =
new TreeMap<ULocale, Counter<Subtag>>(
new Comparator<ULocale>() {
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toString());
}
});
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet =
new UnicodeSet()
.addAll(
localeData.getExemplarSet(
UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(
localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars =
(UnicodeSet)
new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]")
.addAll(exemplarSet)
.freeze();
Set<String> mixedSamples = new TreeSet<String>();
for (String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
UnicodeSet missing = new UnicodeSet();
for (String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total =
counter.getTotal()
- counter.getCount(Subtag.mixed)
- counter.getCount(Subtag.fail);
final String missingDisplay =
mixedSamples.size() == 0
? ""
: "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(
displayLanguage
+ "\t"
+ displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t"
+ (total / (double) counter.getTotal())
+ "\t"
+ total
+ "\t"
+ counter.getCount(Subtag.language)
+ "\t"
+ counter.getCount(Subtag.script)
+ "\t"
+ counter.getCount(Subtag.region)
+ "\t"
+ counter.getCount(Subtag.mixed)
+ "\t"
+ counter.getCount(Subtag.fail)
+ missingDisplay);
}
}
private void add(
ULocale displayLanguage,
Subtag subtag,
String code,
Counter<Subtag> counter,
UnicodeSet okChars,
Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {
code,
localized,
badLocalization
}
private Display canDisplay(
ULocale displayLanguage,
Subtag subtag,
String code,
UnicodeSet okChars,
Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default:
throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
@Test
public void TestLanguageTag() {
String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID(
"gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(
null,
"invalid\\sextlang\\scode",
UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(
null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(
message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(
message,
Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL),
false,
actual);
}
// return handleAssert(expected == actual, message, stringFor(expected),
// stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(
result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
@Test
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
// logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
// logln(sample);
String deva =
"कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(
String testString, String transId, UnicodeSet exceptionsAllowed) {
String pieces[] = testString.split(",\\s*");
UnicodeSet shouldNotBeLeftOver =
new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
UnicodeSet allProblems = new UnicodeSet();
for (String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
// logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing =
new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
warnln("Leftover from " + transId + ": " + missing.toPattern(false));
Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
// Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
// Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
warnln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
@Test
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
@Test
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
@Test
public void TestGrouping() throws IOException {
StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet(
"sc gc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet(
"subhead",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "a=A595");
}
@Test
public void TestStuff() throws IOException {
// int script = UScript.getScript(0xA6E6);
// int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
// logln(propValue);
// logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
try (final PrintWriter printWriter = new PrintWriter(System.out)) {
// if (true) return;
UnicodeJsp.showSet(
"sc gc",
"",
new UnicodeSet("[[:ascii:]{123}{ab}{456}]"),
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"", "", new UnicodeSet("[\\u0080\\U0010FFFF]"), true, true, true, printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"),
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"),
true,
true,
true,
printWriter);
String[] abResults = new String[3];
String[] abLinks = new String[3];
int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\r\n\t" + abResults[i] + "\r\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", "", unicodeSet, true, true, true, printWriter);
// String archaic =
// "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
//
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
//
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
// "";
// UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false,
// false, printWriter);
UnicodeJsp.showSet(
"",
"",
UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"),
false,
false,
true,
printWriter);
}
}
@Test
public void TestShowProperties() throws IOException {
StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
// logln(out);
}
public void TestIdentifiers() throws IOException {
String out = UnicodeUtilities.getIdentifier("Latin");
assertTrue("identifier info", out.toString().contains("U+016F"));
logln(out.toString());
// logln(out);
}
@Test
public void TestShowSet() throws IOException {
StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc",
// UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet(
"sc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"),
false,
true,
true,
out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
@Test
public void TestParameters() {
UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
@Test
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals(
"",
"<u>abcc</u> <u>abxyzc</u> ab$c",
UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
@Test
public void TestIdna() {
boolean[] error = new boolean[1];
String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkValidIdna(Uts46.SINGLETON, "≠"); // valid since Unicode 15.1
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
// checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(
Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertTrue("uts46 not equals", Uts46.SINGLETON.isValid("≠")); // valid since Unicode 15.1
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
// showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue(
"contains hyphen",
UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(
Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
@Test
public void TestBnf() {
UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{"c = a* wq;\n" + "a = xyz;\n" + "b = a{2} c;\n"},
{"c = a* b;\n" + "a = xyz;\n" + "b = a{2} c;\n", "Exception"},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n"
+ "scheme = reserved+;\n"
+ "host = \\/\\/ reserved+;\n"
+ "query = [\\=reserved]+;\n"
+ "fragment = reserved+;\n"
+ "reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"
},
// {
//
// "/Users/markdavis/Documents/workspace/cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (int i = 0; i < tests.length; ++i) {
String test = tests[i][0];
final boolean expectException =
tests[i].length < 2 ? false : tests[i][1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
String result2 =
result.replaceAll(
"[0-9]+%", ""); // just so we can use the language subtag stuff
String resolved = regex.transform(result2);
// logln(resolved);
Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < tests[i].length; ++j) {
String check = tests[i][j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
// logln("Result: " + result + "\n" + checks + "\n" + test);
String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
// logln(randomBnf);
} catch (Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
@Test
public void TestBnfMax() {
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10).addRules("$root=[0-9]+;").complete();
for (int i = 0; i < 100; ++i) {
String s = bnf.next();
assertTrue(
"Max too large? " + i + ", " + s.length() + ", " + s,
1 <= s.length() && s.length() < 11);
}
}
@Test
public void TestBnfGen() {
if (logKnownIssue("x", "old test disabling for now")) {
return;
}
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
String bnf =
"item = word | number;\n"
+ "word = $alpha+;\n"
+ "number = (digits (separator digits)?);\n"
+ "digits = [:Pd:]+;\n"
+ "separator = [[:WB=MB:][:WB=MN:]];\n"
+ "$alpha = [:alphabetic:];";
String fixedbnf = new UnicodeRegex().compileBnf(bnf);
String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
// String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
// assertContains(random, "\\U0002A089");
}
@Test
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertEquals(test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertContains(test, expectedSubset, actual);
}
@Test
public void TestConfusable() {
String test = "l l l l o̸ ä O O v v";
String string = UnicodeJsp.showTransform("confusable", test);
assertEquals(null, test, string);
string = UnicodeJsp.showTransform("confusableLower", test);
assertEquals(null, test, string);
String listedTransforms = UnicodeJsp.listTransforms();
if (!listedTransforms.contains("confusable")) {
errln("Missing 'confusable' " + listedTransforms);
}
}
}
| eggrobin/unicodetools | UnicodeJsps/src/test/java/org/unicode/jsptest/TestJsp.java |
1,614 | package org.unicode.jsptest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.jsp.Common;
import org.unicode.jsp.Idna;
import org.unicode.jsp.Idna.IdnaType;
import org.unicode.unittest.TestFmwkMinusMinus;
import org.unicode.jsp.Idna2003;
import org.unicode.jsp.Idna2008;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeProperty;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.Uts46;
import org.unicode.jsp.XPropertyFactory;
import com.ibm.icu.dev.test.TestFmwk;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
public class TestJsp extends TestFmwkMinusMinus {
private static final String enSample = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 = new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE = new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
static UnicodeSet IPA = new UnicodeSet("[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]").freeze();
static String IPA_SAMPLE = "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {language, script, region, mixed, fail}
static UnicodeSetPrettyPrinter pretty = new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0,max) + "...";
}
return prettySet;
}
@Test
public void TestLanguage() {
String foo = UnicodeJsp.getLanguageOptions("de");
assertContains(foo, "<option value='de' selected>Deutsch / German</option>");
String fii = UnicodeJsp.validateLanguageID("en", "fr");
assertContains(fii, "draft-ietf-ltru-4646bis");
}
@EnabledIf(value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken", disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")="+fii, !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")="+fii, !expectedUni, error[0]);
}
// public void Test2003vsUts46() {
//
// ToolUnicodePropertySource properties = ToolUnicodePropertySource.make("6.0");
// UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
//
// for (UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
// int i = it.codepoint;
// String map2003 = Idna2003.SINGLETON.mappings.get(i);
// String map46 = Uts46.SINGLETON.mappings.get(i);
// IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
// IdnaType type46 = Uts46.SINGLETON.types.get(i);
// if (type46 == IdnaType.ignored) {
// assertNotNull("tr46ignored U+" + codeAndName(i), map46);
// } else if (type46 == IdnaType.deviation) {
// type46 = map46 == null || map46.length() == 0
// ? IdnaType.ignored
// : IdnaType.mapped;
// }
// if (type2003 == IdnaType.ignored) {
// assertNotNull("2003ignored", map2003);
// }
// if (type46 != type2003 || !UnicodeProperty.equals(map46, map2003)) {
// String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
// String nfcf = nfkc_cfMap.get(i);
// if (!map2.equals(nfcf)) continue;
// String typeDiff = type46 + "\tvs 2003\t" + type2003;
// String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
// errln((codeAndName(i)) + "\tdifference:"
// + (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
// + "\tNFKCCF:\t" + codeAndName(nfcf));
// }
// }
// }
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null ? null : (Utility.hex(i, 4, ",", true, new StringBuilder()) + " ( " + i + " ) " + UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void oldTestIdnaAndIcu() {
StringBuffer inbuffer = new StringBuffer();
TypeAndMap typeAndMapIcu = new TypeAndMap();
UnicodeMap<String> errors = new UnicodeMap<String>();
int count = 0;
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type || !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errors.put(cp, (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ? "\tmap:\t" + mapDiff : ""));
// errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
// + (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ? "\tmap:\t" + mapDiff : ""));
if (++count > 50) {
break;
}
}
}
if (errors.size() != 0) {
for (String value : errors.values()) {
UnicodeSet s = errors.getSet(value);
errln(value + "\t" + s.toPattern(false));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer) throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
IDNA icuIdna = IDNA.getUTS46Instance(0);
IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuilder outbuffer = icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna) throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
@EnabledIf(value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken", disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
String map2003 = Idna2003.SINGLETON.mappings.get(i);
String map46 = Uts46.SINGLETON.mappings.get(i);
String map2008 = Idna2008.SINGLETON.mappings.get(i);
IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) return;
if (t1 == IdnaType.valid && t2 == IdnaType.valid) return;
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) return;
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
@Test
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
//showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop); i <= UCharacter.getIntPropertyMaxValue(prop); ++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t"+ nameChoice + "\t" + propertyValueName);
} catch (Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
Set<String> languages = new TreeSet<String>();
Set<String> scripts = new TreeSet<String>();
Set<String> countries = new TreeSet<String>();
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
Map<ULocale,Counter<Subtag>> canDisplay = new TreeMap<ULocale,Counter<Subtag>>(new Comparator<ULocale>() {
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toString());
}
});
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet = new UnicodeSet()
.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars = (UnicodeSet) new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]").addAll(exemplarSet).freeze();
Set<String> mixedSamples = new TreeSet<String>();
for (String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
UnicodeSet missing = new UnicodeSet();
for (String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total = counter.getTotal() - counter.getCount(Subtag.mixed) - counter.getCount(Subtag.fail);
final String missingDisplay = mixedSamples.size() == 0 ? "" : "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(displayLanguage + "\t" + displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t" + (total/(double)counter.getTotal())
+ "\t" + total
+ "\t" + counter.getCount(Subtag.language)
+ "\t" + counter.getCount(Subtag.script)
+ "\t" + counter.getCount(Subtag.region)
+ "\t" + counter.getCount(Subtag.mixed)
+ "\t" + counter.getCount(Subtag.fail)
+ missingDisplay
);
}
}
private void add(ULocale displayLanguage, Subtag subtag, String code, Counter<Subtag> counter, UnicodeSet okChars, Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {code, localized, badLocalization}
private Display canDisplay(ULocale displayLanguage, Subtag subtag, String code, UnicodeSet okChars, Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default: throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
@Test
public void TestLanguageTag() {
String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(null, "invalid\\sextlang\\scode", UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), false, actual);
}
// return handleAssert(expected == actual, message, stringFor(expected), stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
@Test
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
//logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
//logln(sample);
String deva = "कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(String testString, String transId, UnicodeSet exceptionsAllowed) {
String pieces[] = testString.split(",\\s*");
UnicodeSet shouldNotBeLeftOver = new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
UnicodeSet allProblems = new UnicodeSet();
for (String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
//logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing = new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
warnln("Leftover from " + transId + ": " + missing.toPattern(false));
Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
//Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
//Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
warnln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
@Test
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
@Test
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
@Test
public void TestGrouping() throws IOException {
StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet("sc gc", "", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, true, printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet("subhead", "", UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"), true, true, true, printWriter);
assertContains(printWriter.toString(), "a=A595");
}
@Test
public void TestStuff() throws IOException {
//int script = UScript.getScript(0xA6E6);
//int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
//logln(propValue);
//logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
try (final PrintWriter printWriter = new PrintWriter(System.out)) {
//if (true) return;
UnicodeJsp.showSet("sc gc", "", new UnicodeSet("[[:ascii:]{123}{ab}{456}]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080\\U0010FFFF]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"), true, true, true, printWriter);
UnicodeJsp.showSet("", "", new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"), true, true, true, printWriter);
String[] abResults = new String[3];
String[] abLinks = new String[3];
int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\r\n\t" + abResults[i] + "\r\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", "", unicodeSet, true, true, true, printWriter);
// String archaic = "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
//"";
//UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false, false, printWriter);
UnicodeJsp.showSet("","", UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"), false, false, true, printWriter);
}
}
@Test
public void TestShowProperties() throws IOException {
StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
//logln(out);
}
public void TestIdentifiers() throws IOException {
String out = UnicodeUtilities.getIdentifier("Latin");
assertTrue("identifier info", out.toString().contains("U+016F"));
logln(out.toString());
//logln(out);
}
@Test
public void TestShowSet() throws IOException {
StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]", TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet("sc", "", UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"), false, true,true, out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
@Test
public void TestParameters() {
UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
@Test
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals("", "<u>abcc</u> <u>abxyzc</u> ab$c", UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
@Test
public void TestIdna() {
boolean[] error = new boolean[1];
String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkInvalidIdna(Uts46.SINGLETON, "≠");
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
//checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertFalse("uts46 not equals", Uts46.SINGLETON.isValid("≠"));
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
//showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue("contains hyphen", UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
@Test
public void TestBnf() {
UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{
"c = a* wq;\n" +
"a = xyz;\n" +
"b = a{2} c;\n"
},
{
"c = a* b;\n" +
"a = xyz;\n" +
"b = a{2} c;\n",
"Exception"
},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n" +
"scheme = reserved+;\n" +
"host = \\/\\/ reserved+;\n" +
"query = [\\=reserved]+;\n" +
"fragment = reserved+;\n" +
"reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"},
// {
// "/Users/markdavis/Documents/workspace/cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (int i = 0; i < tests.length; ++i) {
String test = tests[i][0];
final boolean expectException = tests[i].length < 2 ? false : tests[i][1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
String result2 = result.replaceAll("[0-9]+%", ""); // just so we can use the language subtag stuff
String resolved = regex.transform(result2);
//logln(resolved);
Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < tests[i].length; ++j) {
String check = tests[i][j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
//logln("Result: " + result + "\n" + checks + "\n" + test);
String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
//logln(randomBnf);
} catch (Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
@Test
public void TestBnfMax() {
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10)
.addRules("$root=[0-9]+;")
.complete();
for (int i = 0; i < 100; ++i) {
String s = bnf.next();
assertTrue("Max too large? " + i + ", " + s.length() + ", " + s, 1 <= s.length() && s.length() < 11);
}
}
@Test
public void TestBnfGen() {
if (logKnownIssue("x", "old test disabling for now")) {
return;
}
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
String bnf = "item = word | number;\n" +
"word = $alpha+;\n" +
"number = (digits (separator digits)?);\n" +
"digits = [:Pd:]+;\n" +
"separator = [[:WB=MB:][:WB=MN:]];\n" +
"$alpha = [:alphabetic:];";
String fixedbnf = new UnicodeRegex().compileBnf(bnf);
String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
//String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
//assertContains(random, "\\U0002A089");
}
@Test
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
assertEquals(test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual , true, false);
assertContains(test, expectedSubset, actual);
}
@Test
public void TestConfusable() {
String test = "l l l l o̸ ä O O v v";
String string = UnicodeJsp.showTransform("confusable", test);
assertEquals(null, test, string);
string = UnicodeJsp.showTransform("confusableLower", test);
assertEquals(null, test, string);
String listedTransforms = UnicodeJsp.listTransforms();
if (!listedTransforms.contains("confusable")) {
errln("Missing 'confusable' " + listedTransforms);
}
}
}
| Mc480/unicodetools | UnicodeJsps/src/test/java/org/unicode/jsptest/TestJsp.java |
1,615 | package org.unicode.jsptest;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.idna.Idna;
import org.unicode.idna.Idna.IdnaType;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.Common;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.XPropertyFactory;
import org.unicode.props.UnicodeProperty;
import org.unicode.unittest.TestFmwkMinusMinus;
public class TestJsp extends TestFmwkMinusMinus {
private static final String enSample =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 =
new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE =
new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
static UnicodeSet IPA =
new UnicodeSet(
"[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]")
.freeze();
static String IPA_SAMPLE =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {
language,
script,
region,
mixed,
fail
}
static UnicodeSetPrettyPrinter pretty =
new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0, max) + "...";
}
return prettySet;
}
@Test
public void TestLanguage() {
String foo = UnicodeJsp.getLanguageOptions("de");
assertContains(foo, "<option value='de' selected>Deutsch / German</option>");
String fii = UnicodeJsp.validateLanguageID("en", "fr");
assertContains(fii, "draft-ietf-ltru-4646bis");
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")=" + fii, !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")=" + fii, !expectedUni, error[0]);
}
// public void Test2003vsUts46() {
//
// ToolUnicodePropertySource properties = ToolUnicodePropertySource.make("6.0");
// UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
//
// for (UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
// int i = it.codepoint;
// String map2003 = Idna2003.SINGLETON.mappings.get(i);
// String map46 = Uts46.SINGLETON.mappings.get(i);
// IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
// IdnaType type46 = Uts46.SINGLETON.types.get(i);
// if (type46 == IdnaType.ignored) {
// assertNotNull("tr46ignored U+" + codeAndName(i), map46);
// } else if (type46 == IdnaType.deviation) {
// type46 = map46 == null || map46.length() == 0
// ? IdnaType.ignored
// : IdnaType.mapped;
// }
// if (type2003 == IdnaType.ignored) {
// assertNotNull("2003ignored", map2003);
// }
// if (type46 != type2003 || !UnicodeProperty.equals(map46, map2003)) {
// String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
// String nfcf = nfkc_cfMap.get(i);
// if (!map2.equals(nfcf)) continue;
// String typeDiff = type46 + "\tvs 2003\t" + type2003;
// String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
// errln((codeAndName(i)) + "\tdifference:"
// + (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
// + "\tNFKCCF:\t" + codeAndName(nfcf));
// }
// }
// }
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null
? null
: (Utility.hex(i, 4, ",", true, new StringBuilder())
+ " ( "
+ i
+ " ) "
+ UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void oldTestIdnaAndIcu() {
StringBuffer inbuffer = new StringBuffer();
TypeAndMap typeAndMapIcu = new TypeAndMap();
UnicodeMap<String> errors = new UnicodeMap<String>();
int count = 0;
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type
|| !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errors.put(
cp,
(type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)
? "\tmap:\t" + mapDiff
: ""));
// errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
// + (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ?
// "\tmap:\t" + mapDiff : ""));
if (++count > 50) {
break;
}
}
}
if (errors.size() != 0) {
for (String value : errors.values()) {
UnicodeSet s = errors.getSet(value);
errln(value + "\t" + s.toPattern(false));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer)
throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
IDNA icuIdna = IDNA.getUTS46Instance(0);
IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuilder outbuffer =
icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna)
throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
String map2003 = Idna2003.SINGLETON.mappings.get(i);
String map46 = Uts46.SINGLETON.mappings.get(i);
String map2008 = Idna2008.SINGLETON.mappings.get(i);
IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(
String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) return;
if (t1 == IdnaType.valid && t2 == IdnaType.valid) return;
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) return;
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
@Test
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
// showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop);
i <= UCharacter.getIntPropertyMaxValue(prop);
++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t" + nameChoice + "\t" + propertyValueName);
} catch (Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
Set<String> languages = new TreeSet<String>();
Set<String> scripts = new TreeSet<String>();
Set<String> countries = new TreeSet<String>();
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
Map<ULocale, Counter<Subtag>> canDisplay =
new TreeMap<ULocale, Counter<Subtag>>(
new Comparator<ULocale>() {
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toString());
}
});
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet =
new UnicodeSet()
.addAll(
localeData.getExemplarSet(
UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(
localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars =
(UnicodeSet)
new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]")
.addAll(exemplarSet)
.freeze();
Set<String> mixedSamples = new TreeSet<String>();
for (String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
UnicodeSet missing = new UnicodeSet();
for (String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total =
counter.getTotal()
- counter.getCount(Subtag.mixed)
- counter.getCount(Subtag.fail);
final String missingDisplay =
mixedSamples.size() == 0
? ""
: "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(
displayLanguage
+ "\t"
+ displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t"
+ (total / (double) counter.getTotal())
+ "\t"
+ total
+ "\t"
+ counter.getCount(Subtag.language)
+ "\t"
+ counter.getCount(Subtag.script)
+ "\t"
+ counter.getCount(Subtag.region)
+ "\t"
+ counter.getCount(Subtag.mixed)
+ "\t"
+ counter.getCount(Subtag.fail)
+ missingDisplay);
}
}
private void add(
ULocale displayLanguage,
Subtag subtag,
String code,
Counter<Subtag> counter,
UnicodeSet okChars,
Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {
code,
localized,
badLocalization
}
private Display canDisplay(
ULocale displayLanguage,
Subtag subtag,
String code,
UnicodeSet okChars,
Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default:
throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
@Test
public void TestLanguageTag() {
String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID(
"gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(
null,
"invalid\\sextlang\\scode",
UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(
null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(
message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(
message,
Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL),
false,
actual);
}
// return handleAssert(expected == actual, message, stringFor(expected),
// stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(
result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
@Test
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
// logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
// logln(sample);
String deva =
"कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(
String testString, String transId, UnicodeSet exceptionsAllowed) {
String pieces[] = testString.split(",\\s*");
UnicodeSet shouldNotBeLeftOver =
new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
UnicodeSet allProblems = new UnicodeSet();
for (String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
// logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing =
new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
warnln("Leftover from " + transId + ": " + missing.toPattern(false));
Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
// Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
// Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
warnln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
@Test
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
@Test
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
@Test
public void TestGrouping() throws IOException {
StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet(
"sc gc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
false,
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet(
"subhead",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
false,
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "a=A595");
}
@Test
public void TestStuff() throws IOException {
// int script = UScript.getScript(0xA6E6);
// int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
// logln(propValue);
// logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
try (final PrintWriter printWriter = new PrintWriter(System.out)) {
// if (true) return;
UnicodeJsp.showSet(
"sc gc",
"",
new UnicodeSet("[[:ascii:]{123}{ab}{456}]"),
false,
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080\\U0010FFFF]"),
false,
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"),
false,
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"),
false,
true,
true,
true,
printWriter);
String[] abResults = new String[3];
String[] abLinks = new String[3];
int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\r\n\t" + abResults[i] + "\r\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", "", unicodeSet, false, true, true, true, printWriter);
// String archaic =
// "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
//
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
//
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
// "";
// UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false,
// false, printWriter);
UnicodeJsp.showSet(
"",
"",
UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"),
false,
false,
false,
true,
printWriter);
}
}
@Test
public void TestShowProperties() throws IOException {
StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, "", false, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
// logln(out);
}
public void TestIdentifiers() throws IOException {
String out = UnicodeUtilities.getIdentifier("Latin", false);
assertTrue("identifier info", out.toString().contains("U+016F"));
logln(out.toString());
// logln(out);
}
@Test
public void TestShowSet() throws IOException {
StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc",
// UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet(
"sc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"),
false,
false,
true,
true,
out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
@Test
public void TestParameters() {
UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
@Test
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals(
"",
"<u>abcc</u> <u>abxyzc</u> ab$c",
UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
@Test
public void TestIdna() {
boolean[] error = new boolean[1];
String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkValidIdna(Uts46.SINGLETON, "≠"); // valid since Unicode 15.1
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
// checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(
Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertTrue("uts46 not equals", Uts46.SINGLETON.isValid("≠")); // valid since Unicode 15.1
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
// showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue(
"contains hyphen",
UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(
Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
@Test
public void TestBnf() {
UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{"c = a* wq;\n" + "a = xyz;\n" + "b = a{2} c;\n"},
{"c = a* b;\n" + "a = xyz;\n" + "b = a{2} c;\n", "Exception"},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n"
+ "scheme = reserved+;\n"
+ "host = \\/\\/ reserved+;\n"
+ "query = [\\=reserved]+;\n"
+ "fragment = reserved+;\n"
+ "reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"
},
// {
//
// "/Users/markdavis/Documents/workspace/cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (int i = 0; i < tests.length; ++i) {
String test = tests[i][0];
final boolean expectException =
tests[i].length < 2 ? false : tests[i][1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
String result2 =
result.replaceAll(
"[0-9]+%", ""); // just so we can use the language subtag stuff
String resolved = regex.transform(result2);
// logln(resolved);
Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < tests[i].length; ++j) {
String check = tests[i][j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
// logln("Result: " + result + "\n" + checks + "\n" + test);
String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
// logln(randomBnf);
} catch (Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
@Test
public void TestBnfMax() {
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10).addRules("$root=[0-9]+;").complete();
for (int i = 0; i < 100; ++i) {
String s = bnf.next();
assertTrue(
"Max too large? " + i + ", " + s.length() + ", " + s,
1 <= s.length() && s.length() < 11);
}
}
@Test
public void TestBnfGen() {
if (logKnownIssue("x", "old test disabling for now")) {
return;
}
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
String bnf =
"item = word | number;\n"
+ "word = $alpha+;\n"
+ "number = (digits (separator digits)?);\n"
+ "digits = [:Pd:]+;\n"
+ "separator = [[:WB=MB:][:WB=MN:]];\n"
+ "$alpha = [:alphabetic:];";
String fixedbnf = new UnicodeRegex().compileBnf(bnf);
String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
// String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
// assertContains(random, "\\U0002A089");
}
@Test
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertEquals(test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertContains(test, expectedSubset, actual);
}
@Test
public void TestConfusable() {
String test = "l l l l o̸ ä O O v v";
String string = UnicodeJsp.showTransform("confusable", test);
assertEquals(null, test, string);
string = UnicodeJsp.showTransform("confusableLower", test);
assertEquals(null, test, string);
String listedTransforms = UnicodeJsp.listTransforms();
if (!listedTransforms.contains("confusable")) {
errln("Missing 'confusable' " + listedTransforms);
}
}
}
| unicode-org/unicodetools | UnicodeJsps/src/test/java/org/unicode/jsptest/TestJsp.java |
1,616 | package org.unicode.jsptest;
import com.ibm.icu.dev.util.UnicodeMap;
import com.ibm.icu.impl.Utility;
import com.ibm.icu.lang.UCharacter;
import com.ibm.icu.lang.UProperty;
import com.ibm.icu.lang.UProperty.NameChoice;
import com.ibm.icu.text.Collator;
import com.ibm.icu.text.IDNA;
import com.ibm.icu.text.StringPrepParseException;
import com.ibm.icu.text.Transliterator;
import com.ibm.icu.text.UTF16;
import com.ibm.icu.text.UnicodeSet;
import com.ibm.icu.util.LocaleData;
import com.ibm.icu.util.ULocale;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledIf;
import org.unicode.cldr.util.BNF;
import org.unicode.cldr.util.Counter;
import org.unicode.cldr.util.Quoter;
import org.unicode.cldr.util.UnicodeSetPrettyPrinter;
import org.unicode.idna.Idna;
import org.unicode.idna.Idna.IdnaType;
import org.unicode.idna.Idna2003;
import org.unicode.idna.Idna2008;
import org.unicode.idna.Uts46;
import org.unicode.jsp.Common;
import org.unicode.jsp.UnicodeJsp;
import org.unicode.jsp.UnicodeRegex;
import org.unicode.jsp.UnicodeSetUtilities;
import org.unicode.jsp.UnicodeUtilities;
import org.unicode.jsp.UtfParameters;
import org.unicode.jsp.XPropertyFactory;
import org.unicode.props.UnicodeProperty;
import org.unicode.unittest.TestFmwkMinusMinus;
public class TestJsp extends TestFmwkMinusMinus {
private static final String enSample =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z";
static final UnicodeSet U5_2 = new UnicodeSet().applyPropertyAlias("age", "5.2").freeze();
public static final UnicodeSet U5_1 =
new UnicodeSet().applyPropertyAlias("age", "5.1").freeze();
static UnicodeSet BREAKING_WHITESPACE =
new UnicodeSet("[\\p{whitespace=true}-\\p{linebreak=glue}]").freeze();
static UnicodeSet IPA =
new UnicodeSet(
"[a-zæçðøħŋœǀ-ǃɐ-ɨɪ-ɶ ɸ-ɻɽɾʀ-ʄʈ-ʒʔʕʘʙʛ-ʝʟʡʢ ʤʧʰ-ʲʴʷʼˈˌːˑ˞ˠˤ̀́̃̄̆̈ ̘̊̋̏-̜̚-̴̠̤̥̩̪̬̯̰̹-̽͜ ͡βθχ↑-↓↗↘]")
.freeze();
static String IPA_SAMPLE =
"a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, æ, ç, ð, ø, ħ, ŋ, œ, ǀ, ǁ, ǂ, ǃ, ɐ, ɑ, ɒ, ɓ, ɔ, ɕ, ɖ, ɗ, ɘ, ə, ɚ, ɛ, ɜ, ɝ, ɞ, ɟ, ɠ, ɡ, ɢ, ɣ, ɤ, ɥ, ɦ, ɧ, ɨ, ɪ, ɫ, ɬ, ɭ, ɮ, ɯ, ɰ, ɱ, ɲ, ɳ, ɴ, ɵ, ɶ, ɸ, ɹ, ɺ, ɻ, ɽ, ɾ, ʀ, ʁ, ʂ, ʃ, ʄ, ʈ, ʉ, ʊ, ʋ, ʌ, ʍ, ʎ, ʏ, ʐ, ʑ, ʒ, ʔ, ʕ, ʘ, ʙ, ʛ, ʜ, ʝ, ʟ, ʡ, ʢ, ʤ, ʧ, ʰ, ʱ, ʲ, ʴ, ʷ, ʼ, ˈ, ˌ, ː, ˑ, ˞, ˠ, ˤ, ̀, ́, ̃, ̄, ̆, ̈, ̊, ̋, ̏, ̐, ̑, ̒, ̓, ̔, ̕, ̖, ̗, ̘, ̙, ̚, ̛, ̜, ̝, ̞, ̟, ̠, ̡, ̢, ̣, ̤, ̥, ̦, ̧, ̨, ̩, ̪, ̫, ̬, ̭, ̮, ̯, ̰, ̱, ̲, ̳, ̴, ̹, ̺, ̻, ̼, ̽, ͜, ͡, β, θ, χ, ↑, →, ↓, ↗, ↘";
enum Subtag {
language,
script,
region,
mixed,
fail
}
static UnicodeSetPrettyPrinter pretty =
new UnicodeSetPrettyPrinter().setOrdering(Collator.getInstance(ULocale.ENGLISH));
static String prettyTruncate(int max, UnicodeSet set) {
String prettySet = pretty.format(set);
if (prettySet.length() > max) {
prettySet = prettySet.substring(0, max) + "...";
}
return prettySet;
}
@Test
public void TestLanguage() {
String foo = UnicodeJsp.getLanguageOptions("de");
assertContains(foo, "<option value='de' selected>Deutsch / German</option>");
String fii = UnicodeJsp.validateLanguageID("en", "fr");
assertContains(fii, "draft-ietf-ltru-4646bis");
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestJoiner() {
checkValidity(Idna2003.SINGLETON, "a", true, true);
checkValidity(Idna2003.SINGLETON, "ÖBB.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2003.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2003.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2003.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2003.SINGLETON, "faß.de", true, true);
checkValidity(Idna2003.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2003.SINGLETON, "\u0080.de", false, true);
checkValidity(Idna2003.SINGLETON, "xn--a.de", true, true);
checkValidity(Uts46.SINGLETON, "a", true, true);
checkValidity(Uts46.SINGLETON, "ÖBB.at", true, true);
checkValidity(Uts46.SINGLETON, "xn--BB-nha.at", false, true);
checkValidity(Uts46.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Uts46.SINGLETON, "a\u200cb", true, true);
checkValidity(Uts46.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Uts46.SINGLETON, "faß.de", true, true);
checkValidity(Uts46.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Uts46.SINGLETON, "\u0080.de", false, true);
checkValidity(Uts46.SINGLETON, "xn--a.de", false, true);
checkValidity(Idna2008.SINGLETON, "a", true, true);
checkValidity(Idna2008.SINGLETON, "ÖBB.at", false, false);
checkValidity(Idna2008.SINGLETON, "xn--BB-nha.at", true, true);
checkValidity(Idna2008.SINGLETON, "xn--bb-eka.at", true, true);
checkValidity(Idna2008.SINGLETON, "a\u200cb", true, true);
checkValidity(Idna2008.SINGLETON, "xn--ab-j1t", true, true);
checkValidity(Idna2008.SINGLETON, "faß.de", true, true);
checkValidity(Idna2008.SINGLETON, "xn--fa-hia.de", true, true);
checkValidity(Idna2008.SINGLETON, "\u0080.de", false, false);
checkValidity(Idna2008.SINGLETON, "xn--a.de", true, true);
}
private void checkValidity(Idna uts46, String url, boolean expectedPuny, boolean expectedUni) {
boolean[] error = new boolean[1];
String fii = uts46.toPunyCode(url, error);
assertEquals(uts46.getName() + "\ttoPunyCode(" + url + ")=" + fii, !expectedPuny, error[0]);
fii = uts46.toUnicode(url, error, true);
assertEquals(uts46.getName() + "\ttoUnicode(" + url + ")=" + fii, !expectedUni, error[0]);
}
// public void Test2003vsUts46() {
//
// ToolUnicodePropertySource properties = ToolUnicodePropertySource.make("6.0");
// UnicodeMap<String> nfkc_cfMap = properties.getProperty("NFKC_CF").getUnicodeMap();
//
// for (UnicodeSetIterator it = new UnicodeSetIterator(IdnaTypes.U32); it.next();) {
// int i = it.codepoint;
// String map2003 = Idna2003.SINGLETON.mappings.get(i);
// String map46 = Uts46.SINGLETON.mappings.get(i);
// IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
// IdnaType type46 = Uts46.SINGLETON.types.get(i);
// if (type46 == IdnaType.ignored) {
// assertNotNull("tr46ignored U+" + codeAndName(i), map46);
// } else if (type46 == IdnaType.deviation) {
// type46 = map46 == null || map46.length() == 0
// ? IdnaType.ignored
// : IdnaType.mapped;
// }
// if (type2003 == IdnaType.ignored) {
// assertNotNull("2003ignored", map2003);
// }
// if (type46 != type2003 || !UnicodeProperty.equals(map46, map2003)) {
// String map2 = map2003 == null ? UTF16.valueOf(i) : map2003;
// String nfcf = nfkc_cfMap.get(i);
// if (!map2.equals(nfcf)) continue;
// String typeDiff = type46 + "\tvs 2003\t" + type2003;
// String mapDiff = "[" + codeAndName(map46) + "\tvs 2003\t" + codeAndName(map2003);
// errln((codeAndName(i)) + "\tdifference:"
// + (type46 != type2003 ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(map46, map2003) ? "\tmap:\t" + mapDiff : "")
// + "\tNFKCCF:\t" + codeAndName(nfcf));
// }
// }
// }
private String codeAndName(int i) {
return Utility.hex(i) + " ( " + UTF16.valueOf(i) + " ) " + UCharacter.getName(i);
}
private String codeAndName(String i) {
return i == null
? null
: (Utility.hex(i, 4, ",", true, new StringBuilder())
+ " ( "
+ i
+ " ) "
+ UCharacter.getName(i, "+"));
}
static class TypeAndMap {
IdnaType type;
String mapping;
}
public void oldTestIdnaAndIcu() {
StringBuffer inbuffer = new StringBuffer();
TypeAndMap typeAndMapIcu = new TypeAndMap();
UnicodeMap<String> errors = new UnicodeMap<String>();
int count = 0;
for (int cp = 0x80; cp < 0x10FFFF; ++cp) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
IdnaType type = Uts46.SINGLETON.getType(cp); // used to be Idna2003.
String mapping = Uts46.SINGLETON.mappings.get(cp); // used to be Idna2003.
if (type != typeAndMapIcu.type
|| !UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)) {
inbuffer.setLength(0);
inbuffer.appendCodePoint(cp);
getIcuIdna(inbuffer, typeAndMapIcu);
String typeDiff = type + "\tvs ICU\t" + typeAndMapIcu.type;
String mapDiff = "[" + mapping + "]\tvs ICU\t[" + typeAndMapIcu.mapping + "]";
errors.put(
cp,
(type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
+ (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping)
? "\tmap:\t" + mapDiff
: ""));
// errln(Utility.hex(cp) + "\t( " + UTF16.valueOf(cp) + " )\tdifference:"
// + (type != typeAndMapIcu.type ? "\ttype:\t" + typeDiff : "")
// + (!UnicodeProperty.equals(mapping, typeAndMapIcu.mapping) ?
// "\tmap:\t" + mapDiff : ""));
if (++count > 50) {
break;
}
}
}
if (errors.size() != 0) {
for (String value : errors.values()) {
UnicodeSet s = errors.getSet(value);
errln(value + "\t" + s.toPattern(false));
}
}
}
private void getIcuIdna(StringBuffer inbuffer, TypeAndMap typeAndMapIcu) {
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuffer intermediate = convertWithHack(inbuffer);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuffer outbuffer = IDNA.convertToUnicode(intermediate, IDNA.USE_STD3_RULES);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuffer convertWithHack(StringBuffer inbuffer)
throws StringPrepParseException {
StringBuffer intermediate;
try {
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
} catch (StringPrepParseException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate = IDNA.convertToASCII(inbuffer, IDNA.USE_STD3_RULES); // USE_STD3_RULES,
}
return intermediate;
}
private void getIcuIdnaUts(StringBuilder inbuffer, TypeAndMap typeAndMapIcu) {
IDNA icuIdna = IDNA.getUTS46Instance(0);
IDNA.Info info = new IDNA.Info();
typeAndMapIcu.type = null;
typeAndMapIcu.mapping = null;
try {
StringBuilder intermediate = convertWithHackUts(inbuffer, icuIdna);
// DEFAULT
if (intermediate.length() == 0) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = "";
} else {
StringBuilder outbuffer =
icuIdna.nameToUnicode(intermediate.toString(), intermediate, info);
if (!UnicodeUtilities.equals(inbuffer, outbuffer)) {
typeAndMapIcu.type = IdnaType.mapped;
typeAndMapIcu.mapping = outbuffer.toString();
} else {
typeAndMapIcu.type = IdnaType.valid;
typeAndMapIcu.mapping = null;
}
}
} catch (StringPrepParseException e) {
if (e.getMessage().startsWith("Found zero length")) {
typeAndMapIcu.type = IdnaType.ignored;
typeAndMapIcu.mapping = null;
} else {
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
} catch (Exception e) {
logln("Failure at: " + Utility.hex(inbuffer));
typeAndMapIcu.type = IdnaType.disallowed;
typeAndMapIcu.mapping = null;
}
}
private static StringBuilder convertWithHackUts(StringBuilder inbuffer, IDNA icuIdna)
throws StringPrepParseException {
StringBuilder intermediate;
try {
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
} catch (RuntimeException e) {
if (!e.getMessage().contains("BIDI")) {
throw e;
}
inbuffer.append("\\u05D9");
intermediate =
icuIdna.nameToASCII(inbuffer.toString(), inbuffer, null); // USE_STD3_RULES,
}
return intermediate;
}
@EnabledIf(
value = "org.unicode.unittest.TestFmwkMinusMinus#getRunBroken",
disabledReason = "Skip unless UNICODETOOLS_RUN_BROKEN_TEST=true")
@Test
public void TestIdnaProps() {
String map = Idna2003.SINGLETON.mappings.get(0x200c);
IdnaType type = Idna2003.SINGLETON.getType(0x200c);
logln("Idna2003\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
map = Uts46.SINGLETON.mappings.get(0x200c);
type = Uts46.SINGLETON.getType(0x200c);
logln("Uts46\t" + (map == null ? "null" : Utility.hex(map)) + ", " + type);
for (int i = 0; i <= 0x10FFFF; ++i) {
// invariants are:
// if mapped, then mapped the same
String map2003 = Idna2003.SINGLETON.mappings.get(i);
String map46 = Uts46.SINGLETON.mappings.get(i);
String map2008 = Idna2008.SINGLETON.mappings.get(i);
IdnaType type2003 = Idna2003.SINGLETON.types.get(i);
IdnaType type46 = Uts46.SINGLETON.types.get(i);
IdnaType type2008 = Idna2008.SINGLETON.types.get(i);
checkNullOrEqual("2003/46", i, type2003, map2003, type46, map46);
checkNullOrEqual("2003/2008", i, type2003, map2003, type2008, map2008);
checkNullOrEqual("46/2008", i, type46, map46, type2008, map2008);
}
showPropValues(XPropertyFactory.make().getProperty("idna"));
showPropValues(XPropertyFactory.make().getProperty("uts46"));
}
private void checkNullOrEqual(
String title, int cp, IdnaType t1, String m1, IdnaType t2, String m2) {
if (t1 == IdnaType.disallowed || t2 == IdnaType.disallowed) return;
if (t1 == IdnaType.valid && t2 == IdnaType.valid) return;
m1 = m1 == null ? UTF16.valueOf(cp) : m1;
m2 = m2 == null ? UTF16.valueOf(cp) : m2;
if (m1.equals(m2)) return;
assertEquals(title + "\t" + Utility.hex(cp), Utility.hex(m1), Utility.hex(m2));
}
@Test
public void TestConfusables() {
String trial = UnicodeJsp.getConfusables("一万", true, true, true, true);
logln("***TRIAL0 : " + trial);
trial = UnicodeJsp.getConfusables("sox", true, true, true, true);
logln("***TRIAL1 : " + trial);
trial = UnicodeJsp.getConfusables("sox", 1);
logln("***TRIAL2 : " + trial);
// showPropValues(
XPropertyFactory.make().getProperty("confusable");
XPropertyFactory.make().getProperty("idr");
}
private void showIcuEnums() {
for (int prop = UProperty.BINARY_START; prop < UProperty.BINARY_LIMIT; ++prop) {
showEnumPropValues(prop);
}
for (int prop = UProperty.INT_START; prop < UProperty.INT_LIMIT; ++prop) {
showEnumPropValues(prop);
}
}
private void showEnumPropValues(int prop) {
logln("Property number:\t" + prop);
for (int nameChoice = 0; ; ++nameChoice) {
try {
String propertyName = UCharacter.getPropertyName(prop, nameChoice);
if (propertyName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t" + nameChoice + "\t" + propertyName);
} catch (Exception e) {
break;
}
}
for (int i = UCharacter.getIntPropertyMinValue(prop);
i <= UCharacter.getIntPropertyMaxValue(prop);
++i) {
logln("\tProperty value number:\t" + i);
for (int nameChoice = 0; ; ++nameChoice) {
String propertyValueName;
try {
propertyValueName = UCharacter.getPropertyValueName(prop, i, nameChoice);
if (propertyValueName == null && nameChoice > NameChoice.LONG) {
break;
}
logln("\t\t" + nameChoice + "\t" + propertyValueName);
} catch (Exception e) {
break;
}
}
}
}
private void showPropValues(UnicodeProperty prop) {
logln(prop.getName());
for (Object value : prop.getAvailableValues()) {
logln(value.toString());
logln("\t" + prop.getSet(value.toString()).toPattern(false));
}
}
public void checkLanguageLocalizations() {
Set<String> languages = new TreeSet<String>();
Set<String> scripts = new TreeSet<String>();
Set<String> countries = new TreeSet<String>();
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
addIfNotEmpty(languages, displayLanguage.getLanguage());
addIfNotEmpty(scripts, displayLanguage.getScript());
addIfNotEmpty(countries, displayLanguage.getCountry());
}
Map<ULocale, Counter<Subtag>> canDisplay =
new TreeMap<ULocale, Counter<Subtag>>(
new Comparator<ULocale>() {
public int compare(ULocale o1, ULocale o2) {
return o1.toLanguageTag().compareTo(o2.toString());
}
});
for (ULocale displayLanguage : ULocale.getAvailableLocales()) {
if (displayLanguage.getCountry().length() != 0) {
continue;
}
Counter<Subtag> counter = new Counter<Subtag>();
canDisplay.put(displayLanguage, counter);
final LocaleData localeData = LocaleData.getInstance(displayLanguage);
final UnicodeSet exemplarSet =
new UnicodeSet()
.addAll(
localeData.getExemplarSet(
UnicodeSet.CASE, LocaleData.ES_STANDARD));
final String language = displayLanguage.getLanguage();
final String script = displayLanguage.getScript();
if (language.equals("zh")) {
if (script.equals("Hant")) {
exemplarSet.removeAll(Common.simpOnly);
} else {
exemplarSet.removeAll(Common.tradOnly);
}
} else {
exemplarSet.addAll(
localeData.getExemplarSet(UnicodeSet.CASE, LocaleData.ES_AUXILIARY));
if (language.equals("ja")) {
exemplarSet.add('ー');
}
}
final UnicodeSet okChars =
(UnicodeSet)
new UnicodeSet("[[:P:][:S:][:Cf:][:m:][:whitespace:]]")
.addAll(exemplarSet)
.freeze();
Set<String> mixedSamples = new TreeSet<String>();
for (String code : languages) {
add(displayLanguage, Subtag.language, code, counter, okChars, mixedSamples);
}
for (String code : scripts) {
add(displayLanguage, Subtag.script, code, counter, okChars, mixedSamples);
}
for (String code : countries) {
add(displayLanguage, Subtag.region, code, counter, okChars, mixedSamples);
}
UnicodeSet missing = new UnicodeSet();
for (String mixed : mixedSamples) {
missing.addAll(mixed);
}
missing.removeAll(okChars);
final long total =
counter.getTotal()
- counter.getCount(Subtag.mixed)
- counter.getCount(Subtag.fail);
final String missingDisplay =
mixedSamples.size() == 0
? ""
: "\t" + missing.toPattern(false) + "\t" + mixedSamples;
logln(
displayLanguage
+ "\t"
+ displayLanguage.getDisplayName(ULocale.ENGLISH)
+ "\t"
+ (total / (double) counter.getTotal())
+ "\t"
+ total
+ "\t"
+ counter.getCount(Subtag.language)
+ "\t"
+ counter.getCount(Subtag.script)
+ "\t"
+ counter.getCount(Subtag.region)
+ "\t"
+ counter.getCount(Subtag.mixed)
+ "\t"
+ counter.getCount(Subtag.fail)
+ missingDisplay);
}
}
private void add(
ULocale displayLanguage,
Subtag subtag,
String code,
Counter<Subtag> counter,
UnicodeSet okChars,
Set<String> mixedSamples) {
switch (canDisplay(displayLanguage, subtag, code, okChars, mixedSamples)) {
case code:
counter.add(Subtag.fail, 1);
break;
case localized:
counter.add(subtag, 1);
break;
case badLocalization:
counter.add(Subtag.mixed, 1);
break;
}
}
enum Display {
code,
localized,
badLocalization
}
private Display canDisplay(
ULocale displayLanguage,
Subtag subtag,
String code,
UnicodeSet okChars,
Set<String> mixedSamples) {
String display;
switch (subtag) {
case language:
display = ULocale.getDisplayLanguage(code, displayLanguage);
break;
case script:
display = ULocale.getDisplayScript("und-" + code, displayLanguage);
break;
case region:
display = ULocale.getDisplayCountry("und-" + code, displayLanguage);
break;
default:
throw new IllegalArgumentException();
}
if (display.equals(code)) {
return Display.code;
} else if (okChars.containsAll(display)) {
return Display.localized;
} else {
mixedSamples.add(display);
UnicodeSet missing = new UnicodeSet().addAll(display).removeAll(okChars);
return Display.badLocalization;
}
}
private void addIfNotEmpty(Collection<String> languages, String language) {
if (language != null && language.length() != 0) {
languages.add(language);
}
}
@Test
public void TestLanguageTag() {
String ulocale = "sq";
assertNotNull("valid list", UnicodeJsp.getLanguageOptions(ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("arb-SU", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-yyy", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("en-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("xxx-cmn", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("zh-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-eng", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("eng-yyy", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID(
"gsw-Hrkt-AQ-pinyin-AbCdE-1901-b-fo-fjdklkfj-23-a-foobar-x-1", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fi-Latn-US", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("fil-Latn-US", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("x-aaa-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertNoMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("aaa-x-Latn-003-FOOBAR-ALPHA-A-xyzw", ulocale));
assertMatch(null, "invalid\\scode", UnicodeJsp.validateLanguageID("zho-Xxxx-248", ulocale));
assertMatch(
null,
"invalid\\sextlang\\scode",
UnicodeJsp.validateLanguageID("aaa-bbb", ulocale));
assertMatch(null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa--bbb", ulocale));
assertMatch(
null, "Ill-Formed", UnicodeJsp.validateLanguageID("aaa-bbb-abcdefghihkl", ulocale));
assertMatch(
null,
"Ill-Formed",
UnicodeJsp.validateLanguageID("1aaa-bbb-abcdefghihkl", ulocale));
}
public void assertMatch(String message, String pattern, Object actual) {
assertMatches(
message, Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL), true, actual);
}
public void assertNoMatch(String message, String pattern, Object actual) {
assertMatches(
message,
Pattern.compile(pattern, Pattern.COMMENTS | Pattern.DOTALL),
false,
actual);
}
// return handleAssert(expected == actual, message, stringFor(expected),
// stringFor(actual), "==", false);
private void assertMatches(String message, Pattern pattern, boolean expected, Object actual) {
final String actualString = actual == null ? "null" : actual.toString();
final boolean result = pattern.matcher(actualString).find() == expected;
handleAssert(
result,
message,
"/" + pattern.toString() + "/",
actualString,
expected ? "matches" : "doesn't match",
true);
}
@Test
public void TestATransform() {
checkCompleteness(enSample, "en-ipa", new UnicodeSet("[a-z]"));
checkCompleteness(IPA_SAMPLE, "ipa-en", new UnicodeSet("[a-z]"));
String sample;
sample = UnicodeJsp.showTransform("en-IPA; IPA-en", enSample);
// logln(sample);
sample = UnicodeJsp.showTransform("en-IPA; IPA-deva", "The quick brown fox.");
// logln(sample);
String deva =
"कँ, कं, कः, ऄ, अ, आ, इ, ई, उ, ऊ, ऋ, ऌ, ऍ, ऎ, ए, ऐ, ऑ, ऒ, ओ, औ, क, ख, ग, घ, ङ, च, छ, ज, झ, ञ, ट, ठ, ड, ढ, ण, त, थ, द, ध, न, ऩ, प, फ, ब, भ, म, य, र, ऱ, ल, ळ, ऴ, व, श, ष, स, ह, ़, ऽ, क्, का, कि, की, कु, कू, कृ, कॄ, कॅ, कॆ, के, कै, कॉ, कॊ, को, कौ, क्, क़, ख़, ग़, ज़, ड़, ढ़, फ़, य़, ॠ, ॡ, कॢ, कॣ, ०, १, २, ३, ४, ५, ६, ७, ८, ९, ।";
checkCompleteness(IPA_SAMPLE, "ipa-deva", null);
checkCompleteness(deva, "deva-ipa", null);
}
private void checkCompleteness(
String testString, String transId, UnicodeSet exceptionsAllowed) {
String pieces[] = testString.split(",\\s*");
UnicodeSet shouldNotBeLeftOver =
new UnicodeSet().addAll(testString).remove(' ').remove(',');
if (exceptionsAllowed != null) {
shouldNotBeLeftOver.removeAll(exceptionsAllowed);
}
UnicodeSet allProblems = new UnicodeSet();
for (String piece : pieces) {
String sample = UnicodeJsp.showTransform(transId, piece);
// logln(piece + " => " + sample);
if (shouldNotBeLeftOver.containsSome(sample)) {
final UnicodeSet missing =
new UnicodeSet().addAll(sample).retainAll(shouldNotBeLeftOver);
allProblems.addAll(missing);
warnln("Leftover from " + transId + ": " + missing.toPattern(false));
Transliterator foo = Transliterator.getInstance(transId, Transliterator.FORWARD);
// Transliterator.DEBUG = true;
sample = UnicodeJsp.showTransform(transId, piece);
// Transliterator.DEBUG = false;
}
}
if (allProblems.size() != 0) {
warnln("ALL Leftover from " + transId + ": " + allProblems.toPattern(false));
}
}
@Test
public void TestBidi() {
String sample;
sample = UnicodeJsp.showBidi("mark \u05DE\u05B7\u05E8\u05DA\nHelp", 0, true);
if (!sample.contains(">WS<")) {
errln(sample);
}
}
@Test
public void TestMapping() {
String sample;
sample = UnicodeJsp.showTransform("(.) > '<' $1 '> ' &hex/perl($1) ', ';", "Hi There.");
assertContains(sample, "\\x{69}");
sample = UnicodeJsp.showTransform("lower", "Abcd");
assertContains(sample, "abcd");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "Abcd");
assertContains(sample, "ACBd");
sample = UnicodeJsp.showTransform("lower", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0A\u00A0");
sample = UnicodeJsp.showTransform("bc > CB; X > xx;", "[[:ascii:]{Abcd}]");
assertContains(sample, "\u00A0ACBd\u00A0");
sample = UnicodeJsp.showTransform("casefold", "[\\u0000-\\u00FF]");
assertContains(sample, "\u00A0\u00E1\u00A0");
}
@Test
public void TestGrouping() throws IOException {
StringWriter printWriter = new StringWriter();
UnicodeJsp.showSet(
"sc gc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "General_Category=Letter_Number");
printWriter.getBuffer().setLength(0);
UnicodeJsp.showSet(
"subhead",
"",
UnicodeSetUtilities.parseUnicodeSet("[:subhead=/Syllables/:]"),
true,
true,
true,
printWriter);
assertContains(printWriter.toString(), "a=A595");
}
@Test
public void TestStuff() throws IOException {
// int script = UScript.getScript(0xA6E6);
// int script2 = UCharacter.getIntPropertyValue(0xA6E6, UProperty.SCRIPT);
String propValue = Common.getXStringPropertyValue(Common.SUBHEAD, 0xA6E6, NameChoice.LONG);
// logln(propValue);
// logln("Script for A6E6: " + script + ", " + UScript.getName(script) + ", " + script2);
try (final PrintWriter printWriter = new PrintWriter(System.out)) {
// if (true) return;
UnicodeJsp.showSet(
"sc gc",
"",
new UnicodeSet("[[:ascii:]{123}{ab}{456}]"),
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"", "", new UnicodeSet("[\\u0080\\U0010FFFF]"), true, true, true, printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080\\U0010FFFF{abc}]"),
true,
true,
true,
printWriter);
UnicodeJsp.showSet(
"",
"",
new UnicodeSet("[\\u0080-\\U0010FFFF{abc}]"),
true,
true,
true,
printWriter);
String[] abResults = new String[3];
String[] abLinks = new String[3];
int[] abSizes = new int[3];
UnicodeJsp.getDifferences("[:letter:]", "[:idna:]", false, abResults, abSizes, abLinks);
for (int i = 0; i < abResults.length; ++i) {
logln(abSizes[i] + "\r\n\t" + abResults[i] + "\r\n\t" + abLinks[i]);
}
final UnicodeSet unicodeSet = new UnicodeSet();
logln("simple: " + UnicodeJsp.getSimpleSet("[a-bm-p\uAc00]", unicodeSet, true, false));
UnicodeJsp.showSet("", "", unicodeSet, true, true, true, printWriter);
// String archaic =
// "[[\u018D\u01AA\u01AB\u01B9-\u01BB\u01BE\u01BF\u021C\u021D\u025F\u0277\u027C\u029E\u0343\u03D0\u03D1\u03D5-\u03E1\u03F7-\u03FB\u0483-\u0486\u05A2\u05C5-\u05C7\u066E\u066F\u068E\u0CDE\u10F1-\u10F6\u1100-\u115E\u1161-\u11FF\u17A8\u17D1\u17DD\u1DC0-\u1DC3\u3165-\u318E\uA700-\uA707\\U00010140-\\U00010174]" +
//
// "[\u02EF-\u02FF\u0363-\u0373\u0376\u0377\u07E8-\u07EA\u1DCE-\u1DE6\u1DFE\u1DFF\u1E9C\u1E9D\u1E9F\u1EFA-\u1EFF\u2056\u2058-\u205E\u2180-\u2183\u2185-\u2188\u2C77-\u2C7D\u2E00-\u2E17\u2E2A-\u2E30\uA720\uA721\uA730-\uA778\uA7FB-\uA7FF]" +
//
// "[\u0269\u027F\u0285-\u0287\u0293\u0296\u0297\u029A\u02A0\u02A3\u02A5\u02A6\u02A8-\u02AF\u0313\u037B-\u037D\u03CF\u03FD-\u03FF]" +
// "";
// UnicodeJsp.showSet("",UnicodeSetUtilities.parseUnicodeSet("[:usage=/.+/:]"), false,
// false, printWriter);
UnicodeJsp.showSet(
"",
"",
UnicodeSetUtilities.parseUnicodeSet("[:hantype=/simp/:]"),
false,
false,
true,
printWriter);
}
}
@Test
public void TestShowProperties() throws IOException {
StringWriter out = new StringWriter();
UnicodeJsp.showProperties(0x00C5, out);
assertTrue("props for character", out.toString().contains("Line_Break"));
logln(out.toString());
// logln(out);
}
public void TestIdentifiers() throws IOException {
String out = UnicodeUtilities.getIdentifier("Latin");
assertTrue("identifier info", out.toString().contains("U+016F"));
logln(out.toString());
// logln(out);
}
@Test
public void TestShowSet() throws IOException {
StringWriter out = new StringWriter();
// UnicodeJsp.showSet("sc gc",
// UnicodeSetUtilities.parseUnicodeSet("[:Hangul_Syllable_Type=LVT_Syllable:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("Hangul"));
// logln(out);
//
// out.getBuffer().setLength(0);
// UnicodeJsp.showSet("sc gc", UnicodeSetUtilities.parseUnicodeSet("[:cn:]",
// TableStyle.extras), false, true, out);
// assertTrue("props table", out.toString().contains("unassigned"));
// logln(out);
out.getBuffer().setLength(0);
UnicodeJsp.showSet(
"sc",
"",
UnicodeSetUtilities.parseUnicodeSet("[:script=/Han/:]"),
false,
true,
true,
out);
assertFalse("props table", out.toString().contains("unassigned"));
logln(out.toString());
}
@Test
public void TestParameters() {
UtfParameters parameters = new UtfParameters("ab%61=%C3%A2%CE%94");
assertEquals("parameters", "\u00E2\u0394", parameters.getParameter("aba"));
}
@Test
public void TestRegex() {
final String fix = UnicodeRegex.fix("ab[[:ascii:]&[:Ll:]]*c");
assertEquals("", "ab[a-z]*c", fix);
assertEquals(
"",
"<u>abcc</u> <u>abxyzc</u> ab$c",
UnicodeJsp.showRegexFind(fix, "abcc abxyzc ab$c"));
}
@Test
public void TestIdna() {
boolean[] error = new boolean[1];
String uts46unic = Uts46.SINGLETON.toUnicode("faß.de", error, true);
logln(uts46unic + ", " + error[0]);
checkValues(error, Uts46.SINGLETON);
checkValidIdna(Uts46.SINGLETON, "À。÷");
checkInvalidIdna(Uts46.SINGLETON, "≠");
checkInvalidIdna(Uts46.SINGLETON, "\u0001");
checkToUnicode(Uts46.SINGLETON, "ß。ab", "ß.ab");
// checkToPunyCode(Uts46.SINGLETON, "\u0002", "xn---");
checkToPunyCode(Uts46.SINGLETON, "ß。ab", "ss.ab");
checkToUnicodeAndPunyCode(Uts46.SINGLETON, "faß.de", "faß.de", "fass.de");
checkValues(error, Idna2003.SINGLETON);
checkToUnicode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkToPunyCode(Idna2003.SINGLETON, "ß。ab", "ss.ab");
checkValidIdna(Idna2003.SINGLETON, "À÷");
checkValidIdna(Idna2003.SINGLETON, "≠");
checkToUnicodeAndPunyCode(
Idna2003.SINGLETON, "نامه\u200Cای.de", "نامهای.de", "xn--mgba3gch31f.de");
checkValues(error, Idna2008.SINGLETON);
checkToUnicode(Idna2008.SINGLETON, "ß", "ß");
checkToPunyCode(Idna2008.SINGLETON, "ß", "xn--zca");
checkInvalidIdna(Idna2008.SINGLETON, "À");
checkInvalidIdna(Idna2008.SINGLETON, "÷");
checkInvalidIdna(Idna2008.SINGLETON, "≠");
checkInvalidIdna(Idna2008.SINGLETON, "ß。");
Uts46.SINGLETON.isValid("≠");
assertTrue("uts46 a", Uts46.SINGLETON.isValid("a"));
assertFalse("uts46 not equals", Uts46.SINGLETON.isValid("≠"));
String testLines = UnicodeJsp.testIdnaLines("ΣΌΛΟΣ", "[]");
assertContains(testLines, "xn--wxaikc6b");
testLines = UnicodeJsp.testIdnaLines(UnicodeJsp.getDefaultIdnaInput(), "[]");
assertContains(testLines, "xn--bb-eka.at");
// showIDNARemapDifferences(printWriter);
expectError("][:idna=valid:][abc]");
assertTrue(
"contains hyphen",
UnicodeSetUtilities.parseUnicodeSet("[:idna=valid:]").contains('-'));
}
private void checkValues(boolean[] error, Idna idna) {
checkToUnicodeAndPunyCode(idna, "α.xn--mxa", "α.α", "xn--mxa.xn--mxa");
checkValidIdna(idna, "a");
checkInvalidIdna(idna, "=");
}
private void checkToUnicodeAndPunyCode(
Idna idna, String source, String toUnicode, String toPunycode) {
checkToUnicode(idna, source, toUnicode);
checkToPunyCode(idna, source, toPunycode);
}
private void checkToUnicode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toUnicode, " + source;
assertEquals(head, expected, idna.toUnicode(source, error, true));
String head2 = idna.getName() + ".toUnicode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkToPunyCode(Idna idna, String source, String expected) {
boolean[] error = new boolean[1];
String head = idna.getName() + ".toPunyCode, " + source;
assertEquals(head, expected, idna.toPunyCode(source, error));
String head2 = idna.getName() + ".toPunyCode error?, " + source + " = " + expected;
assertFalse(head2, error[0]);
}
private void checkInvalidIdna(Idna idna, String value) {
assertFalse(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
private void checkValidIdna(Idna idna, String value) {
assertTrue(idna.getName() + ".isValid: " + value, idna.isValid(value));
}
public void expectError(String input) {
try {
UnicodeSetUtilities.parseUnicodeSet(input);
errln("Failure to detect syntax error.");
} catch (IllegalArgumentException e) {
logln("Expected error: " + e.getMessage());
}
}
@Test
public void TestBnf() {
UnicodeRegex regex = new UnicodeRegex();
final String[][] tests = {
{"c = a* wq;\n" + "a = xyz;\n" + "b = a{2} c;\n"},
{"c = a* b;\n" + "a = xyz;\n" + "b = a{2} c;\n", "Exception"},
{
"uri = (?: (scheme) \\:)? (host) (?: \\? (query))? (?: \\u0023 (fragment))?;\n"
+ "scheme = reserved+;\n"
+ "host = \\/\\/ reserved+;\n"
+ "query = [\\=reserved]+;\n"
+ "fragment = reserved+;\n"
+ "reserved = [[:ascii:][:sc=grek:]&[:alphabetic:]];\n",
"http://αβγ?huh=hi#there"
},
// {
//
// "/Users/markdavis/Documents/workspace/cldr/tools/java/org/unicode/cldr/util/data/langtagRegex.txt"
// }
};
for (int i = 0; i < tests.length; ++i) {
String test = tests[i][0];
final boolean expectException =
tests[i].length < 2 ? false : tests[i][1].equals("Exception");
try {
String result;
if (test.endsWith(".txt")) {
List<String> lines = UnicodeRegex.loadFile(test, new ArrayList<String>());
result = regex.compileBnf(lines);
} else {
result = regex.compileBnf(test);
}
if (expectException) {
errln("Expected exception for " + test);
continue;
}
String result2 =
result.replaceAll(
"[0-9]+%", ""); // just so we can use the language subtag stuff
String resolved = regex.transform(result2);
// logln(resolved);
Matcher m = Pattern.compile(resolved, Pattern.COMMENTS).matcher("");
String checks = "";
for (int j = 1; j < tests[i].length; ++j) {
String check = tests[i][j];
if (!m.reset(check).matches()) {
checks = checks + "Fails " + check + "\n";
} else {
for (int k = 1; k <= m.groupCount(); ++k) {
checks += "(" + m.group(k) + ")";
}
checks += "\n";
}
}
// logln("Result: " + result + "\n" + checks + "\n" + test);
String randomBnf = UnicodeJsp.getBnf(result, 10, 10);
// logln(randomBnf);
} catch (Exception e) {
if (!expectException) {
errln(e.getClass().getName() + ": " + e.getMessage());
}
continue;
}
}
}
@Test
public void TestBnfMax() {
BNF bnf = new BNF(new Random(), new Quoter.RuleQuoter());
bnf.setMaxRepeat(10).addRules("$root=[0-9]+;").complete();
for (int i = 0; i < 100; ++i) {
String s = bnf.next();
assertTrue(
"Max too large? " + i + ", " + s.length() + ", " + s,
1 <= s.length() && s.length() < 11);
}
}
@Test
public void TestBnfGen() {
if (logKnownIssue("x", "old test disabling for now")) {
return;
}
String stuff = UnicodeJsp.getBnf("([:Nd:]{3} 90% | abc 10%)", 100, 10);
assertContains(stuff, "<p>\\U0001D7E8");
stuff = UnicodeJsp.getBnf("[0-9]+ ([[:WB=MB:][:WB=MN:]] [0-9]+)?", 100, 10);
assertContains(stuff, "726283663");
String bnf =
"item = word | number;\n"
+ "word = $alpha+;\n"
+ "number = (digits (separator digits)?);\n"
+ "digits = [:Pd:]+;\n"
+ "separator = [[:WB=MB:][:WB=MN:]];\n"
+ "$alpha = [:alphabetic:];";
String fixedbnf = new UnicodeRegex().compileBnf(bnf);
String fixedbnf2 = UnicodeRegex.fix(fixedbnf);
// String fixedbnfNoPercent = fixedbnf2.replaceAll("[0-9]+%", "");
String random = UnicodeJsp.getBnf(fixedbnf2, 100, 10);
// assertContains(random, "\\U0002A089");
}
@Test
public void TestSimpleSet() {
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2003=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{uts46=valid}");
checkUnicodeSetParseContains("[a-z\u00e4\u03b1]", "\\p{idna2008=PVALID}");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD-U+AC00");
checkUnicodeSetParse("[\\u1234\\uABCD-\\uAC00]", "U+1234 U+ABCD..U+AC00");
}
private void checkUnicodeSetParse(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expected = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertEquals(test, expected, actual);
}
private void checkUnicodeSetParseContains(String expected1, String test) {
UnicodeSet actual = new UnicodeSet();
UnicodeSet expectedSubset = new UnicodeSet(expected1);
UnicodeJsp.getSimpleSet(test, actual, true, false);
assertContains(test, expectedSubset, actual);
}
@Test
public void TestConfusable() {
String test = "l l l l o̸ ä O O v v";
String string = UnicodeJsp.showTransform("confusable", test);
assertEquals(null, test, string);
string = UnicodeJsp.showTransform("confusableLower", test);
assertEquals(null, test, string);
String listedTransforms = UnicodeJsp.listTransforms();
if (!listedTransforms.contains("confusable")) {
errln("Missing 'confusable' " + listedTransforms);
}
}
}
| acidburn0zzz/unicodetools | UnicodeJsps/src/test/java/org/unicode/jsptest/TestJsp.java |
1,621 |
public class BankAccount {
// public = ορατή στις υποκλάσεις αλλά όχι στον υπόλοιπο κόσμο. Δεν επιτρέπεται πρόσβαση και αλλαγή τιμής.
// protected = υποδηλώνει ότι μια ιδιότητα δεν είναι προσπελάσιμη από αντικείμενα άλλων κλάσεων,
// επιτρέπεται όμως η πρόσβαση από αντικείμενα των υποκλάσεων.
// εδώ κληρονομείται στην SavingAccount και είναι προσβάσιμη μέσα σε αυτήν
protected String name;
protected double balance;
public BankAccount(String aName, double aBalance){
name = aName;
balance = aBalance;
}
public void printData(){
System.out.println("This is the regular bankaccount");
System.out.println("Name: " + name);
System.out.println("Balance: " + balance);
}
public void deposit(double amount){
balance += amount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/Bank/src/BankAccount.java |
1,623 | package logic;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Η κλάση QuestionList διαχειρίζεται μια λίστα από αντικείμενα Question. Σκοπός της είναι να δημιουργεί
* αντικείμενα Question με βάση τα δεδομένα, και με μεθόδους να επιστρέφει αυτά τα αντικείμενα με τυχαίο τρόπο.
*
* @author tasosxak
* @author Thanasis
* @since 8/11/16
* @version 1.0
*
*/
public class QuestionList {
private List<Question> questions; //Λίστα ερωτήσεων
public QuestionList() {
this.questions = new ArrayList<>();
}
/**
* Η συνάρτηση αυτή δέχεται έναν θετικό αριθμό ως παράμετρο και επιστρέφει
* ένα τυχαίο αριθμό στο διάστημα [0,τυχαίος_αριθμός) Σε περίπτωση που
* δέχεται αρνητικό, παίρνει την απόλυτη τιμή αυτού.
*
* @param range Το άνω όριο του διαστήματος [0,range) όπου θα επιλέγεται
* ένας τυχαίος αριθμός
* @return Επιστρέφει τον τυχαίο αριθμό
*/
private int getRandomIndexOfQuestion(int range) {
Random ran = new Random();
return ran.nextInt(Math.abs(range));
}
/**
* Η nextQuestion παίρνει ένα τυχαίο αντικείμενο τύπου Question και έπειτα
* το διαγράφει από τη λίστα ερωτήσεων.
*
* @return Επιστρέφει ένα τυχαίο αντικείμενο τύπου Question
*/
public Question nextQuestion() {
if (!(this.questions.isEmpty())) {
int rand = this.getRandomIndexOfQuestion(this.questions.size()); //Λαμβάνει έναν τυχαίο αριθμό [0,μέγεθος πίνακα questions)
Question luckyQuestion = this.questions.get(rand); // Παίρνει την ερώτηση με index τον τυχαίο αριθμό
this.questions.remove(rand); // Διαγράφει την ερώτηση για να μην επαναχρησιμοποιηθεί
return luckyQuestion;
}
return null;
}
/**
* Η nextQuestion(String category) επιστρέφει μια τυχαία ερώτηση κατηγορίας
* category.
*
* @param category Η κατηγορία που θέλουμε να ανήκει η ερώτηση
* @return Επιστρέφει ερώτηση κατηγορίας category και null αν δεν υπάρχει η
* συγκεκριμένη κατηγορία ή δεν υπάρχει ερώτηση αυτής της κατηγορίας (δηλαδή
* μπορεί να υπήρχε αλλά χρησιμοποιήθηκε ήδη)
*/
public Question nextQuestion(String category) {
List<Question> questionsOfCategory = new ArrayList<>();
for (Question question : this.questions) {
if (question.getCategory().equals(category.toUpperCase())) //Έλεγχος αν η ερώτηση ανήκει στην κατηγορία category
{
questionsOfCategory.add(question);
}
}
/*Ελέγχει αν ο πίνακας ερωτήσεων συγκεκριμένης κατηγορίας είναι κενός ή οχι
*/
if (questionsOfCategory.isEmpty()) {
return null; //Επιστρέφει null αν είναι
} else {
// Επιστρέφει μια τυχαία ερώτηση από τον πίνακα ερωτήσεων συγκεκριμένης κατηγορίας
int rand = this.getRandomIndexOfQuestion(questionsOfCategory.size());
Question luckyquestion = questionsOfCategory.get(rand);
this.questions.remove(luckyquestion);
return luckyquestion;
}
}
/**
* Η addQuestion προσθέτει ένα αντικείμενο Question στην λίστα ερωτήσεων.
* Επιτρέπει την πολλαπλή προσθήκη του ίδιου αντικειμένου
*
* @param question Το αντικείμενο Question που θα προστεθεί στη λίστα
* ερωτήσεων
* @return true αν η προσθήκη έγινε επιτυχώς και false αν η προσθήκη
* αντικειμένου απέτυχε ( null)
*/
public boolean addQuestion(Question question) {
if (question != null) {
this.questions.add(question);
return true;
}
return false;
}
/**
*
* @return Επιστρέφει τον αριθμό ερωτήσεων που είναι αποθηκευμένο στη λίστα
* ερωτήσεων
*/
public int numOfQuestions() {
return this.questions.size();
}
}
| TeamLS/Buzz | src/logic/QuestionList.java |
1,624 | package week13_Reflection;
import java.util.TreeSet;
/**
* Uses the SimpleGUICard. It just add some arbitrary objects to that
*
* @author Yannis Tzitzikas ([email protected])
*
*/
public class GraphicalObjects_Client {
public static void main(String[] args) {
int[] pinakas={2,3,4,5};
SimpleGUICard sc = new SimpleGUICard();
sc.add("This is a test");
sc.add(2);
sc.add(new week13_Reflection.CCC());
//sc.add(new Person());
sc.add(new Runnable() {
public void run() {
}
});
sc.add(new Person() {
public String toString() {
return super.toString() + super.toString();
}
});
/*
sc.add(3);
sc.add(pinakas);
sc.add(new Person());
sc.add(new Person() { public String toString() {
return super.toString() + " αλλά με λένε Γιάννη";
} } );
sc.add(new Runnable(){ public void run() {;}});
sc.add(new Runnable(){ public void run() {;}});
sc.add(new TreeSet());
sc.add(new Class[]{});
sc.add(sc); // to check
*/
}
}
| YannisTzitzikas/CS252playground | CS252playground/src/week13_Reflection/GraphicalObjects_Client.java |
1,626 | package UserClientV1;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JSpinner;
/**
* Κλάση η οποία ουσιαστικά είναι το παραθυράκι (JDialog) που εμφανίζεται
* για να δοθεί η δυνατότητα στο χρήστη να αλλάξει την τιμή κάποιας μονάδας
* με την βοήθεια μπάρας ή και ακόμη με το παραδοσιακό τρόπο της απλής
* εισαγωγής με γραφή .
* Εμφανίζεται όταν κάνει ο χρήστης "διπλό κλικ" πάνω σε κάποιο εικονίδιο μονάδας.
* Βέβαια για να εμφανιστεί πρέπει ο χρήστης να έχει δικαίωμα να αλλάζει την τιμή
* όπως επίσης και η μονάδα να είναι σε mode που να της επιτρέπετε να αλλάξει η
* τιμή της και μάλιστα να είναι η μονάδα τύπου διακριτής τιμής με TR-trackbar(και όχι SW-Switch).
* @author Michael Galliakis
*/
public class DfChangeValue extends javax.swing.JDialog {
private UnitControl parentUC ;
/**
* Κατασκευαστής που κάνει όλα τα απαραίτητα βήματα για να αρχικοποιηθεί
* κατάλληλα το dialog μας .
* @param modal True αν θέλουμε να είναι συνέχεια onTop μέχρι να κλείσουμε το dialog μας
* αλλιώς False αν θέλουμε ο χρήστης να μπορεί να κάνει τρέχον παράθυρο την φόρμα που ανήκει το dialog.
* Πρακτικά δεν χρησιμοποιείται γιατί θέλουμε την προεπιλογή (default).
* @param v Ένας Double αριθμός που παριστάνει την τρέχον τιμή της μονάδας .
* @param uc Το {@link UnitControl} το οποίο αντιστοιχεί στην μονάδα .
*/
public DfChangeValue(boolean modal,Double v,UnitControl uc) {
//super(modal);
initComponents();
spValue.setValue((int) Math.round(v));
sValue.setValue((int) Math.round(v));
JSpinner.DefaultEditor editor = (JSpinner.DefaultEditor) spValue.getEditor();
parentUC = uc ;
Point paOnScreen = parentUC.getLocationOnScreen() ;
Dimension mainFSize = Globals.objMainFrame.getSize() ;
Point mainFOnSc = Globals.objMainFrame.getLocationOnScreen();
mainFOnSc.x += mainFSize.width ;
if (paOnScreen.x + this.size().width>mainFOnSc.x)
paOnScreen.x = mainFOnSc.x - this.size().width ;
else
paOnScreen.x += parentUC.size().width-8 ;
//System.out.println(paOnScreen.x);
//System.out.println(mainFOnSc.x);
setLocation(paOnScreen);
/**
* Προστέτουμε προγραμματιστικά άμεσα κάποιο Listener για τον spinner
*/
editor.getTextField().addKeyListener(new KeyListener() {
//Event το οποίο πρέπει να γίνει override , αλλά ουσιαστικά δεν κάνει τίποτα.
@Override
public void keyTyped(KeyEvent ke) {
}
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης κάποιο κουμπί μέσα στον spinner(editor) του value.
* @param ke Το Default KeyEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην keyPressedEvent.
*/
@Override
public void keyPressed(KeyEvent ke) {
keyPressedEvent(ke);
}
//Event το οποίο πρέπει να γίνει override , αλλά ουσιαστικά δεν κάνει τίποτα.
@Override
public void keyReleased(KeyEvent ke) {
}
});
}
/**
* Μέθοδος που κάνει όλους του απαραίτητους ελέγχους και ενέργειες ούτως
* ώστε να αλλάξει επιτυχημένα την τιμή της ανάλογης μονάδας τόσο τοπικά
* στο πρόγραμμα μας όσο και απομακρυσμένα στην συσκευή που ανήκει η μονάδα
* και βέβαια και σε όλους τους άλλους UserClient που έχουν "ζωντανή" εποπτεία
* στην ίδια συσκευή (μέσω του server) .
*/
private void setValue()
{
if (Tools.isNumeric(spValue.getValue().toString()))
{
parentUC.setValue(spValue.getValue().toString());
parentUC.getUnit().setValue(spValue.getValue().toString());
if (parentUC.getMode() == 3)
{
parentUC.setMode(4) ;
parentUC.unit.setMode(String.valueOf(parentUC.mode));
parentUC.unit.device.changeRemoteMode(parentUC.unit.getFullMode());
}
parentUC.getUnit().device.changeRemoteValue(parentUC.getUnit().getFullValue());
this.dispose();
}
else
this.dispose();
}
/**
* Μέθοδος που αναλαμβάνει να κλείνει το dialog αν ο χρήστης
* πατήσει το πλήκτρο "Esqape" .
* Δημιουργήθηκε (όπως και άλλοι παρόμοιοι τέτοιοι μέθοδοι σε όλα τα project
* του συστήματος) για να μην επαναλαμβάνεται συνέχεια το ίδιο κομμάτι
* κώδικα και για να έχουμε καλύτερη διαχείριση .
* @param evt Ένα KeyEvent αντικείμενο που το αξιοποιούμε με το να βρούμε
* μέσω αυτού πιο ακριβώς πλήκτρο πάτησε ο χρήστης .
*/
private void keyPressedEvent(java.awt.event.KeyEvent evt)
{
/*if (evt.getKeyCode() == KeyEvent.VK_ENTER)
{
setValue();
}
else */if (evt.getKeyCode() == KeyEvent.VK_ESCAPE)
this.dispose();
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
sValue = new javax.swing.JSlider();
jLabel1 = new javax.swing.JLabel();
spValue = new javax.swing.JSpinner();
bOK = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setUndecorated(true);
setType(java.awt.Window.Type.POPUP);
addWindowFocusListener(new java.awt.event.WindowFocusListener() {
public void windowGainedFocus(java.awt.event.WindowEvent evt) {
formWindowGainedFocus(evt);
}
public void windowLostFocus(java.awt.event.WindowEvent evt) {
formWindowLostFocus(evt);
}
});
addWindowListener(new java.awt.event.WindowAdapter() {
public void windowDeactivated(java.awt.event.WindowEvent evt) {
formWindowDeactivated(evt);
}
public void windowDeiconified(java.awt.event.WindowEvent evt) {
formWindowDeiconified(evt);
}
});
addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
formKeyPressed(evt);
}
});
sValue.setMaximum(255);
sValue.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
sValueStateChanged(evt);
}
});
sValue.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
sValueKeyPressed(evt);
}
});
jLabel1.setText("Value : ");
jLabel1.setToolTipText("");
jLabel1.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
jLabel1KeyPressed(evt);
}
});
spValue.setModel(new javax.swing.SpinnerNumberModel(0, 0, 255, 1));
spValue.addChangeListener(new javax.swing.event.ChangeListener() {
public void stateChanged(javax.swing.event.ChangeEvent evt) {
spValueStateChanged(evt);
}
});
spValue.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
spValueMouseClicked(evt);
}
});
spValue.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
spValueKeyPressed(evt);
}
});
bOK.setText("OK");
bOK.setToolTipText("");
bOK.setMargin(new java.awt.Insets(0, 0, 0, 0));
bOK.setMaximumSize(new java.awt.Dimension(40, 22));
bOK.setMinimumSize(new java.awt.Dimension(40, 22));
bOK.setPreferredSize(new java.awt.Dimension(40, 22));
bOK.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bOKMouseClicked(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(sValue, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(spValue, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(bOK, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(spValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(bOK, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(sValue, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
/**
* Μέθοδος που εκτελείτε όταν το παραθυράκι μας γίνει ανενεργό και πρακτικά
* όταν πατήσει ο χρήστης κάπου έξω από το dialog .
* Ο σκοπός του είναι να κλείνει αυτόματα το dialog χωρίς να γίνεται κάποια αλλαγή τιμής.
* @param evt Το Default WindowEvent που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται.
*/
private void formWindowDeactivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowDeactivated
this.dispose();
}//GEN-LAST:event_formWindowDeactivated
/**
* Μέθοδος που εκτελείτε όταν ο χρήστης αλλάξει την τιμή του trackBar (JSlider) .
* @param evt Το Default ChangeEvent που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται.
*/
private void sValueStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_sValueStateChanged
spValue.setValue(sValue.getValue());
}//GEN-LAST:event_sValueStateChanged
/**
* Μέθοδος που εκτελείτε όταν ο χρήστης αλλάξει την τιμή του spinner .
* @param evt Το Default ChangeEvent που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται.
*/
private void spValueStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_spValueStateChanged
sValue.setValue((int) spValue.getValue());
}//GEN-LAST:event_spValueStateChanged
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης κάποιο κουμπί μέσα στο spinner του value.
* @param evt Το Default KeyEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην keyPressedEvent.
*/
private void spValueKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_spValueKeyPressed
keyPressedEvent(evt) ;
}//GEN-LAST:event_spValueKeyPressed
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης κάποιο πλήκτρο ενώ βρίσκεται στην trackBar (JSlider).
* @param evt Το Default KeyEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην keyPressedEvent.
*/
private void sValueKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_sValueKeyPressed
keyPressedEvent(evt) ;
}//GEN-LAST:event_sValueKeyPressed
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης κάποιο κουμπί ενώ βρίσκεται στην ετικέτα του "Value :".
* @param evt Το Default KeyEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην keyPressedEvent.
*/
private void jLabel1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jLabel1KeyPressed
keyPressedEvent(evt) ;
}//GEN-LAST:event_jLabel1KeyPressed
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης κάποιο κουμπί μέσα στο dialog.
* @param evt Το Default KeyEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας χρησιμοποιείται με το να δίνεται σαν παράμετρος στην keyPressedEvent.
*/
private void formKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_formKeyPressed
keyPressedEvent(evt) ;
}//GEN-LAST:event_formKeyPressed
private void spValueMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_spValueMouseClicked
}//GEN-LAST:event_spValueMouseClicked
private void formWindowDeiconified(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowDeiconified
}//GEN-LAST:event_formWindowDeiconified
private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
}//GEN-LAST:event_formWindowGainedFocus
private void formWindowLostFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowLostFocus
}//GEN-LAST:event_formWindowLostFocus
/**
* Μέθοδος που εκτελείτε όταν πατήσει ο χρήστης το κουμπί "OK" .
* Ο σκοπός του είναι να αλλάζει να εκτελεί την setValue και κατά επέκταση
* να αλλάζει την τιμή της μονάδας και να κλείνει το dialog.
* @param evt Το Default MouseEvent που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται.
*/
private void bOKMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bOKMouseClicked
setValue();
}//GEN-LAST:event_bOKMouseClicked
/**
* Κλασική static main μέθοδος που δίνει την δυνατότητα να ξεκινήσει η εκτέλεση
* του project μας από εδώ και πρακτικά χρησιμοποιείται για να μπορούμε να κάνουμε
* αλλαγές και ελέγχους όσο αναφορά κυρίως στην εμφάνιση του dialog μας.
* Δεν έχει καμία χρήση κατά την λειτουργία του User Client στην κανονική ροή εκτέλεσης.
* @param args Default παράμετροι που δεν χρησιμοποιούνται και που μπορεί δυνητικά να πάρει
* το πρόγραμμα μας στην περίπτωση που εκτελεστεί από περιβάλλον γραμμής εντολών και όταν
* συγχρόνως το project μας έχει σαν κύριο-αρχικό αρχείο εκτέλεσης το DfChangeValue.java.
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
DfChangeValue dialog = new DfChangeValue(true,0.0,null);
dialog.addWindowListener(new java.awt.event.WindowAdapter() {
@Override
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
}
});
dialog.setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bOK;
private javax.swing.JLabel jLabel1;
private javax.swing.JSlider sValue;
private javax.swing.JSpinner spValue;
// End of variables declaration//GEN-END:variables
}
/*
* * * * * * * * * * * * * * * * * * * * * * *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| P P P P M M M M G G G G |+ *
* +| P P M M M M G G |+ *
* +| P P P p M M M M G |+ *
* +| P M M M G G G G |+ *
* +| P M M G G |+ *
* +| P ® M M ® G G G G |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + .----. @ @ |+ *
* + / .-"-.`. \v/ |+ *
* + | | '\ \ \_/ ) |+ *
* + ,-\ `-.' /.' / |+ *
* + '---`----'----' |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| Thesis Michael Galliakis 2016 |+ *
* +| Program m_g ; -) [email protected] |+ *
* +| TEI Athens - IT department. |+ *
* +| [email protected] |+ *
* +| https://github.com/michaelgalliakis |+ *
* +| (myThesis.git) |+ *
* +- - - - - - - - - - - - - - - - - - - -+ *
* + + + + + + + + + + + + + + + + + + + + + *
* * * * * * * * * * * * * * * * * * * * * * *
*/ | michaelgalliakis/myThesis | UserClientV1/src/UserClientV1/DfChangeValue.java |
1,627 | package gr.aueb.cf.ch8;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
public class JULApp {
public static void main(String[] args) {
try {
Scanner sc = getFileDescriptor("C:\\tmp\\arxeiopoudenuparxei.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
public static Scanner getFileDescriptor(String s) throws FileNotFoundException{
File fd = new File(s);
Logger logger = getLogger();
try{
return new Scanner(fd);
} catch (FileNotFoundException e){
logger.severe("File not found" + e.getMessage());
throw e;
}
}
public static Logger getLogger() {
Logger logger = Logger.getLogger(JULApp.class.getName());
Handler fileHandler;
try{
fileHandler = new FileHandler("cf.log", true);
fileHandler.setFormatter(new SimpleFormatter()); // δεν δίνει xml αλλά δίνει ένα απλό κείμενο
} catch (IOException e){
throw new RuntimeException(e);
}
logger.addHandler(fileHandler);
return logger; // παρέχει έναν logger cf.log
}
}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch8/JULApp.java |