file_id
int64 1
46.7k
| content
stringlengths 14
344k
| repo
stringlengths 7
109
| path
stringlengths 8
171
|
---|---|---|---|
1,628 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αποφασίζει αν χιονίζει ή όχι
* με βάση όχι μονό τη θερμοκρασία
* αλλά και με το αν βρέχει.
*
*/
public class SnowingApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isSnowing = false;
boolean isRaining = false;
int temp = 0;
System.out.println("Please insert if its raining (True / False): ");
isRaining = in.nextBoolean();
System.out.println("Please insert Temperature: ");
temp = in.nextInt();
isSnowing = isRaining && (temp < 0);
System.out.println("Is snowing: " + isSnowing);
}
}
| jordanpapaditsas/codingfactory-java | src/gr/aueb/cf/ch3/SnowingApp.java |
1,629 | /**
* Η κλάση υλοποιεί τον αποδέκτης του μηνύματος από το κανάλι θορύβου και εξετάζει αν το μήνυμα περιέχει σφάλμα
* χρησιμοποιώντας τον αλγόριθμο εντοπισμού σφαλμάτων CRC.
*
* @author Δημήτριος Παντελεήμων Γιακάτος
* @version 1.0.0
*/
public class Receiver {
private String key;
private String bitErrorData;
private int lenOfKey;
private int errorMessagesCrc;
private int totalErrorMessages;
private int errorMessageCrcCorrect;
private boolean hasError;
/**
* Η μέθοδος είναι ο constructor που αρχικοποιεί κάποιες μεταβλητές που θα χρειαστούν για τον υπολογισμό των
* ζητούμενων ποσοστών.
*/
public Receiver() {
this.errorMessagesCrc = 0;
this.totalErrorMessages = 0;
this.errorMessageCrcCorrect = 0;
}
/**
* Η μέθοδος αποθηκεύει στη μεταβλητή key τον αριθμό P και αποθηκεύει στη μεταβλητή lenOf Key το μήλος του αριθμού P.
* @param key Μία συμβολοσειρά που περιλαμβάνει τον αριθμό P.
*/
public void setKey(String key) {
this.key = key;
lenOfKey = key.length();
}
/**
* H μέθοδος αποθηκεύει το μήνυμα T που έχει ληφθεί από το κανάλι θορύβου στη μεταβλητή bitErrorData αλλά αποθηκεύει
* και το μήνυμα Τ αναλλοίωτο στη μεταβλητή data. Ύστερα ελέγχει αν τα δύο μηνύματα είναι ίδια. Αν είναι δεν ίδια
* τότε αυξάνει τη μεταβλητή totalErrorMessages κατά ένα, που θα χρησιμοποιηθεί για τον υπολογισμό του ποσοστού των
* συνολικών μηνυμάτων με σφάλμα.
* @param bitErrorData Το μήνυμα T που έχει ληφθεί από το κανάλι θορύβου
* @param data Το μήνυμα Τ αναλλοίωτο
*/
public void setData(String bitErrorData, String data) {
this.bitErrorData = bitErrorData;
hasError = false;
if (!data.equals(bitErrorData)) {
totalErrorMessages++;
hasError = true;
}
}
/**
* Η μέθοδος είναι ο εκκινητής της διαδικασίας του αλγορίθμου για τον εντοπισμό σφαλμάτων CRC. Αν το υπόλοιπο της
* διαίρεσης που έχει προηγηθεί με τη μέθοδο division είναι 1 τότε αυξάνεται κατά ένα η μεταβλητή errorMessagesCrc
* που δείχνει το συνολικό αριθμό των μηνυμάτων που ανιχνεύτηκαν με σφάλμα από το CRC. Διαφορετικά αν το υπόλοιπο
* είναι 0 τότε αυξάνεται κατά ένα η μεταβλητή errorMessageCrcCorrect που δείχνει το συνολικό αριθμό των μηνυμάτων
* που δεν ανιχνεύτηκαν με σφάλμα από το CRC αλλά έχουν σφάλμα.
*/
public void start() {
division();
if (bitErrorData.contains("1")) {
errorMessagesCrc++;
} else if (hasError){
errorMessageCrcCorrect++;
}
}
/**
* @return Ο συνολικός αριθμός των μηνυμάτων που ανιχνεύτηκαν με σφάλμα από το CRC
*/
public int getErrorMessagesCrc() {return errorMessagesCrc;}
/**
* @return Ο συνολικός αριθμός των μηνυμάτων με σφάλμα.
*/
public int getTotalErrorMessages() {return totalErrorMessages;}
/**
* @return Ο συνολικός αριθμός των μηνυμάτων που δεν ανιχνεύτηκαν με σφάλμα από το CRC αλλά έχουν σφάλμα.
*/
public int getErrorMessageCrcCorrect() {return errorMessageCrcCorrect;}
/**
* Η μέθοδος διαιρεί τον αριθμό του μηνύματος T με τον αριθμό P από όπου θα προκύψει το υπόλοιπο το οποίο θα
* εξετάσουμε αν το μήνυμα έχει σφάλμα.
*/
private void division() {
String value;
String result;
while (bitErrorData.length()>=lenOfKey) {
value = bitErrorData.substring(0, lenOfKey);
result = Long.toBinaryString(Long.parseLong(value, 2) ^ Long.parseLong(key, 2));
bitErrorData = result + bitErrorData.substring(lenOfKey);
}
}
}
| dpgiakatos/CRC | src/Receiver.java |
1,631 | package griniaris;
import java.awt.Color;
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.LinkedHashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.Set;
import javax.swing.AbstractButton;
import javax.swing.ButtonGroup;
import javax.swing.ButtonModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.event.EventListenerList;
public class Game extends javax.swing.JFrame {
Color buffer,b;
Dice d = new Dice();
boolean rolledDice=false;
Board b1 = new Board();
int nextplayer = 0;
ArrayList<JButton> buttons = new ArrayList<>();
ArrayList<Pawn> pawns = new ArrayList<>();
JButton previous;
Color arxiko, defaultcolor;
ArrayList<JLabel> playersLabels = new ArrayList<>();
String defaultrgb;
int cnt=1;
Colors a = Colors.blue;
String str;
private int caught=1;
Map<JButton,Color > tesi = new LinkedHashMap<>();
ArrayList <Player> players = new ArrayList<>();
public Game() {
initComponents();
//αρχικοποιούμε το πίνακα με τα πιόνια των παικτών και τα χρώματα τους
pawns.add(new Pawn(jButton55.getBackground(), jButton55, 1));
pawns.add(new Pawn(jButton57.getBackground(), jButton57, 2));
pawns.add(new Pawn(jButton58.getBackground(), jButton58, 3));
pawns.add(new Pawn(jButton59.getBackground(), jButton59, 4));
pawns.add(new Pawn(jButton60.getBackground(), jButton60, 1));
pawns.add(new Pawn(jButton61.getBackground(), jButton61, 2));
pawns.add(new Pawn(jButton62.getBackground(), jButton62, 3));
pawns.add(new Pawn(jButton63.getBackground(), jButton63, 4));
pawns.add(new Pawn(jButton64.getBackground(), jButton64, 1));
pawns.add(new Pawn(jButton65.getBackground(), jButton65, 2));
pawns.add(new Pawn(jButton66.getBackground(), jButton66, 3));
pawns.add(new Pawn(jButton67.getBackground(), jButton67, 4));
pawns.add(new Pawn(jButton68.getBackground(), jButton68, 1));
pawns.add(new Pawn(jButton69.getBackground(), jButton69, 2));
pawns.add(new Pawn(jButton70.getBackground(), jButton70, 3));
pawns.add(new Pawn(jButton71.getBackground(), jButton71, 4));
//Κρύβουμε το παιχνίδι μέχρι ο χρήστης να πατήσει είσοδος στο παιχνίδι
jPanel2.setVisible(false);
jPanel3.setVisible(false);
jPanel4.setVisible(false);
a = a.Colors(a);
Color o;
for(int i=0;i<4;i++){
o = a.nextColor();
players.add(new Player("Player"+(1+i), o));
for(Pawn p : pawns)
if(o == p.getpawnColor())
players.get(i).setPawn(p);
}
arxiko = button1.getBackground();
defaultcolor = button1.getBackground();
defaultrgb = defaultcolor.getRed()+","+defaultcolor.getGreen()+","+defaultcolor.getBlue();
//προσθέτουμε τα στοιχεία στον πίνακα όπου αναγράφονται τα labels των παικτών
playersLabels.add(jLabel6);
playersLabels.add(jLabel8);
playersLabels.add(jLabel10);
playersLabels.add(jLabel12);
int thePlayer=0;
for(JLabel jl: playersLabels) {
jl.setText(players.get(thePlayer).getname());
thePlayer++;
}
//prosthetoume tous listeners sta koumpia
button1.addActionListener(listener);
button2.addActionListener(listener);
button3.addActionListener(listener);
button4.addActionListener(listener);
button5.addActionListener(listener);
button6.addActionListener(listener);
button7.addActionListener(listener);
button8.addActionListener(listener);
button9.addActionListener(listener);
button10.addActionListener(listener);
button11.addActionListener(listener);
button12.addActionListener(listener);
button13.addActionListener(listener);
button14.addActionListener(listener);
button15.addActionListener(listener);
button16.addActionListener(listener);
button17.addActionListener(listener);
button18.addActionListener(listener);
button19.addActionListener(listener);
button20.addActionListener(listener);
button21.addActionListener(listener);
button22.addActionListener(listener);
button23.addActionListener(listener);
button24.addActionListener(listener);
button25.addActionListener(listener);
button26.addActionListener(listener);
button27.addActionListener(listener);
button28.addActionListener(listener);
button29.addActionListener(listener);
button30.addActionListener(listener);
button31.addActionListener(listener);
button32.addActionListener(listener);
button33.addActionListener(listener);
button34.addActionListener(listener);
button34.addActionListener(listener);
button35.addActionListener(listener);
button36.addActionListener(listener);
button37.addActionListener(listener);
button38.addActionListener(listener);
button39.addActionListener(listener);
button40.addActionListener(listener);
button41.addActionListener(listener);
button42.addActionListener(listener);
button43.addActionListener(listener);
button44.addActionListener(listener);
button45.addActionListener(listener);
button46.addActionListener(listener);
button47.addActionListener(listener);
button48.addActionListener(listener);
button49.addActionListener(listener);
button50.addActionListener(listener);
button51.addActionListener(listener);
button52.addActionListener(listener);
button53.addActionListener(listener);
button54.addActionListener(listener);
button55.addActionListener(listener);
button56.addActionListener(listener);
button57.addActionListener(listener);
button58.addActionListener(listener);
button59.addActionListener(listener);
button60.addActionListener(listener);
button61.addActionListener(listener);
button62.addActionListener(listener);
button63.addActionListener(listener);
button64.addActionListener(listener);
button65.addActionListener(listener);
button66.addActionListener(listener);
button67.addActionListener(listener);
button68.addActionListener(listener);
button69.addActionListener(listener);
button70.addActionListener(listener);
button71.addActionListener(listener);
button72.addActionListener(listener);
//προσθέτουμε ειδικούς listeners στα κουμπιά που συμβολίζουν τα πιόνια του παίκτη
jButton55.addActionListener(startpos);
jButton57.addActionListener(startpos);
jButton58.addActionListener(startpos);
jButton59.addActionListener(startpos);
jButton60.addActionListener(startpos);
jButton61.addActionListener(startpos);
jButton62.addActionListener(startpos);
jButton63.addActionListener(startpos);
jButton64.addActionListener(startpos);
jButton65.addActionListener(startpos);
jButton66.addActionListener(startpos);
jButton67.addActionListener(startpos);
jButton68.addActionListener(startpos);
jButton69.addActionListener(startpos);
jButton70.addActionListener(startpos);
jButton71.addActionListener(startpos);
//εισαγωγή των κουμπιών και του αρχικού τους χρώματος στο map
tesi.put(button1,button1.getBackground());
tesi.put(button2,button2.getBackground());
tesi.put(button3,button3.getBackground());
tesi.put(button4,button4.getBackground());
tesi.put(button5,button5.getBackground());
tesi.put(button6,button6.getBackground());
tesi.put(button7,button7.getBackground());
tesi.put(button8,button8.getBackground());
tesi.put(button9,button9.getBackground());
tesi.put(button10,button10.getBackground());
tesi.put(button11,button11.getBackground());
tesi.put(button12,button12.getBackground());
tesi.put(button13,button13.getBackground());
tesi.put(button14,button14.getBackground());
tesi.put(button15,button15.getBackground());
tesi.put(button16,button16.getBackground());
tesi.put(button17,button17.getBackground());
tesi.put(button18,button18.getBackground());
tesi.put(button19,button19.getBackground());
tesi.put(button20,button20.getBackground());
tesi.put(button21,button21.getBackground());
tesi.put(button22,button22.getBackground());
tesi.put(button23,button23.getBackground());
tesi.put(button24,button24.getBackground());
tesi.put(button25,button25.getBackground());
tesi.put(button26,button26.getBackground());
tesi.put(button27,button27.getBackground());
tesi.put(button28,button28.getBackground());
tesi.put(button29,button29.getBackground());
tesi.put(button30,button30.getBackground());
tesi.put(button31,button31.getBackground());
tesi.put(button32,button32.getBackground());
tesi.put(button33,button33.getBackground());
tesi.put(button34,button34.getBackground());
tesi.put(button35,button35.getBackground());
tesi.put(button36,button36.getBackground());
tesi.put(button37,button37.getBackground());
tesi.put(button38,button38.getBackground());
tesi.put(button39,button39.getBackground());
tesi.put(button40,button40.getBackground());
tesi.put(button41,button41.getBackground());
tesi.put(button42,button42.getBackground());
tesi.put(button43,button43.getBackground());
tesi.put(button44,button44.getBackground());
tesi.put(button45,button45.getBackground());
tesi.put(button46,button46.getBackground());
tesi.put(button47,button47.getBackground());
tesi.put(button48,button48.getBackground());
tesi.put(button49,button49.getBackground());
tesi.put(button50,button50.getBackground());
tesi.put(button51,button51.getBackground());
tesi.put(button52,button52.getBackground());
tesi.put(button53,button53.getBackground());
tesi.put(button54,button54.getBackground());
tesi.put(button55,button55.getBackground());
tesi.put(button56,button56.getBackground());
tesi.put(button57,button57.getBackground());
tesi.put(button58,button58.getBackground());
tesi.put(button59,button59.getBackground());
tesi.put(button60,button60.getBackground());
tesi.put(button61,button61.getBackground());
tesi.put(button62,button62.getBackground());
tesi.put(button63,button63.getBackground());
tesi.put(button64,button64.getBackground());
tesi.put(button65,button65.getBackground());
tesi.put(button66,button66.getBackground());
tesi.put(button67,button67.getBackground());
tesi.put(button68,button68.getBackground());
tesi.put(button69,button69.getBackground());
tesi.put(button70,button70.getBackground());
tesi.put(button71,button71.getBackground());
tesi.put(button72,button72.getBackground());
//εισαγωγή των κουμπιών της διαδρομής στο arraylist buttons
//στα οποία έχει γίνει ειδική αρίθμηση για να χρησιμοποιηθούν
//αργότερα από την κλάση board (η οποία συμβολίζει το ταμπλό)
buttons.add(button1);
buttons.add(button2);
buttons.add(button3);
buttons.add(button6);
buttons.add(button9);
buttons.add(button12);
buttons.add(button15);
buttons.add(button18);
buttons.add(button37);
buttons.add(button38);
buttons.add(button39);
buttons.add(button40);
buttons.add(button41);
buttons.add(button42);
buttons.add(button48);
buttons.add(button54);
buttons.add(button53);
buttons.add(button52);
buttons.add(button51);
buttons.add(button50);
buttons.add(button49);
buttons.add(button57);
buttons.add(button60);
buttons.add(button63);
buttons.add(button66);
buttons.add(button69);
buttons.add(button72);
buttons.add(button71);
buttons.add(button70);
buttons.add(button67);
buttons.add(button64);
buttons.add(button61);
buttons.add(button58);
buttons.add(button55);
buttons.add(button36);
buttons.add(button35);
buttons.add(button34);
buttons.add(button33);
buttons.add(button32);
buttons.add(button31);
buttons.add(button25);
buttons.add(button19);
buttons.add(button20);
buttons.add(button21);
buttons.add(button22);
buttons.add(button23);
buttons.add(button24);
buttons.add(button16);
buttons.add(button13);
buttons.add(button10);
buttons.add(button7);
buttons.add(button4);
this.setDefaultCloseOperation(Game.DO_NOTHING_ON_CLOSE);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int choice = JOptionPane.showConfirmDialog(null, "Do you really want to close the application ?",
"Confirm Exit", JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE);
if (choice == JOptionPane.YES_OPTION) {
//if(jMenuItem3.isEnabled() == true)
//{
e.getWindow().dispose();
System.out.println("Chose to exit");
//}
//else{
//JOptionPane.showMessageDialog(null, "Δεν μπορείς να βγεις ενώ είσαι σε παιχνίδι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
//}
}
else
System.out.println("Chose to stay");
}
});
}
public void setjLabel6(String s) {
System.out.println(s + " -> jlabel6 string");
jLabel6.setText(s);
}
public void setjLabel8(String s) {
jLabel8.setText(s);
}
public void setjLabel10(String s) {
jLabel10.setText(s);
}
public void setjLabel12(String s) {
jLabel12.setText(s);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
java.awt.GridBagConstraints gridBagConstraints;
buttonGroup1 = new javax.swing.ButtonGroup();
jPanel2 = new javax.swing.JPanel();
jPanel5 = new javax.swing.JPanel();
jPanel12 = new javax.swing.JPanel();
jButton55 = new javax.swing.JButton();
jButton57 = new javax.swing.JButton();
jButton58 = new javax.swing.JButton();
jButton59 = new javax.swing.JButton();
jPanel6 = new javax.swing.JPanel();
button1 = new javax.swing.JButton();
button2 = new javax.swing.JButton();
button3 = new javax.swing.JButton();
button4 = new javax.swing.JButton();
button5 = new javax.swing.JButton();
button6 = new javax.swing.JButton();
button7 = new javax.swing.JButton();
button8 = new javax.swing.JButton();
button9 = new javax.swing.JButton();
button10 = new javax.swing.JButton();
button11 = new javax.swing.JButton();
button12 = new javax.swing.JButton();
button13 = new javax.swing.JButton();
button14 = new javax.swing.JButton();
button15 = new javax.swing.JButton();
button16 = new javax.swing.JButton();
button17 = new javax.swing.JButton();
button18 = new javax.swing.JButton();
jPanel7 = new javax.swing.JPanel();
jPanel13 = new javax.swing.JPanel();
jButton60 = new javax.swing.JButton();
jButton61 = new javax.swing.JButton();
jButton62 = new javax.swing.JButton();
jButton63 = new javax.swing.JButton();
filler1 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(15, 15), new java.awt.Dimension(32767, 0));
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
jButton56 = new javax.swing.JButton();
jPanel3 = new javax.swing.JPanel();
jPanel8 = new javax.swing.JPanel();
button19 = new javax.swing.JButton();
button20 = new javax.swing.JButton();
button21 = new javax.swing.JButton();
button22 = new javax.swing.JButton();
button23 = new javax.swing.JButton();
button24 = new javax.swing.JButton();
button25 = new javax.swing.JButton();
button26 = new javax.swing.JButton();
button27 = new javax.swing.JButton();
button28 = new javax.swing.JButton();
button29 = new javax.swing.JButton();
button30 = new javax.swing.JButton();
button31 = new javax.swing.JButton();
button32 = new javax.swing.JButton();
button33 = new javax.swing.JButton();
button34 = new javax.swing.JButton();
button35 = new javax.swing.JButton();
button36 = new javax.swing.JButton();
jPanel9 = new javax.swing.JPanel();
jButton2 = new javax.swing.JButton();
jPanel10 = new javax.swing.JPanel();
button37 = new javax.swing.JButton();
button38 = new javax.swing.JButton();
button39 = new javax.swing.JButton();
button40 = new javax.swing.JButton();
button41 = new javax.swing.JButton();
button42 = new javax.swing.JButton();
button43 = new javax.swing.JButton();
button44 = new javax.swing.JButton();
button45 = new javax.swing.JButton();
button46 = new javax.swing.JButton();
button47 = new javax.swing.JButton();
button48 = new javax.swing.JButton();
button49 = new javax.swing.JButton();
button50 = new javax.swing.JButton();
button51 = new javax.swing.JButton();
button52 = new javax.swing.JButton();
button53 = new javax.swing.JButton();
button54 = new javax.swing.JButton();
filler2 = new javax.swing.Box.Filler(new java.awt.Dimension(0, 0), new java.awt.Dimension(15, 15), new java.awt.Dimension(32767, 0));
jPanel21 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel15 = new javax.swing.JLabel();
jPanel4 = new javax.swing.JPanel();
jPanel14 = new javax.swing.JPanel();
jPanel15 = new javax.swing.JPanel();
jPanel18 = new javax.swing.JPanel();
jButton64 = new javax.swing.JButton();
jButton65 = new javax.swing.JButton();
jButton66 = new javax.swing.JButton();
jButton67 = new javax.swing.JButton();
jPanel16 = new javax.swing.JPanel();
button55 = new javax.swing.JButton();
button56 = new javax.swing.JButton();
button57 = new javax.swing.JButton();
button58 = new javax.swing.JButton();
button59 = new javax.swing.JButton();
button60 = new javax.swing.JButton();
button61 = new javax.swing.JButton();
button62 = new javax.swing.JButton();
button63 = new javax.swing.JButton();
button64 = new javax.swing.JButton();
button65 = new javax.swing.JButton();
button66 = new javax.swing.JButton();
button67 = new javax.swing.JButton();
button68 = new javax.swing.JButton();
button69 = new javax.swing.JButton();
button70 = new javax.swing.JButton();
button71 = new javax.swing.JButton();
button72 = new javax.swing.JButton();
jPanel17 = new javax.swing.JPanel();
jPanel19 = new javax.swing.JPanel();
jButton68 = new javax.swing.JButton();
jButton69 = new javax.swing.JButton();
jButton70 = new javax.swing.JButton();
jButton71 = new javax.swing.JButton();
filler3 = new javax.swing.Box.Filler(new java.awt.Dimension(15, 15), new java.awt.Dimension(15, 15), new java.awt.Dimension(15, 15));
jPanel11 = new javax.swing.JPanel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
jLabel8 = new javax.swing.JLabel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
jLabel11 = new javax.swing.JLabel();
jLabel12 = new javax.swing.JLabel();
jLabel13 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenuItem3 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem4 = new javax.swing.JMenuItem();
jMenuItem5 = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Client");
setMaximumSize(new java.awt.Dimension(680, 537));
setMinimumSize(new java.awt.Dimension(680, 537));
setPreferredSize(new java.awt.Dimension(680, 537));
setResizable(false);
getContentPane().setLayout(new javax.swing.BoxLayout(getContentPane(), javax.swing.BoxLayout.Y_AXIS));
jPanel2.setMaximumSize(new java.awt.Dimension(680, 185));
jPanel2.setMinimumSize(new java.awt.Dimension(680, 185));
jPanel2.setPreferredSize(new java.awt.Dimension(680, 185));
jPanel2.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0));
jPanel5.setBackground(new java.awt.Color(0, 255, 0));
jPanel5.setForeground(new java.awt.Color(0, 255, 0));
jPanel5.setMaximumSize(new java.awt.Dimension(150, 150));
jPanel5.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel5.setPreferredSize(new java.awt.Dimension(185, 185));
jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 50));
jPanel12.setMaximumSize(new java.awt.Dimension(85, 85));
jPanel12.setMinimumSize(new java.awt.Dimension(85, 85));
jPanel12.setName(""); // NOI18N
jPanel12.setPreferredSize(new java.awt.Dimension(85, 85));
jPanel12.setLayout(new java.awt.GridLayout(2, 2));
jButton55.setBackground(new java.awt.Color(0, 130, 0));
jButton55.setForeground(new java.awt.Color(0, 130, 0));
jPanel12.add(jButton55);
jButton57.setBackground(new java.awt.Color(0, 130, 0));
jButton57.setForeground(new java.awt.Color(0, 130, 0));
jPanel12.add(jButton57);
jButton58.setBackground(new java.awt.Color(0, 130, 0));
jButton58.setForeground(new java.awt.Color(0, 130, 0));
jPanel12.add(jButton58);
jButton59.setBackground(new java.awt.Color(0, 130, 0));
jButton59.setForeground(new java.awt.Color(0, 130, 0));
jPanel12.add(jButton59);
jPanel5.add(jPanel12);
jPanel2.add(jPanel5);
jPanel6.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel6.setPreferredSize(new java.awt.Dimension(100, 185));
jPanel6.setLayout(new java.awt.GridLayout(6, 3));
buttonGroup1.add(button1);
jPanel6.add(button1);
buttonGroup1.add(button2);
jPanel6.add(button2);
buttonGroup1.add(button3);
jPanel6.add(button3);
buttonGroup1.add(button4);
jPanel6.add(button4);
button5.setBackground(new java.awt.Color(255, 0, 0));
button5.setForeground(new java.awt.Color(255, 0, 0));
button5.setBorder(null);
buttonGroup1.add(button5);
jPanel6.add(button5);
button6.setBackground(new java.awt.Color(255, 0, 0));
button6.setForeground(new java.awt.Color(255, 0, 0));
buttonGroup1.add(button6);
jPanel6.add(button6);
buttonGroup1.add(button7);
jPanel6.add(button7);
button8.setBackground(new java.awt.Color(255, 0, 0));
buttonGroup1.add(button8);
jPanel6.add(button8);
buttonGroup1.add(button9);
jPanel6.add(button9);
button10.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/ball.png"))); // NOI18N
buttonGroup1.add(button10);
jPanel6.add(button10);
button11.setBackground(new java.awt.Color(255, 0, 0));
buttonGroup1.add(button11);
jPanel6.add(button11);
buttonGroup1.add(button12);
jPanel6.add(button12);
buttonGroup1.add(button13);
jPanel6.add(button13);
button14.setBackground(new java.awt.Color(255, 0, 0));
buttonGroup1.add(button14);
jPanel6.add(button14);
button15.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/s.png"))); // NOI18N
buttonGroup1.add(button15);
jPanel6.add(button15);
buttonGroup1.add(button16);
jPanel6.add(button16);
button17.setBackground(new java.awt.Color(255, 0, 0));
buttonGroup1.add(button17);
jPanel6.add(button17);
buttonGroup1.add(button18);
jPanel6.add(button18);
jPanel2.add(jPanel6);
jPanel7.setBackground(new java.awt.Color(255, 0, 0));
jPanel7.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel7.setPreferredSize(new java.awt.Dimension(185, 185));
jPanel7.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 50));
jPanel13.setMaximumSize(new java.awt.Dimension(85, 85));
jPanel13.setMinimumSize(new java.awt.Dimension(85, 85));
jPanel13.setName(""); // NOI18N
jPanel13.setPreferredSize(new java.awt.Dimension(85, 85));
jPanel13.setLayout(new java.awt.GridLayout(2, 2));
jButton60.setBackground(new java.awt.Color(130, 0, 0));
jButton60.setForeground(new java.awt.Color(130, 0, 0));
jPanel13.add(jButton60);
jButton61.setBackground(new java.awt.Color(130, 0, 0));
jButton61.setForeground(new java.awt.Color(130, 0, 0));
jPanel13.add(jButton61);
jButton62.setBackground(new java.awt.Color(130, 0, 0));
jButton62.setForeground(new java.awt.Color(130, 0, 0));
jPanel13.add(jButton62);
jButton63.setBackground(new java.awt.Color(130, 0, 0));
jButton63.setForeground(new java.awt.Color(130, 0, 0));
jPanel13.add(jButton63);
jPanel7.add(jPanel13);
jPanel2.add(jPanel7);
jPanel2.add(filler1);
jPanel1.setPreferredSize(new java.awt.Dimension(150, 180));
jPanel1.setLayout(new java.awt.GridLayout(0, 1));
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("YELLOW'S TURN");
jPanel1.add(jLabel1);
jButton1.setText("I CAN'T MOVE");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
jPanel1.add(jButton1);
jButton56.setText("ROLL THE DICE");
jButton56.setMaximumSize(new java.awt.Dimension(120, 25));
jButton56.setMinimumSize(new java.awt.Dimension(120, 25));
jButton56.setPreferredSize(new java.awt.Dimension(120, 25));
jButton56.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton56ActionPerformed(evt);
}
});
jPanel1.add(jButton56);
jPanel2.add(jPanel1);
getContentPane().add(jPanel2);
jPanel2.getAccessibleContext().setAccessibleName("");
jPanel3.setMaximumSize(new java.awt.Dimension(680, 105));
jPanel3.setMinimumSize(new java.awt.Dimension(680, 105));
jPanel3.setPreferredSize(new java.awt.Dimension(650, 105));
jPanel3.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0));
jPanel8.setPreferredSize(new java.awt.Dimension(185, 100));
jPanel8.setLayout(new java.awt.GridLayout(3, 6));
buttonGroup1.add(button19);
jPanel8.add(button19);
button20.setBackground(new java.awt.Color(0, 255, 0));
button20.setToolTipText("");
buttonGroup1.add(button20);
jPanel8.add(button20);
buttonGroup1.add(button21);
jPanel8.add(button21);
buttonGroup1.add(button22);
jPanel8.add(button22);
button23.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/s.png"))); // NOI18N
buttonGroup1.add(button23);
jPanel8.add(button23);
buttonGroup1.add(button24);
jPanel8.add(button24);
buttonGroup1.add(button25);
jPanel8.add(button25);
button26.setBackground(new java.awt.Color(0, 255, 0));
buttonGroup1.add(button26);
jPanel8.add(button26);
button27.setBackground(new java.awt.Color(0, 255, 0));
buttonGroup1.add(button27);
jPanel8.add(button27);
button28.setBackground(new java.awt.Color(0, 255, 0));
buttonGroup1.add(button28);
jPanel8.add(button28);
button29.setBackground(new java.awt.Color(0, 255, 0));
buttonGroup1.add(button29);
jPanel8.add(button29);
button30.setBackground(new java.awt.Color(0, 255, 0));
buttonGroup1.add(button30);
jPanel8.add(button30);
buttonGroup1.add(button31);
jPanel8.add(button31);
buttonGroup1.add(button32);
jPanel8.add(button32);
buttonGroup1.add(button33);
jPanel8.add(button33);
button34.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/ball.png"))); // NOI18N
buttonGroup1.add(button34);
jPanel8.add(button34);
buttonGroup1.add(button35);
jPanel8.add(button35);
buttonGroup1.add(button36);
jPanel8.add(button36);
jPanel3.add(jPanel8);
jPanel9.setPreferredSize(new java.awt.Dimension(102, 102));
jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/centre.png"))); // NOI18N
jButton2.setMaximumSize(new java.awt.Dimension(95, 95));
jButton2.setMinimumSize(new java.awt.Dimension(95, 95));
jButton2.setPreferredSize(new java.awt.Dimension(95, 95));
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});
jPanel9.add(jButton2);
jPanel3.add(jPanel9);
jPanel10.setPreferredSize(new java.awt.Dimension(185, 100));
jPanel10.setLayout(new java.awt.GridLayout(3, 6));
buttonGroup1.add(button37);
jPanel10.add(button37);
buttonGroup1.add(button38);
jPanel10.add(button38);
button39.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/ball.png"))); // NOI18N
buttonGroup1.add(button39);
jPanel10.add(button39);
buttonGroup1.add(button40);
jPanel10.add(button40);
buttonGroup1.add(button41);
jPanel10.add(button41);
buttonGroup1.add(button42);
jPanel10.add(button42);
button43.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button43);
jPanel10.add(button43);
button44.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button44);
jPanel10.add(button44);
button45.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button45);
jPanel10.add(button45);
button46.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button46);
jPanel10.add(button46);
button47.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button47);
jPanel10.add(button47);
buttonGroup1.add(button48);
jPanel10.add(button48);
buttonGroup1.add(button49);
jPanel10.add(button49);
button50.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/s.png"))); // NOI18N
buttonGroup1.add(button50);
jPanel10.add(button50);
buttonGroup1.add(button51);
jPanel10.add(button51);
buttonGroup1.add(button52);
jPanel10.add(button52);
button53.setBackground(new java.awt.Color(0, 0, 255));
buttonGroup1.add(button53);
jPanel10.add(button53);
buttonGroup1.add(button54);
jPanel10.add(button54);
jPanel3.add(jPanel10);
jPanel3.add(filler2);
jPanel21.setLayout(new java.awt.GridBagLayout());
jLabel3.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/dice.gif"))); // NOI18N
jLabel3.setMaximumSize(new java.awt.Dimension(140, 49));
jLabel3.setMinimumSize(new java.awt.Dimension(45, 49));
jLabel3.setPreferredSize(new java.awt.Dimension(140, 80));
jPanel21.add(jLabel3, new java.awt.GridBagConstraints());
jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel15.setText("Ο αριθμός είναι...");
jLabel15.setMaximumSize(new java.awt.Dimension(140, 16));
jLabel15.setPreferredSize(new java.awt.Dimension(140, 16));
gridBagConstraints = new java.awt.GridBagConstraints();
gridBagConstraints.gridx = 0;
gridBagConstraints.gridy = 1;
jPanel21.add(jLabel15, gridBagConstraints);
jPanel3.add(jPanel21);
getContentPane().add(jPanel3);
jPanel4.setMaximumSize(new java.awt.Dimension(680, 250));
jPanel4.setMinimumSize(new java.awt.Dimension(680, 250));
jPanel4.setPreferredSize(new java.awt.Dimension(680, 250));
jPanel4.setLayout(new java.awt.GridLayout(1, 0));
jPanel14.setMaximumSize(new java.awt.Dimension(600, 185));
jPanel14.setMinimumSize(new java.awt.Dimension(600, 185));
jPanel14.setPreferredSize(new java.awt.Dimension(600, 185));
jPanel14.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0));
jPanel15.setBackground(new java.awt.Color(255, 255, 0));
jPanel15.setForeground(new java.awt.Color(255, 255, 0));
jPanel15.setMaximumSize(new java.awt.Dimension(150, 150));
jPanel15.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel15.setPreferredSize(new java.awt.Dimension(185, 185));
jPanel15.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 50));
jPanel18.setMaximumSize(new java.awt.Dimension(85, 85));
jPanel18.setMinimumSize(new java.awt.Dimension(85, 85));
jPanel18.setName(""); // NOI18N
jPanel18.setPreferredSize(new java.awt.Dimension(85, 85));
jPanel18.setLayout(new java.awt.GridLayout(2, 2));
jButton64.setBackground(new java.awt.Color(160, 160, 0));
jButton64.setForeground(new java.awt.Color(160, 160, 0));
jPanel18.add(jButton64);
jButton65.setBackground(new java.awt.Color(160, 160, 0));
jButton65.setForeground(new java.awt.Color(160, 160, 0));
jPanel18.add(jButton65);
jButton66.setBackground(new java.awt.Color(160, 160, 0));
jButton66.setForeground(new java.awt.Color(160, 160, 0));
jPanel18.add(jButton66);
jButton67.setBackground(new java.awt.Color(160, 160, 0));
jButton67.setForeground(new java.awt.Color(160, 160, 0));
jPanel18.add(jButton67);
jPanel15.add(jPanel18);
jPanel14.add(jPanel15);
jPanel16.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel16.setPreferredSize(new java.awt.Dimension(100, 185));
jPanel16.setLayout(new java.awt.GridLayout(6, 3));
buttonGroup1.add(button55);
jPanel16.add(button55);
button56.setBackground(new java.awt.Color(255, 255, 0));
buttonGroup1.add(button56);
jPanel16.add(button56);
buttonGroup1.add(button57);
jPanel16.add(button57);
button58.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/s.png"))); // NOI18N
buttonGroup1.add(button58);
jPanel16.add(button58);
button59.setBackground(new java.awt.Color(255, 255, 0));
button59.setForeground(new java.awt.Color(255, 0, 0));
button59.setBorder(null);
buttonGroup1.add(button59);
jPanel16.add(button59);
buttonGroup1.add(button60);
jPanel16.add(button60);
buttonGroup1.add(button61);
jPanel16.add(button61);
button62.setBackground(new java.awt.Color(255, 255, 0));
buttonGroup1.add(button62);
jPanel16.add(button62);
button63.setIcon(new javax.swing.ImageIcon(getClass().getResource("/griniaris/ball.png"))); // NOI18N
buttonGroup1.add(button63);
jPanel16.add(button63);
buttonGroup1.add(button64);
jPanel16.add(button64);
button65.setBackground(new java.awt.Color(255, 255, 0));
buttonGroup1.add(button65);
jPanel16.add(button65);
buttonGroup1.add(button66);
jPanel16.add(button66);
button67.setBackground(new java.awt.Color(255, 255, 0));
buttonGroup1.add(button67);
jPanel16.add(button67);
button68.setBackground(new java.awt.Color(255, 255, 0));
buttonGroup1.add(button68);
jPanel16.add(button68);
buttonGroup1.add(button69);
jPanel16.add(button69);
buttonGroup1.add(button70);
jPanel16.add(button70);
buttonGroup1.add(button71);
jPanel16.add(button71);
buttonGroup1.add(button72);
jPanel16.add(button72);
jPanel14.add(jPanel16);
jPanel17.setBackground(new java.awt.Color(0, 0, 255));
jPanel17.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel17.setPreferredSize(new java.awt.Dimension(185, 185));
jPanel17.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.CENTER, 5, 50));
jPanel19.setMaximumSize(new java.awt.Dimension(85, 85));
jPanel19.setMinimumSize(new java.awt.Dimension(85, 85));
jPanel19.setName(""); // NOI18N
jPanel19.setPreferredSize(new java.awt.Dimension(85, 85));
jPanel19.setLayout(new java.awt.GridLayout(2, 2));
jButton68.setBackground(new java.awt.Color(0, 0, 130));
jButton68.setForeground(new java.awt.Color(0, 0, 130));
jPanel19.add(jButton68);
jButton69.setBackground(new java.awt.Color(0, 0, 130));
jButton69.setForeground(new java.awt.Color(0, 0, 130));
jPanel19.add(jButton69);
jButton70.setBackground(new java.awt.Color(0, 0, 130));
jButton70.setForeground(new java.awt.Color(0, 0, 130));
jPanel19.add(jButton70);
jButton71.setBackground(new java.awt.Color(0, 0, 130));
jButton71.setForeground(new java.awt.Color(0, 0, 130));
jPanel19.add(jButton71);
jPanel17.add(jPanel19);
jPanel14.add(jPanel17);
jPanel14.add(filler3);
jPanel11.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 2));
jPanel11.setMaximumSize(new java.awt.Dimension(150, 150));
jPanel11.setMinimumSize(new java.awt.Dimension(150, 150));
jPanel11.setPreferredSize(new java.awt.Dimension(150, 150));
jPanel11.setLayout(new java.awt.GridLayout(5, 2));
jLabel4.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel4.setText("Όνομα");
jPanel11.add(jLabel4);
jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel5.setText("Χρώμα");
jPanel11.add(jLabel5);
jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel6.setText("...");
jPanel11.add(jLabel6);
jLabel7.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel7.setText("Yellow");
jPanel11.add(jLabel7);
jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel8.setText("...");
jPanel11.add(jLabel8);
jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel9.setText("Green");
jPanel11.add(jLabel9);
jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel10.setText("...");
jPanel11.add(jLabel10);
jLabel11.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel11.setText("Red");
jPanel11.add(jLabel11);
jLabel12.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel12.setText("...");
jPanel11.add(jLabel12);
jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel13.setText("Blue");
jPanel11.add(jLabel13);
jPanel14.add(jPanel11);
jPanel4.add(jPanel14);
getContentPane().add(jPanel4);
jMenu1.setText("Παιχνίδι");
jMenuItem1.setText("Έναρξη παιχνιδιού");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Διακοπή παιχνιδιού");
jMenu1.add(jMenuItem2);
jMenuItem3.setText("Έξοδος");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem3);
jMenuBar1.add(jMenu1);
jMenu2.setText("Βοήθεια");
jMenuItem4.setText("Βοήθεια");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem4);
jMenuItem5.setText("Σχετικά με τον «Γκρινιάρη»");
jMenuItem5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem5ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem5);
jMenuBar1.add(jMenu2);
setJMenuBar(jMenuBar1);
pack();
setLocationRelativeTo(null);
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
if(jMenuItem1.isEnabled()==true)
{
//ipinfo ip= new ipinfo();
//ip.setVisible(true);
//int c=ip.jbuttonc;
//System.out.println(c);
jMenuItem1.setEnabled(false);
jMenuItem3.setEnabled(false);
jPanel2.setVisible(true);
jPanel3.setVisible(true);
jPanel4.setVisible(true);
// if(c==1)
// {
// jMenuItem1.setEnabled(false);
// System.out.println("ame");
// }
}
}//GEN-LAST:event_jMenuItem1ActionPerformed
public JPanel getjPanel2() {
return jPanel2;
}
public JPanel getjPanel3() {
return jPanel3;
}
public JPanel getjPanel4() {
return jPanel4;
}
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
if(jMenuItem1.isEnabled()==true){
int n = JOptionPane.showConfirmDialog(this,"Είσαι σίγουρος ότι θες να τερματίσεις το παιχνίδι ;","", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if(n == JOptionPane.YES_OPTION) {
this.dispose();
}
else {
//do nothing
}
}
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(jMenuItem4, " Κάθε παίκτης έχει τέσσερα πιόνια του ίδιου χρώματος (κίτρινο, πράσινο, κόκκινο ή μπλε) τα \n οποία αρχικά τοποθετούνται στη γωνία του αντίστοιχου χρώματος (περιοχή εκκίνησης). Κάθε \n πιόνι διατρέχει, ανάλογα με το αποτέλεσμα της ρίψης ενός ζαριού, τη διαδρομή με τα άσπρα τε- \n τράγωνα στο ταμπλό, με τη φορά των δεικτών του ρολογιού. Όταν ολοκληρώσει έναν ολόκληρο \n γύρο εισέρχεται στα τελικά τετράγωνα του χρώματός του. Εκεί θα πρέπει να φτάσει ακριβώς στο \n κεντρικό τετράγωνο του ταμπλό ώστε να τερματίσει. Νικητής είναι ο παίκτης του οποίου τα πιό- \n νια τερματίζουν πρώτα.\n Για να βγει ένα πιόνι από την περιοχή εκκίνησης πρέπει ο παίκτης να φέρει 5. Αυτό το 5 δεν \n το παίζει, αλλά τοποθετεί το πιόνι του στο πρώτο τετράγωνο της διαδρομής του, ξαναρίχνει το \n ζάρι και προχωρεί το πιόνι του τόσες θέσεις όσες η ζαριά. \n Ο παίκτης μπορεί να έχει πολλά πιόνια του στο ταμπλό ταυτόχρονα, και σε κάθε κίνηση επι- \n λέγει ποιο θα κινήσει. Αν για διάφορους λόγους δεν μπορεί να κινήσει κανένα πιόνι, απλώς χάνει \n τη σειρά του."," Βοήθεια", JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE,null,options,options[0]);
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem5ActionPerformed
Object[] options = {"OK"};
int n = JOptionPane.showOptionDialog(jMenuItem5,"Galatis Athanasios , email: [email protected] , AM:2022201500017 \nVakouftsis Athanasios , email: [email protected] , AM:2022201500007","",JOptionPane.OK_OPTION, JOptionPane.INFORMATION_MESSAGE,null,options,options[0]);
}//GEN-LAST:event_jMenuItem5ActionPerformed
private void jButton56ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton56ActionPerformed
d = new Dice();
jLabel3.setIcon(d.getDiceIcon());
jLabel15.setText(d+"");
rolledDice = true;
jButton56.setEnabled(false);
}//GEN-LAST:event_jButton56ActionPerformed
class myActionListener2 implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
buffer = ((JButton) e.getSource()).getBackground();
previous = ((JButton) e.getSource());
}
}
class myActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//το κουμπί στο οποίο πάτησε ο χρήστης
JButton button = (JButton) e.getSource();
//το χρώμα του προηγούμενου κουμπιού
Color prevcolor = previous.getBackground();
//το χρώμα σε string με rgb
String color_previous = prevcolor.getRed()+","+prevcolor.getGreen()+","+prevcolor.getBlue();
Color rescolor = ((JButton) e.getSource()).getBackground();
String button_color = rescolor.getRed()+","+rescolor.getGreen()+","+rescolor.getBlue();
System.out.println(button_color);
//έλεγχος για το αν η σειρά είναι σωστή
if(!players.get(nextplayer).getcolor().equals(button_color) && !players.get(nextplayer).getcolor().equals(color_previous) )
{
System.out.println("not right color");
}
else if (!button_color.equals(color_previous)) {
//αν ο χρήστης πατήσει σε κάποιο από τα πιόνια του
if(button_color.equals("160,160,0") || button_color.equals("0,130,0") || button_color.equals("130,0,0") || button_color.equals("0,0,130")) {
buffer = ((JButton) e.getSource()).getBackground();
previous = ((JButton) e.getSource());
return;
}
else {
if(!rolledDice) {
JOptionPane.showMessageDialog(null, "Πάτα στο κουμπί Roll The Dice για να ρίξεις το ζάρι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
return;
}
//ελέγχουμε αν ο χρήστης τοποθετεί ένα πιόνι από την αρχική του θέση στο ταμπλό
if(!tesi.containsKey(previous)) {
if (color_previous.equals("130,0,0")) {
if(!rolledDice) {
JOptionPane.showMessageDialog(null, "Πάτα στο κουμπί Roll The Dice για να ρίξεις το ζάρι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
return;
}
if (button == button6 && d.getN()==5)
{
//set button's color on the board
b1.setButtonsColor(((JButton) e.getSource()), buffer);
//((JButton) e.getSource()).setBackground(buffer);
buffer = ((JButton) e.getSource()).getBackground();
}
else return;
}
else if(color_previous.equals("0,0,130")) {
if(!rolledDice) {
JOptionPane.showMessageDialog(null, "Πάτα στο κουμπί Roll The Dice για να ρίξεις το ζάρι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
return;
}
if (button == button53 && d.getN()==5)
{
//set button's color on the board
b1.setButtonsColor(((JButton) e.getSource()), buffer);
//((JButton) e.getSource()).setBackground(buffer);
buffer = ((JButton) e.getSource()).getBackground();
}
else return;
}
else if(color_previous.equals("160,160,0")) {
if(!rolledDice) {
JOptionPane.showMessageDialog(null, "Πάτα στο κουμπί Roll The Dice για να ρίξεις το ζάρι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
return;
}
if (button == button67 && d.getN()==5)
{
//set button's color on the board
b1.setButtonsColor(((JButton) e.getSource()), buffer);
//((JButton) e.getSource()).setBackground(buffer);
buffer = ((JButton) e.getSource()).getBackground();
}
else return;
}
else if(color_previous.equals("0,130,0")) {
if(!rolledDice) {
JOptionPane.showMessageDialog(null, "Πάτα στο κουμπί Roll The Dice για να ρίξεις το ζάρι!", " Προειδοποίηση", JOptionPane.WARNING_MESSAGE);
return;
}
if (button == button20 && d.getN()==5)
{
//set button's color on the board
b1.setButtonsColor(((JButton) e.getSource()), buffer);
//((JButton) e.getSource()).setBackground(buffer);
buffer = ((JButton) e.getSource()).getBackground();
}
else return;
}
}
//ελέγχουμε αν η κίνηση είναι έγκυρη
else if(tesi.containsKey(previous) && !b1.checkBoard(buttons, previous, (JButton) e.getSource(), d.getN())) {
System.out.println("Can't move there!");
return;
}
//an o xrhsths pathsei se asteri kai dn oloklhronei ton guro tou metaferetai sto epomeno asteri
if(button == button23 && !color_previous.equals("130,0,0")) {
//set button's color on the board
b1.setButtonsColor(((JButton) button15), buffer);
//((JButton) button15).setBackground(buffer);
buffer = ((JButton) button15).getBackground();
}
else if(button == button15 && !color_previous.equals("0,0,130")) {
//set button's color on the board
b1.setButtonsColor(((JButton) button50), buffer);
//((JButton) button15).setBackground(buffer);
buffer = ((JButton) button50).getBackground();
}
else if(button == button50 && !color_previous.equals("160,160,0")) {
//set button's color on the board
b1.setButtonsColor(((JButton) button58), buffer);
//((JButton) button15).setBackground(buffer);
buffer = ((JButton) button58).getBackground();
}
else if(button == button58 && !color_previous.equals("0,130,0")) {
//set button's color on the board
b1.setButtonsColor(((JButton) button23), buffer);
//((JButton) button15).setBackground(buffer);
buffer = ((JButton) button23).getBackground();
}
else {
b1.setButtonsColor(((JButton) e.getSource()), buffer);
//((JButton) e.getSource()).setBackground(buffer);
buffer = ((JButton) e.getSource()).getBackground();
}
//χρησιμοποιούμε το map μας για να ενημερώσουμε το χρώμα του τετραγώνου της διαδρομής από το οποίο
//ο χρήστης έφυγε, το οποίο αποκτά το αρχικό του χρώμα και πάλι
boolean found = false;
for (Map.Entry<JButton,Color> entry : tesi.entrySet())
{
if(previous == entry.getKey())
{
//set the button's color on the board
b1.setButtonsColor(previous, entry.getValue());
previous.setBackground(entry.getValue());
System.out.println("value"+entry.getValue());
found = true;
}
}
if(!found){
b1.setButtonsColor(previous, defaultcolor);
previous.setBackground(defaultcolor);
}
previous = ((JButton) e.getSource());
check();
}
}
else {
buffer = ((JButton) e.getSource()).getBackground();
previous = ((JButton) e.getSource());
}
}
}
//αρχικοποιούμε τους listeners για τα τετράγωνα της διαδρομής και των πιονιών
myActionListener listener = new myActionListener ();
myActionListener2 startpos = new myActionListener2 ();
public void check()
{
//check player's turn
Player currentPlayer = players.get(nextplayer);
b=a.nextColor();
String b_color = b.getRed()+","+b.getGreen()+","+b.getBlue();
//ενημέρωση του label ανάλογα με το ποιος παίκτης παίζει τώρα
if(currentPlayer.getcolor().equals("160,160,0"))
jLabel1.setText("GREEN'S TURN");
else if(currentPlayer.getcolor().equals("0,130,0"))
jLabel1.setText("RED'S TURN");
else if(currentPlayer.getcolor().equals("130,0,0"))
jLabel1.setText("BLUE'S TURN");
if(currentPlayer.getcolor().equals("0,0,130"))
jLabel1.setText("YELLOW'S TURN");
//System.out.println("\n"+b+":Make your move");
buffer = b;
//b_color = buffer.getRed()+","+buffer.getGreen()+","+buffer.getBlue();
//System.out.println(b_color);
rolledDice = !rolledDice;
jButton56.setEnabled(true);
nextplayer=(nextplayer+1)%4;
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
JOptionPane.showMessageDialog(null, "Νίκησες Το Παιχνίδι!!!", "Νίκη", JOptionPane.INFORMATION_MESSAGE);
}//GEN-LAST:event_jButton2ActionPerformed
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
check();
}//GEN-LAST:event_jButton1ActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* 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(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Game.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Game().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton button1;
private javax.swing.JButton button10;
private javax.swing.JButton button11;
private javax.swing.JButton button12;
private javax.swing.JButton button13;
private javax.swing.JButton button14;
private javax.swing.JButton button15;
private javax.swing.JButton button16;
private javax.swing.JButton button17;
private javax.swing.JButton button18;
private javax.swing.JButton button19;
private javax.swing.JButton button2;
private javax.swing.JButton button20;
private javax.swing.JButton button21;
private javax.swing.JButton button22;
private javax.swing.JButton button23;
private javax.swing.JButton button24;
private javax.swing.JButton button25;
private javax.swing.JButton button26;
private javax.swing.JButton button27;
private javax.swing.JButton button28;
private javax.swing.JButton button29;
private javax.swing.JButton button3;
private javax.swing.JButton button30;
private javax.swing.JButton button31;
private javax.swing.JButton button32;
private javax.swing.JButton button33;
private javax.swing.JButton button34;
private javax.swing.JButton button35;
private javax.swing.JButton button36;
private javax.swing.JButton button37;
private javax.swing.JButton button38;
private javax.swing.JButton button39;
private javax.swing.JButton button4;
private javax.swing.JButton button40;
private javax.swing.JButton button41;
private javax.swing.JButton button42;
private javax.swing.JButton button43;
private javax.swing.JButton button44;
private javax.swing.JButton button45;
private javax.swing.JButton button46;
private javax.swing.JButton button47;
private javax.swing.JButton button48;
private javax.swing.JButton button49;
private javax.swing.JButton button5;
private javax.swing.JButton button50;
private javax.swing.JButton button51;
private javax.swing.JButton button52;
private javax.swing.JButton button53;
private javax.swing.JButton button54;
private javax.swing.JButton button55;
private javax.swing.JButton button56;
private javax.swing.JButton button57;
private javax.swing.JButton button58;
private javax.swing.JButton button59;
private javax.swing.JButton button6;
private javax.swing.JButton button60;
private javax.swing.JButton button61;
private javax.swing.JButton button62;
private javax.swing.JButton button63;
private javax.swing.JButton button64;
private javax.swing.JButton button65;
private javax.swing.JButton button66;
private javax.swing.JButton button67;
private javax.swing.JButton button68;
private javax.swing.JButton button69;
private javax.swing.JButton button7;
private javax.swing.JButton button70;
private javax.swing.JButton button71;
private javax.swing.JButton button72;
private javax.swing.JButton button8;
private javax.swing.JButton button9;
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.Box.Filler filler1;
private javax.swing.Box.Filler filler2;
private javax.swing.Box.Filler filler3;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton55;
private javax.swing.JButton jButton56;
private javax.swing.JButton jButton57;
private javax.swing.JButton jButton58;
private javax.swing.JButton jButton59;
private javax.swing.JButton jButton60;
private javax.swing.JButton jButton61;
private javax.swing.JButton jButton62;
private javax.swing.JButton jButton63;
private javax.swing.JButton jButton64;
private javax.swing.JButton jButton65;
private javax.swing.JButton jButton66;
private javax.swing.JButton jButton67;
private javax.swing.JButton jButton68;
private javax.swing.JButton jButton69;
private javax.swing.JButton jButton70;
private javax.swing.JButton jButton71;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel12;
private javax.swing.JLabel jLabel13;
private javax.swing.JLabel jLabel15;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel10;
private javax.swing.JPanel jPanel11;
private javax.swing.JPanel jPanel12;
private javax.swing.JPanel jPanel13;
private javax.swing.JPanel jPanel14;
private javax.swing.JPanel jPanel15;
private javax.swing.JPanel jPanel16;
private javax.swing.JPanel jPanel17;
private javax.swing.JPanel jPanel18;
private javax.swing.JPanel jPanel19;
private javax.swing.JPanel jPanel2;
private javax.swing.JPanel jPanel21;
private javax.swing.JPanel jPanel3;
private javax.swing.JPanel jPanel4;
private javax.swing.JPanel jPanel5;
private javax.swing.JPanel jPanel6;
private javax.swing.JPanel jPanel7;
private javax.swing.JPanel jPanel8;
private javax.swing.JPanel jPanel9;
// End of variables declaration//GEN-END:variables
}
| NasosG/Griniaris-Ludo-Java | Griniaris/src/griniaris/Game.java |
1,633 | /*
This file is part of SmartLib Project.
SmartLib is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SmartLib is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with SmartLib. If not, see <http://www.gnu.org/licenses/>.
Author: Paschalis Mpeis
Affiliation:
Data Management Systems Laboratory
Dept. of Computer Science
University of Cyprus
P.O. Box 20537
1678 Nicosia, CYPRUS
Web: http://dmsl.cs.ucy.ac.cy/
Email: [email protected]
Tel: +357-22-892755
Fax: +357-22-892701
*/
package cy.ac.ucy.paschalis.client.android;
/**
* The Library User
*
* @author paschalis
*/
public class User {
/**
* Username User puts on login form
*/
String username;
/**
* Password User puts on login form
*/
String password;
/**
* Name of user
*/
String name;
/**
* Surname of user
*/
String surname;
String email;
String telephone;
/* @formatter:off */
/**
* Level Explanation
* 0: ούτε ειδοποιήσεις εντός εφαρμογής, ούτε email
* 1: μόνο ειδοποιήσεις εντός εφαρμογής
* 2: μόνο ειδοποιήσεις μέσω email
* 3: και ειδοποιήσεις εντός εφαρμογής αλλά και email
*/
/* @formatter:on */
int allowRequests = ALLOW_REQUESTS_NOT_SET;
public static final int ALLOW_REQUESTS_NOTHING = 0;
public static final int ALLOW_REQUESTS_APP = 1;
public static final int ALLOW_REQUESTS_EMAIL = 2;
public static final int ALLOW_REQUESTS_ALL = 3;
public static final int ALLOW_REQUESTS_NOT_SET = -10;
/* @formatter:off */
/**
* Level of User
* Level 2: Μπορεί να κάνει κάποιον Level2(mod), ή να διαγράψει κάποιον χρήστη από την Βιβλιοθήκη
* Level 1: Μπορεί να εισάγει τις προσωπικές του Βιβλιοθήκες
* Level 0: Ο χρήστης δεν ενεργοποίησε ακόμη τον λογαριασμό του μέσω του email του.
* Level -1: Ο χρήστης είναι επισκέπτης στο σύστημα.
*/
/* @formatter:on */
int level = LEVEL_NOT_SET;
public int totalBooks = 0;
public static final int LEVEL_MOD = 2;
public static final int LEVEL_ACTIVATED = 1;
public static final int LEVEL_NOT_ACTIVATED = 0;
public static final int LEVEL_VISITOR = -1;
/**
* Exists only in Android enviroment, to flag user credencials as invalid
*/
public static final int LEVEL_BANNED = -2;
public static final int LEVEL_NOT_SET = -10;
}
| dmsl/smartlib | Android - Corrected - Play Version/src/cy/ac/ucy/paschalis/client/android/User.java |
1,634 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.Vivliothiki;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.stage.Stage;
public class EpistrofiVivliouController implements Initializable {
@FXML
public Label eponimo, onoma, patronimo, dieuthinsi, tilefono, date, titlos, siggrafeas, katigoria, selides, isbn, ekdotikos;
@FXML
public DatePicker dateEpistrofis;
int sel = sopho.ResultKeeper.selectedIndex;
ResultSet oldrs = sopho.ResultKeeper.rs;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
@Override
public void initialize(URL url, ResourceBundle rb) {
try {
oldrs.first();
if(sel>0){
oldrs.relative(sel);
}
Tooltip t = new Tooltip();
t.setText("Ημερομηνία επιστροφής");
dateEpistrofis.setTooltip(t);//we set a tooltip because as the field is filled with the current date the prompt text will not appear.
dateEpistrofis.setValue(LocalDate.now());//setting the date to today
//setting the text to the labels
eponimo.setText(oldrs.getString("eponimo"));
onoma.setText(oldrs.getString("onoma"));
patronimo.setText(oldrs.getString("patronimo"));
dieuthinsi.setText(oldrs.getString("dieuthinsi"));
tilefono.setText(oldrs.getString("tilefono"));
date.setText(oldrs.getDate("date").toString());
titlos.setText(oldrs.getString("titlos"));
siggrafeas.setText(oldrs.getString("siggrafeas"));
ekdotikos.setText(oldrs.getString("ekdotikos"));
selides.setText(oldrs.getString("selides"));
katigoria.setText(oldrs.getString("katigoria"));
isbn.setText(oldrs.getString("isbn"));
} catch (SQLException ex) {
Logger.getLogger(EpistrofiVivliouController.class.getName()).log(Level.SEVERE, null, ex);
}
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) onoma.getScene().getWindow();
sl.StageLoad("/sopho/Vivliothiki/ListaDaneismenon.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Save(ActionEvent e) throws IOException, SQLException{
if(dateEpistrofis.getValue()==null){
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Δεν έχετε ορίσει ημερομηνία επιστροφής του βιβλίου.", "error");
cm.showAndWait();
}else{
int id = oldrs.getInt("id");
String sql = "INSERT INTO vivliothikiistoriko (eponimo, onoma, patronimo, dieuthinsi, tilefono, date, dateEpistrofis, siggrafeas, titlos, ekdotikos, katigoria, selides, isbn) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)";
conn=db.ConnectDB();
pst=conn.prepareStatement(sql);
pst.setString(1, oldrs.getString(("eponimo")));
pst.setString(2, oldrs.getString(("onoma")));
pst.setString(3, oldrs.getString(("patronimo")));
pst.setString(4, oldrs.getString(("dieuthinsi")));
pst.setString(5, oldrs.getString(("tilefono")));
pst.setDate(6, oldrs.getDate(("date")));
//now we have to convert the date to a suitable format to be able to push it to the database
if(dateEpistrofis.getValue()!=null){
Date d = Date.from(dateEpistrofis.getValue().atStartOfDay(ZoneId.systemDefault()).toInstant());
java.sql.Date sqlDate = new java.sql.Date(d.getTime());
pst.setDate(7,sqlDate);
}else{
pst.setDate(7, null);
}
pst.setString(8, oldrs.getString(("siggrafeas")));
pst.setString(9, oldrs.getString(("titlos")));
pst.setString(10, oldrs.getString(("ekdotikos")));
pst.setString(11, oldrs.getString(("katigoria")));
pst.setString(12, oldrs.getString(("selides")));
pst.setString(13, oldrs.getString(("isbn")));
int flag = pst.executeUpdate();
if(flag>0){
sql="UPDATE vivliothiki SET daneismeno=0, eponimo='', onoma='', patronimo='', dieuthinsi='', tilefono='', date=null WHERE id = ?";
pst = conn.prepareStatement(sql);
pst.setInt(1,oldrs.getInt("id"));
int flag2 = pst.executeUpdate();
if(flag2>0){
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Τέλεια!", "Η επιστροφή του βιβλίου καταχωρήθηκε με επιτυχία. Δείτε το ιστορικό των δανεισμών βιβλίων.", "confirm");
cm.showAndWait();
Stage stage = (Stage) onoma.getScene().getWindow();
sl.StageLoad("/sopho/Vivliothiki/IstorikoDaneismou.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Ο δανεισμός του βιβλίου καταγράφηκε στο ιστορικό αλλά δεν μπόρεσε να δηλωθεί η επιστροφή του βιβλίου στη βάση δεδομένων. Συνεπώς, το βιβλίο φαίνεται να είναι δανεισμένο ακόμα.", "error");
cm2.showAndWait();
}
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να κατοχυρωθεί η επιστροφή του βιβλίου.", "error");
cm.showAndWait();
}
}
}
}
| ellak-monades-aristeias/Sopho | src/sopho/Vivliothiki/EpistrofiVivliouController.java |
1,636 | import java.io.IOException;
import java.util.*;
/**
* Αυτή η κλάση χειρίζεται τα καταλύματα και τα χαρακτηριστικά τους μέσα στο πρόγραμμα, καθώς και την αποθήκευση τους
* στην κύρια μνήμη του υπολογιστή.
* Εμπεριέχει μεθόδους για την προβολή και επεξεργασία των δεδομένων κάθε καταλύματος ξεχωριστά, αλλά και την αναζήτηση
* στο σύνολο όλων των καταλυμάτων
*/
public class Rental
{
/**
* Η βάση στην οποία αποθηκεύονται τα δεδομένα όλων των καταλυμάτων.
*/
private static Database rentalsDatabase;
/**
* Το ΜΟΝΑΔΙΚΟ αναγνωριστικό κάθε καταλύματος
*/
private String id;
/**
* Ο πίνακας με τα στοιχεία κάθε καταλύματος
*/
private HashMap<String,String> characteristics;
//Basic Methods
//----------------------------------------------------------------------------------------------------------------------
/**
* Δημιουργεί ένα νέο κατάλυμα, και αν το κατάλυμα υπάρχει ήδη στη βάση, φορτίζει τα χαρακτηριστικά του
* @param id το Αναγνωριστικό του καταλύματος
*/
public Rental(String id)
{
this.id=id;
this.characteristics = new HashMap<>();
if (rentalsDatabase.search(id) != -1)
{
loadCharacteristics();
}
else
{
this.create();
}
}
/**
* @return Το αναγνωριστικό ενός Καταλύματος
*/
public String getId()
{
return this.id;
}
//Characteristics Methods (work with the Characteristics HashMap)
//----------------------------------------------------------------------------------------------------------------------
/**
* Αλλάζει την τιμή ενός χαρακτηριστικού του καταλύματος
* @param type ο τύπος του χαρακτηριστικού που θα αλλάξει
* @param value η νέα τιμή του χαρακτηριστικού που θα αλλάξει
* @return <p>false αν δεν υπήρχε ο τύπος χαρακτηριστικού στα characteristics</p>
* <p>true αν άλλαξε επιτυχώς</p>
*/
public boolean setCharacteristic(String type,String value)
{
if(!characteristics.keySet().contains(type))
{
return false;
}
characteristics.put(type,value);
return true;
}
/**
* Δημιουργεί ένα καινούργιο χαρακτηριστικού για το καταλύματος
* @param type ο τύπος του νέου χαρακτηριστικού
* @param value η τιμή του νέου χαρακτηριστικού
* @return <p>false αν υπήρχε ήδη ο τύπος χαρακτηριστικού στα characteristics</p>
* <p>true αν προστέθηκε επιτυχώς</p>
*/
public boolean addCharacteristic(String type,String value)
{
if(characteristics.keySet().contains(type))
{
return false;
}
characteristics.put(type,value);
return true;
}
/**
* Διαγράφει ένα χαρακτηριστικό του καταλύματος
* @param type ο τύπος του χαρακτηριστικού που θα διαγραφεί
* @return <p>false αν δεν υπήρχε ο τύπος χαρακτηριστικού στα characteristics</p>
* <p>true αν διαγράφηκε επιτυχώς</p>
*/
public boolean deleteCharacteristic(String type)
{
if(!characteristics.keySet().contains(type))
{
return false;
}
characteristics.remove(type);
return true;
}
/**
* @param type ο τύπος του χαρακτηριστικό που θέλουμε
* @return η τιμή του χαρακτηριστικού που θέλουμε
*/
public String getCharacteristic(String type)
{
return characteristics.get(type);
}
/**
* Μας λέει αν ένα κατάλυμα έχει έναν χαρακτηριστικό
* @param type ο τύπος του χαρακτηριστικού
* @return <p>true αν το έχει</p>
* <p>false αν δεν το έχει</p>
*/
public boolean has(String type)
{
if (this.getCharacteristic(type).equals("yes"))
{
return true;
}
else
{
return false;
}
}
/**
* Don't look at this one... it's a mistake
* @param type
* @return true if this rental has the type of Characteristic in the database
*/
public boolean contains(String type)
{
if (this.getCharacteristic(type) != null)
{
return true;
}
else
{
return false;
}
}
/**
* Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος, στο εσωτερικό μέρος της rentalsDatabase (το ArrayList)
* ΠΡΟΣΟΧΗ: Πρέπει να καλείται κάθε φορά που τελειώνουμε την επεξεργασία ή δημιουργία ενός καταλύματος
*/
public void updateCharacteristics()
{
int from = rentalsDatabase.search(id,SearchType.first);
int to = rentalsDatabase.search(id,SearchType.last);
for (int i = from; i <= to; i++)
{
rentalsDatabase.remove(i);
i--;
to--;
}
for (String cType:characteristics.keySet())
{
rentalsDatabase.add(id,cType,characteristics.get(cType));
}
}
/**
* Φορτίζει τα χαρακτηριστικά ενός καταλύματος απο το rentalsDataBase στο characteristics
*/
private void loadCharacteristics()
{
int from = rentalsDatabase.search(id,SearchType.first);
int to = rentalsDatabase.search(id,SearchType.last);
for (int i = from; i <= to; i++)
{
characteristics.put(rentalsDatabase.get(1,i), rentalsDatabase.get(2,i));
}
}
//Holistic Methods (static methods that work with all rentals in the database)
//----------------------------------------------------------------------------------------------------------------------
/**
* Φορτίζει τις αλλαγές που έγιναν κατά την εκτέλεση του προγράμματος στο εξωτερικό μέρος του rentalsDatabase (το αρχείο .txt)
* ΠΡΟΣΟΧΗ: Πρέπει να καλείται πάντα στο τέλος του προγράμματος
*/
public static void updateDatabase() throws IOException
{
rentalsDatabase.update();
}
/**
* Δημιουργεί καινούργιο database με το όνομα που του δίνεται για τα characteristics ΟΛΩΝ των καταλυμάτων
* (και αυτόματα φορτίζει και τα δεδομένα της)
* ΠΡΟΣΟΧΗ: Πρέπει να καλείται στην αρχή κάθε προγράμματος
* (Δίνοντας διαφορετικά filenames μπορούμε να δημιουργήσουμε οποιονδήποτε αριθμό βάσεων δεδομένων θέλουμε)
* @param filename Το όνομα του φακέλου που θα εμπεριέχει το rentalsDatabase
*/
public static void initializeDatabase(String filename) throws IOException
{
rentalsDatabase = new Database(filename);
}
/**
* Αυτή η μέθοδος φιλτράρει τα δοθέντα id καταλυμάτων με ένα συγκεκριμένο κριτήριο
* (τιμή καταλύματος.contains(τιμή κριτηρίου) || τιμή κριτηρίου.contains(τιμή καταλύματος))
* @param ids Αν δε δοθεί η μέθοδος φιλτράρει όλα τα id
* @param type Ο τύπος του κριτηρίου
* @param value Η τιμή του κριτηρίου
* @return Το σύνολο των αναγνωριστικών των οποίων τα καταλύματα πληρούν το κριτήριο
*/
public static HashSet<String> filter(HashSet<String> ids, String type, String value)
{
//In this version we have a HashSet of ids already so that we can apply more than one filter
HashSet<String> filteredIds = new HashSet<>();
for (String id:ids)
{
int search = rentalsDatabase.search(id,type);
String curValue = rentalsDatabase.get(2,search);
if (curValue.contains(value) || value.contains(curValue))
{
filteredIds.add(id);
}
}
return filteredIds;
}
/**
* @see #filter(HashSet, String, String)
*/
public static HashSet<String> filter(String type, String value)
{
HashSet<String> ids = getAll();
HashSet<String> filteredIds = new HashSet<>();
for (String id:ids)
{
int search = rentalsDatabase.search(id,type);
String curValue = rentalsDatabase.get(2,search);
if (curValue.contains(value) || value.contains(curValue))
{
filteredIds.add(id);
}
}
return filteredIds;
}
/**
* Κάνει το ίδιο με τη filter αλλά βλέπει άν οι τιμές των καταλυμάτων είναι ακριβώς ίδιες
* (Τιμή καταλύματος.equals(τιμή κριτηρίου))
* @see #filter(HashSet, String, String)
*/
public static HashSet<String> strongFilter(String type, String value)
{
HashSet<String> ids = getAll();
HashSet<String> filteredIds = new HashSet<>();
for (String id:ids)
{
int search = rentalsDatabase.search(id,type);
String curValue = rentalsDatabase.get(2,search);
if (curValue.equals(value))
{
filteredIds.add(id);
}
}
return filteredIds;
}
/**
* @see #strongFilter(HashSet, String, String)
*/
public static HashSet<String> strongFilter(HashSet<String> ids, String type, String value)
{
//In this version we have a HashSet of ids already so that we can apply more than one filter
HashSet<String> filteredIds = new HashSet<>();
for (String id:ids)
{
int search = rentalsDatabase.search(id,type);
String curValue = rentalsDatabase.get(2,search);
if (curValue.equals(value))
{
filteredIds.add(id);
}
}
return filteredIds;
}
/**
* @return το σύνολο όλων των ids, όλων των καταλυμάτων
*/
public static HashSet<String> getAll()
{
return rentalsDatabase.getCategorySet();
}
/**
* Βλέπει αν ένα id υπάρχει ήδη στη βάση δεδομένων
* @param id
* @return true αν δεν υπάρχει,false αν υπάρχει
*/
public static boolean checkIdAvailability(String id)
{
if(rentalsDatabase.search(id) == -1)
return true;
else
return false;
}
/**
* Εκτυπώνει όλη τη βάση δεδομένων στο terminal
*/
public static void showAll()
{
rentalsDatabase.show();
}
//Helper methods (Help with other methods and smaller stuff)
//----------------------------------------------------------------------------------------------------------------------
/**
* @return ένα αναγνωριστικό που δε βρίσκεται σε χρήση από άλλο κατάλυμα
*/
public static String getAvailableID()
{
boolean flag = true;
Random rand = new Random();
String id = "";
while (flag)
{
Integer idNum = rand.nextInt(100000,999999);
id = idNum.toString();
if(checkIdAvailability(id))
{
flag = false;
}
}
return id;
}
/**
* Αρχικοποιεί ένα rental στο database
*/
private void create()
{
rentalsDatabase.add(id,"initializer","nothing");
}
}
| KonnosBaz/AUTh_CSD_Projects | Object Oriented Programming (2021)/src/Rental.java |
1,637 | abstract class ArrayStack implements Stack { // TODO: ΔΕΝ ΧΡΗΣΙΜΟΠΟΙΕΙΤΑΙ ΠΟΥΘΕΝΑ. ΝΑ ΕΛΕΧΘΕΙ ΚΑΙ ΝΑ ΔΙΑΓΡΑΦΕΙ
private int stackCapacity;
private Object[] S;
private int top = -1;
// Default constructor
public ArrayStack() {
this(MAX_CAPACITY);
}
// Full constructor
public ArrayStack(int newCapacity) {
this.stackCapacity = newCapacity;
this.S = new Object[this.stackCapacity];
}
public int getStackSize() {
// Επιστρέφει το μέγεθος της Στοίβας
return (this.top + 1);
}
public int getMaxStackCapacity() {
// Επιστρέφει το μέγεθος της Στοίβας
return this.stackCapacity;
}
public boolean stackIsEmpty() {
// Επιστρέφει true αν η Στοίβα είναι κενή
return (this.top < 0);
}
public Object topStackElement() throws StackEmptyException {
// Επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
return this.S[this.top];
}
public void pushStackElement(Object item) throws StackFullException {
// Εισάγει ένα νέο στοιχείο στην κορυφή της Στοίβας
//if (this.getStackSize() == this.stackCapacity - 1) // Στις σημειώσεις έχει αυτή τη γραμμή αλλά δεν επιστρέφει σωστό μέγεθος της Στοίβας
if (this.getStackSize() == this.stackCapacity) // Αυτή η γραμμή φαίνεται να επιστρέφει σωστό μέγεθος της Στοίβας
throw new StackFullException(MSG_STACK_FULL);
// System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[++this.top] = item; // ΠΡΟΣΟΧΗ! Πρώτα αυξάνει το top και μετά εισάγει το στοιχείο (item) στον πίνακα
// System.out.println("*** Top after push: " + this.top); // FOR TESTS
}
public Object popStackElement() throws StackEmptyException {
// Εξάγει και επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
Object tmpElement;
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
tmpElement = this.S[top];
// System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[this.top--] = null; // ΠΡΟΣΟΧΗ! Πρώτα θέτει null στη θέση του top για τον garbage collector (εκκαθάριση της μνήμης από τα "σκουπίδια") και μετά το μειώνει
// System.out.println("*** Top after push: " + this.top); // FOR TESTS
return tmpElement;
}
}
| panosale/DIPAE_DataStructures_3rd_Term | Askisi4.1(alt1)/src/ArrayStack.java |
1,638 | package thesis;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* Η κλάση Professors υλοποιεί την κλάση Serializable και είναι υπεύθυνη για την αποθήκευση στοιχείων των καθηγητών
*
* @author Nektarios Gkouvousis
* @author ice18390193
*
* @param profSurname Επώνυμο καθηγητή
* @param profFirstname Όνομα καθηγητή
* @param profField Ειδικότητα καθηγητή
* @param availability Λίστα με αντικείμενα της κλάσης Availability
*/
public class Professor{
private String profSurname;
private String profFirstname;
private String profField;
private List<Availability> availability;
Professor(String a, String b, String c){
profSurname = a;
profFirstname = b;
profField = c;
availability = new ArrayList<>();
}
public void setProfSurname(String x){
this.profSurname = x;
}
public void setProfFirstname(String x){
this.profFirstname = x;
}
public void setProfField(String x){
this.profField = x;
}
public String getProfSurname(){
return this.profSurname;
}
public String getProfFirstname(){
return this.profFirstname;
}
public String getProfField(){
return this.profField;
}
public void setAvailability(List<Availability> availability) {
this.availability = availability;
}
/**
* Η μέθοδος επιστρέφει την διαθεσιμότητα ενός καθηγητή για συγκεκριμένη
* ημερομηνία και χρονική περίοδο
* @param date Η ημερομηνία της διαθεσιμότητας προς έλεγχο
* @param timeslot Η χρονική περίοδος της διαθεσιμότητας προς έλεγχο
* @return 0 όταν ο καθηγητής δεν είναι διαθέσιμος
* 1 όταν ο καθηγητής είναι διαθέσιμος
* 2 όταν ο καθηγητής είναι διαθέσιμος αλλά έχει δεσμευθεί από άλλο μάθημα για εκείνη την ημερομηνία
*/
public int isAvailable(String date, String timeslot){
for (Availability a : availability){
if (a.getDate().equals(date) && a.getTimeSlot().equals(timeslot)){
if(a.getIsAvailable() == 0){
return 0;
}else if (a.getIsAvailable() == 1){
return 1;
}else if (a.getIsAvailable() == 2){
return 2;
}
}
}
return -1;
}
/**
* Η μέθοδος αλλάζει την διαθεσιμότητα ενός καθηγητή για συγκεκριμένη
* ημερομηνία και χρονική περίοδο
* @param date Η ημερομηνία της διαθεσιμότητας προς αλλαγή
* @param timeslot Η χρονική περίοδος της διαθεσιμότητας προς αλλαγή
* @param res Η νέα τιμή διαθεσιμότητας που θα οριστεί (0,1,2)
*/
public void changeSpecificAvailability(String date, String timeslot, int res){
for (Availability a : availability){
if (a.getDate().equals(date) && a.getTimeSlot().equals(timeslot)){
a.setIsAvailable(res);
}
}
}
/**
* Η μέθοδος ελέγχει την ισότητα μεταξύ δύο αντικειμένων καθηγητών
* @param obj Αντικείμενο
* @return true ή false αντίστοιχα με το εάν είναι το ίδιο αντικείμενο καθηγητή ή όχι
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
Professor professor = (Professor) obj;
return Objects.equals(profSurname, professor.profSurname) &&
Objects.equals(profFirstname, professor.profFirstname) &&
Objects.equals(profField, professor.profField);
}
public void prinAvailability(){
for(Availability a: availability){
System.out.println("Professor: " + profSurname + " Date: " + a.getDate() + " and timeslot: " + a.getTimeSlot() + " : " + a.getIsAvailable());
}
}
}
| Gouvo7/Exam-Schedule-Creator | src/thesis/Professor.java |
1,641 | public class ArrayStack implements StackInterface {
private static final String MSG_STACK_FULL = "Υπερχείλιση στοίβας. Η στοίβα είναι πλήρης."; // Δήλωση σταθεράς μηνύματος πλήρους στοίβας
private static final String MSG_STACK_EMPTY = "Η στοίβα είναι κενή."; // Δήλωση σταθεράς μηνύματος κενής στοίβας
public static final int MAX_CAPACITY = 100; // Δήλωση σταθεράς μέγιστου μεγέθους στοίβας
private int stackCapacity;
private Student[] S;
private int top = -1;
// Default constructor
public ArrayStack() {
this(MAX_CAPACITY);
}
// Full constructor
public ArrayStack(int newCapacity) {
this.stackCapacity = newCapacity;
this.S = new Student[this.stackCapacity];
}
public int getStackSize() {
// Επιστρέφει το μέγεθος της Στοίβας
return (this.top + 1);
}
public int getMaxStackCapacity() {
// Επιστρέφει το μέγεθος της Στοίβας
return this.stackCapacity;
}
public boolean stackIsEmpty() {
// Επιστρέφει true αν η Στοίβα είναι κενή
return (this.top < 0);
}
public Student topStackElement() throws StackEmptyException {
// Επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
return this.S[this.top];
}
public void pushStackElement(Student stud) throws StackFullException {
// Εισάγει ένα νέο στοιχείο στην κορυφή της Στοίβας
//if (this.getStackSize() == this.stackCapacity - 1) // Στις σημειώσεις έχει αυτή τη γραμμή αλλά δεν επιστρέφει σωστό μέγεθος της Στοίβας
if (this.getStackSize() == this.stackCapacity) // Αυτή η γραμμή φαίνεται να επιστρέφει σωστό μέγεθος της Στοίβας
throw new StackFullException(MSG_STACK_FULL);
// System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[++this.top] = stud; // ΠΡΟΣΟΧΗ! Πρώτα αυξάνει το top και μετά εισάγει το στοιχείο (item) στον πίνακα
// System.out.println("*** Top after push: " + this.top); // FOR TESTS
}
public Student popStackElement() throws StackEmptyException {
// Εξάγει και επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
Student tmpElement;
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
tmpElement = this.S[top];
// System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[this.top--] = null; // ΠΡΟΣΟΧΗ! Πρώτα θέτει null στη θέση του top για τον garbage collector (εκκαθάριση της μνήμης από τα "σκουπίδια") και μετά το μειώνει
// System.out.println("*** Top after push: " + this.top); // FOR TESTS
return tmpElement;
}
public void showAllStackElements() {
if (this.stackIsEmpty())
System.out.println("Η Στοίβα είναι κενή.");
else {
// ΓΙΑ ΕΜΦΑΝΙΣΗ ΣΥΜΦΩΝΑ ΜΕ ΤΗ ΘΕΩΡΗΤΙΚΗ ΔΙΑΤΑΞΗ ΤΗΣ ΣΤΟΙΒΑΣ (ΦΘΙΝΟΥΣΑ) ΟΛΩΝ ΤΩΝ ΣΤΟΙΧΕΙΩΝ ΤΗΣ ΣΤΟΙΒΑΣ ΕΝΕΡΓΟΠΟΙΟΥΜΕ ΤΑ ΠΑΡΑΚΑΤΩ
for (int i = this.top; i >= 0; i--)
System.out.println("Ονοματεπώνυμο: " + S[i].getLastName() + ", " + S[i].getFirstName() + ", ΑΜ: " + S[i].getAM());
// Ή ΓΙΑ ΚΑΝΟΝΙΚΗ ΕΜΦΑΝΙΣΗ (ΑΥΞΟΥΣΑ ΣΥΜΦΩΝΑ ΜΕ ΤΗΝ ΠΡΑΓΜΑΤΙΚΗ ΘΕΣΗ) ΟΛΩΝ ΤΩΝ ΣΤΟΙΧΕΙΩΝ ΤΗΣ ΣΤΟΙΒΑΣ ΕΝΕΡΓΟΠΟΙΟΥΜΕ ΤΑ ΠΑΡΑΚΑΤΩ
// for (int i = 0; i < this.top + 1; i++)
// System.out.println("Ονοματεπώνυμο: " + S[i].getLastName() + ", " + S[i].getFirstName() + ", ΑΜ: " + S[i].getAM());
}
}
}
| panosale/DIPAE_DataStructures_3rd_Term | Askisi2/src/ArrayStack.java |
1,642 | package gr.aueb.cf.OOProjects.ch18_accounts_big;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dao.AccountDAOImpl;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dao.IAccountDAO;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dao.IOverdraftAccountDAO;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dao.OverdraftAccountDAOImpl;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dto.AccountInsertDTO;
import gr.aueb.cf.OOProjects.ch18_accounts_big.dto.UserInsertDTO;
import gr.aueb.cf.OOProjects.ch18_accounts_big.model.Account;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.AccountServiceImpl;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.IAccountService;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.IOverdraftAccountService;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.OverdraftAccountServiceImpl;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.exceptions.AccountNotFoundException;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.exceptions.InsufficientBalanceException;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.exceptions.NegativeAmountException;
import gr.aueb.cf.OOProjects.ch18_accounts_big.service.exceptions.SsnNotValidException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Account> accounts = new ArrayList<>();
IAccountDAO accountDAO = new AccountDAOImpl();
IAccountService accountService = new AccountServiceImpl(accountDAO);
// Κλήση της μεθόδου insert για προσθήκη νέου λογαριασμού
AccountInsertDTO insertDTO = new AccountInsertDTO("IBAN123", new UserInsertDTO("John", "Doe", "123456789"), 1000.0);
accountService.insertAccount(insertDTO);
// Εκτύπωση όλων των λογαριασμών του datasource (λίστα)
accounts = accountService.getAllAccounts();
System.out.println(accounts);
// Κλήση της μεθόδου deposit για κατάθεση ποσού
try {
accountService.deposit("IBAN123", 500.0);
System.out.println("Deposit successful");
} catch (AccountNotFoundException | NegativeAmountException e) {
e.printStackTrace();
}
// Κλήση της μεθόδου withdraw για ανάληψη ποσού
try {
accountService.withdraw("IBAN123", "123456789", 500.0);
System.out.println("Withdrawal successful");
} catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException |
InsufficientBalanceException e) {
e.printStackTrace();
}
// Δοκιμή ανάληψης με IBAN που δεν υπάρχει στο datasource.
try {
accountService.withdraw("IBAN12345", "123456789", 300.0);
System.out.println("Withdrawal successful");
} catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException |
InsufficientBalanceException e) {
e.printStackTrace();
}
// Δοκιμή ανάληψης ποσού με IBAN που υπάρχει στο datasource αλλά με λάθος ssn.
try {
accountService.withdraw("IBAN123", "123456700", 300.0);
System.out.println("Withdrawal successful");
} catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException |
InsufficientBalanceException e) {
e.printStackTrace();
}
/* Overdraft Account */
IOverdraftAccountDAO overdraftAccountDAO = new OverdraftAccountDAOImpl();
IOverdraftAccountService overdraftAccountService = new OverdraftAccountServiceImpl(overdraftAccountDAO);
// Προσθήκη νέου overdraft λογαριασμού
AccountInsertDTO insertDTO2 = new AccountInsertDTO("IBAN890", new UserInsertDTO("Mary",
"bell", "00000000"), 1000.0);
accountService.insertAccount(insertDTO2);
// Ανάληψη ποσού μεγαλύτερου από το τρέχον υπόλοιπο του λογαριασμού
try {
overdraftAccountService.withdraw("IBAN890", "00000000", 3000.0);
System.out.println("Withdrawal successful for account " + overdraftAccountService.getAccountByIban("IBAN890"));
} catch (AccountNotFoundException | SsnNotValidException | NegativeAmountException e) {
e.printStackTrace();
}
}
}
| RenaMygdali/java-oo-projects | ch18_accounts_big/Main.java |
1,646 | public interface LaboratoryCourseInterface
{
public void printNumberOfStudents();
//• Εκτύπωση του συνολικού πλήθους των φοιτητών
public void printSuccesStatus();
//• Εκτύπωση του πλήθους των φοιτητών που πέτυχαν-απέτυχαν στο μάθημα
public void printAverageCourseGrades();
//• Εκτύπωση του μέσου όρου του βαθμού των φοιτητών ανά εργαστήριο και το συνολικό μέσο όρο για το μάθημα
public void printSuccesStatistics();
//• Εκτύπωση των ποσοστών επιτυχίας-αποτυχίας ανα εργαστήριο αλλά και συνολικά για το μάθημα
}
| alexoiik/Data-Structures-Java | DataStructures_Ex1(AbstractDataTypes)/src/LaboratoryCourseInterface.java |
1,647 | package utils;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Duration;
import org.joda.time.DurationFieldType;
import org.joda.time.LocalDate;
import actions.HandleApiRequests;
import objects.Decision;
import objects.Organization;
import ontology.Ontology;
/**
* @author G. Razis
*/
public class HelperMethods {
/**
* Find and transform the previous day's date into the yyyy-MM-dd format.
*
* @return String the previous day's date in the yyyy-MM-dd format
*/
public String getPreviousDate() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.add(Calendar.DATE, -1);
String previousDate = sdf.format(cal.getTime());
return previousDate;
}
/**
* Get the list of dates among the starting and ending date.
*
* @param LocalDate the starting date
* @param LocalDate the ending date
* @return List<String> the list of dates between the starting and ending date
*/
public List<String> getListOfDates(LocalDate startDate, LocalDate endDate) {
List<String> datesList = new ArrayList<String>();
int days = Days.daysBetween(startDate, endDate).getDays();
for (int i = 0; i < days; i++) {
LocalDate dt = startDate.withFieldAdded(DurationFieldType.days(), i);
datesList.add(dt.toString());
}
return datesList;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the decision.
*
* @param String the status of the decision
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided status of the decision
*/
public String[] findDecisionStatusIndividual(String decisionStatus) {
String[] statusDtls = null;
if (decisionStatus.equalsIgnoreCase("Published")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Published", "Αναρτημένη και σε ισχύ", "Published and Active"};
} else if (decisionStatus.equalsIgnoreCase("Pending_Revocation")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "PendingRevocation", "Αναρτημένη και σε ισχύ, έχει υποβληθεί αίτημα ανάκλησής της", "Published and Active, revocation request has been submitted"};
} else if (decisionStatus.equalsIgnoreCase("Revoked")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Revoked", "Ανακληθείσα", "Revoked"};
} else if (decisionStatus.equalsIgnoreCase("Submitted")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Submitted", "Έχει υποβληθεί αλλά δεν έχει αποδοθεί ΑΔΑ", "Submitted but ADA code has not been assigned"};
} else {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Unknown", "", ""};
writeUnknownMetadata("decisionStatus", decisionStatus);
}
return statusDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the organization.
*
* @param String the status of the organization
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided status of the organization
*/
public String[] findOrganizationStatusDetails(String organizationStatus) {
String[] statusDtls = null;
if (organizationStatus.equalsIgnoreCase("active")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Active", "Ενεργός και ενταγμένος στη Δι@ύγεια", "Active and registered in Di@vgeia"};
} else if (organizationStatus.equalsIgnoreCase("pending")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Pending", "Ενταγμένος στη Δι@ύγεια αλλά δεν είναι πλέον σε ισχύ", "Registered in Di@vgeia but is no longer active"};
} else if (organizationStatus.equalsIgnoreCase("inactive")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Inactive", "Εκκρεμεί η ενεργοποίησή του και η ένταξή του στη Δι@ύγεια", "Pending activation and registration in Di@vgeia"};
} else {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Unknown", "", ""};
writeUnknownMetadata("organizationStatus", organizationStatus);
}
return statusDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the status of the decision
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided budget type
*/
public String[] findBudgetTypeIndividual(String budgetType) {
String[] budgetDtls = null;
if (budgetType.equalsIgnoreCase("Τακτικός Προϋπολογισμός")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "RegularBudget", "Τακτικός Προϋπολογισμός", "Regular Budget"};
} else if (budgetType.equalsIgnoreCase("Πρόγραμμα Δημοσίων Επενδύσεων")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "PublicInvestmentProject", "Πρόγραμμα Δημοσίων Επενδύσεων", "Public Investment Project"};
} else if (budgetType.equalsIgnoreCase("Ίδια Έσοδα")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "OwnSourceRevenue", "Ίδια Έσοδα", "Own Source Revenue"};
} else if (budgetType.equalsIgnoreCase("Συγχρηματοδοτούμενο Έργο")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "CofundedProject", "Συγχρηματοδοτούμενο Έργο", "Co-funded Project"};
} else {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "Unknown", "", ""};
writeUnknownMetadata("budgetType", budgetType);
}
return budgetDtls;
}
/**
* Find the corresponding SKOS Concept from the provided status of the decision.
*
* @param String the status of the decision
* @return String the corresponding URI of the SKOS Concept
*/
public String findKindIndividual(String contractType) {
String uri = "";
if (contractType.equalsIgnoreCase("Έργα")) {
uri = Ontology.publicContractsPrefix + "Works";
} else if (contractType.equalsIgnoreCase("Υπηρεσίες")) {
uri = Ontology.publicContractsPrefix + "Services";
} else if (contractType.equalsIgnoreCase("Προμήθειες")) {
uri = Ontology.publicContractsPrefix + "Supplies";
} else if (contractType.equalsIgnoreCase("Μελέτες")) {
uri = Ontology.eLodPrefix + "Researches";
}
return uri;
}
/**
* Find the corresponding SKOS Concept from the provided type of the procedure.
*
* @param String the type of the procedure
* @return String the corresponding URI of the SKOS Concept
*/
public String findProcedureTypeIndividual(String procedureType) {
String uri = "";
if (procedureType.equalsIgnoreCase("Ανοικτός")) {
uri = Ontology.publicContractsPrefix + "Open";
} else if (procedureType.equalsIgnoreCase("Κλειστός")) {
uri = Ontology.publicContractsPrefix + "Restricted";
} else if (procedureType.equalsIgnoreCase("Πρόχειρος")) {
uri = Ontology.eLodPrefix + "LowValue";
} else {
writeUnknownMetadata("procedureType", procedureType);
}
return uri;
}
/**
* Find the corresponding SKOS Concept, its weight and the Greek and English name from the provided type of the criterion.
*
* @param String the type of the criterion
* @return String the corresponding URI of the SKOS Concept, its weight and the Greek and English name
* of the provided type of the criterion
*/
public String[] findCriterionIndividual(String criterionType) {
String[] criterionDtls = null;
if (criterionType.equalsIgnoreCase("Χαμηλότερη Τιμή")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "LowestPrice", "100", "Χαμηλότερη Τιμή", "Lowest Price"};
} else if (criterionType.equalsIgnoreCase("Συμφερότερη από οικονομικής άποψης")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "MostEconomicalOffer", "100", "Συμφερότερη από οικονομικής άποψης", "Most Economical Offer"};
} else if (criterionType.equalsIgnoreCase("Τεχνική ποιότητα")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "TechnicalQuality", "100", "Τεχνική ποιότητα", "Technical Quality"};
} else {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "Unknown", "100", "", ""};
writeUnknownMetadata("selectionCriterion", criterionType);
}
return criterionDtls;
}
/**
* Export to a file the unknown metadata.
*
* @param String the output filename
* @param String the unknown metadata
*/
public void writeUnknownMetadata(String fileName, String metadata) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + ".txt", true)));
out.println(metadata);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Write in a file the unknown metadata.
*
* @param String the output filename
* @param String the unknown metadata
*/
public void writeMetadata(String fileName, String csvFileName, String[] fields) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + ".txt", true)));
out.println(csvFileName + " -> " + fields[0] + ": " + fields[1]);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Check if a field retrieved from API contains non-printable data
* and return its proper format.
*
* @param String a field which may need cleansing from non-printable data
* @return String the cleaned data of the field.
*/
public String cleanInputData(String field) {
try {
//Pattern regex = Pattern.compile("[\\x00\\x08\\x0B\\x0C\\x0E-\\x1F]"); //non-printable data
Pattern regex = Pattern.compile("[\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]"); //non-printable data
Matcher regexMatcher = regex.matcher(field);
if (regexMatcher.find()) {
field = field.replaceAll("[\\p{Cntrl}]", "");
System.out.print("Cleaned field: " + field + "\n");
}
if (field.contains("\"")) {
field = field.replace("\"", "");
}
if (field.contains("\\")) {
field = field.replace("\\", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return field;
}
/**
* Clean and the return the new representation of a provided Vat Id.
*
* @param String a Vat Id to be cleaned
* @return String the cleaned representation of the input Vat Id
*/
public String cleanVatId(String vatId) {
if (vatId.startsWith("O")) {
vatId = vatId.replaceFirst("O", "0");
}
if (vatId.contains("ΑΦΜ.")) {
vatId = vatId.replace("ΑΦΜ.", "");
}
if (vatId.contains("ΑΦΜ")) {
vatId = vatId.replace("ΑΦΜ", "");
}
if ( vatId.contains("VAT No") || vatId.contains("VATNo")) {
vatId = vatId.replace("VAT No", "");
vatId = vatId.replace("VATNo", "");
}
vatId = vatId.replace(" ", "");
vatId = vatId.replace("`", "");
vatId = vatId.replace("\"", "");
vatId = vatId.replaceAll("[^a-zA-Z0-9 ]*", "");
return vatId;
}
/**
* Convert the plain text containing CPVs to a list.
*
* @param String the CPV field as retrieved from the API
* @return List<String> list of CPVs
*/
public List<String> cpv(String cpvCsvData) {
List<String> cpvCodes = new ArrayList<String>();
String[] splittedCpvCodes = cpvCsvData.split(";");
for (int i = 0; i < splittedCpvCodes.length; i++) {
Pattern regex = Pattern.compile("[0-9]{8}-[0-9]");
Matcher regexMatcher = regex.matcher(splittedCpvCodes[i]);
while (regexMatcher.find()) {
cpvCodes.add(regexMatcher.group(0));
}
}
return cpvCodes;
}
/**
* Find the instance of the class that the related decision belongs to,
* the respective resource type and the respective object property.
*
* @param String the related Ada of the decision
* @return Object[] the instance of the class that the related decision belongs to,
* the respective resource type and the respective object property
*/
public Object[] findDecisionTypeInstance(String relatedAda) {
Object[] instanceData = null;
HandleApiRequests handleReq = new HandleApiRequests();
Decision decisionObj = handleReq.searchSingleDecision(relatedAda);
if (decisionObj != null) {
String decisionTypeId = decisionObj.getDecisionTypeId();
if (decisionTypeId.equalsIgnoreCase("Β.1.3")) {
instanceData = new Object[]{"CommittedItem", Ontology.committedItemResource, Ontology.hasRelatedCommittedItem};
} else if (decisionTypeId.equalsIgnoreCase("Β.2.1")) {
instanceData = new Object[]{"ExpenseApprovalItem", Ontology.expenseApprovalItemResource, Ontology.hasRelatedExpenseApprovalItem};
} else if (decisionTypeId.equalsIgnoreCase("Β.2.2")) {
instanceData = new Object[]{"SpendingItem", Ontology.spendingItemResource, Ontology.hasRelatedSpendingItem};
} else if (decisionTypeId.equalsIgnoreCase("Δ.1") || decisionTypeId.equalsIgnoreCase("Δ.2.1") ||
decisionTypeId.equalsIgnoreCase("Δ.2.2")) {
instanceData = new Object[]{"Contract", Ontology.contractResource, Ontology.hasRelatedContract};
} else {
instanceData = new Object[]{"Decision", Ontology.decisionResource, Ontology.hasRelatedDecision};
}
}
return instanceData;
}
/**
* Find the instance of the class that the related decisions belong to, their resource type
* and the object property that is used for the relation of that type of decisions.
*
* @param String the decision type
* @return Object[] the instance of the class that the related decisions belong to, their
* resource type and the object property that is used for the relation of that type of decisions
*/
public Object[] findRelatedPropertyOfDecisionType(String decisionTypeId) {
Object[] instanceData = null;
if (decisionTypeId.equalsIgnoreCase("Δ.1") || decisionTypeId.equalsIgnoreCase("Δ.2.1") ) {
instanceData = new Object[]{"CommittedItem", Ontology.committedItemResource, Ontology.hasRelatedCommittedItem};
} else if (decisionTypeId.equalsIgnoreCase("Δ.2.2")) {
instanceData = new Object[]{"Contract", Ontology.contractResource, Ontology.hasRelatedContract};
}
return instanceData;
}
/**
* Find the name of the thematic category id that the related decision belongs to.
*
* @param String the id of the thematic category
* @return String the greek name of the thematic category
*/
public String findThematicCategoryName(String thematicCategoryId) {
String thematicCategoryName = "";
if (thematicCategoryId.equalsIgnoreCase("04")) {
thematicCategoryName = "ΠΟΛΙΤΙΚΗ ΖΩΗ";
} else if (thematicCategoryId.equalsIgnoreCase("08")) {
thematicCategoryName = "ΔΙΕΘΝΕΙΣ ΣΧΕΣΕΙΣ";
} else if (thematicCategoryId.equalsIgnoreCase("10")) {
thematicCategoryName = "ΕΥΡΩΠΑΪΚΗ ΈΝΩΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("12")) {
thematicCategoryName = "ΔΙΚΑΙΟ";
} else if (thematicCategoryId.equalsIgnoreCase("16")) {
thematicCategoryName = "ΟΙΚΟΝΟΜΙΚΗ ΖΩΗ";
} else if (thematicCategoryId.equalsIgnoreCase("20")) {
thematicCategoryName = "ΟΙΚΟΝΟΜΙΚΕΣ ΚΑΙ ΕΜΠΟΡΙΚΕΣ ΣΥΝΑΛΛΑΓΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("24")) {
thematicCategoryName = "ΔΗΜΟΣΙΟΝΟΜΙΚΑ";
} else if (thematicCategoryId.equalsIgnoreCase("28")) {
thematicCategoryName = "ΚΟΙΝΩΝΙΚΑ ΘΕΜΑΤΑ";
} else if (thematicCategoryId.equalsIgnoreCase("32")) {
thematicCategoryName = "ΕΠΙΚΟΙΝΩΝΙΑ ΚΑΙ ΜΟΡΦΩΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("36")) {
thematicCategoryName = "ΕΠΙΣΤΗΜΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("40")) {
thematicCategoryName = "ΕΠΙΧΕΙΡΗΣΕΙΣ ΚΑΙ ΑΝΤΑΓΩΝΙΣΜΟΣ";
} else if (thematicCategoryId.equalsIgnoreCase("44")) {
thematicCategoryName = "ΑΠΑΣΧΟΛΗΣΗ ΚΑΙ ΕΡΓΑΣΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("48")) {
thematicCategoryName = "ΜΕΤΑΦΟΡΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("52")) {
thematicCategoryName = "ΠΕΡΙΒΑΛΛΟΝ";
} else if (thematicCategoryId.equalsIgnoreCase("56")) {
thematicCategoryName = "ΓΕΩΡΓΙΑ, ΔΑΣΟΚΟΜΙΑ ΚΑΙ ΑΛΙΕΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("60")) {
thematicCategoryName = "ΔΙΑΤΡΟΦΗ ΚΑΙ ΓΕΩΡΓΙΚΑ ΠΡΟΪΟΝΤΑ";
} else if (thematicCategoryId.equalsIgnoreCase("64")) {
thematicCategoryName = "ΠΑΡΑΓΩΓΗ, ΤΕΧΝΟΛΟΓΙΑ ΚΑΙ ΕΡΕΥΝΑ";
} else if (thematicCategoryId.equalsIgnoreCase("66")) {
thematicCategoryName = "ΕΝΕΡΓΕΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("68")) {
thematicCategoryName = "ΒΙΟΜΗΧΑΝΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("72")) {
thematicCategoryName = "ΓΕΩΡΓΡΑΦΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("76")) {
thematicCategoryName = "ΔΙΕΘΝΕΙΣ ΟΡΓΑΝΙΣΜΟΙ";
} else if (thematicCategoryId.equalsIgnoreCase("10004")) {
thematicCategoryName = "ΔΗΜΟΣΙΑ ΔΙΟΙΚΗΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("10007")) {
thematicCategoryName = "ΥΓΕΙΑ";
} else {
writeUnknownMetadata("thematicCategory", thematicCategoryId);
}
return thematicCategoryName;
}
/**
* Find the name of the category id that the related organization belongs to.
*
* @param String the id of the category of the organization
* @return String[] the Greek and English name of the category of the organization
*/
public String[] findOrganizationCategoryName(String organizationCategoryId) {
String[] organizationCategoryName = null;
if (organizationCategoryId.equalsIgnoreCase("ADMINISTRATIVEREGION")) {
organizationCategoryName = new String[]{"Περιφέρεια", "Administrative Region"};
} else if (organizationCategoryId.equalsIgnoreCase("COMPANYSA")) {
organizationCategoryName = new String[]{"Ανώνυμες Εταιρείες Α.Ε.", "Company S.A."};
} else if (organizationCategoryId.equalsIgnoreCase("COURT")) {
organizationCategoryName = new String[]{"Δικαστήριο", "Court"};
} else if (organizationCategoryId.equalsIgnoreCase("DEKO")) {
organizationCategoryName = new String[]{"ΔΕΚΟ", "DEKO"};
} else if (organizationCategoryId.equalsIgnoreCase("GENERALGOVERNMENT")) {
organizationCategoryName = new String[]{"Γενική Κυβέρνηση", "General Government"};
} else if (organizationCategoryId.equalsIgnoreCase("INDEPENDENTAUTHORITY")) {
organizationCategoryName = new String[]{"Ανεξάρτητες Αρχές", "Independent Authority"};
} else if (organizationCategoryId.equalsIgnoreCase("INSTITUTION")) {
organizationCategoryName = new String[]{"Ιδρύματα", "Institution"};
} else if (organizationCategoryId.equalsIgnoreCase("LOCAL_AUTHORITY")) {
organizationCategoryName = new String[]{"ΟΤΑ (μόνο Δήμοι ή Αιρετές Περιφέρειες)", "Local Authority"};
} else if (organizationCategoryId.equalsIgnoreCase("MINISTRY")) {
organizationCategoryName = new String[]{"Υπουργείο", "Ministry"};
} else if (organizationCategoryId.equalsIgnoreCase("MUNICIPALITY")) {
organizationCategoryName = new String[]{"Δήμος", "Municipality"};
} else if (organizationCategoryId.equalsIgnoreCase("NONPROFITCOMPANY")) {
organizationCategoryName = new String[]{"Μη κερδοσκοπικές εταιρείες", "Non Profit Organization"};
} else if (organizationCategoryId.equalsIgnoreCase("NPDD")) {
organizationCategoryName = new String[]{"ΝΠΔΔ", "NPDD"};
} else if (organizationCategoryId.equalsIgnoreCase("NPID")) {
organizationCategoryName = new String[]{"ΝΠΙΔ", "NPID"};
} else if (organizationCategoryId.equalsIgnoreCase("OTHERTYPE")) {
organizationCategoryName = new String[]{"ΑΛΛΟ", "Other Type"};
} else if (organizationCategoryId.equalsIgnoreCase("PRESIDENTOFREPUBLIC")) {
organizationCategoryName = new String[]{"Πρόεδρος της Δημοκρατίας", "President of the Republic"};
} else if (organizationCategoryId.equalsIgnoreCase("UNIVERSITY")) {
organizationCategoryName = new String[]{"Πανεπιστήμιο", "University"};
} else if (organizationCategoryId.equalsIgnoreCase("DEYA")) {
organizationCategoryName = new String[]{"ΔΕΥΑ", "DEYA"};
} else if (organizationCategoryId.equalsIgnoreCase("REGION")) {
organizationCategoryName = new String[]{"Περιφέρεια", "Region"};
} else if (organizationCategoryId.equalsIgnoreCase("PRIME_MINISTER")) {
organizationCategoryName = new String[]{"Γραφείο πρωθυπουργού", "Prime Minister"};
} else if (organizationCategoryId.equalsIgnoreCase("HOSPITAL")) {
organizationCategoryName = new String[]{"Νοσοκομείο", "Hospital"};
} else if (organizationCategoryId.equalsIgnoreCase("SECRETARIAT_GENERAL")) {
organizationCategoryName = new String[]{"Γενική Γραμματεία", "SECRETARIAT GENERAL"};
} else {
organizationCategoryName = new String[]{"", ""};
writeUnknownMetadata("organizationCategory", organizationCategoryId);
}
return organizationCategoryName;
}
/**
* Find the name of the category id that the related unit belongs to.
*
* @param String the id of the category of the unit
* @return String[] the Greek and English name of the category of the unit
*/
public String[] findUnitCategoryName(String unitCategoryId) {
String[] unitCategoryName = null;
if (unitCategoryId.equalsIgnoreCase("ADMINISTRATION")) {
unitCategoryName = new String[]{"Διεύθυνση", "Administration"};
} else if (unitCategoryId.equalsIgnoreCase("BRANCH")) {
unitCategoryName = new String[]{"Κλάδος", "Branch"};
} else if (unitCategoryId.equalsIgnoreCase("COMMAND")) {
unitCategoryName = new String[]{"Αρχηγείο", "Command"};
} else if (unitCategoryId.equalsIgnoreCase("COMMITTEE")) {
unitCategoryName = new String[]{"Επιτροπή", "Committee"};
} else if (unitCategoryId.equalsIgnoreCase("DECENTRALISED_AGENCY")) {
unitCategoryName = new String[]{"Αποκεντρωμένη Υπηρεσία", "Decentralised Agency"};
} else if (unitCategoryId.equalsIgnoreCase("DEPARTMENT")) {
unitCategoryName = new String[]{"Τμήμα", "Department"};
} else if (unitCategoryId.equalsIgnoreCase("DIOIKISI")) {
unitCategoryName = new String[]{"Διοίκηση", "Administration"};
} else if (unitCategoryId.equalsIgnoreCase("FACULTY")) {
unitCategoryName = new String[]{"Σχολή", "Faculty"};
} else if (unitCategoryId.equalsIgnoreCase("GENERAL_ADMINISTRATION")) {
unitCategoryName = new String[]{"Γενική Διεύθυνση", "General Administration"};
} else if (unitCategoryId.equalsIgnoreCase("GENERAL_SECRETARIAT")) {
unitCategoryName = new String[]{"Γενική Γραμματεία", "General Secretariat"};
} else if (unitCategoryId.equalsIgnoreCase("OFFICE")) {
unitCategoryName = new String[]{"Γραφείο", "Office"};
} else if (unitCategoryId.equalsIgnoreCase("ORG_UNIT_OTHER")) {
unitCategoryName = new String[]{"Άλλο", "Org Unit Other"};
} else if (unitCategoryId.equalsIgnoreCase("PERIPHERAL_AGENCY")) {
unitCategoryName = new String[]{"Περιφερειακή Υπηρεσία", "Peripheral Agency"};
} else if (unitCategoryId.equalsIgnoreCase("PERIPHERAL_OFFICE")) {
unitCategoryName = new String[]{"Περιφερειακό Γραφείο", "PeripheraL Office"};
} else if (unitCategoryId.equalsIgnoreCase("SECTOR")) {
unitCategoryName = new String[]{"Τομέας", "Sector"};
} else if (unitCategoryId.equalsIgnoreCase("SMINARXIA")) {
unitCategoryName = new String[]{"Σμηναρχία", "Sminarxia"};
} else if (unitCategoryId.equalsIgnoreCase("SPECIAL_SECRETARIAT")) {
unitCategoryName = new String[]{"Ειδική Γραμματεία", "Special Secretariat"};
} else if (unitCategoryId.equalsIgnoreCase("TEAM")) {
unitCategoryName = new String[]{"Ομάδα", "Team"};
} else if (unitCategoryId.equalsIgnoreCase("TREASURY")) {
unitCategoryName = new String[]{"Ταμείο", "Treasury"};
} else if (unitCategoryId.equalsIgnoreCase("UNIT")) {
unitCategoryName = new String[]{"Μονάδα", "Unit"};
} else if (unitCategoryId.equalsIgnoreCase("VICE_ADMINISTRATION")) {
unitCategoryName = new String[]{"Υποδιεύθυνση", "Vice Administration"};
} else if (unitCategoryId.equalsIgnoreCase("VICE_ADMINISTRATION_HEAD")) {
unitCategoryName = new String[]{"Προϊστάμενος Υποδιεύθυνσης", "Vice Administration Head"};
} else if (unitCategoryId.equalsIgnoreCase("WATCH")) {
unitCategoryName = new String[]{"Παρατηρητήριο", "Watch"};
} else if (unitCategoryId.equalsIgnoreCase("WING")) {
unitCategoryName = new String[]{"Πτέρυγα", "Wing"};
} else {
unitCategoryName = new String[]{"", ""};
writeUnknownMetadata("unitCategory", unitCategoryId);
}
return unitCategoryName;
}
/**
* Find the name of the domain id that the related organization belongs to.
*
* @param String the id of the domain of the organization
* @return String[] the Greek and English name of the domain of the organization
*/
public String[] findOrganizationDomainName(String organizationDomainId) {
String[] organizationDomainName = new String[]{"", ""};
if (organizationDomainId.equalsIgnoreCase("Age")) {
organizationDomainName = new String[]{"Ηλικία", "Age"};
} else if (organizationDomainId.equalsIgnoreCase("Agriculture")) {
organizationDomainName = new String[]{"Γεωργία", "Agriculture"};
} else if (organizationDomainId.equalsIgnoreCase("AgricultureCompensations")) {
organizationDomainName = new String[]{"Γεωργικές αποζημιώσεις", "Agriculture Compensations"};
} else if (organizationDomainId.equalsIgnoreCase("AgricultureEnvironmentNaturalResources")) {
organizationDomainName = new String[]{"Γεωργία, Περιβάλλον και Φυσικοί Πόροι", "Agriculture Environment Natural Resources"};
} else if (organizationDomainId.equalsIgnoreCase("AnimalHealth")) {
organizationDomainName = new String[]{"Υγεία των ζώων", "Animal Health"};
} else if (organizationDomainId.equalsIgnoreCase("AnimalRights")) {
organizationDomainName = new String[]{"Δικαιώματα και πρόνοια ζώων", "Animal Rights"};
} else if (organizationDomainId.equalsIgnoreCase("ArbitrarConstructions")) {
organizationDomainName = new String[]{"Αυθαίρετα", "Arbitrar Constructions"};
} else if (organizationDomainId.equalsIgnoreCase("ArmedForces")) {
organizationDomainName = new String[]{"Ένοπλες Δυνάμεις", "Armed Forces"};
} else if (organizationDomainId.equalsIgnoreCase("ArmyLaws")) {
organizationDomainName = new String[]{"Στρατιωτική Νομοθεσία", "Army Laws"};
} else if (organizationDomainId.equalsIgnoreCase("AutoBicyclesBikes")) {
organizationDomainName = new String[]{"Αυτοκίνητα - Μοτοποδήλατα - Μοτοσικλέτες", "Auto - Bicycles - Bikes"};
} else if (organizationDomainId.equalsIgnoreCase("AutoWorkshops")) {
organizationDomainName = new String[]{"Συνεργεία", "Auto Workshops"};
} else if (organizationDomainId.equalsIgnoreCase("Bankruptcies")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Πτώχευση", "Bankruptcies"};
} else if (organizationDomainId.equalsIgnoreCase("Baptism")) {
organizationDomainName = new String[]{"Βάφτιση", "Baptism"};
} else if (organizationDomainId.equalsIgnoreCase("Birth")) {
organizationDomainName = new String[]{"Γέννηση", "Birth"};
} else if (organizationDomainId.equalsIgnoreCase("BoyRecordArchives")) {
organizationDomainName = new String[]{"Μητρώο Αρρένων", "Boy Record Archives"};
} else if (organizationDomainId.equalsIgnoreCase("Buildings")) {
organizationDomainName = new String[]{"Οικοδομές", "Buildings"};
} else if (organizationDomainId.equalsIgnoreCase("Business")) {
organizationDomainName = new String[]{"Επιχειρήσεις και κλάδοι", "Business"};
} else if (organizationDomainId.equalsIgnoreCase("BussesTracks")) {
organizationDomainName = new String[]{"Λεωφορεία - Φορτηγά", "Busses - Tracks"};
} else if (organizationDomainId.equalsIgnoreCase("CaringBusinesses")) {
organizationDomainName = new String[]{"Επιχειρήσεις πρόνοιας - Φροντίδα ηλικιωμένων - ΑΜΕΑ", "Caring Businesses"};
} else if (organizationDomainId.equalsIgnoreCase("Chambers")) {
organizationDomainName = new String[]{"Επιμελητήρια", "Chambers"};
} else if (organizationDomainId.equalsIgnoreCase("Charity")) {
organizationDomainName = new String[]{"Φιλανθρωπία", "Charity"};
} else if (organizationDomainId.equalsIgnoreCase("CityArchives")) {
organizationDomainName = new String[]{"Δημοτολόγιο και Μεταδημότευση", "City Archives"};
} else if (organizationDomainId.equalsIgnoreCase("CityRing")) {
organizationDomainName = new String[]{"Δακτύλιος", "City Ring"};
} else if (organizationDomainId.equalsIgnoreCase("CivilId")) {
organizationDomainName = new String[]{"Αστυνομική Ταυτότητα", "Civil Id"};
} else if (organizationDomainId.equalsIgnoreCase("CivilLaws")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Αναγκαστική διαχείριση", "Civil Laws"};
} else if (organizationDomainId.equalsIgnoreCase("CivilRights")) {
organizationDomainName = new String[]{"Πολιτικά και ανθρώπινα δικαιώματα", "Civil Rights"};
} else if (organizationDomainId.equalsIgnoreCase("Companies")) {
organizationDomainName = new String[]{"Εταιρείες - Σύσταση και λειτουργία εταιρειών", "Companies"};
} else if (organizationDomainId.equalsIgnoreCase("Constitution")) {
organizationDomainName = new String[]{"Σύνταγμα της Ελλάδας", "Constitution"};
} else if (organizationDomainId.equalsIgnoreCase("ConstructionEquipment")) {
organizationDomainName = new String[]{"Μηχανήματα έργων", "Construction Equipment"};
} else if (organizationDomainId.equalsIgnoreCase("Consumer")) {
organizationDomainName = new String[]{"Καταναλωτές", "Consumer"};
} else if (organizationDomainId.equalsIgnoreCase("Courts")) {
organizationDomainName = new String[]{"Δικαστήρια - Δικάσιμοι - Αποφάσεις - Ένδικα μέσα", "Courts"};
} else if (organizationDomainId.equalsIgnoreCase("Crime")) {
organizationDomainName = new String[]{"Έγκλημα", "Crime"};
} else if (organizationDomainId.equalsIgnoreCase("Culture")) {
organizationDomainName = new String[]{"Πολιτισμός", "Culture"};
} else if (organizationDomainId.equalsIgnoreCase("Customs")) {
organizationDomainName = new String[]{"Τελωνεία", "Customs"};
} else if (organizationDomainId.equalsIgnoreCase("Demolution")) {
organizationDomainName = new String[]{"Κατεδάφιση", "Demolition"};
} else if (organizationDomainId.equalsIgnoreCase("Divorce")) {
organizationDomainName = new String[]{"Διαζύγιο", "Divorce"};
} else if (organizationDomainId.equalsIgnoreCase("DriveSecurity")) {
organizationDomainName = new String[]{"Οδική ασφάλεια και κυκλοφορία", "Drive Security"};
} else if (organizationDomainId.equalsIgnoreCase("EarthResources")) {
organizationDomainName = new String[]{"Γεωφυσικοί Πόροι", "Earth Resources"};
} else if (organizationDomainId.equalsIgnoreCase("EducationInstitutes")) {
organizationDomainName = new String[]{"Εκπαιδευτήρια - Παιδότοποι - Φροντιστήρια", "Education Institutes"};
} else if (organizationDomainId.equalsIgnoreCase("EducationPersonnel")) {
organizationDomainName = new String[]{"Εκπαιδευτικοί", "Education Personnel"};
} else if (organizationDomainId.equalsIgnoreCase("EducationProfession")) {
organizationDomainName = new String[]{"Εκπαίδευση, Καριέρα και Απασχόληση", "Education Profession"};
} else if (organizationDomainId.equalsIgnoreCase("EducationSkills")) {
organizationDomainName = new String[]{"Εκπαίδευση και Ικανότητες", "Education Skills"};
} else if (organizationDomainId.equalsIgnoreCase("Elections")) {
organizationDomainName = new String[]{"Εκλογές - Εκλογική νομοθεσία - Εκλογικοί κατάλογοι", "Elections"};
} else if (organizationDomainId.equalsIgnoreCase("ElectricPowerManagement")) {
organizationDomainName = new String[]{"Ηλεκτροδότηση - Ηλεκτρική ενέργεια", "Electric Power Management"};
} else if (organizationDomainId.equalsIgnoreCase("EnvironmentPollution")) {
organizationDomainName = new String[]{"Περιβάλλον - Θόρυβος - Ρύπανση", "Environment - Pollution"};
} else if (organizationDomainId.equalsIgnoreCase("EUcitizens")) {
organizationDomainName = new String[]{"Υπήκοοι Κρατών - Μελών της Ε.Ε.", "E.U. Citizens"};
} else if (organizationDomainId.equalsIgnoreCase("Expatriates")) {
organizationDomainName = new String[]{"Ομογενείς - Πανινοστούντες", "Expatriates"};
} else if (organizationDomainId.equalsIgnoreCase("Explosives")) {
organizationDomainName = new String[]{"Εκρηκτικές ύλες - Επικίνδυνα υλικά", "Explosives"};
} else if (organizationDomainId.equalsIgnoreCase("Family")) {
organizationDomainName = new String[]{"Οικογένεια", "Family"};
} else if (organizationDomainId.equalsIgnoreCase("Financial")) {
organizationDomainName = new String[]{"Χρηματοοικονομικά", "Financial"};
} else if (organizationDomainId.equalsIgnoreCase("FinancialInstitutions")) {
organizationDomainName = new String[]{"Χρηματοπιστωτικά Ιδρύματα - Οργανισμοί", "Financial Institutions"};
} else if (organizationDomainId.equalsIgnoreCase("FireSafety")) {
organizationDomainName = new String[]{"Χρηματοπιστωτικά Ιδρύματα - Οργανισμοί", "Fire Safety"};
} else if (organizationDomainId.equalsIgnoreCase("Fireworks")) {
organizationDomainName = new String[]{"Βεγγαλικά", "Fireworks"};
} else if (organizationDomainId.equalsIgnoreCase("Fishing")) {
organizationDomainName = new String[]{"Αλιεία και υδατοκαλλιέργειες", "Fishing"};
} else if (organizationDomainId.equalsIgnoreCase("FoodDrinks")) {
organizationDomainName = new String[]{"Τρόφιμα και ποτά - Κανόνες υγιεινής", "Food - Drinks"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignCurrency")) {
organizationDomainName = new String[]{"Συνάλλαγμα", "ForeignCurrency"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignEducation")) {
organizationDomainName = new String[]{"Σπουδές εκτός Ελλάδας - Αναγνώριση τίτλου σπουδών", "Foreign Education"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignLanguages")) {
organizationDomainName = new String[]{"Ξένες γλώσσες", "Foreign Languages"};
} else if (organizationDomainId.equalsIgnoreCase("Forrest")) {
organizationDomainName = new String[]{"Δάση", "Forrest"};
} else if (organizationDomainId.equalsIgnoreCase("ForrestHarvesting")) {
organizationDomainName = new String[]{"Υλοτομία", "Forrest Harvesting"};
} else if (organizationDomainId.equalsIgnoreCase("Fuels")) {
organizationDomainName = new String[]{"Καύσιμα", "Fuels"};
} else if (organizationDomainId.equalsIgnoreCase("Funeral")) {
organizationDomainName = new String[]{"Θάνατος και κηδεία", "Funeral"};
} else if (organizationDomainId.equalsIgnoreCase("GarbageDisposal")) {
organizationDomainName = new String[]{"Απόβλητα", "Garbage Disposal"};
} else if (organizationDomainId.equalsIgnoreCase("GeneralPension")) {
organizationDomainName = new String[]{"Συντάξεις - Γενικά θέματα", "General Pension"};
} else if (organizationDomainId.equalsIgnoreCase("GovermentPolitics")) {
organizationDomainName = new String[]{"Κυβέρνηση, Πολιτική και Δημόσια Διοίκηση", "Goverment Politics"};
} else if (organizationDomainId.equalsIgnoreCase("Governance")) {
organizationDomainName = new String[]{"Δημόσια διοίκηση - Πολίτες", "Governance"};
} else if (organizationDomainId.equalsIgnoreCase("GovernanceInstrumentation")) {
organizationDomainName = new String[]{"Κυβέρνηση και Κυβερνητικά όργανα", "Governance Instrumentation"};
} else if (organizationDomainId.equalsIgnoreCase("GovernanceProcess")) {
organizationDomainName = new String[]{"Κώδικας διοικητικής διαδικασίας", "Governance Process"};
} else if (organizationDomainId.equalsIgnoreCase("Guns")) {
organizationDomainName = new String[]{"Όπλα", "Guns"};
} else if (organizationDomainId.equalsIgnoreCase("HagueConvention")) {
organizationDomainName = new String[]{"Επισημείωση Εγγράφων (Σύμβαση Χάγης)", "Hague Convention"};
} else if (organizationDomainId.equalsIgnoreCase("Handicap")) {
organizationDomainName = new String[]{"Άτομα με αναπηρία (ΑΜΕΑ)", "Handicap"};
} else if (organizationDomainId.equalsIgnoreCase("Health")) {
organizationDomainName = new String[]{"Υγεία", "Health"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBenefits")) {
organizationDomainName = new String[]{"Επιδόματα σχετικά με υγεία και πρόνοια", "Health Benefits"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBook")) {
organizationDomainName = new String[]{"Βιβλιάριο υγείας", "Health Book"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBusinesses")) {
organizationDomainName = new String[]{"Επιχειρήσεις υγείας και υγειονομικού ενδιαφέροντος", "Health Businesses"};
} else if (organizationDomainId.equalsIgnoreCase("HealthEmployees")) {
organizationDomainName = new String[]{"Εργαζόμενοι στα επαγγέλματα υγείας και φροντίδος", "Health Employees"};
} else if (organizationDomainId.equalsIgnoreCase("HealthNutrition")) {
organizationDomainName = new String[]{"Υγεία, Διατροφή και Πρόνοια", "Health Nutrition"};
} else if (organizationDomainId.equalsIgnoreCase("HelthExprenses")) {
organizationDomainName = new String[]{"Δαπάνες Υγείας", "Helth Exprenses"};
} else if (organizationDomainId.equalsIgnoreCase("HigherEducation")) {
organizationDomainName = new String[]{"Ανώτατη και ανώτερη εκπαίδευση", "Higher Education"};
} else if (organizationDomainId.equalsIgnoreCase("Hospitalization")) {
organizationDomainName = new String[]{"Νοσηλεία", "Hospitalization"};
} else if (organizationDomainId.equalsIgnoreCase("Hunting")) {
organizationDomainName = new String[]{"Κυνήγι", "Hunting"};
} else if (organizationDomainId.equalsIgnoreCase("IEK")) {
organizationDomainName = new String[]{"ΙΕΚ (Ινστιτούτο επαγγελματικής κατάρτισης)", "IEK"};
} else if (organizationDomainId.equalsIgnoreCase("IKA")) {
organizationDomainName = new String[]{"ΙΚΑ (Ίδρυμα Κοινωνικών Ασφαλίσεων)", "IKA"};
} else if (organizationDomainId.equalsIgnoreCase("Immigrants")) {
organizationDomainName = new String[]{"Μετανάστες - Οικονομικοί μετανάστες - Πρόσφυγες", "Immigrants"};
} else if (organizationDomainId.equalsIgnoreCase("Industru")) {
organizationDomainName = new String[]{"Βιομηχανία - Βιοτεχνία", "Industry"};
} else if (organizationDomainId.equalsIgnoreCase("InfrormationTech")) {
organizationDomainName = new String[]{"Τεχνιλογίες πληροφορικής και επικοινωνιών - Υπηρεσίες πιστοποίησης - Ψηφιακά πιστοποιητικά", "Infrormation - Tech"};
} else if (organizationDomainId.equalsIgnoreCase("Inheritance")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Κληρονομιά", "Inheritance"};
} else if (organizationDomainId.equalsIgnoreCase("InstallationSecurity")) {
organizationDomainName = new String[]{"Ασφάλεια εγκαταστάσεων και τεχνικού προσωπικού", "Installation Security"};
} else if (organizationDomainId.equalsIgnoreCase("InsuracePension")) {
organizationDomainName = new String[]{"Ασφάλιση και Σύνταξη", "Insurace and Pension"};
} else if (organizationDomainId.equalsIgnoreCase("InsuranceAgencies")) {
organizationDomainName = new String[]{"Ασφαλιστικοί Φορείς Ειδικών Κατηγοριών", "Insurance Agencies"};
} else if (organizationDomainId.equalsIgnoreCase("Kioks")) {
organizationDomainName = new String[]{"Περίπτερα", "Kiosks"};
} else if (organizationDomainId.equalsIgnoreCase("LaborHomes")) {
organizationDomainName = new String[]{"Εργατική κατοικία", "Labor Homes"};
} else if (organizationDomainId.equalsIgnoreCase("LaborHours")) {
organizationDomainName = new String[]{"Ώρες εργασίας, όροι και συνθήκες", "Labor Hours"};
} else if (organizationDomainId.equalsIgnoreCase("LaborMatters")) {
organizationDomainName = new String[]{"Εργασιακά θέματα και σχέσεις", "Labor Matters"};
} else if (organizationDomainId.equalsIgnoreCase("LaborSupport")) {
organizationDomainName = new String[]{"Εργατική εστία - Κοινωνικός τουρισμός", "Labor Support"};
} else if (organizationDomainId.equalsIgnoreCase("LandArchives")) {
organizationDomainName = new String[]{"Κτηματολόγιο", "Land Archives"};
} else if (organizationDomainId.equalsIgnoreCase("LawArchives")) {
organizationDomainName = new String[]{"Ποινικό μητρώο - Ποινική Διώξη", "Law Archives"};
} else if (organizationDomainId.equalsIgnoreCase("LawSupport")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Δικαστική συμπαράσταση", "Law Support"};
} else if (organizationDomainId.equalsIgnoreCase("LawyerInsurance")) {
organizationDomainName = new String[]{"Ταμείο Νομικών και κλάδο Επικουρικής ασφάλισης Δικηγόρων - ΚΕΑΔ", "Lawyer Insurance"};
} else if (organizationDomainId.equalsIgnoreCase("Lawyers")) {
organizationDomainName = new String[]{"Δικηγόροι", "Lawyers"};
} else if (organizationDomainId.equalsIgnoreCase("Leases")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Μισθώσεις", "Leases"};
} else if (organizationDomainId.equalsIgnoreCase("LicencePlates")) {
organizationDomainName = new String[]{"Πινακίδες οχημάτων και μηχανημάτων", "Licence Plates"};
} else if (organizationDomainId.equalsIgnoreCase("LocalGovernance")) {
organizationDomainName = new String[]{"Τοπική αυτοδιοίκηση", "Local Governance"};
} else if (organizationDomainId.equalsIgnoreCase("Marriage")) {
organizationDomainName = new String[]{"Γάμος", "Marriage"};
} else if (organizationDomainId.equalsIgnoreCase("Medicines")) {
organizationDomainName = new String[]{"Φάρμακα", "Medicines"};
} else if (organizationDomainId.equalsIgnoreCase("MilitaryService")) {
organizationDomainName = new String[]{"Στρατιωτική Θητεία", "Military Service"};
} else if (organizationDomainId.equalsIgnoreCase("Museum")) {
organizationDomainName = new String[]{"Αρχαιολογικοί Χώροι - Μουσεία", "Museum"};
} else if (organizationDomainId.equalsIgnoreCase("Nationality")) {
organizationDomainName = new String[]{"Ιθαγένεια, Κοινωνική ένταξη, Ομογενείς, Μετανάστες, Ξένοι υπήκοοι", "Nationality"};
} else if (organizationDomainId.equalsIgnoreCase("NationalityGeneral")) {
organizationDomainName = new String[]{"Ιθαγένεια", "Nationality"};
} else if (organizationDomainId.equalsIgnoreCase("NationalResistance")) {
organizationDomainName = new String[]{"Εθνική αντίσταση", "National Resistance"};
} else if (organizationDomainId.equalsIgnoreCase("NationRelationsDefence")) {
organizationDomainName = new String[]{"Διεθνείς Σχέσεις και Άμυνα", "Nation Relations Defence"};
} else if (organizationDomainId.equalsIgnoreCase("NavyAcademy")) {
organizationDomainName = new String[]{"Ακαδημία Εμπορικού Ναυτικού", "Navy Academy"};
} else if (organizationDomainId.equalsIgnoreCase("NewsAndInformation")) {
organizationDomainName = new String[]{"Πληροφορία και Επικοινωνία", "News and Information"};
} else if (organizationDomainId.equalsIgnoreCase("OGA")) {
organizationDomainName = new String[]{"ΟΓΑ (Οργανισμός Γεωργικών Ασφαλίσεων)", "OGA"};
} else if (organizationDomainId.equalsIgnoreCase("Passports")) {
organizationDomainName = new String[]{"Διαβατήρια και visas", "Passports"};
} else if (organizationDomainId.equalsIgnoreCase("PaymentOrder")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Διαταγή πληρωμής", "Payment Order"};
} else if (organizationDomainId.equalsIgnoreCase("PeopleSocietiesLiving")) {
organizationDomainName = new String[]{"Άνθρωποι, Κοινότητες και Διαβίωση", "People Societies Living"};
} else if (organizationDomainId.equalsIgnoreCase("PersonalData")) {
organizationDomainName = new String[]{"Προστασία προσωπικών δεδομένων", "Personal Data"};
} else if (organizationDomainId.equalsIgnoreCase("Plots")) {
organizationDomainName = new String[]{"Οικόπεδα", "Plots"};
} else if (organizationDomainId.equalsIgnoreCase("Policing")) {
organizationDomainName = new String[]{"Αστυνόμευση", "Policing"};
} else if (organizationDomainId.equalsIgnoreCase("PreservedConstructions")) {
organizationDomainName = new String[]{"Διατηρητέα", "Preserved Constructions"};
} else if (organizationDomainId.equalsIgnoreCase("ProfessionRights")) {
organizationDomainName = new String[]{"Άδειες επαγγέλματος", "Profession Rights"};
} else if (organizationDomainId.equalsIgnoreCase("Prostitution")) {
organizationDomainName = new String[]{"Εκδιδόμενα πρόσωπα", "Prostitution"};
} else if (organizationDomainId.equalsIgnoreCase("PublicMarkets")) {
organizationDomainName = new String[]{"Λαϊκές αγορές", "Public Markets"};
} else if (organizationDomainId.equalsIgnoreCase("PublicResourcesManagement")) {
organizationDomainName = new String[]{"Διαχείριση δημοσίου υλικού", "Public Resources Management"};
} else if (organizationDomainId.equalsIgnoreCase("PublicSecuriryCivilRights")) {
organizationDomainName = new String[]{"Ασφάλεια, Δημόσια Τάξη, Δικαιοσύνη και Δικαιώματα", "Public Securiry Civil Rights"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServantIssues")) {
organizationDomainName = new String[]{"Θέματα δημοσίων υπαλλήλων", "Public Servant Issues"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServantRecruitment")) {
organizationDomainName = new String[]{"Πρόσληψη στο δημόσιο", "Public Servant Recruitment"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServants")) {
organizationDomainName = new String[]{"Ασφαλισμένοι δημοσίου", "Public Servants"};
} else if (organizationDomainId.equalsIgnoreCase("PublicTransportation")) {
organizationDomainName = new String[]{"Μέσα μεταφοράς", "Public Transportation"};
} else if (organizationDomainId.equalsIgnoreCase("Quarries")) {
organizationDomainName = new String[]{"Λατομεία", "Quarries"};
} else if (organizationDomainId.equalsIgnoreCase("Recruitment")) {
organizationDomainName = new String[]{"Προκηρύξεις - Προσλήψεις", "Recruitment"};
} else if (organizationDomainId.equalsIgnoreCase("Residence")) {
organizationDomainName = new String[]{"Κατοικία", "Residence"};
} else if (organizationDomainId.equalsIgnoreCase("Seaside")) {
organizationDomainName = new String[]{"Αιγιαλός", "Seaside"};
} else if (organizationDomainId.equalsIgnoreCase("SecurityBusiness")) {
organizationDomainName = new String[]{"Κλειδαράδες - Ιδιωτικές επιχειρήσεις ασφαλείας - Συναγερμοί - Αδειοδοτήσεις επαγγελματιών", "Security Business"};
} else if (organizationDomainId.equalsIgnoreCase("Settlements")) {
organizationDomainName = new String[]{"Οικισμοί", "Settlements"};
} else if (organizationDomainId.equalsIgnoreCase("Ships")) {
organizationDomainName = new String[]{"Πλοία", "Ships"};
} else if (organizationDomainId.equalsIgnoreCase("ShipsEmployment")) {
organizationDomainName = new String[]{"Πληρώματα εμπορικών πλοίων", "Ships Employment"};
} else if (organizationDomainId.equalsIgnoreCase("SmallShips")) {
organizationDomainName = new String[]{"Σκάφη", "Small Ships"};
} else if (organizationDomainId.equalsIgnoreCase("SocialAccession")) {
organizationDomainName = new String[]{"Κοινωνική ένταξη", "Social Accession"};
} else if (organizationDomainId.equalsIgnoreCase("SocialPolitics")) {
organizationDomainName = new String[]{"Κοινωνική πολιτική", "Social Politics"};
} else if (organizationDomainId.equalsIgnoreCase("Sports")) {
organizationDomainName = new String[]{"Αθλητισμός - Αθλητική Νομοθεσία - Αθλητικά θέματα", "Sports"};
} else if (organizationDomainId.equalsIgnoreCase("SportsCultureTourism")) {
organizationDomainName = new String[]{"Αθλητισμός, Πολιτισμός, Τέχνες, Ψυχαγωγία, Τουρισμός", "Sports Culture Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("StockRaising")) {
organizationDomainName = new String[]{"Κτηνοτροφία - Πτηνοτροφία", "Stock Raising"};
} else if (organizationDomainId.equalsIgnoreCase("StreetLayout")) {
organizationDomainName = new String[]{"Ρυμοτομία", "Street Layout"};
} else if (organizationDomainId.equalsIgnoreCase("Students")) {
organizationDomainName = new String[]{"Μαθητές - Σπουδαστές - Φοιτητές", "Students"};
} else if (organizationDomainId.equalsIgnoreCase("Surname")) {
organizationDomainName = new String[]{"Επώνυμο", "Surname"};
} else if (organizationDomainId.equalsIgnoreCase("TAE")) {
organizationDomainName = new String[]{"ΤΑΕ", "TAE"};
} else if (organizationDomainId.equalsIgnoreCase("TAJI")) {
organizationDomainName = new String[]{"ΤΑΞΥ (Ταμείο aσφάλισης Ξενοδοχοϋπαλλήλων", "TAXY"};
} else if (organizationDomainId.equalsIgnoreCase("Taxi")) {
organizationDomainName = new String[]{"Ταξί", "Taxi"};
} else if (organizationDomainId.equalsIgnoreCase("TaxIssuesCertificates")) {
organizationDomainName = new String[]{"Φορολογικά θέματα - Υπηρεσίες φορολογίας εισοδήματος - Πιστοποιητικά", "Tax Issue Certificates"};
} else if (organizationDomainId.equalsIgnoreCase("TaxIssuesLaws")) {
organizationDomainName = new String[]{"Φορολογικά θέματα - Υποχρεώσεις - Κανονισμοί", "Tax Issue Laws"};
} else if (organizationDomainId.equalsIgnoreCase("TEAYEK")) {
organizationDomainName = new String[]{"ΤΕΑΥΕΚ (Ταμείο επικουρικής ασφαλίσεως υπαλλήλων εμπορικών καταστημάτων)", "TEAYEK"};
} else if (organizationDomainId.equalsIgnoreCase("TEBE")) {
organizationDomainName = new String[]{"ΤΕΒΕ", "TEBE"};
} else if (organizationDomainId.equalsIgnoreCase("TelecomFaire")) {
organizationDomainName = new String[]{"Τηλεπικοινωνιακές συνδέσεις και τέλη", "Telecom Faire"};
} else if (organizationDomainId.equalsIgnoreCase("TelecommunicationsLaw")) {
organizationDomainName = new String[]{"θεσμικά, ρυθμιστικά και κανονιστικά θέματα τηλεπικοινωνιών και ταχυδρομείων", "Telecommunications Law"};
} else if (organizationDomainId.equalsIgnoreCase("ThirdAge")) {
organizationDomainName = new String[]{"Τρίτη ηλικία", "Third Age"};
} else if (organizationDomainId.equalsIgnoreCase("Tourism")) {
organizationDomainName = new String[]{"Κοινωνικός τουρισμός - Νεανικός Τουρισμός", "Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("TourismAccomodation")) {
organizationDomainName = new String[]{"Ξενοδοχεία - Τουριστικά καταλύματα - Τουριστικά γραφεία", "Tourism Accomodation"};
} else if (organizationDomainId.equalsIgnoreCase("Transplants")) {
organizationDomainName = new String[]{"Μεταμοσχεύσεις - Δωρεά Οργάνων", "Transplants"};
} else if (organizationDomainId.equalsIgnoreCase("Transportations")) {
organizationDomainName = new String[]{"Μεταφορές", "Transportations"};
} else if (organizationDomainId.equalsIgnoreCase("TSA")) {
organizationDomainName = new String[]{"ΤΣΑ", "TSA"};
} else if (organizationDomainId.equalsIgnoreCase("TSAY")) {
organizationDomainName = new String[]{"ΤΣΑΥ", "TSAY"};
} else if (organizationDomainId.equalsIgnoreCase("TSMEDE")) {
organizationDomainName = new String[]{"ΤΣΜΕΔΕ", "TSMEDE"};
} else if (organizationDomainId.equalsIgnoreCase("Unemployment")) {
organizationDomainName = new String[]{"Ανεργία και αναζήτηση εργασίας", "Unemployment"};
} else if (organizationDomainId.equalsIgnoreCase("Unions")) {
organizationDomainName = new String[]{"Σωματεία - Σύλλογοι - Συνεταιρισμοί", "Unions"};
} else if (organizationDomainId.equalsIgnoreCase("UrbanPlanning")) {
organizationDomainName = new String[]{"Πολεοδομία, Ρυμοτομία, Οικοδομές και Κτηματολόγιο", "Urban Planning"};
} else if (organizationDomainId.equalsIgnoreCase("UrbanServices")) {
organizationDomainName = new String[]{"Πολεοδομία - Σχέδιο πόλης", "Urban Services"};
} else if (organizationDomainId.equalsIgnoreCase("Vaccination")) {
organizationDomainName = new String[]{"Εμβολιασμοί - Εμβόλια", "Vaccination"};
} else if (organizationDomainId.equalsIgnoreCase("WaterResources")) {
organizationDomainName = new String[]{"Υδάτινοι Πόροι", "Water Resources"};
} else if (organizationDomainId.equalsIgnoreCase("WaterSupply")) {
organizationDomainName = new String[]{"Ύδρευση - Αποχέτευση", "Water Supply"};
} else if (organizationDomainId.equalsIgnoreCase("Will")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Διαθήκη", "Will"};
} else if (organizationDomainId.equalsIgnoreCase("WorkSafety")) {
organizationDomainName = new String[]{"Ασφάλεια και υγεία στην εργασία", "Work Safety"};
} else if (organizationDomainId.equalsIgnoreCase("Youth")) {
organizationDomainName = new String[]{"Νέα γενιά - Τουρισμός - Επιχειρηματικότητα", "Youth"};
} else if (organizationDomainId.equalsIgnoreCase("YouthTourism")) {
organizationDomainName = new String[]{"Κοινωνικός τουρισμός - Νεανικός Τουρισμός", "Youth Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("Εntrepreneurship")) {
organizationDomainName = new String[]{"Επιχειρηματικότητα", "Εntrepreneurship"};
} else {
organizationDomainName = new String[]{"", ""};
writeUnknownMetadata("organizationDomain", organizationDomainId);
}
return organizationDomainName;
}
/**
* Find the name of the VAT type id.
*
* @param String the id of the VAT type
* @return String[] the Greek and English name of the VAT type
*/
public String[] findVatTypeName(String vatTypeId) {
String[] vatTypeName = null;
if (vatTypeId.equalsIgnoreCase("EL")) {
vatTypeName = new String[]{"Εθνικό (Φυσικά και Νομικά πρόσωπα)", "National (Natural persons and Legal entities)"};
} else if (vatTypeId.equalsIgnoreCase("EU")) {
vatTypeName = new String[]{"Νομικό πρόσωπο Κράτους-μέλους της ΕΕ", "Legal entity of a member state of the EU"};
} else if (vatTypeId.equalsIgnoreCase("EUP")) {
vatTypeName = new String[]{"Φυσικό πρόσωπο Κράτους-μέλους της ΕΕ", "Natural person of a member State of the EU"};
} else if (vatTypeId.equalsIgnoreCase("INT")) {
vatTypeName = new String[]{"Οργανισμός χωρίς ΑΦΜ", "Organization without VAT"};
} else if (vatTypeId.equalsIgnoreCase("O")) {
vatTypeName = new String[]{"Χώρας εκτός ΕΕ", "Country outside the EU"};
} else {
vatTypeName = new String[]{"", ""};
writeUnknownMetadata("unitCategory", vatTypeId);
}
return vatTypeName;
}
/**
* Convert a Date to its Calendar instance.
*
* @param Date a date
* @return Calendar the Calendar instance of the provided Date
*/
public Calendar dateToCalendarConverter(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
/**
* Create the ending part of the URI of the provided organization.
*
* @param Organization the organization under investigation
* @param Organization the supervisor of the organization
* @return String the ending part of the URI of the provided organization
*/
public String organizationUriBuilder(Organization org, Organization supervisor) {
String uri = "";
String orgVatId = org.getVatNumber().replace(" ", "");
if (orgVatId.equalsIgnoreCase("")) {
orgVatId = "VatNotProvided";
}
/*if (org.getSupervisorId() != null) { //org has supervisor
if (supervisor != null) {
String superVatId = supervisor.getVatNumber().replace(" ", "");
if (orgVatId != "") {
if (superVatId.equalsIgnoreCase(orgVatId)) { //epoptevomenos foreas me idio AFM
uri = superVatId + "/" + org.getUid().replace(" ", "");
} else { //epoptevomenos foreas me diaforetiko AFM
uri = orgVatId;
}
} else {
uri = superVatId + "/" + org.getUid().replace(" ", "");
}
} else {
uri = "NullSupervisor" + "/" + orgVatId;
}
} else { //org does not have supervisor
uri = orgVatId;
}*/
if (supervisor != null) {
uri = orgVatId + "/" + org.getUid().replace(" ", "");
} else {
if (orgVatId.equalsIgnoreCase("")) {
uri = orgVatId + "/" + org.getUid().replace(" ", "");
} else {
uri = orgVatId;
}
}
//uri = orgVatId + "/" + org.getUid().replace(" ", "");
return uri;
}
/**
* Calculate the suspension time until the execution time
* (daily at 00:15 local time).
*
* @return int the suspension time until the execution time
*/
public int timeUntilExecution() {
DateTime today = new DateTime();
DateTime tommorrow = today.plusDays(1).withTimeAtStartOfDay().plusMinutes(15); //00:15
Duration duration = new Duration(today, tommorrow);
int diffMinutes = (int) duration.getStandardMinutes();
System.out.println("Sleeping for: " + diffMinutes + " minutes...");
return diffMinutes;
}
} | YourDataStories/harvesters | DiavgeiaGeneralHarvester/src/utils/HelperMethods.java |
1,649 | package utils;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.joda.time.Duration;
import org.joda.time.DurationFieldType;
import org.joda.time.LocalDate;
import actions.HandleApiRequests;
import objects.Decision;
import objects.Organization;
import ontology.Ontology;
/**
* @author G. Razis
* @author G. Vafeiadis
*/
public class HelperMethods {
/**
* Find and transform the previous day's date into the yyyy-MM-dd format.
*
* @return String the previous day's date in the yyyy-MM-dd format
*/
public String getPreviousDate() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.add(Calendar.DATE, -1);
String previousDate = sdf.format(cal.getTime());
return previousDate;
}
/**
* Get the list of dates among the starting and ending date.
*
* @param LocalDate the starting date
* @param LocalDate the ending date
* @return List<String> the list of dates between the starting and ending date
*/
public List<String> getListOfDates(LocalDate startDate, LocalDate endDate) {
List<String> datesList = new ArrayList<String>();
int days = Days.daysBetween(startDate, endDate).getDays();
for (int i = 0; i < days; i++) {
LocalDate dt = startDate.withFieldAdded(DurationFieldType.days(), i);
datesList.add(dt.toString());
}
return datesList;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the decision.
*
* @param String the status of the decision
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided status of the decision
*/
public String[] findDecisionStatusIndividual(String decisionStatus) {
String[] statusDtls = null;
if (decisionStatus.equalsIgnoreCase("Published")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Published", "Αναρτημένη και σε ισχύ", "Published and Active"};
} else if (decisionStatus.equalsIgnoreCase("Pending_Revocation")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "PendingRevocation", "Αναρτημένη και σε ισχύ, έχει υποβληθεί αίτημα ανάκλησής της", "Published and Active, revocation request has been submitted"};
} else if (decisionStatus.equalsIgnoreCase("Revoked")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Revoked", "Ανακληθείσα", "Revoked"};
} else if (decisionStatus.equalsIgnoreCase("Submitted")) {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Submitted", "Έχει υποβληθεί αλλά δεν έχει αποδοθεί ΑΔΑ", "Submitted but ADA code has not been assigned"};
} else {
statusDtls = new String[]{Ontology.instancePrefix + "DecisionStatus/" + "Unknown", "", ""};
writeUnknownMetadata("decisionStatus", decisionStatus);
}
return statusDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the decision.
*
* @param String the Regulatory Act
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided Regulatory Act
*/
public String[] findKanonistikiIndividual(String decisionType) {
String[] statusDtls = null;
if (decisionType.equalsIgnoreCase("Υπουργική Απόφαση")) {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "Ministerial", "Υπουργική Απόφαση", "Ministerial Decision"};
} else if (decisionType.equalsIgnoreCase("Πράξη Γενικού Γραμματέα Αποκεντρωμένης Διοίκησης")) {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "DecentralizedDecision", "Πράξη Γενικού Γραμματέα Αποκεντρωμένης Διοίκησης", "Decentralized Decision of General Secretary"};
} else if (decisionType.equalsIgnoreCase("Πράξη Οργάνου Διοίκησης Ν.Π.Δ.Δ.")) {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "AdministrationBody", "Πράξη Οργάνου Διοίκησης Ν.Π.Δ.Δ.", "Administration Body Act"};
} else if (decisionType.equalsIgnoreCase("Πράξη Οργάνου Διοίκησης ΟΤΑ Α’ και Β’ Βαθμού (και εποπτευόμενων φορέων τους)")) {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "AdministrationOTA", "Πράξη Οργάνου Διοίκησης ΟΤΑ Α’ και Β’ Βαθμού (και εποπτευόμενων φορέων τους)", "Administration Body Act OTA"};
} else if (decisionType.equalsIgnoreCase("Λοιπές Κανονιστικές Πράξεις")) {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "RestAct", "Λοιπές Κανονιστικές Πράξεις", "Rest Regulatory Act"};
} else {
statusDtls = new String[]{Ontology.instancePrefix + "RegulatoryAct/" + "Unknown", "", ""};
writeUnknownMetadata("regulatoryAct", decisionType);
}
return statusDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the budget kind
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided budget kind
*/
public String[] findBudgetKindIndividual(String budgetKind) {
String[] budgetDtls = null;
if (budgetKind.equalsIgnoreCase("Φορέα")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetKind/" + "Buyer", "Φορέα", "Buyer"};
} else if (budgetKind.equalsIgnoreCase("Κρατικός")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetKind/" + "Governmental", "Κρατικός", "Governmental"};
} else {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetKind/" + "Unknown", "", ""};
writeUnknownMetadata("budgetKind", budgetKind);
}
return budgetDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the account type
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided account type
*/
public String[] findAccountTypeIndividual(String accountType) {
String[] accountDtls = null;
if (accountType.equalsIgnoreCase("Ισολογισμός")) {
accountDtls = new String[]{Ontology.instancePrefix + "AccountType/" + "Balance", "Ισολογισμός", "Balance"};
} else if (accountType.equalsIgnoreCase("Απολογισμός")) {
accountDtls = new String[]{Ontology.instancePrefix + "AccountType/" + "Report", "Απολογισμός", "Report"};
} else if (accountType.equalsIgnoreCase("Ισολογισμός και Απολογισμός")) {
accountDtls = new String[]{Ontology.instancePrefix + "AccountType/" + "BalanceAndReport", "Ισολογισμός και Απολογισμός", "Balance and Report"};
} else {
accountDtls = new String[]{Ontology.instancePrefix + "AccountType/" + "Unknown", "", ""};
writeUnknownMetadata("accountType", accountType);
}
return accountDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the time period
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided time period
*/
public String[] findTimePeriodIndividual(String timePeriod) {
String[] timeDtls = null;
if (timePeriod.equalsIgnoreCase("Έτος")) {
timeDtls = new String[]{Ontology.instancePrefix + "TimePeriod/" + "Year", "Έτος", "Year"};
} else if (timePeriod.equalsIgnoreCase("ΝΟΕΜΒΡΙΟΣ")) {
timeDtls = new String[]{Ontology.instancePrefix + "TimePeriod/" + "November", "Νοέμβριος", "November"};
} else if (timePeriod.equalsIgnoreCase("ΟΚΤΩΒΡΙΟΣ")) {
timeDtls = new String[]{Ontology.instancePrefix + "TimePeriod/" + "October", "Οκτώβριος", "October"};
} else if (timePeriod.equalsIgnoreCase("Τρίμηνο")) {
timeDtls = new String[]{Ontology.instancePrefix + "TimePeriod/" + "Trimester", "Τρίμηνο", "Trimester"};
} else {
timeDtls = new String[]{Ontology.instancePrefix + "TimePeriod/" + "Unknown", "", ""};
writeUnknownMetadata("accountType", timePeriod);
}
return timeDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the position type
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided position type
*/
public String[] findPositionTypeIndividual(String positionType) {
String[] positionDtls = null;
if (positionType.equalsIgnoreCase("Μονομελές Όργανο")) {
positionDtls = new String[]{Ontology.instancePrefix + "PositionType/" + "SingleAdministration", "Μονομελές Όργανο", "Single Administration Body"};
} else if (positionType.equalsIgnoreCase("ΕΙΔΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ Σ.Δ.Ο.Ε.")) {
positionDtls = new String[]{Ontology.instancePrefix + "PositionType/" + "SpecialSecretary", "ΕΙΔΙΚΟΣ ΓΡΑΜΜΑΤΕΑΣ Σ.Δ.Ο.Ε.", "Special Secretary"};
} else if (positionType.equalsIgnoreCase("Γενικός Γραμματέας Υπουργείου")) {
positionDtls = new String[]{Ontology.instancePrefix + "PositionType/" + "GeneralSecretary", "Γενικός Γραμματέας Υπουργείου", "General Secretary of the Ministry"};
} else {
positionDtls = new String[]{Ontology.instancePrefix + "PositionType/" + "Unknown", "", ""};
writeUnknownMetadata("positionType", positionType);
}
return positionDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the collective type
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided collective type
*/
public String[] findCollectiveTypeIndividual(String collectiveType) {
String[] colTypeDtls = null;
if (collectiveType.equalsIgnoreCase("Συλλογικό όργανο Διοίκησης")) {
colTypeDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyType/" + "CollectiveManagement", "Συλλογικό όργανο Διοίκησης", "Collective Management Body"};
} else if (collectiveType.equalsIgnoreCase("Επιτροπή")) {
colTypeDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyType/" + "Commission", "Επιτροπή", "Commission"};
} else if (collectiveType.equalsIgnoreCase("Ομάδα εργασίας")) {
colTypeDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyType/" + "WorkingGroup", "Ομάδα εργασίας", "Working Group"};
} else {
colTypeDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyType/" + "Unknown", "", ""};
writeUnknownMetadata("collectiveType", collectiveType);
}
return colTypeDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the collective kind
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided collective kind
*/
public String[] findCollectiveKindIndividual(String collectiveKind) {
String[] colKindDtls = null;
if (collectiveKind.equalsIgnoreCase("Παύση - Αντικατάσταση μέλους")) {
colKindDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyKind/" + "ReplacementMember", "Παύση - Αντικατάσταση μέλους", "Pause - Replacement of a Member"};
} else if (collectiveKind.equalsIgnoreCase("Συγκρότηση")) {
colKindDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyKind/" + "Formation", "Συγκρότηση", "Formation"};
} else if (collectiveKind.equalsIgnoreCase("Καθορισμός Αμοιβής – Αποζημίωσης")) {
colKindDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyKind/" + "Compensation", "Καθορισμός Αμοιβής – Αποζημίωσης", "Designation Fee - Compensation"};
} else {
colKindDtls = new String[]{Ontology.instancePrefix + "CollectiveBodyKind/" + "Unknown", "", ""};
writeUnknownMetadata("collectiveKind", collectiveKind);
}
return colKindDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the vacancy type
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided vacancy type
*/
public String[] findVacancyTypeIndividual(String vacancyType) {
String[] vacancyDtls = null;
if (vacancyType.equalsIgnoreCase("Προκήρυξη Πλήρωσης Θέσεων με διαγωνισμό ή επιλογή στις οποίες περιλαμβάνονται και οι προκηρύξεις για επιλογή και πλήρωση θέσεων διευθυντικών στελεχών των ΝΠΔΔ, φορέων του ευρύτερου δημόσιου τομέα, και των επιχειρήσεων και φορέων των ΟΤΑ Α’ & Β’ βαθμού")) {
vacancyDtls = new String[]{Ontology.instancePrefix + "VacancyType/" + "ContractFillingPosition", "Προκήρυξη Πλήρωσης Θέσεων με διαγωνισμό", "Contract Filling Positions by tender"};
} else if (vacancyType.equalsIgnoreCase("Προκήρυξη Πλήρωσης Θέσεων Εκπαιδευτικού Προσωπικού (ΕΠ) Τεχνολογικού τομέα της Ανώτατης Εκπαίδευσης")) {
vacancyDtls = new String[]{Ontology.instancePrefix + "VacancyType/" + "ContractFillingPositionEducation", "Προκήρυξη Πλήρωσης Θέσεων Εκπαιδευτικού Προσωπικού", "Contract Filling Positions of Education"};
} else if (vacancyType.equalsIgnoreCase("Προκήρυξη Πλήρωσης Θέσεων Διδακτικού Ερευνητικού Προσωπικού (ΔΕΠ) Πανεπιστημιακού τομέα")) {
vacancyDtls = new String[]{Ontology.instancePrefix + "VacancyType/" + "ContractFillingPositionResearch", "Προκήρυξη Πλήρωσης Θέσεων Διδακτικού Ερευνητικού Προσωπικού", "Contract Filling Positions of Researchers"};
} else {
vacancyDtls = new String[]{Ontology.instancePrefix + "VacancyType/" + "Unknown", "", ""};
writeUnknownMetadata("VacancyType", vacancyType);
}
return vacancyDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the administrative change
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided administrative change
*/
public String[] findAdministrativeChangeIndividual(String adminChange) {
String[] changeDtls = null;
if (adminChange.equalsIgnoreCase("Μετάταξη")) {
changeDtls = new String[]{Ontology.instancePrefix + "OfficialAdministrativeChange/" + "Switching", "Μετάταξη", "Switching"};
} else if (adminChange.equalsIgnoreCase("Λύση Υπαλληλικής Σχέσης")) {
changeDtls = new String[]{Ontology.instancePrefix + "OfficialAdministrativeChange/" + "Dismissal", "Λύση Υπαλληλικής Σχέσης", "Dismissal"};
} else if (adminChange.equalsIgnoreCase("Υποβιβασμός")) {
changeDtls = new String[]{Ontology.instancePrefix + "OfficialAdministrativeChange/" + "Relegation", "Υποβιβασμός", "Relegation"};
} else if (adminChange.equalsIgnoreCase("Αποδοχή Παραίτησης")) {
changeDtls = new String[]{Ontology.instancePrefix + "OfficialAdministrativeChange/" + "ResignationAcceptance", "Αποδοχή Παραίτησης", "Resignation Acceptance"};
} else {
changeDtls = new String[]{Ontology.instancePrefix + "OfficialAdministrativeChange/" + "Unknown", "", ""};
writeUnknownMetadata("adminChange", adminChange);
}
return changeDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the decision.
*
* @param String opinion type
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided opinion type
*/
public String[] findOpinionOrgIndividual(String opinionType) {
String[] opinionDtls = null;
if (opinionType.equalsIgnoreCase("Ανεξάρτητη Αρχή")) {
opinionDtls = new String[]{Ontology.instancePrefix + "OpinionOrgType/" + "IndependentAuthority", "Ανεξάρτητη Αρχή", "Independent Authority"};
} else if (opinionType.equalsIgnoreCase("ΝΣΚ")) {
opinionDtls = new String[]{Ontology.instancePrefix + "OpinionOrgType/" + "NSK", "ΝΣΚ", "NSK"};
} else {
opinionDtls = new String[]{Ontology.instancePrefix + "OpinionOrgType/" + "Unknown", "", ""};
writeUnknownMetadata("opinionOrgType", opinionType);
}
return opinionDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from the provided status of the organization.
*
* @param String the status of the organization
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided status of the organization
*/
public String[] findOrganizationStatusDetails(String organizationStatus) {
String[] statusDtls = null;
if (organizationStatus.equalsIgnoreCase("active")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Active", "Ενεργός και ενταγμένος στη Δι@ύγεια", "Active and registered in Di@vgeia"};
} else if (organizationStatus.equalsIgnoreCase("pending")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Pending", "Ενταγμένος στη Δι@ύγεια αλλά δεν είναι πλέον σε ισχύ", "Registered in Di@vgeia but is no longer active"};
} else if (organizationStatus.equalsIgnoreCase("inactive")) {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Inactive", "Εκκρεμεί η ενεργοποίησή του και η ένταξή του στη Δι@ύγεια", "Pending activation and registration in Di@vgeia"};
} else {
statusDtls = new String[]{Ontology.instancePrefix + "OrganizationStatus/" + "Unknown", "", ""};
writeUnknownMetadata("organizationStatus", organizationStatus);
}
return statusDtls;
}
/**
* Find the corresponding SKOS Concept, Greek and English name from from the provided budget type.
*
* @param String the status of the decision
* @return String[] the corresponding URI of the SKOS Concept and the Greek and English name
* of the provided budget type
*/
public String[] findBudgetTypeIndividual(String budgetType) {
String[] budgetDtls = null;
if (budgetType.equalsIgnoreCase("Τακτικός Προϋπολογισμός")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "RegularBudget", "Τακτικός Προϋπολογισμός", "Regular Budget"};
} else if (budgetType.equalsIgnoreCase("Πρόγραμμα Δημοσίων Επενδύσεων")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "PublicInvestmentProject", "Πρόγραμμα Δημοσίων Επενδύσεων", "Public Investment Project"};
} else if (budgetType.equalsIgnoreCase("Ίδια Έσοδα")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "OwnSourceRevenue", "Ίδια Έσοδα", "Own Source Revenue"};
} else if (budgetType.equalsIgnoreCase("Συγχρηματοδοτούμενο Έργο")) {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "CofundedProject", "Συγχρηματοδοτούμενο Έργο", "Co-funded Project"};
} else {
budgetDtls = new String[]{Ontology.instancePrefix + "BudgetCategory/" + "Unknown", "", ""};
writeUnknownMetadata("budgetType", budgetType);
}
return budgetDtls;
}
/**
* Find the corresponding SKOS Concept from the provided status of the decision.
*
* @param String the status of the decision
* @return String the corresponding URI of the SKOS Concept
*/
public String findKindIndividual(String contractType) {
String uri = "";
if (contractType.equalsIgnoreCase("Έργα")) {
uri = Ontology.publicContractsPrefix + "Works";
} else if (contractType.equalsIgnoreCase("Υπηρεσίες")) {
uri = Ontology.publicContractsPrefix + "Services";
} else if (contractType.equalsIgnoreCase("Προμήθειες")) {
uri = Ontology.publicContractsPrefix + "Supplies";
} else if (contractType.equalsIgnoreCase("Μελέτες")) {
uri = Ontology.eLodPrefix + "Researches";
}
return uri;
}
/**
* Find the corresponding SKOS Concept from the provided type of the procedure.
*
* @param String the type of the procedure
* @return String the corresponding URI of the SKOS Concept
*/
public String findProcedureTypeIndividual(String procedureType) {
String uri = "";
if (procedureType.equalsIgnoreCase("Ανοικτός")) {
uri = Ontology.publicContractsPrefix + "Open";
} else if (procedureType.equalsIgnoreCase("Κλειστός")) {
uri = Ontology.publicContractsPrefix + "Restricted";
} else if (procedureType.equalsIgnoreCase("Πρόχειρος")) {
uri = Ontology.eLodPrefix + "LowValue";
} else {
writeUnknownMetadata("procedureType", procedureType);
}
return uri;
}
/**
* Find the corresponding SKOS Concept, its weight and the Greek and English name from the provided type of the criterion.
*
* @param String the type of the criterion
* @return String the corresponding URI of the SKOS Concept, its weight and the Greek and English name
* of the provided type of the criterion
*/
public String[] findCriterionIndividual(String criterionType) {
String[] criterionDtls = null;
if (criterionType.equalsIgnoreCase("Χαμηλότερη Τιμή")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "LowestPrice", "100", "Χαμηλότερη Τιμή", "Lowest Price"};
} else if (criterionType.equalsIgnoreCase("Συμφερότερη από οικονομικής άποψης")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "MostEconomicalOffer", "100", "Συμφερότερη από οικονομικής άποψης", "Most Economical Offer"};
} else if (criterionType.equalsIgnoreCase("Τεχνική ποιότητα")) {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "TechnicalQuality", "100", "Τεχνική ποιότητα", "Technical Quality"};
} else {
criterionDtls = new String[]{Ontology.instancePrefix + "SelectionCriterion/" + "Unknown", "100", "", ""};
writeUnknownMetadata("selectionCriterion", criterionType);
}
return criterionDtls;
}
/**
* Export to a file the unknown metadata.
*
* @param String the output filename
* @param String the unknown metadata
*/
public void writeUnknownMetadata(String fileName, String metadata) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + ".txt", true)));
out.println(metadata);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Write in a file the unknown metadata.
*
* @param String the output filename
* @param String the unknown metadata
*/
public void writeMetadata(String fileName, String csvFileName, String[] fields) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fileName + ".txt", true)));
out.println(csvFileName + " -> " + fields[0] + ": " + fields[1]);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Check if a field retrieved from API contains non-printable data
* and return its proper format.
*
* @param String a field which may need cleansing from non-printable data
* @return String the cleaned data of the field.
*/
public String cleanInputData(String field) {
try {
//Pattern regex = Pattern.compile("[\\x00\\x08\\x0B\\x0C\\x0E-\\x1F]"); //non-printable data
Pattern regex = Pattern.compile("[\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]"); //non-printable data
Matcher regexMatcher = regex.matcher(field);
if (regexMatcher.find()) {
field = field.replaceAll("[\\p{Cntrl}]", "");
System.out.print("Cleaned field: " + field + "\n");
}
if (field.contains("\"")) {
field = field.replace("\"", "");
}
if (field.contains("\\")) {
field = field.replace("\\", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return field;
}
/**
* Clean and the return the new representation of a provided Vat Id.
*
* @param String a Vat Id to be cleaned
* @return String the cleaned representation of the input Vat Id
*/
public String cleanVatId(String vatId) {
if (vatId.startsWith("O")) {
vatId = vatId.replaceFirst("O", "0");
}
if (vatId.contains("ΑΦΜ.")) {
vatId = vatId.replace("ΑΦΜ.", "");
}
if (vatId.contains("ΑΦΜ")) {
vatId = vatId.replace("ΑΦΜ", "");
}
if ( vatId.contains("VAT No") || vatId.contains("VATNo")) {
vatId = vatId.replace("VAT No", "");
vatId = vatId.replace("VATNo", "");
}
vatId = vatId.replace(" ", "");
vatId = vatId.replace("`", "");
vatId = vatId.replace("\"", "");
vatId = vatId.replaceAll("[^a-zA-Z0-9 ]*", "");
return vatId;
}
/**
* Convert the plain text containing CPVs to a list.
*
* @param String the CPV field as retrieved from the API
* @return List<String> list of CPVs
*/
public List<String> cpv(String cpvCsvData) {
List<String> cpvCodes = new ArrayList<String>();
String[] splittedCpvCodes = cpvCsvData.split(";");
for (int i = 0; i < splittedCpvCodes.length; i++) {
Pattern regex = Pattern.compile("[0-9]{8}-[0-9]");
Matcher regexMatcher = regex.matcher(splittedCpvCodes[i]);
while (regexMatcher.find()) {
cpvCodes.add(regexMatcher.group(0));
}
}
return cpvCodes;
}
/**
* Find the instance of the class that the related decision belongs to,
* the respective resource type and the respective object property.
*
* @param String the related Ada of the decision
* @return Object[] the instance of the class that the related decision belongs to,
* the respective resource type and the respective object property
*/
public Object[] findDecisionTypeInstance(String relatedAda) {
Object[] instanceData = null;
HandleApiRequests handleReq = new HandleApiRequests();
Decision decisionObj = handleReq.searchSingleDecision(relatedAda);
if (decisionObj != null) {
String decisionTypeId = decisionObj.getDecisionTypeId();
if (decisionTypeId.equalsIgnoreCase("Β.1.3")) {
instanceData = new Object[]{"CommittedItem", Ontology.committedItemResource, Ontology.hasRelatedCommittedItem};
} else if (decisionTypeId.equalsIgnoreCase("Β.2.1")) {
instanceData = new Object[]{"ExpenseApprovalItem", Ontology.expenseApprovalItemResource, Ontology.hasRelatedExpenseApprovalItem};
} else if (decisionTypeId.equalsIgnoreCase("Β.2.2")) {
instanceData = new Object[]{"SpendingItem", Ontology.spendingItemResource, Ontology.hasRelatedSpendingItem};
} else if (decisionTypeId.equalsIgnoreCase("Δ.1") || decisionTypeId.equalsIgnoreCase("Δ.2.1") ||
decisionTypeId.equalsIgnoreCase("Δ.2.2")) {
instanceData = new Object[]{"Contract", Ontology.contractResource, Ontology.hasRelatedContract};
} else {
instanceData = new Object[]{"Decision", Ontology.decisionResource, Ontology.hasRelatedDecision};
}
}
return instanceData;
}
/**
* Find the instance of the class that the related decisions belong to, their resource type
* and the object property that is used for the relation of that type of decisions.
*
* @param String the decision type
* @return Object[] the instance of the class that the related decisions belong to, their
* resource type and the object property that is used for the relation of that type of decisions
*/
public Object[] findRelatedPropertyOfDecisionType(String decisionTypeId) {
Object[] instanceData = null;
if (decisionTypeId.equalsIgnoreCase("Δ.1") || decisionTypeId.equalsIgnoreCase("Δ.2.1") ) {
instanceData = new Object[]{"CommittedItem", Ontology.committedItemResource, Ontology.hasRelatedCommittedItem};
} else if (decisionTypeId.equalsIgnoreCase("Δ.2.2")) {
instanceData = new Object[]{"Contract", Ontology.contractResource, Ontology.hasRelatedContract};
}
return instanceData;
}
/**
* Find the name of the thematic category id that the related decision belongs to.
*
* @param String the id of the thematic category
* @return String the greek name of the thematic category
*/
public String findThematicCategoryName(String thematicCategoryId) {
String thematicCategoryName = "";
if (thematicCategoryId.equalsIgnoreCase("04")) {
thematicCategoryName = "ΠΟΛΙΤΙΚΗ ΖΩΗ";
} else if (thematicCategoryId.equalsIgnoreCase("08")) {
thematicCategoryName = "ΔΙΕΘΝΕΙΣ ΣΧΕΣΕΙΣ";
} else if (thematicCategoryId.equalsIgnoreCase("10")) {
thematicCategoryName = "ΕΥΡΩΠΑΪΚΗ ΈΝΩΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("12")) {
thematicCategoryName = "ΔΙΚΑΙΟ";
} else if (thematicCategoryId.equalsIgnoreCase("16")) {
thematicCategoryName = "ΟΙΚΟΝΟΜΙΚΗ ΖΩΗ";
} else if (thematicCategoryId.equalsIgnoreCase("20")) {
thematicCategoryName = "ΟΙΚΟΝΟΜΙΚΕΣ ΚΑΙ ΕΜΠΟΡΙΚΕΣ ΣΥΝΑΛΛΑΓΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("24")) {
thematicCategoryName = "ΔΗΜΟΣΙΟΝΟΜΙΚΑ";
} else if (thematicCategoryId.equalsIgnoreCase("28")) {
thematicCategoryName = "ΚΟΙΝΩΝΙΚΑ ΘΕΜΑΤΑ";
} else if (thematicCategoryId.equalsIgnoreCase("32")) {
thematicCategoryName = "ΕΠΙΚΟΙΝΩΝΙΑ ΚΑΙ ΜΟΡΦΩΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("36")) {
thematicCategoryName = "ΕΠΙΣΤΗΜΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("40")) {
thematicCategoryName = "ΕΠΙΧΕΙΡΗΣΕΙΣ ΚΑΙ ΑΝΤΑΓΩΝΙΣΜΟΣ";
} else if (thematicCategoryId.equalsIgnoreCase("44")) {
thematicCategoryName = "ΑΠΑΣΧΟΛΗΣΗ ΚΑΙ ΕΡΓΑΣΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("48")) {
thematicCategoryName = "ΜΕΤΑΦΟΡΕΣ";
} else if (thematicCategoryId.equalsIgnoreCase("52")) {
thematicCategoryName = "ΠΕΡΙΒΑΛΛΟΝ";
} else if (thematicCategoryId.equalsIgnoreCase("56")) {
thematicCategoryName = "ΓΕΩΡΓΙΑ, ΔΑΣΟΚΟΜΙΑ ΚΑΙ ΑΛΙΕΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("60")) {
thematicCategoryName = "ΔΙΑΤΡΟΦΗ ΚΑΙ ΓΕΩΡΓΙΚΑ ΠΡΟΪΟΝΤΑ";
} else if (thematicCategoryId.equalsIgnoreCase("64")) {
thematicCategoryName = "ΠΑΡΑΓΩΓΗ, ΤΕΧΝΟΛΟΓΙΑ ΚΑΙ ΕΡΕΥΝΑ";
} else if (thematicCategoryId.equalsIgnoreCase("66")) {
thematicCategoryName = "ΕΝΕΡΓΕΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("68")) {
thematicCategoryName = "ΒΙΟΜΗΧΑΝΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("72")) {
thematicCategoryName = "ΓΕΩΡΓΡΑΦΙΑ";
} else if (thematicCategoryId.equalsIgnoreCase("76")) {
thematicCategoryName = "ΔΙΕΘΝΕΙΣ ΟΡΓΑΝΙΣΜΟΙ";
} else if (thematicCategoryId.equalsIgnoreCase("10004")) {
thematicCategoryName = "ΔΗΜΟΣΙΑ ΔΙΟΙΚΗΣΗ";
} else if (thematicCategoryId.equalsIgnoreCase("10007")) {
thematicCategoryName = "ΥΓΕΙΑ";
} else {
writeUnknownMetadata("thematicCategory", thematicCategoryId);
}
return thematicCategoryName;
}
/**
* Find the name of the category id that the related organization belongs to.
*
* @param String the id of the category of the organization
* @return String[] the Greek and English name of the category of the organization
*/
public String[] findOrganizationCategoryName(String organizationCategoryId) {
String[] organizationCategoryName = null;
if (organizationCategoryId.equalsIgnoreCase("ADMINISTRATIVEREGION")) {
organizationCategoryName = new String[]{"Περιφέρεια", "Administrative Region"};
} else if (organizationCategoryId.equalsIgnoreCase("COMPANYSA")) {
organizationCategoryName = new String[]{"Ανώνυμες Εταιρείες Α.Ε.", "Company S.A."};
} else if (organizationCategoryId.equalsIgnoreCase("COURT")) {
organizationCategoryName = new String[]{"Δικαστήριο", "Court"};
} else if (organizationCategoryId.equalsIgnoreCase("DEKO")) {
organizationCategoryName = new String[]{"ΔΕΚΟ", "DEKO"};
} else if (organizationCategoryId.equalsIgnoreCase("GENERALGOVERNMENT")) {
organizationCategoryName = new String[]{"Γενική Κυβέρνηση", "General Government"};
} else if (organizationCategoryId.equalsIgnoreCase("INDEPENDENTAUTHORITY")) {
organizationCategoryName = new String[]{"Ανεξάρτητες Αρχές", "Independent Authority"};
} else if (organizationCategoryId.equalsIgnoreCase("INSTITUTION")) {
organizationCategoryName = new String[]{"Ιδρύματα", "Institution"};
} else if (organizationCategoryId.equalsIgnoreCase("LOCAL_AUTHORITY")) {
organizationCategoryName = new String[]{"ΟΤΑ (μόνο Δήμοι ή Αιρετές Περιφέρειες)", "Local Authority"};
} else if (organizationCategoryId.equalsIgnoreCase("MINISTRY")) {
organizationCategoryName = new String[]{"Υπουργείο", "Ministry"};
} else if (organizationCategoryId.equalsIgnoreCase("MUNICIPALITY")) {
organizationCategoryName = new String[]{"Δήμος", "Municipality"};
} else if (organizationCategoryId.equalsIgnoreCase("NONPROFITCOMPANY")) {
organizationCategoryName = new String[]{"Μη κερδοσκοπικές εταιρείες", "Non Profit Organization"};
} else if (organizationCategoryId.equalsIgnoreCase("NPDD")) {
organizationCategoryName = new String[]{"ΝΠΔΔ", "NPDD"};
} else if (organizationCategoryId.equalsIgnoreCase("NPID")) {
organizationCategoryName = new String[]{"ΝΠΙΔ", "NPID"};
} else if (organizationCategoryId.equalsIgnoreCase("OTHERTYPE")) {
organizationCategoryName = new String[]{"ΑΛΛΟ", "Other Type"};
} else if (organizationCategoryId.equalsIgnoreCase("PRESIDENTOFREPUBLIC")) {
organizationCategoryName = new String[]{"Πρόεδρος της Δημοκρατίας", "President of the Republic"};
} else if (organizationCategoryId.equalsIgnoreCase("UNIVERSITY")) {
organizationCategoryName = new String[]{"Πανεπιστήμιο", "University"};
} else if (organizationCategoryId.equalsIgnoreCase("DEYA")) {
organizationCategoryName = new String[]{"ΔΕΥΑ", "DEYA"};
} else if (organizationCategoryId.equalsIgnoreCase("REGION")) {
organizationCategoryName = new String[]{"Περιφέρεια", "Region"};
} else if (organizationCategoryId.equalsIgnoreCase("PRIME_MINISTER")) {
organizationCategoryName = new String[]{"Γραφείο πρωθυπουργού", "Prime Minister"};
} else if (organizationCategoryId.equalsIgnoreCase("HOSPITAL")) {
organizationCategoryName = new String[]{"Νοσοκομείο", "Hospital"};
} else if (organizationCategoryId.equalsIgnoreCase("SECRETARIAT_GENERAL")) {
organizationCategoryName = new String[]{"Γενική Γραμματεία", "SECRETARIAT GENERAL"};
} else {
organizationCategoryName = new String[]{"", ""};
writeUnknownMetadata("organizationCategory", organizationCategoryId);
}
return organizationCategoryName;
}
/**
* Find the name of the category id that the related unit belongs to.
*
* @param String the id of the category of the unit
* @return String[] the Greek and English name of the category of the unit
*/
public String[] findUnitCategoryName(String unitCategoryId) {
String[] unitCategoryName = null;
if (unitCategoryId.equalsIgnoreCase("ADMINISTRATION")) {
unitCategoryName = new String[]{"Διεύθυνση", "Administration"};
} else if (unitCategoryId.equalsIgnoreCase("BRANCH")) {
unitCategoryName = new String[]{"Κλάδος", "Branch"};
} else if (unitCategoryId.equalsIgnoreCase("COMMAND")) {
unitCategoryName = new String[]{"Αρχηγείο", "Command"};
} else if (unitCategoryId.equalsIgnoreCase("COMMITTEE")) {
unitCategoryName = new String[]{"Επιτροπή", "Committee"};
} else if (unitCategoryId.equalsIgnoreCase("DECENTRALISED_AGENCY")) {
unitCategoryName = new String[]{"Αποκεντρωμένη Υπηρεσία", "Decentralised Agency"};
} else if (unitCategoryId.equalsIgnoreCase("DEPARTMENT")) {
unitCategoryName = new String[]{"Τμήμα", "Department"};
} else if (unitCategoryId.equalsIgnoreCase("DIOIKISI")) {
unitCategoryName = new String[]{"Διοίκηση", "Administration"};
} else if (unitCategoryId.equalsIgnoreCase("FACULTY")) {
unitCategoryName = new String[]{"Σχολή", "Faculty"};
} else if (unitCategoryId.equalsIgnoreCase("GENERAL_ADMINISTRATION")) {
unitCategoryName = new String[]{"Γενική Διεύθυνση", "General Administration"};
} else if (unitCategoryId.equalsIgnoreCase("GENERAL_SECRETARIAT")) {
unitCategoryName = new String[]{"Γενική Γραμματεία", "General Secretariat"};
} else if (unitCategoryId.equalsIgnoreCase("OFFICE")) {
unitCategoryName = new String[]{"Γραφείο", "Office"};
} else if (unitCategoryId.equalsIgnoreCase("ORG_UNIT_OTHER")) {
unitCategoryName = new String[]{"Άλλο", "Org Unit Other"};
} else if (unitCategoryId.equalsIgnoreCase("PERIPHERAL_AGENCY")) {
unitCategoryName = new String[]{"Περιφερειακή Υπηρεσία", "Peripheral Agency"};
} else if (unitCategoryId.equalsIgnoreCase("PERIPHERAL_OFFICE")) {
unitCategoryName = new String[]{"Περιφερειακό Γραφείο", "PeripheraL Office"};
} else if (unitCategoryId.equalsIgnoreCase("SECTOR")) {
unitCategoryName = new String[]{"Τομέας", "Sector"};
} else if (unitCategoryId.equalsIgnoreCase("SMINARXIA")) {
unitCategoryName = new String[]{"Σμηναρχία", "Sminarxia"};
} else if (unitCategoryId.equalsIgnoreCase("SPECIAL_SECRETARIAT")) {
unitCategoryName = new String[]{"Ειδική Γραμματεία", "Special Secretariat"};
} else if (unitCategoryId.equalsIgnoreCase("TEAM")) {
unitCategoryName = new String[]{"Ομάδα", "Team"};
} else if (unitCategoryId.equalsIgnoreCase("TREASURY")) {
unitCategoryName = new String[]{"Ταμείο", "Treasury"};
} else if (unitCategoryId.equalsIgnoreCase("UNIT")) {
unitCategoryName = new String[]{"Μονάδα", "Unit"};
} else if (unitCategoryId.equalsIgnoreCase("VICE_ADMINISTRATION")) {
unitCategoryName = new String[]{"Υποδιεύθυνση", "Vice Administration"};
} else if (unitCategoryId.equalsIgnoreCase("VICE_ADMINISTRATION_HEAD")) {
unitCategoryName = new String[]{"Προϊστάμενος Υποδιεύθυνσης", "Vice Administration Head"};
} else if (unitCategoryId.equalsIgnoreCase("WATCH")) {
unitCategoryName = new String[]{"Παρατηρητήριο", "Watch"};
} else if (unitCategoryId.equalsIgnoreCase("WING")) {
unitCategoryName = new String[]{"Πτέρυγα", "Wing"};
} else {
unitCategoryName = new String[]{"", ""};
writeUnknownMetadata("unitCategory", unitCategoryId);
}
return unitCategoryName;
}
/**
* Find the name of the domain id that the related organization belongs to.
*
* @param String the id of the domain of the organization
* @return String[] the Greek and English name of the domain of the organization
*/
public String[] findOrganizationDomainName(String organizationDomainId) {
String[] organizationDomainName = new String[]{"", ""};
if (organizationDomainId.equalsIgnoreCase("Age")) {
organizationDomainName = new String[]{"Ηλικία", "Age"};
} else if (organizationDomainId.equalsIgnoreCase("Agriculture")) {
organizationDomainName = new String[]{"Γεωργία", "Agriculture"};
} else if (organizationDomainId.equalsIgnoreCase("AgricultureCompensations")) {
organizationDomainName = new String[]{"Γεωργικές αποζημιώσεις", "Agriculture Compensations"};
} else if (organizationDomainId.equalsIgnoreCase("AgricultureEnvironmentNaturalResources")) {
organizationDomainName = new String[]{"Γεωργία, Περιβάλλον και Φυσικοί Πόροι", "Agriculture Environment Natural Resources"};
} else if (organizationDomainId.equalsIgnoreCase("AnimalHealth")) {
organizationDomainName = new String[]{"Υγεία των ζώων", "Animal Health"};
} else if (organizationDomainId.equalsIgnoreCase("AnimalRights")) {
organizationDomainName = new String[]{"Δικαιώματα και πρόνοια ζώων", "Animal Rights"};
} else if (organizationDomainId.equalsIgnoreCase("ArbitrarConstructions")) {
organizationDomainName = new String[]{"Αυθαίρετα", "Arbitrar Constructions"};
} else if (organizationDomainId.equalsIgnoreCase("ArmedForces")) {
organizationDomainName = new String[]{"Ένοπλες Δυνάμεις", "Armed Forces"};
} else if (organizationDomainId.equalsIgnoreCase("ArmyLaws")) {
organizationDomainName = new String[]{"Στρατιωτική Νομοθεσία", "Army Laws"};
} else if (organizationDomainId.equalsIgnoreCase("AutoBicyclesBikes")) {
organizationDomainName = new String[]{"Αυτοκίνητα - Μοτοποδήλατα - Μοτοσικλέτες", "Auto - Bicycles - Bikes"};
} else if (organizationDomainId.equalsIgnoreCase("AutoWorkshops")) {
organizationDomainName = new String[]{"Συνεργεία", "Auto Workshops"};
} else if (organizationDomainId.equalsIgnoreCase("Bankruptcies")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Πτώχευση", "Bankruptcies"};
} else if (organizationDomainId.equalsIgnoreCase("Baptism")) {
organizationDomainName = new String[]{"Βάφτιση", "Baptism"};
} else if (organizationDomainId.equalsIgnoreCase("Birth")) {
organizationDomainName = new String[]{"Γέννηση", "Birth"};
} else if (organizationDomainId.equalsIgnoreCase("BoyRecordArchives")) {
organizationDomainName = new String[]{"Μητρώο Αρρένων", "Boy Record Archives"};
} else if (organizationDomainId.equalsIgnoreCase("Buildings")) {
organizationDomainName = new String[]{"Οικοδομές", "Buildings"};
} else if (organizationDomainId.equalsIgnoreCase("Business")) {
organizationDomainName = new String[]{"Επιχειρήσεις και κλάδοι", "Business"};
} else if (organizationDomainId.equalsIgnoreCase("BussesTracks")) {
organizationDomainName = new String[]{"Λεωφορεία - Φορτηγά", "Busses - Tracks"};
} else if (organizationDomainId.equalsIgnoreCase("CaringBusinesses")) {
organizationDomainName = new String[]{"Επιχειρήσεις πρόνοιας - Φροντίδα ηλικιωμένων - ΑΜΕΑ", "Caring Businesses"};
} else if (organizationDomainId.equalsIgnoreCase("Chambers")) {
organizationDomainName = new String[]{"Επιμελητήρια", "Chambers"};
} else if (organizationDomainId.equalsIgnoreCase("Charity")) {
organizationDomainName = new String[]{"Φιλανθρωπία", "Charity"};
} else if (organizationDomainId.equalsIgnoreCase("CityArchives")) {
organizationDomainName = new String[]{"Δημοτολόγιο και Μεταδημότευση", "City Archives"};
} else if (organizationDomainId.equalsIgnoreCase("CityRing")) {
organizationDomainName = new String[]{"Δακτύλιος", "City Ring"};
} else if (organizationDomainId.equalsIgnoreCase("CivilId")) {
organizationDomainName = new String[]{"Αστυνομική Ταυτότητα", "Civil Id"};
} else if (organizationDomainId.equalsIgnoreCase("CivilLaws")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Αναγκαστική διαχείριση", "Civil Laws"};
} else if (organizationDomainId.equalsIgnoreCase("CivilRights")) {
organizationDomainName = new String[]{"Πολιτικά και ανθρώπινα δικαιώματα", "Civil Rights"};
} else if (organizationDomainId.equalsIgnoreCase("Companies")) {
organizationDomainName = new String[]{"Εταιρείες - Σύσταση και λειτουργία εταιρειών", "Companies"};
} else if (organizationDomainId.equalsIgnoreCase("Constitution")) {
organizationDomainName = new String[]{"Σύνταγμα της Ελλάδας", "Constitution"};
} else if (organizationDomainId.equalsIgnoreCase("ConstructionEquipment")) {
organizationDomainName = new String[]{"Μηχανήματα έργων", "Construction Equipment"};
} else if (organizationDomainId.equalsIgnoreCase("Consumer")) {
organizationDomainName = new String[]{"Καταναλωτές", "Consumer"};
} else if (organizationDomainId.equalsIgnoreCase("Courts")) {
organizationDomainName = new String[]{"Δικαστήρια - Δικάσιμοι - Αποφάσεις - Ένδικα μέσα", "Courts"};
} else if (organizationDomainId.equalsIgnoreCase("Crime")) {
organizationDomainName = new String[]{"Έγκλημα", "Crime"};
} else if (organizationDomainId.equalsIgnoreCase("Culture")) {
organizationDomainName = new String[]{"Πολιτισμός", "Culture"};
} else if (organizationDomainId.equalsIgnoreCase("Customs")) {
organizationDomainName = new String[]{"Τελωνεία", "Customs"};
} else if (organizationDomainId.equalsIgnoreCase("Demolution")) {
organizationDomainName = new String[]{"Κατεδάφιση", "Demolition"};
} else if (organizationDomainId.equalsIgnoreCase("Divorce")) {
organizationDomainName = new String[]{"Διαζύγιο", "Divorce"};
} else if (organizationDomainId.equalsIgnoreCase("DriveSecurity")) {
organizationDomainName = new String[]{"Οδική ασφάλεια και κυκλοφορία", "Drive Security"};
} else if (organizationDomainId.equalsIgnoreCase("EarthResources")) {
organizationDomainName = new String[]{"Γεωφυσικοί Πόροι", "Earth Resources"};
} else if (organizationDomainId.equalsIgnoreCase("EducationInstitutes")) {
organizationDomainName = new String[]{"Εκπαιδευτήρια - Παιδότοποι - Φροντιστήρια", "Education Institutes"};
} else if (organizationDomainId.equalsIgnoreCase("EducationPersonnel")) {
organizationDomainName = new String[]{"Εκπαιδευτικοί", "Education Personnel"};
} else if (organizationDomainId.equalsIgnoreCase("EducationProfession")) {
organizationDomainName = new String[]{"Εκπαίδευση, Καριέρα και Απασχόληση", "Education Profession"};
} else if (organizationDomainId.equalsIgnoreCase("EducationSkills")) {
organizationDomainName = new String[]{"Εκπαίδευση και Ικανότητες", "Education Skills"};
} else if (organizationDomainId.equalsIgnoreCase("Elections")) {
organizationDomainName = new String[]{"Εκλογές - Εκλογική νομοθεσία - Εκλογικοί κατάλογοι", "Elections"};
} else if (organizationDomainId.equalsIgnoreCase("ElectricPowerManagement")) {
organizationDomainName = new String[]{"Ηλεκτροδότηση - Ηλεκτρική ενέργεια", "Electric Power Management"};
} else if (organizationDomainId.equalsIgnoreCase("EnvironmentPollution")) {
organizationDomainName = new String[]{"Περιβάλλον - Θόρυβος - Ρύπανση", "Environment - Pollution"};
} else if (organizationDomainId.equalsIgnoreCase("EUcitizens")) {
organizationDomainName = new String[]{"Υπήκοοι Κρατών - Μελών της Ε.Ε.", "E.U. Citizens"};
} else if (organizationDomainId.equalsIgnoreCase("Expatriates")) {
organizationDomainName = new String[]{"Ομογενείς - Πανινοστούντες", "Expatriates"};
} else if (organizationDomainId.equalsIgnoreCase("Explosives")) {
organizationDomainName = new String[]{"Εκρηκτικές ύλες - Επικίνδυνα υλικά", "Explosives"};
} else if (organizationDomainId.equalsIgnoreCase("Family")) {
organizationDomainName = new String[]{"Οικογένεια", "Family"};
} else if (organizationDomainId.equalsIgnoreCase("Financial")) {
organizationDomainName = new String[]{"Χρηματοοικονομικά", "Financial"};
} else if (organizationDomainId.equalsIgnoreCase("FinancialInstitutions")) {
organizationDomainName = new String[]{"Χρηματοπιστωτικά Ιδρύματα - Οργανισμοί", "Financial Institutions"};
} else if (organizationDomainId.equalsIgnoreCase("FireSafety")) {
organizationDomainName = new String[]{"Χρηματοπιστωτικά Ιδρύματα - Οργανισμοί", "Fire Safety"};
} else if (organizationDomainId.equalsIgnoreCase("Fireworks")) {
organizationDomainName = new String[]{"Βεγγαλικά", "Fireworks"};
} else if (organizationDomainId.equalsIgnoreCase("Fishing")) {
organizationDomainName = new String[]{"Αλιεία και υδατοκαλλιέργειες", "Fishing"};
} else if (organizationDomainId.equalsIgnoreCase("FoodDrinks")) {
organizationDomainName = new String[]{"Τρόφιμα και ποτά - Κανόνες υγιεινής", "Food - Drinks"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignCurrency")) {
organizationDomainName = new String[]{"Συνάλλαγμα", "ForeignCurrency"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignEducation")) {
organizationDomainName = new String[]{"Σπουδές εκτός Ελλάδας - Αναγνώριση τίτλου σπουδών", "Foreign Education"};
} else if (organizationDomainId.equalsIgnoreCase("ForeignLanguages")) {
organizationDomainName = new String[]{"Ξένες γλώσσες", "Foreign Languages"};
} else if (organizationDomainId.equalsIgnoreCase("Forrest")) {
organizationDomainName = new String[]{"Δάση", "Forrest"};
} else if (organizationDomainId.equalsIgnoreCase("ForrestHarvesting")) {
organizationDomainName = new String[]{"Υλοτομία", "Forrest Harvesting"};
} else if (organizationDomainId.equalsIgnoreCase("Fuels")) {
organizationDomainName = new String[]{"Καύσιμα", "Fuels"};
} else if (organizationDomainId.equalsIgnoreCase("Funeral")) {
organizationDomainName = new String[]{"Θάνατος και κηδεία", "Funeral"};
} else if (organizationDomainId.equalsIgnoreCase("GarbageDisposal")) {
organizationDomainName = new String[]{"Απόβλητα", "Garbage Disposal"};
} else if (organizationDomainId.equalsIgnoreCase("GeneralPension")) {
organizationDomainName = new String[]{"Συντάξεις - Γενικά θέματα", "General Pension"};
} else if (organizationDomainId.equalsIgnoreCase("GovermentPolitics")) {
organizationDomainName = new String[]{"Κυβέρνηση, Πολιτική και Δημόσια Διοίκηση", "Goverment Politics"};
} else if (organizationDomainId.equalsIgnoreCase("Governance")) {
organizationDomainName = new String[]{"Δημόσια διοίκηση - Πολίτες", "Governance"};
} else if (organizationDomainId.equalsIgnoreCase("GovernanceInstrumentation")) {
organizationDomainName = new String[]{"Κυβέρνηση και Κυβερνητικά όργανα", "Governance Instrumentation"};
} else if (organizationDomainId.equalsIgnoreCase("GovernanceProcess")) {
organizationDomainName = new String[]{"Κώδικας διοικητικής διαδικασίας", "Governance Process"};
} else if (organizationDomainId.equalsIgnoreCase("Guns")) {
organizationDomainName = new String[]{"Όπλα", "Guns"};
} else if (organizationDomainId.equalsIgnoreCase("HagueConvention")) {
organizationDomainName = new String[]{"Επισημείωση Εγγράφων (Σύμβαση Χάγης)", "Hague Convention"};
} else if (organizationDomainId.equalsIgnoreCase("Handicap")) {
organizationDomainName = new String[]{"Άτομα με αναπηρία (ΑΜΕΑ)", "Handicap"};
} else if (organizationDomainId.equalsIgnoreCase("Health")) {
organizationDomainName = new String[]{"Υγεία", "Health"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBenefits")) {
organizationDomainName = new String[]{"Επιδόματα σχετικά με υγεία και πρόνοια", "Health Benefits"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBook")) {
organizationDomainName = new String[]{"Βιβλιάριο υγείας", "Health Book"};
} else if (organizationDomainId.equalsIgnoreCase("HealthBusinesses")) {
organizationDomainName = new String[]{"Επιχειρήσεις υγείας και υγειονομικού ενδιαφέροντος", "Health Businesses"};
} else if (organizationDomainId.equalsIgnoreCase("HealthEmployees")) {
organizationDomainName = new String[]{"Εργαζόμενοι στα επαγγέλματα υγείας και φροντίδος", "Health Employees"};
} else if (organizationDomainId.equalsIgnoreCase("HealthNutrition")) {
organizationDomainName = new String[]{"Υγεία, Διατροφή και Πρόνοια", "Health Nutrition"};
} else if (organizationDomainId.equalsIgnoreCase("HelthExprenses")) {
organizationDomainName = new String[]{"Δαπάνες Υγείας", "Helth Exprenses"};
} else if (organizationDomainId.equalsIgnoreCase("HigherEducation")) {
organizationDomainName = new String[]{"Ανώτατη και ανώτερη εκπαίδευση", "Higher Education"};
} else if (organizationDomainId.equalsIgnoreCase("Hospitalization")) {
organizationDomainName = new String[]{"Νοσηλεία", "Hospitalization"};
} else if (organizationDomainId.equalsIgnoreCase("Hunting")) {
organizationDomainName = new String[]{"Κυνήγι", "Hunting"};
} else if (organizationDomainId.equalsIgnoreCase("IEK")) {
organizationDomainName = new String[]{"ΙΕΚ (Ινστιτούτο επαγγελματικής κατάρτισης)", "IEK"};
} else if (organizationDomainId.equalsIgnoreCase("IKA")) {
organizationDomainName = new String[]{"ΙΚΑ (Ίδρυμα Κοινωνικών Ασφαλίσεων)", "IKA"};
} else if (organizationDomainId.equalsIgnoreCase("Immigrants")) {
organizationDomainName = new String[]{"Μετανάστες - Οικονομικοί μετανάστες - Πρόσφυγες", "Immigrants"};
} else if (organizationDomainId.equalsIgnoreCase("Industru")) {
organizationDomainName = new String[]{"Βιομηχανία - Βιοτεχνία", "Industry"};
} else if (organizationDomainId.equalsIgnoreCase("InfrormationTech")) {
organizationDomainName = new String[]{"Τεχνιλογίες πληροφορικής και επικοινωνιών - Υπηρεσίες πιστοποίησης - Ψηφιακά πιστοποιητικά", "Infrormation - Tech"};
} else if (organizationDomainId.equalsIgnoreCase("Inheritance")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Κληρονομιά", "Inheritance"};
} else if (organizationDomainId.equalsIgnoreCase("InstallationSecurity")) {
organizationDomainName = new String[]{"Ασφάλεια εγκαταστάσεων και τεχνικού προσωπικού", "Installation Security"};
} else if (organizationDomainId.equalsIgnoreCase("InsuracePension")) {
organizationDomainName = new String[]{"Ασφάλιση και Σύνταξη", "Insurace and Pension"};
} else if (organizationDomainId.equalsIgnoreCase("InsuranceAgencies")) {
organizationDomainName = new String[]{"Ασφαλιστικοί Φορείς Ειδικών Κατηγοριών", "Insurance Agencies"};
} else if (organizationDomainId.equalsIgnoreCase("Kioks")) {
organizationDomainName = new String[]{"Περίπτερα", "Kiosks"};
} else if (organizationDomainId.equalsIgnoreCase("LaborHomes")) {
organizationDomainName = new String[]{"Εργατική κατοικία", "Labor Homes"};
} else if (organizationDomainId.equalsIgnoreCase("LaborHours")) {
organizationDomainName = new String[]{"Ώρες εργασίας, όροι και συνθήκες", "Labor Hours"};
} else if (organizationDomainId.equalsIgnoreCase("LaborMatters")) {
organizationDomainName = new String[]{"Εργασιακά θέματα και σχέσεις", "Labor Matters"};
} else if (organizationDomainId.equalsIgnoreCase("LaborSupport")) {
organizationDomainName = new String[]{"Εργατική εστία - Κοινωνικός τουρισμός", "Labor Support"};
} else if (organizationDomainId.equalsIgnoreCase("LandArchives")) {
organizationDomainName = new String[]{"Κτηματολόγιο", "Land Archives"};
} else if (organizationDomainId.equalsIgnoreCase("LawArchives")) {
organizationDomainName = new String[]{"Ποινικό μητρώο - Ποινική Διώξη", "Law Archives"};
} else if (organizationDomainId.equalsIgnoreCase("LawSupport")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Δικαστική συμπαράσταση", "Law Support"};
} else if (organizationDomainId.equalsIgnoreCase("LawyerInsurance")) {
organizationDomainName = new String[]{"Ταμείο Νομικών και κλάδο Επικουρικής ασφάλισης Δικηγόρων - ΚΕΑΔ", "Lawyer Insurance"};
} else if (organizationDomainId.equalsIgnoreCase("Lawyers")) {
organizationDomainName = new String[]{"Δικηγόροι", "Lawyers"};
} else if (organizationDomainId.equalsIgnoreCase("Leases")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Μισθώσεις", "Leases"};
} else if (organizationDomainId.equalsIgnoreCase("LicencePlates")) {
organizationDomainName = new String[]{"Πινακίδες οχημάτων και μηχανημάτων", "Licence Plates"};
} else if (organizationDomainId.equalsIgnoreCase("LocalGovernance")) {
organizationDomainName = new String[]{"Τοπική αυτοδιοίκηση", "Local Governance"};
} else if (organizationDomainId.equalsIgnoreCase("Marriage")) {
organizationDomainName = new String[]{"Γάμος", "Marriage"};
} else if (organizationDomainId.equalsIgnoreCase("Medicines")) {
organizationDomainName = new String[]{"Φάρμακα", "Medicines"};
} else if (organizationDomainId.equalsIgnoreCase("MilitaryService")) {
organizationDomainName = new String[]{"Στρατιωτική Θητεία", "Military Service"};
} else if (organizationDomainId.equalsIgnoreCase("Museum")) {
organizationDomainName = new String[]{"Αρχαιολογικοί Χώροι - Μουσεία", "Museum"};
} else if (organizationDomainId.equalsIgnoreCase("Nationality")) {
organizationDomainName = new String[]{"Ιθαγένεια, Κοινωνική ένταξη, Ομογενείς, Μετανάστες, Ξένοι υπήκοοι", "Nationality"};
} else if (organizationDomainId.equalsIgnoreCase("NationalityGeneral")) {
organizationDomainName = new String[]{"Ιθαγένεια", "Nationality"};
} else if (organizationDomainId.equalsIgnoreCase("NationalResistance")) {
organizationDomainName = new String[]{"Εθνική αντίσταση", "National Resistance"};
} else if (organizationDomainId.equalsIgnoreCase("NationRelationsDefence")) {
organizationDomainName = new String[]{"Διεθνείς Σχέσεις και Άμυνα", "Nation Relations Defence"};
} else if (organizationDomainId.equalsIgnoreCase("NavyAcademy")) {
organizationDomainName = new String[]{"Ακαδημία Εμπορικού Ναυτικού", "Navy Academy"};
} else if (organizationDomainId.equalsIgnoreCase("NewsAndInformation")) {
organizationDomainName = new String[]{"Πληροφορία και Επικοινωνία", "News and Information"};
} else if (organizationDomainId.equalsIgnoreCase("OGA")) {
organizationDomainName = new String[]{"ΟΓΑ (Οργανισμός Γεωργικών Ασφαλίσεων)", "OGA"};
} else if (organizationDomainId.equalsIgnoreCase("Passports")) {
organizationDomainName = new String[]{"Διαβατήρια και visas", "Passports"};
} else if (organizationDomainId.equalsIgnoreCase("PaymentOrder")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Διαταγή πληρωμής", "Payment Order"};
} else if (organizationDomainId.equalsIgnoreCase("PeopleSocietiesLiving")) {
organizationDomainName = new String[]{"Άνθρωποι, Κοινότητες και Διαβίωση", "People Societies Living"};
} else if (organizationDomainId.equalsIgnoreCase("PersonalData")) {
organizationDomainName = new String[]{"Προστασία προσωπικών δεδομένων", "Personal Data"};
} else if (organizationDomainId.equalsIgnoreCase("Plots")) {
organizationDomainName = new String[]{"Οικόπεδα", "Plots"};
} else if (organizationDomainId.equalsIgnoreCase("Policing")) {
organizationDomainName = new String[]{"Αστυνόμευση", "Policing"};
} else if (organizationDomainId.equalsIgnoreCase("PreservedConstructions")) {
organizationDomainName = new String[]{"Διατηρητέα", "Preserved Constructions"};
} else if (organizationDomainId.equalsIgnoreCase("ProfessionRights")) {
organizationDomainName = new String[]{"Άδειες επαγγέλματος", "Profession Rights"};
} else if (organizationDomainId.equalsIgnoreCase("Prostitution")) {
organizationDomainName = new String[]{"Εκδιδόμενα πρόσωπα", "Prostitution"};
} else if (organizationDomainId.equalsIgnoreCase("PublicMarkets")) {
organizationDomainName = new String[]{"Λαϊκές αγορές", "Public Markets"};
} else if (organizationDomainId.equalsIgnoreCase("PublicResourcesManagement")) {
organizationDomainName = new String[]{"Διαχείριση δημοσίου υλικού", "Public Resources Management"};
} else if (organizationDomainId.equalsIgnoreCase("PublicSecuriryCivilRights")) {
organizationDomainName = new String[]{"Ασφάλεια, Δημόσια Τάξη, Δικαιοσύνη και Δικαιώματα", "Public Securiry Civil Rights"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServantIssues")) {
organizationDomainName = new String[]{"Θέματα δημοσίων υπαλλήλων", "Public Servant Issues"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServantRecruitment")) {
organizationDomainName = new String[]{"Πρόσληψη στο δημόσιο", "Public Servant Recruitment"};
} else if (organizationDomainId.equalsIgnoreCase("PublicServants")) {
organizationDomainName = new String[]{"Ασφαλισμένοι δημοσίου", "Public Servants"};
} else if (organizationDomainId.equalsIgnoreCase("PublicTransportation")) {
organizationDomainName = new String[]{"Μέσα μεταφοράς", "Public Transportation"};
} else if (organizationDomainId.equalsIgnoreCase("Quarries")) {
organizationDomainName = new String[]{"Λατομεία", "Quarries"};
} else if (organizationDomainId.equalsIgnoreCase("Recruitment")) {
organizationDomainName = new String[]{"Προκηρύξεις - Προσλήψεις", "Recruitment"};
} else if (organizationDomainId.equalsIgnoreCase("Residence")) {
organizationDomainName = new String[]{"Κατοικία", "Residence"};
} else if (organizationDomainId.equalsIgnoreCase("Seaside")) {
organizationDomainName = new String[]{"Αιγιαλός", "Seaside"};
} else if (organizationDomainId.equalsIgnoreCase("SecurityBusiness")) {
organizationDomainName = new String[]{"Κλειδαράδες - Ιδιωτικές επιχειρήσεις ασφαλείας - Συναγερμοί - Αδειοδοτήσεις επαγγελματιών", "Security Business"};
} else if (organizationDomainId.equalsIgnoreCase("Settlements")) {
organizationDomainName = new String[]{"Οικισμοί", "Settlements"};
} else if (organizationDomainId.equalsIgnoreCase("Ships")) {
organizationDomainName = new String[]{"Πλοία", "Ships"};
} else if (organizationDomainId.equalsIgnoreCase("ShipsEmployment")) {
organizationDomainName = new String[]{"Πληρώματα εμπορικών πλοίων", "Ships Employment"};
} else if (organizationDomainId.equalsIgnoreCase("SmallShips")) {
organizationDomainName = new String[]{"Σκάφη", "Small Ships"};
} else if (organizationDomainId.equalsIgnoreCase("SocialAccession")) {
organizationDomainName = new String[]{"Κοινωνική ένταξη", "Social Accession"};
} else if (organizationDomainId.equalsIgnoreCase("SocialPolitics")) {
organizationDomainName = new String[]{"Κοινωνική πολιτική", "Social Politics"};
} else if (organizationDomainId.equalsIgnoreCase("Sports")) {
organizationDomainName = new String[]{"Αθλητισμός - Αθλητική Νομοθεσία - Αθλητικά θέματα", "Sports"};
} else if (organizationDomainId.equalsIgnoreCase("SportsCultureTourism")) {
organizationDomainName = new String[]{"Αθλητισμός, Πολιτισμός, Τέχνες, Ψυχαγωγία, Τουρισμός", "Sports Culture Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("StockRaising")) {
organizationDomainName = new String[]{"Κτηνοτροφία - Πτηνοτροφία", "Stock Raising"};
} else if (organizationDomainId.equalsIgnoreCase("StreetLayout")) {
organizationDomainName = new String[]{"Ρυμοτομία", "Street Layout"};
} else if (organizationDomainId.equalsIgnoreCase("Students")) {
organizationDomainName = new String[]{"Μαθητές - Σπουδαστές - Φοιτητές", "Students"};
} else if (organizationDomainId.equalsIgnoreCase("Surname")) {
organizationDomainName = new String[]{"Επώνυμο", "Surname"};
} else if (organizationDomainId.equalsIgnoreCase("TAE")) {
organizationDomainName = new String[]{"ΤΑΕ", "TAE"};
} else if (organizationDomainId.equalsIgnoreCase("TAJI")) {
organizationDomainName = new String[]{"ΤΑΞΥ (Ταμείο aσφάλισης Ξενοδοχοϋπαλλήλων", "TAXY"};
} else if (organizationDomainId.equalsIgnoreCase("Taxi")) {
organizationDomainName = new String[]{"Ταξί", "Taxi"};
} else if (organizationDomainId.equalsIgnoreCase("TaxIssuesCertificates")) {
organizationDomainName = new String[]{"Φορολογικά θέματα - Υπηρεσίες φορολογίας εισοδήματος - Πιστοποιητικά", "Tax Issue Certificates"};
} else if (organizationDomainId.equalsIgnoreCase("TaxIssuesLaws")) {
organizationDomainName = new String[]{"Φορολογικά θέματα - Υποχρεώσεις - Κανονισμοί", "Tax Issue Laws"};
} else if (organizationDomainId.equalsIgnoreCase("TEAYEK")) {
organizationDomainName = new String[]{"ΤΕΑΥΕΚ (Ταμείο επικουρικής ασφαλίσεως υπαλλήλων εμπορικών καταστημάτων)", "TEAYEK"};
} else if (organizationDomainId.equalsIgnoreCase("TEBE")) {
organizationDomainName = new String[]{"ΤΕΒΕ", "TEBE"};
} else if (organizationDomainId.equalsIgnoreCase("TelecomFaire")) {
organizationDomainName = new String[]{"Τηλεπικοινωνιακές συνδέσεις και τέλη", "Telecom Faire"};
} else if (organizationDomainId.equalsIgnoreCase("TelecommunicationsLaw")) {
organizationDomainName = new String[]{"θεσμικά, ρυθμιστικά και κανονιστικά θέματα τηλεπικοινωνιών και ταχυδρομείων", "Telecommunications Law"};
} else if (organizationDomainId.equalsIgnoreCase("ThirdAge")) {
organizationDomainName = new String[]{"Τρίτη ηλικία", "Third Age"};
} else if (organizationDomainId.equalsIgnoreCase("Tourism")) {
organizationDomainName = new String[]{"Κοινωνικός τουρισμός - Νεανικός Τουρισμός", "Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("TourismAccomodation")) {
organizationDomainName = new String[]{"Ξενοδοχεία - Τουριστικά καταλύματα - Τουριστικά γραφεία", "Tourism Accomodation"};
} else if (organizationDomainId.equalsIgnoreCase("Transplants")) {
organizationDomainName = new String[]{"Μεταμοσχεύσεις - Δωρεά Οργάνων", "Transplants"};
} else if (organizationDomainId.equalsIgnoreCase("Transportations")) {
organizationDomainName = new String[]{"Μεταφορές", "Transportations"};
} else if (organizationDomainId.equalsIgnoreCase("TSA")) {
organizationDomainName = new String[]{"ΤΣΑ", "TSA"};
} else if (organizationDomainId.equalsIgnoreCase("TSAY")) {
organizationDomainName = new String[]{"ΤΣΑΥ", "TSAY"};
} else if (organizationDomainId.equalsIgnoreCase("TSMEDE")) {
organizationDomainName = new String[]{"ΤΣΜΕΔΕ", "TSMEDE"};
} else if (organizationDomainId.equalsIgnoreCase("Unemployment")) {
organizationDomainName = new String[]{"Ανεργία και αναζήτηση εργασίας", "Unemployment"};
} else if (organizationDomainId.equalsIgnoreCase("Unions")) {
organizationDomainName = new String[]{"Σωματεία - Σύλλογοι - Συνεταιρισμοί", "Unions"};
} else if (organizationDomainId.equalsIgnoreCase("UrbanPlanning")) {
organizationDomainName = new String[]{"Πολεοδομία, Ρυμοτομία, Οικοδομές και Κτηματολόγιο", "Urban Planning"};
} else if (organizationDomainId.equalsIgnoreCase("UrbanServices")) {
organizationDomainName = new String[]{"Πολεοδομία - Σχέδιο πόλης", "Urban Services"};
} else if (organizationDomainId.equalsIgnoreCase("Vaccination")) {
organizationDomainName = new String[]{"Εμβολιασμοί - Εμβόλια", "Vaccination"};
} else if (organizationDomainId.equalsIgnoreCase("WaterResources")) {
organizationDomainName = new String[]{"Υδάτινοι Πόροι", "Water Resources"};
} else if (organizationDomainId.equalsIgnoreCase("WaterSupply")) {
organizationDomainName = new String[]{"Ύδρευση - Αποχέτευση", "Water Supply"};
} else if (organizationDomainId.equalsIgnoreCase("Will")) {
organizationDomainName = new String[]{"Αστικό Δίκαιο - Διαθήκη", "Will"};
} else if (organizationDomainId.equalsIgnoreCase("WorkSafety")) {
organizationDomainName = new String[]{"Ασφάλεια και υγεία στην εργασία", "Work Safety"};
} else if (organizationDomainId.equalsIgnoreCase("Youth")) {
organizationDomainName = new String[]{"Νέα γενιά - Τουρισμός - Επιχειρηματικότητα", "Youth"};
} else if (organizationDomainId.equalsIgnoreCase("YouthTourism")) {
organizationDomainName = new String[]{"Κοινωνικός τουρισμός - Νεανικός Τουρισμός", "Youth Tourism"};
} else if (organizationDomainId.equalsIgnoreCase("Εntrepreneurship")) {
organizationDomainName = new String[]{"Επιχειρηματικότητα", "Εntrepreneurship"};
} else {
organizationDomainName = new String[]{"", ""};
writeUnknownMetadata("organizationDomain", organizationDomainId);
}
return organizationDomainName;
}
/**
* Find the name of the VAT type id.
*
* @param String the id of the VAT type
* @return String[] the Greek and English name of the VAT type
*/
public String[] findVatTypeName(String vatTypeId) {
String[] vatTypeName = null;
if (vatTypeId.equalsIgnoreCase("EL")) {
vatTypeName = new String[]{"Εθνικό (Φυσικά και Νομικά πρόσωπα)", "National (Natural persons and Legal entities)"};
} else if (vatTypeId.equalsIgnoreCase("EU")) {
vatTypeName = new String[]{"Νομικό πρόσωπο Κράτους-μέλους της ΕΕ", "Legal entity of a member state of the EU"};
} else if (vatTypeId.equalsIgnoreCase("EUP")) {
vatTypeName = new String[]{"Φυσικό πρόσωπο Κράτους-μέλους της ΕΕ", "Natural person of a member State of the EU"};
} else if (vatTypeId.equalsIgnoreCase("INT")) {
vatTypeName = new String[]{"Οργανισμός χωρίς ΑΦΜ", "Organization without VAT"};
} else if (vatTypeId.equalsIgnoreCase("O")) {
vatTypeName = new String[]{"Χώρας εκτός ΕΕ", "Country outside the EU"};
} else {
vatTypeName = new String[]{"", ""};
writeUnknownMetadata("unitCategory", vatTypeId);
}
return vatTypeName;
}
/**
* Convert a Date to its Calendar instance.
*
* @param Date a date
* @return Calendar the Calendar instance of the provided Date
*/
public Calendar dateToCalendarConverter(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
return cal;
}
/**
* Create the ending part of the URI of the provided organization.
*
* @param Organization the organization under investigation
* @param Organization the supervisor of the organization
* @return String the ending part of the URI of the provided organization
*/
public String organizationUriBuilder(Organization org, Organization supervisor) {
String uri = "";
String orgVatId = org.getVatNumber().replace(" ", "");
if (orgVatId.equalsIgnoreCase("")) {
orgVatId = "VatNotProvided";
}
/*if (org.getSupervisorId() != null) { //org has supervisor
if (supervisor != null) {
String superVatId = supervisor.getVatNumber().replace(" ", "");
if (orgVatId != "") {
if (superVatId.equalsIgnoreCase(orgVatId)) { //epoptevomenos foreas me idio AFM
uri = superVatId + "/" + org.getUid().replace(" ", "");
} else { //epoptevomenos foreas me diaforetiko AFM
uri = orgVatId;
}
} else {
uri = superVatId + "/" + org.getUid().replace(" ", "");
}
} else {
uri = "NullSupervisor" + "/" + orgVatId;
}
} else { //org does not have supervisor
uri = orgVatId;
}*/
if (supervisor != null) {
uri = orgVatId + "/" + org.getUid().replace(" ", "");
} else {
if (orgVatId.equalsIgnoreCase("")) {
uri = orgVatId + "/" + org.getUid().replace(" ", "");
} else {
uri = orgVatId;
}
}
//uri = orgVatId + "/" + org.getUid().replace(" ", "");
return uri;
}
/**
* Calculate the suspension time until the execution time
* (daily at 00:15 local time).
*
* @return int the suspension time until the execution time
*/
public int timeUntilExecution() {
DateTime today = new DateTime();
DateTime tommorrow = today.plusDays(1).withTimeAtStartOfDay().plusMinutes(15); //00:15
Duration duration = new Duration(today, tommorrow);
int diffMinutes = (int) duration.getStandardMinutes();
System.out.println("Sleeping for: " + diffMinutes + " minutes...");
return diffMinutes;
}
} | YourDataStories/harvesters | DiavgeiaProjectHarvester/src/utils/HelperMethods.java |
1,650 | package api;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Αυτή η κλάση αναπαριστά έναν γενικό χρήστη. Με τη βοήθεια της κληρονομικότητας μπορεί να χρησιμοποιηθεί για τη δημιουργία
* της κλάσης του παρόχου καταλυμάτων, του απλού χρήστη αλλά και για την ανάπτυξη νέων ειδών χρήστη (πχ διαχειριστή).
* @author Γεώργιος Δάλλας
*/
public class GeneralUser implements Serializable {
private String name,surname;
private String username,password;
private String userType;
/**
* Κατασκευαστής που παίρνει ως παράμετρο το όνομα, το επίθετο, το Username, το Password και τον τύπο ενός χρήστη.
* @param name Το όνομα του χρήστη
* @param surname Το επίθετο του χρήστη
* @param username Το username που χρησιμοποιεί ο χρήστης για τη σύνδεση του.
* @param password Το password που χρησιμοποιεί ο χρήστης για τη σύνδεση του.
* @param userType Ο τύπος του χρήστη (πχ πάροχος, χρήστης).
*/
public GeneralUser(String name, String surname, String username, String password, String userType) {
this.name = name;
this.surname = surname;
this.username = username;
this.password = password;
this.userType = userType;
}
/**
* Μέθοδος ελέγχου στοιχείων για τη σύνδεση ενός χρήστη στην εφαρμογή.
* @param username το username του χρήστη
* @param password ο κωδικός πρόσβασης του χρήστη
* @return true αν τα στοιχεία ταιριάζουν με αυτά ενός χρήστη στην λίστα χρηστών που υπάρχει αποθηκευμένη.
*/
public static boolean checkLogin(String username, String password){
ArrayList<GeneralUser>AccountsDB = (ArrayList<GeneralUser>) FileInteractions.loadFromBinaryFile("src/files/accounts.bin");
boolean found=false;
for(GeneralUser acc : AccountsDB){
if(acc.getUsername().equals(username) && acc.getPassword().equals(password)){
found=true;
break;
}
}
return found;
}
/**
* ελέγχει αν υπάρχει χρήστης με το συγκεκριμένο username στη λίστα χρηστών που υπάρχει αποθηκευμένη.
* @param username username του χρήστη που ελέγχεται.
* @return επιστρέφει true αν υπάρχει χρήστης που να ταιριάζει με αυτό το username αλλιώς false.
*/
public static boolean checkExistence(String username){
ArrayList<GeneralUser>AccountsDB = (ArrayList<GeneralUser>) FileInteractions.loadFromBinaryFile("src/files/accounts.bin");
boolean found=false;
for(GeneralUser acc : AccountsDB){
if(acc.getUsername().equals(username)){
found=true;
break;
}
}
return found;
}
/**
* Μέθοδος επιστροφής ενός χρήστη χρησιμοποιώντας απλά το username του για παράμετρο αναζήτησης.
* @param username το username του χρήστη
* @return επιστρέφει έναν χρήστη τύπου general user που έχει το username της παραμέτρου.
*/
public static GeneralUser getUserByUsername(String username){
ArrayList<GeneralUser>AccountsDB = (ArrayList<GeneralUser>) FileInteractions.loadFromBinaryFile("src/files/accounts.bin");
for(GeneralUser acc : AccountsDB){
if(acc.getUsername().equals(username)){
return acc;
}
}
return null;
}
/**
* Μέθοδος δημιουργίας ενός χρήστη και αποθήκευσης αυτού στο αρχείο με την λίστα χρηστών.
* @param name το όνομα του χρήστη
* @param surname το επίθετο του χρήστη
* @param username το username του χρήστη
* @param password ο κωδικός πρόσβασης του χρήστη
* @param userType ο τύπος του χρήστη πχ Provider
* @return επιστρέφει true αν η δημιουργία του χρήστη ήταν επιτυχείς, αλλιώς false.
*/
public static boolean createAccount(String name, String surname, String username, String password, String userType){
if(checkExistence(username)==false){
ArrayList<GeneralUser>AccountsDB = (ArrayList<GeneralUser>) FileInteractions.loadFromBinaryFile("src/files/accounts.bin");
GeneralUser newAcc = new GeneralUser(name,surname,username,password,userType);
AccountsDB.add(newAcc);
FileInteractions.saveToBinaryFile("src/files/accounts.bin",AccountsDB);
return true;
}
return false;
};
/**
* Αυτή η μέθοδος δέχεται ως παράμετρο ένα username και το αναθέτει ως username του χρήστη για τον οποίο καλείται.
* @param username Το username που χρησιμοποιεί ο χρήστης για τη σύνδεση του.
*/
public void setUsername(String username) {
this.username = username;
}
/**
* Αυτή η μέθοδος δέχεται ως παράμετρο ένα password και το αναθέτει ως password του χρήστη για τον οποίο καλείται.
* @param password Το password που χρησιμοποιεί ο χρήστης για τη σύνδεση του.
*/
public void setPassword(String password) {
this.password = password;
}
/**
* Αυτή η μέθοδος δέχεται ως παράμετρο ένα όνομα και το αναθέτει ως όνομα του χρήστη για τον οποίο καλείται.
* @param name Το όνομα του χρήστη
*/
public void setName(String name) {
this.name = name;
}
/**
* Αυτή η μέθοδος δέχεται ως παράμετρο ένα επίθετο και το αναθέτει ως επίθετο του χρήστη για τον οποίο καλείται.
* @param surname Το επίθετο του χρήστη
*/
public void setSurname(String surname) {
this.surname = surname;
}
/**
* Αυτή η μέθοδος δέχεται ως παράμετρο ένα τύπο χρήστη (πχ πάροχος) και το αναθέτει ως τύπο του χρήστη για τον οποίο καλείται.
* @param userType Ο τύπος του χρήστη (πχ πάροχος, χρήστης).
*/
public void setUserType(String userType) {
this.userType = userType;
}
/**
* Μέθοδος για την επιστροφή του ονόματος ενός χρήστη.
* @return το όνομα του χρήστη
*/
public String getName() {
return name;
}
/**
* Μέθοδος για την επιστροφή του επιθέτου ενός χρήστη.
* @return το επίθετο του χρήστη
*/
public String getSurname() {
return surname;
}
/**
* Μέθοδος για την επιστροφή του κωδικού ενός χρήστη.
* @return τον κωδικό του χρήστη
*/
public String getPassword() {
return password;
}
/**
* Μέθοδος για την επιστροφή του username ενός χρήστη.
* @return το username του χρήστη
*/
public String getUsername() {
return username;
}
/**
* Μέθοδος για την επιστροφή του τύπου ενός χρήστη.
* @return τον τύπου του χρήστη (πχ πάροχος)
*/
public String getUserType() {
return userType;
}
}
| dallasGeorge/reviewsApp | src/api/GeneralUser.java |
1,651 | package mvc.model.Board;
/**
* Enumeration Palace consists of the 4 palaces of the game
*/
public enum Palace {
Knossos, Malia, Phaistos, Zakros;
/** <b>Accessor</b>
* <b>Postcondition</b> Returns the name of this enum constant, exactly as declared in its enum declaration.
*
* @return the string name of the enum
*/
@Override
public String toString() {
return this.name();
}
/** <b>Accessor</b>
* <b>Postcondition</b> Returns the description of each palace
* for the display.
*
* @return String with the description of the palace
*/
public String getDescription() {
switch (this) {
case Knossos:
return "<html>Έφτασες στο Ανάκτορο της Κνωσού!!!;<br>"
+ "Το μινωικό ανάκτορο είναι ο κύριος επισκέψιμος χώρος <br>"
+ "της Κνωσού (ή Κνωσσού), σημαντικής πόλης κατά την αρχαιότητα, <br>"
+ "με συνεχή ζωή από τα νεολιθικά χρόνια έως τον 5ο αι. Είναι <br>"
+ "χτισμένο στο λόφο της Κεφάλας, με εύκολη πρόσβαση στη θάλασσα <br>"
+ "αλλά και στο εσωτερικό της Κρήτης. Κατά την παράδοση, υπήρξε η <br>"
+ "έδρα του σοφού βασιλιά Μίνωα. Συναρπαστικοί μύθοι, του Λαβύρινθου <br>"
+ "με το Μινώταυρο και του Δαίδαλου με τον Ίκαρο, συνδέονται με το <br>"
+ "ανάκτορο της Κνωσσού.</html>";
case Malia:
return "<html>Έφτασες στο Ανάκτορο των Μαλίων!!! <br>"
+ "Ανατολικά από τα σημερινά Μάλια βρίσκεται το μινωικό ανάκτορο των <br>"
+ "Μαλίων. Είναι το τρίτο σε μέγεθος ανάκτορο της μινωικής Κρήτης και <br>"
+ "είναι χτισμένο σε μια τοποθεσία προνομιακή, κοντά στη θάλασσα και πάνω <br>"
+ "στο δρόμο που συνδέει την ανατολική με την κεντρική Κρήτη. Το ανάκτορο <br>"
+ "των Μαλίων κατά τη μυθολογία χρησίμευε σαν κατοικία του Σαρπηδόνα, αδερφού <br>"
+ "του Μίνωα, και πρωτοχτίζεται το 1900 π.Χ. Ο προϋπάρχων ισχυρός οικισμός, από <br>"
+ "τον οποίο σώζονται συνοικίες γύρω από το ανάκτορο, μετατρέπεται έτσι σε <br>"
+ "ανακτορικό κέντρο-πόλη.</html>";
case Phaistos:
return "<html>Έφτασες στο Ανάκτορο της Φαιστού!!!; <br>"
+ "Το Μινωικό Ανάκτορο της Φαιστού βρίσκεται στην νότιο-κεντρική Κρήτη, στην <br>"
+ "πεδιάδα της Μεσαράς, 55 χιλιόμετρα νότια από το Ηράκλειο και σε μικρή απόσταση <br>"
+ "από τον αρχαιολογικό χώρο στην Αγία Τριάδα, τον αρχαιολογικό χώρο στη Γόρτυνα <br>"
+ "και τα Μάταλα. Το μινωικό ανάκτορο της Φαιστού αντιστοιχεί σε ακμαία πόλη που, <br>"
+ "όχι τυχαία, αναπτύχθηκε στην έφορη πεδιάδα της Μεσαράς κατά τους προϊστορικούς <br>"
+ "χρόνους, δηλαδή από το 6.000 π.Χ. περίπου μέχρι και τον 1ο π.Χ. αιώνα, όπως <br>"
+ "επιβεβαιώνουν τα αρχαιολογικά ευρήματα.</html>";
case Zakros:
return "<html>Έφτασες στο Ανάκτορο της Ζάκρου!!!;<br>"
+ "Το ανάκτορο της Ζάκρου είναι το τέταρτο σε μέγεθος της Μινωικής Κρήτης. Βρισκόταν <br>"
+ "σε σημαντικό στρατηγικό σημείο, σε ασφαλισμένο κολπίσκο, και ήταν κέντρο εμπορικών <br>"
+ "ανταλλαγών με τις χώρες της Ανατολής, όπως φαίνεται από τα ευρήματα (χαυλιόδοντες <br>"
+ "ελέφαντα, φαγεντιανή, χαλκός κλπ). Το ανάκτορο αποτέλεσε το κέντρο διοίκησης,<br>"
+ " θρησκείας και εμπορίου. Το περιστοίχιζε η πόλη. Στο χώρο δεν έγινε νέα οικοδόμηση, <br>"
+ "εκτός από κάποιες καλλιέργειες. </html>";
default:
throw new AssertionError(this.name());
}
}
}
| GeorgiaSamaritaki/Lost-Relics-Game | src/mvc/model/Board/Palace.java |
1,653 |
package graph;
import edu.uci.ics.jung.io.GraphMLWriter;
import edu.uci.ics.jung.io.graphml.EdgeMetadata;
import edu.uci.ics.jung.io.graphml.HyperEdgeMetadata;
import org.apache.commons.collections15.Transformer;
/**
* ΕΑΠ - ΠΛΗ31 - 4η ΕΡΓΑΣΙΑ 2015-2016
* @author Tsakiridis Sotiris
*/
public class Edge implements Comparable<Edge> {
// Πεδία της κλάσης
private double weight; // Το βάρος της ακμής
private Operator operator; // Ο τελεστής δράσης
// flag διαγραφής ακμής κατά την σχεδίαση - δεν αποθηκεύεται
private boolean deleted = false;
// Default constructor
public Edge() {
this.weight = 1;
}
// Constructor
public Edge(double weight, Operator operator) {
this.weight = weight;
this.operator = operator;
}
// constructor - αρχικοποίηση από άλλο edge
public Edge(Edge edge) {
this.weight = edge.weight;
this.operator = edge.operator;
}
// getters
public double getWeight() { return this.weight; }
public Operator getOperator() { return this.operator; }
public boolean isDeleted() { return this.deleted; }
// setters
public void setWeight(double weight) { this.weight = weight; }
public void setOperator(Operator operator) { this.operator = operator; }
public void setDeleted(boolean b) { this.deleted = b; }
// Override toString() method
@Override
public String toString() {
return this.operator.getLabel();
}
// Edge Transformer για την ανάκτηση από xml
public static Transformer<EdgeMetadata, Edge> getEdgeTransformer() {
Transformer<EdgeMetadata, Edge> edgeTransformer =
new Transformer<EdgeMetadata, Edge>() {
@Override
public Edge transform(EdgeMetadata metadata) {
double weight = Double.parseDouble(metadata.getProperty("weight"));
String operator = metadata.getProperty("operator");
return new Edge(weight, Operator.explode(operator));
}
};
return edgeTransformer;
}
// Hyperedge Transformer - Απαιτείται αλλά δεν χρησιμοποιείται
public static Transformer<HyperEdgeMetadata, Edge> getHyperedgeTransformer() {
Transformer<HyperEdgeMetadata, Edge> hyperEdgeTransformer =
new Transformer<HyperEdgeMetadata, Edge>() {
@Override
public Edge transform(HyperEdgeMetadata metadata) {
double weight = Double.parseDouble(metadata.getProperty("weight"));
String operator = metadata.getProperty("operator");
return new Edge(weight, Operator.explode(operator));
}
};
return hyperEdgeTransformer;
}
// για την σύγκριση και ταξινόμηση ακμών με βάση την προτεραιότητα
// του τελεστή δράσης
@Override
public int compareTo(Edge e) {
return this.operator.getPriority() - e.getOperator().getPriority();
}
// Αποθήκευση δεδομένων του Node σε GraphML
public static void saveToGraphML(GraphMLWriter<Node, Edge> ml) {
// weight
ml.addEdgeData("weight", null, "0",
new Transformer<Edge, String>() {
@Override
public String transform(Edge edge) {
return Double.toString(edge.getWeight());
}
});
// operator
ml.addEdgeData("operator", null, "",
new Transformer<Edge, String>() {
@Override
public String transform(Edge edge) {
return edge.getOperator().implode();
}
});
}
}
| artibet/graphix | src/graph/Edge.java |
1,654 | public class RoomTypeE extends RoomTypeC//Δωμάτιο τύπου C,αλλά με έκπτωση 50% ανά άτομο μετά την τρίτη μέρα.
{
public double getPriceOfRoom()//Μέθοδος για τον υπολογισμό των εσόδων δωματίου τύπου E,λαμβάνοντας υπόψη τα ελάχιστα//
{ //άτομα και μέρες,καθώς και την έκπτωση.
int i=0;
double moneyEarnedFromRoom=0; //Μεταβλητή για έσοδα από δωμάτιο.
double discountPerPerson; //Μεταβλητή για έκπτωση ανά άτομο.
for(i=1; i<31; i++)
{
if(roomAvailability[i]!=null)
{
if(i<=3)
{
discountPerPerson = (getPricePerPerson() / 2 );
moneyEarnedFromRoom+=(roomAvailability[i].getPeopleNum()*( getPricePerPerson() - discountPerPerson));
continue;
}
moneyEarnedFromRoom = (moneyEarnedFromRoom + (roomAvailability[i].getPeopleNum() * getPricePerPerson()));
}
}
return moneyEarnedFromRoom;
}
}
| DimitrisKostorrizos/UndergraduateCeidProjects | Project Οντοκεντρικός Προγραμματισμός/Java Project/Hotel Project, Swing/RoomTypeE.java |
1,656 | public class ArrayStack implements StackInterface {
private static final String MSG_STACK_FULL = "Υπερχείλιση στοίβας. Η στοίβα είναι πλήρης."; // Δήλωση σταθεράς μηνύματος πλήρους στοίβας
private static final String MSG_STACK_EMPTY = "Η στοίβα είναι κενή."; // Δήλωση σταθεράς μηνύματος κενής στοίβας
public static final int MAX_CAPACITY = 100; // Δήλωση σταθεράς μέγιστου μεγέθους στοίβας
private int stackCapacity;
private Object[] S;
private int top = -1;
// Default constructor
public ArrayStack() {
this(MAX_CAPACITY);
}
// Full constructor
public ArrayStack(int newCapacity) {
this.stackCapacity = newCapacity;
this.S = new Object[this.stackCapacity];
}
public int getStackSize() {
// Επιστρέφει το μέγεθος της Στοίβας
return (this.top + 1);
}
public int getMaxStackCapacity() {
// Επιστρέφει το μέγεθος της Στοίβας
return this.stackCapacity;
}
public boolean stackIsEmpty() {
// Επιστρέφει true αν η Στοίβα είναι κενή
return (this.top < 0);
}
public Object topStackElement() throws StackEmptyException {
// Επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
return this.S[this.top];
}
public void pushStackElement(Object stud) throws StackFullException {
// Εισάγει ένα νέο στοιχείο στην κορυφή της Στοίβας
//if (this.getStackSize() == this.stackCapacity - 1) // Στις σημειώσεις έχει αυτή τη γραμμή αλλά δεν επιστρέφει σωστό μέγεθος της Στοίβας
if (this.getStackSize() == this.stackCapacity) // Αυτή η γραμμή φαίνεται να επιστρέφει σωστό μέγεθος της Στοίβας
throw new StackFullException(MSG_STACK_FULL);
//System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[++this.top] = stud; // ΠΡΟΣΟΧΗ! Πρώτα αυξάνει το top και μετά εισάγει το στοιχείο (item) στον πίνακα
//System.out.println("*** Top after push: " + this.top); // FOR TESTS
}
public Object popStackElement() throws StackEmptyException {
// Εξάγει και επιστρέφει το στοιχείο που βρίσκεται στην κορυφή της Στοίβας
Object tmpElement;
if (this.stackIsEmpty())
throw new StackEmptyException(MSG_STACK_EMPTY);
tmpElement = this.S[top];
// System.out.println("*** Top before push: " + this.top); // FOR TESTS
this.S[this.top--] = null; // ΠΡΟΣΟΧΗ! Πρώτα θέτει null στη θέση του top για τον garbage collector (εκκαθάριση της μνήμης από τα "σκουπίδια") και μετά το μειώνει
// System.out.println("*** Top after push: " + this.top); // FOR TESTS
return tmpElement;
}
// Added by Panos
public void showAllStackElements() { // ΝΑ ΔΙΝΩ ΣΑΝ ΠΑΡΑΜΑΕΤΡΟ ΤΗΝ ΚΛΑΣΗ ΠΟΥ ΘΕΛΩ, ΝΑ ΕΛΕΓΧΕΙ ΑΝ ΤΟ ΑΝΤΙΚΕΙΜΕΝΟ ΕΙΝΑΙ ΑΥΤΗΣ ΤΗΣ ΚΛΑΣΗΣ ΚΑΙ ΝΑ ΤΟ ΤΥΠΩΝΕΙ
if (this.stackIsEmpty())
System.out.println("Η Στοίβα είναι κενή.");
// else {
//// ΓΙΑ ΕΜΦΑΝΙΣΗ ΣΥΜΦΩΝΑ ΜΕ ΤΗ ΘΕΩΡΗΤΙΚΗ ΔΙΑΤΑΞΗ ΤΗΣ ΣΤΟΙΒΑΣ (ΦΘΙΝΟΥΣΑ) ΟΛΩΝ ΤΩΝ ΣΤΟΙΧΕΙΩΝ ΤΗΣ ΣΤΟΙΒΑΣ ΕΝΕΡΓΟΠΟΙΟΥΜΕ ΤΑ ΠΑΡΑΚΑΤΩ
// for (int i = this.top; i >= 0; i--)
// System.out.println("Ονοματεπώνυμο: " + S[i].getLastName() + ", " + S[i].getFirstName() + ", ΑΜ: " + S[i].getAM());
// Ή ΓΙΑ ΚΑΝΟΝΙΚΗ ΕΜΦΑΝΙΣΗ (ΑΥΞΟΥΣΑ ΣΥΜΦΩΝΑ ΜΕ ΤΗΝ ΠΡΑΓΜΑΤΙΚΗ ΘΕΣΗ) ΟΛΩΝ ΤΩΝ ΣΤΟΙΧΕΙΩΝ ΤΗΣ ΣΤΟΙΒΑΣ ΕΝΕΡΓΟΠΟΙΟΥΜΕ ΤΑ ΠΑΡΑΚΑΤΩ
// for (int i = 0; i < this.top + 1; i++)
// System.out.println("Ονοματεπώνυμο: " + S[i].getLastName() + ", " + S[i].getFirstName() + ", ΑΜ: " + S[i].getAM());
// }
} // Added by Panos
}
| panosale/DIPAE_DataStructures_3rd_Term | Askisi2 (alternative)/src/ArrayStack.java |
1,657 | package Control;
import java.sql.SQLException;
import Model.DataBaseHandler;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.HPos;
import javafx.geometry.Pos;
import javafx.scene.Cursor;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
public class ChangeShippingNumberHandler implements EventHandler<ActionEvent>
{
private DataBaseHandler myDB;
private Stage stage;
private Scene scene;
private Button select;
private Button cancel;
private HBox hbox;
private VBox vbox;
private TextField textField;
public ChangeShippingNumberHandler()
{
this.myDB = DataBaseHandler.getInstance();
}
@Override
public void handle(ActionEvent arg0)
{
stage = new Stage();
createButtons();
createBoxes();
scene = new Scene(vbox, 400, 400);
scene.getStylesheets().add("application.css");
createStage();
vbox.setAlignment(Pos.BASELINE_CENTER);
vbox.setStyle("-fx-background-color: grey;");
textField = new TextField();
GridPane gridPane = new GridPane();
gridPane.setHgap(10);
gridPane.setVgap(10);
Label checkInlabel;
Label currentShippingNumber;
checkInlabel = new Label("Εισάγετε τον επιθυμητό αριθμό αποστολής:");
checkInlabel.setStyle("-fx-font-weight: bold; -fx-text-fill: white;");
gridPane.add(checkInlabel, 0, 0);
GridPane.setHalignment(checkInlabel, HPos.CENTER);
try {
currentShippingNumber = new Label("Τρέχον Αριθμός Αποστολής = "+myDB.getShippingInvoiceNumber());
currentShippingNumber.setStyle("-fx-font-weight: bold; -fx-text-fill: white;");
gridPane.add(currentShippingNumber, 0, 1);
GridPane.setHalignment(currentShippingNumber, HPos.CENTER);
} catch (SQLException e2) {
errorWindow(e2.getMessage());
// TODO Auto-generated catch block
e2.printStackTrace();
}
gridPane.add(textField, 0, 2);
gridPane.add(hbox, 0, 3);
gridPane.setAlignment(Pos.CENTER);
vbox.getChildren().add(gridPane);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
scene.setOnKeyPressed(new EventHandler<KeyEvent>()
{
@Override
public void handle(KeyEvent ke)
{
if (ke.getCode().equals(KeyCode.ENTER))
{
getValueAction();
}
}
});
}
private void createButtons()
{
select = new Button("Επιλογή");
cancel = new Button("Ακύρωση");
cancel.setId("exitButton");
select.setMaxWidth(Double.MAX_VALUE);
cancel.setMaxWidth(Double.MAX_VALUE);
select.setCursor(Cursor.HAND);
cancel.setCursor(Cursor.HAND);
cancel.setOnAction(new EventHandler<ActionEvent>() {
@Override public void handle(ActionEvent e) {
stage.close();
}
});
select.setOnAction(new EventHandler<ActionEvent>()
{
@Override public void handle(ActionEvent e)
{
getValueAction();
}
});
}
private void getValueAction()
{
String text = textField.getText();
if(text.length() == 1 && text.equals("0"))
{
warningWindowForFlag(text);
}else if(text == null || text.trim().isEmpty())
{
warningWindowForFlag(text);
}else if(text.matches("[0-9]*"))
{
if(text.length()<8 && Long.parseLong(text)<9999999)
{
try {
myDB.setShippingInvoiceNumber(text);
rigthWindow(text);
stage.close();
} catch (NumberFormatException | SQLException e1) {
errorWindow(e1.getMessage());
e1.printStackTrace();
}
}else if(text.length()==7 && Long.parseLong(text)==9999999)
{
try {
myDB.setShippingInvoiceNumber(text);
maxNumberWindow(text);
stage.close();
} catch (SQLException e1) {
errorWindow(e1.getMessage());
e1.printStackTrace();
}
}else
{
warningWindowForFlag(text);
}
// stage.close();
}else
{
warningWindowForFlag(text);
}
}
private void createBoxes()
{
hbox = new HBox(5, select, cancel);
hbox.setAlignment(Pos.BASELINE_CENTER);
vbox = new VBox(20);
vbox.setStyle("-fx-padding: 10;");
}
private void createStage()
{
stage.setScene(scene);
stage.setTitle("Αλλαγή Αριθμού Αποστολής");
stage.setHeight(370);
stage.setWidth(300);
stage.setResizable(false);
}
private void warningWindowForFlag(String text)
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Σφάλμα");
alert.setHeaderText("Ο '"+text+"' δεν αποτελεί έγκυρο Αριθμό Αποστολής!");
alert.setContentText("Παρακαλώ εισάγετε έναν έγκυρο Αριθμό Αποστολής πρωτού συνεχίσετε.\nΕπιτρέπονται μόνο αριθμοί μέχρι 7 ψηφίων οι οποίοι είναι μεταξύ 0 και 9999999.");
alert.showAndWait();
}
private void rigthWindow(String text)
{
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Επιτυχής Εκτέλεση!");
alert.setHeaderText("Επιτυχής ενημέρωση Αριθμού Αποστολής!");
alert.setContentText("Ο νέος Αριθμός Αποστολής -> '" + text +"'");
alert.showAndWait();
}
private void maxNumberWindow(String text)
{
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Ειδοποίηση");
alert.setHeaderText("Επιτυχής ενημέρωση Αριθμού Αποστολής!\nΜέγιστη καταχώρηση!");
alert.setContentText("Ο νέος Αριθμός Αποστολής -> '" + text +"'.\nΗ τρέχουσα παραγγελία θα ενημερωθεί με αυτόν τον αριθμό αποστολής.\nΕπειδή όμως καταχωρήσατε τον μέγιστο επιτρεπτό Αριθμό Αποστολής δεν θα προσαυξηθεί κατά 1 όπως πάντα αλλά θα καταχωρηθεί η τιμή 1 αυτόματα στην επόμενη παραγγελία!");
alert.showAndWait();
}
private void errorWindow(String errorMessage)
{
Alert alert = new Alert(Alert.AlertType.ERROR);
alert.setTitle("Σφάλμα");
alert.setHeaderText(null);
alert.setContentText(errorMessage);
alert.showAndWait();
}
}
| johnprif/Database-Toolbox | src/Control/ChangeShippingNumberHandler.java |
1,658 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Boolean Expressions. Αποφασίζει αν χιονίζει
* με βάση όχι μόνο τη θερμοκρασία, αλλά κα το
* αν βρέχει. Αν βρέχει και η θερμοκρασία είναι
* < 0, τότε χιονίζει, αλλιώς όχι
*/
public class BoolApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean isRaining = false;
boolean isSnowing = false;
int temp = 0;
System.out.println("Please insert if is raining (true/false)");
isRaining = in.nextBoolean();
System.out.println("Please insert temperature (int)");
temp = in.nextInt();
isSnowing = isRaining && temp < 0;
System.out.println("Is snowing: " + isSnowing);
}
}
| a8anassis/cf4 | src/gr/aueb/cf/ch3/BoolApp.java |
1,660 | package gr.aueb.codingfactory.exr.ch3;
/*
Θέλουμε να αναπτύξουμε ένα πρόγραμμα που να αποφαίνεται αν ένα έτος είναι δίσεκτο ή όχι
Δηλαδή να προτρέπει τον χρήστη να δώσει ένα έτος από το πληκτρολόγιο, να διαβάζει
με Scanner το έτος (ακέραιος), να κάνει την επεξεργασία και να εμφανίζει
στην οθόνη αν το έτος αυτό είναι δίσεκτο ή όχι. Δίσεκτο είναι ένα έτος αν έχει 366 ημέρες, αντί 365. Πότε όμως ένα έτος έχει 366 ημέρες
Αν διαιρείται με το 4 ΕΚΤΟΣ ΕΆΝ
Διαιρείται ακριβώς και με το 100
Αλλά όχι με το 400.
Άλλος τρόπος να το εκφράσουμε πιο απλά είναι: ένα έτος είναι δίσεκτο
αν (διαιρείται ακριβώς με το 4 και όχι με το 100) ή αν (διαιρείται ακριβώς με το 400)
Σύμφωνα με τον ορισμό του δίσεκτου έτους αν ένα έτος διαιρείται με το 4 (και όχι με το 100)
τότε είναι δίσεκτο, Για αυτό τα έτη 1904, 1908, 1964, 2004, 2008, 2012, 2016, 2020 ΕΊΝΑΙ δίσεκτα
Ωστόσο, τα ακόλουθα έτη1700, 1800, 1900, 2100, 2200, 2300, 2500, 2600 ΔΕΝ είναι δίσεκτα,
επειδή διαιρούνται μεν με το 4 αλλά διαιρούνται και με το 100 αλλά ΟΧΙ και με το 400
Τα ακόλουθα έτη: 1600, 2000, 2400ΕΙΝΑΙ δίσεκτα, επειδή διαιρούνται με το 4,
διαιρούνται και με το 100 αλλά και με το 400 (ή απλά επειδή διαιρούνται με το 400)
*/
import java.util.Scanner;
public class ExerciseOneCh3 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int yearInput = 0;
boolean leap = false;
System.out.println("Insert year to check if is a leap year or not: ");
yearInput = in.nextInt();
boolean parameterOne = ((yearInput%4)==0);
boolean parameterTwo = ((yearInput%100)==0);
boolean parameterThree = ((yearInput%400)==0);
if ((parameterOne && !parameterTwo)){
leap = true;
System.out.printf("The year: %d is a leap! Divided by 4!",yearInput);
} else if (parameterOne && !parameterTwo && parameterThree) {
leap = true;
System.out.printf("The year: %d is a leap! Divided by 4 and 100!",yearInput);
} else if ((parameterOne && parameterTwo && parameterThree)) {
leap = true;
System.out.printf("The year: %d is a leap! Divided by 4 and 100 and 400!",yearInput);
} else {
System.out.printf("The year: %d is not a leap!",yearInput);
}
}
}
| purplebeam/Java-CF-Chapters | src/gr/aueb/codingfactory/exr/ch3/ExerciseOneCh3.java |
1,662 |
package aem2521;
import java.util.ArrayList;
import java.util.List;
/**
* @author Sotiria Antaranian
*/
public class KnapSack
{
List<Integer> accepted; //λίστα με τους πελάτες που δέχεται
/**
* συγκρίνει δυο πραγματικούς αριθμούς και επιστρέφει το μεγαλύτερο
* @param a
* @param b
* @return το μεγαλύτερο
*/
float max(float a, float b)
{
return (a > b)? a : b;
}
/**
* Η δεύτερη λειτουργία λύνεται όπως το πρόβλημα του σάκου, δυναμικά, όπου η χωρητικότητα του σάκου είναι οι διαθέσιμοι πυρήνες σε όλους τους servers,
* τα βάρη των στοιχείων είναι οι απαιτήσεις σε πυρήνες του κάθε πελάτη,
* η αξία κάθε στοιχείου είναι το συνολικό ποσό που θα πληρώσει ο κάθε πελάτης σύμφωνα με την προσφορά του ανά πυρήνα και
* το πλήθος των στοιχείων είναι το πλήθος των πελατών.
* Σκοπός είναι να βρεθεί το πολυτιμότερο υποσύνολο των στοιχείων που χωράνε στο σάκο.
* Για κάθε στοιχείο θα ισχύουν δυο περιπτώσεις: είτε δεν θα χωράει (wt[i-1]>w), οπότε η βέλτιστη λύση θα είναι ίδια με την περίπτωση για i-1 στοιχεία,
* είτε χωράει αλλά θα μπει αν val[i-1]+V[i-1][w-wt[i-1]] > V[i-1][w] , αλλιώς δεν θα μπει και η βέλτιστη λύση θα είναι πάλι η ίδια με την περίπτωση για i-1 στοιχεία.
* Η πολυπλοκότητα, χωρική και χρονική, του προβλήματος του σάκου είναι Θ(n*W) όπου n το πλήθος των στοιχείων και W η χωριτηκότητα του σάκου και προκύπτει από τα εμφολευμένα δύο for.
*
* Για την εύρεση των πελατών που γίνονται δεκτοί, ξεκινώντας από το τελευταίο δεξιά κελί του πίνακα που προέκυψε από την εκτέλεση του αλγορίθμου knap sack,
* συγκρίνουμε κάθε κελί με το κελί πάνω του και αν είναι διαφορετικό τότε ο πελάτης που πρέπει να πληρώσει το ποσό του κελιού γίνεται δεκτός.
* Σε αυτή την περίπτωση μετακινούμαστε προς τα αριστερά στο πίνακα, στο κελί που βρίσκεται στη στήλη για τους διαθέσιμους πυρήνες χωρίς τους πυρήνες που ζήτησε ο πελάτης που έγινε δεκτός,στην ακριβώς από πάνω γραμμή.
* Μετά συγκρίνουμε το περιεχόμενο του κελιού με το από πάνω του κ.ο.κ.
* Σε κάθε περίπτωση, αν τα κελιά που συγκρίνουμε είναι ίδια, πάμε στην ακριβώς από πάνω γραμμή (στην ίδια στήλη) και συγκρίνουμε το κελί σε αυτή τη γραμμή με το από πάνω του κ.ο.κ.
* Για την εύρεση των αποδεκτών πελατών η πολυπλοκότητα είναι Ο(n+W) στη χειρότερη περίπτωση.
* Η συνολική πολυπλοκότητα είναι Ο(n*W+n+W).
*
* @param W η χωρητικότητα του σάκου
* @param wt πίνακας με τα βάρη των n στοιχείων
* @param val πίνακας με την αξία του κάθε στοιχείου
* @param n το πλήθος των στοιχείων
* @return συνολικό ποσό πληρωμής από όλους τους πελάτες
*/
float knapSack(int W,int wt[],float val[],int n)
{
accepted=new ArrayList<>();
float [][]V=new float[n+1][W+1];
for(int i=0;i<=n;i++) //πολυπλοκότητα Ο(n)
{
for(int w=0;w<=W;w++) //πολυπλοκότητα O(W)
{
if(i==0 || w==0)
V[i][w]=0;
else if(wt[i-1]-w<=0) //χωράει
V[i][w]=max(val[i-1]+V[i-1][w-wt[i-1]],V[i-1][w]);
else //δεν χωράει
V[i][w]=V[i-1][w];
}
}
int k=n;
int j=W;
while(j!=0)
{
if(V[k][j]!=V[k-1][j]) //δεκτός πελάτης
{
accepted.add(k);
j=j-wt[k-1]; //αλλαγή στήλης
}
k--; //αλλαγή γραμμής
if(k==0)//αν όλα τα στοιχεία μιας στήλης είναι ίδια, πάει στο τελευταίο στοιχείο της αριστερής του στήλης
{
k=n;
j--;
}
}
return V[n][W];
}
}
| sotiria3103/visual-machine-assigning | src/aem2521/KnapSack.java |
1,663 | public class Baby {
String name;
double weight = 4.0;
boolean isABoy;
int numTeeth = 0;
public Baby(String name, boolean boy)
{
this.name = name;
this.isABoy = boy;
}
public static void main(String[] args) {
// Δημιουργούμε το μωρό
Baby george = new Baby("George", true);
// Εμφανίζουμε το όνομά του
System.out.println("New baby is "+george.name);
// Θα εμφανίσει: George
// Αλλάζουμε το όνομά του
george.name = "Nancy"; //το θέλουμε αυτό;
// Εμφανίζουμε το τροποποιημένο όνομά του
System.out.println("New baby is "+george.name);
// Θα εμφανίσει: Nancy
}
}
| riggas-ionio/java | lecture-examples/03-classes-objects-intro/01-member-access/Baby.java |
1,673 | package project2;
import static java.lang.Math.abs;
/**
*
* @author Gthanasis
*/
public abstract class Board
{
private Piece[][] pieces = new Piece[8][8];
private final Color a = Color.WHITE;
private final Color b = Color.BLACK;
private Location loc;
private int scorea=0,scoreb=0;
private int l;
public Board(){}
public Board(int i)
{
l=i;
}
public int get()
{
return l;
}
public Piece getPieceAt(Location loc)
{
return pieces[loc.getRow()][7-loc.getCol()];
}
public Piece getPieceAt(int r, int c)
{
return pieces[r][7-c];
}
public void setPiece(Piece[][] pc)
{
for(int i=0;i<8;i++)
for(int j=0;j<8;j++)
pieces[i][7-j]=pc[i][j];
}
void init()
{
Board br;
br=new Board(1){};
for(int i=2; i<6; i++){
for(int j=0; j<8; j++){
pieces[i][j]=new Empty(i,j,a,br);
}
}
for(int i=0; i<8; i++){
pieces[6][i]=(new Pawn(1,i,b,br));
}
pieces[7][0]=(new Rook(0,0,b,br));
pieces[7][7]=(new Rook(0,7,b,br));
pieces[7][2]=(new Bishop(0, 2, b,br));
pieces[7][5]=(new Bishop(0, 5, b,br));
pieces[7][1]=(new Knight(0, 1, b,br));
pieces[7][6]=(new Knight(0, 6, b,br));
pieces[7][4]=(new Queen(0, 4, b,br));
pieces[7][3]=(new King(0, 3, b,br));
for(int i=0; i<8; i++){
pieces[1][i]=(new Pawn(6,i,a,br));
}
pieces[0][0]=(new Rook(7, 0, a,br));
pieces[0][7]=(new Rook(7, 7, a,br));
pieces[0][2]=(new Bishop(7, 2, a,br));
pieces[0][5]=(new Bishop(7, 5, a,br));
pieces[0][1]=(new Knight(7, 1, a,br));
pieces[0][6]=(new Knight(7, 6, a,br));
pieces[0][4]=(new Queen(7, 4, a,br));
pieces[0][3]=(new King(7, 3, a,br));
print();
}
public void print()
{/*Εκτύπωση κομματιών χωρίς αποθήκευση σε στρινγκ μετά απο αυτή ακολουθεί
και η συνάρτηση toString() που μπορεί να κάνει το ίδιο αλλά τα αποθηκέυει σε κατάλληλο αλφαριθμητικό*/
System.out.print(" ");
for(char ch = 'a' ; ch <= 'h' ; ch++ )
System.out.print(ch);
System.out.println();
for (int i=7;i>=0;i--){
System.out.print((i+1)+" ");
for (int j=7;j>=0;j--){
if(pieces[i][j]!=null)
if (pieces[i][j].toString().equals("r") ){
//if (pieces[i][j].c==0 ||pieces[i][j].c==7){
if (pieces[i][j].color==a)
System.out.print("R");
else
System.out.print("r");
}
else if (pieces[i][j].toString().equals("b")){
if (pieces[i][j].color==a)
System.out.print("B");
else
System.out.print("b");
}
else if (pieces[i][j].toString().equals("k")){
if (pieces[i][j].color==a)
System.out.print("K");
else
System.out.print("k");
}
else if (pieces[i][j].toString().equals("q")){
if (pieces[i][j].color==a)
System.out.print("Q");
else
System.out.print("q");
}
else if (pieces[i][j].toString().equals("n")){
if (pieces[i][j].color==a)
System.out.print("N");
else
System.out.print("n");
}
else if (pieces[i][j].toString().equals("p")){
if (pieces[i][j].color==a)
System.out.print("P");
else
System.out.print("p");
}
else System.out.print(" ");
}
System.out.print(" "+(i+1));
System.out.print(" |");
if (i==7) System.out.print(" SCORE");
else if (i==5) System.out.print(" WHITE | BLACK");
else if (i==3) System.out.printf(" %d %d", scorea, scoreb);
System.out.println();
}
System.out.print(" ");
for(char ch = 'a' ; ch <= 'h' ; ch++ )
System.out.print(ch);
System.out.println();
}
@Override
public String toString()
{
String str;
str=(" ");
for(char ch = 'a' ; ch <= 'h' ; ch++ )
str=str+ch;
str=str+"\n";
for (int i=7;i>=0;i--){
str=str+((i+1)+" ");
for (int j=7;j>=0;j--){
if(pieces[i][j]!=null)
if (pieces[i][j].toString().equals("r") ){
if (pieces[i][j].color==a)
str=str+"R";
else
str=str+"r";
}
else if (pieces[i][j].toString().equals("b")){
if (pieces[i][j].color==a)
str=str+"B";
else
str=str+"b";
}
else if (pieces[i][j].toString().equals("k")){
if (pieces[i][j].color==a)
str=str+"K";
else
str=str+"k";
}
else if (pieces[i][j].toString().equals("q")){
if (pieces[i][j].color==a)
str=str+"Q";
else
str=str+"q";
}
else if (pieces[i][j].toString().equals("n")){
if (pieces[i][j].color==a)
str=str+"N";
else
str=str+"n";
}
else if (pieces[i][j].toString().equals("p")){
if (pieces[i][j].color==a)
str=str+"P";
else
str=str+"p";
}
else str=str+" ";
}
str=str+(" "+(i+1));
str=str+"\n";
}
str=str+(" ");
for(char ch = 'a' ; ch <= 'h' ; ch++ )
str=str+(ch);
str=str+"\n";
//System.out.println(str);
return str;
}
public void movePiece(Location from, Location to)
{//kinhsh kommatiou otan h telikh thesh einai kenh
int r,c,r2,c2;
r=from.getRow();
c=from.getCol();
r2=to.getRow();
c2=to.getCol();
Piece temp = pieces[r][7-c];
pieces[r][7-c] = pieces[r2][7-c2];
pieces[r2][7-c2] = temp;
}
public void movePieceCapturing(Location from, Location to)
{//kinhsh kommatiou otan h telikh thesh einai kateilhmenh apo antipalo kommati
int r,c,r2,c2;
r=from.getRow();
c=from.getCol();
r2=to.getRow();
c2=to.getCol();
Piece temp = pieces[r][7-c];
Board bb=temp.brd;
String s = pieces[r2][7-c2].toString();
Color cl = pieces[r2][7-c2].color;
pieces[r][7-c] = new Empty(r,7-c,a,bb);
pieces[r2][7-c2] = temp;
if(cl==a){//auxhsh antistoixou score
if(s.equals("p"))scoreb++;
else if(s.equals("r"))scoreb+=5;
else if(s.equals("n"))scoreb+=3;
else if(s.equals("b"))scoreb+=3;
else if(s.equals("q"))scoreb+=9;
}
else{
if(s.equals("p"))scorea++;
else if(s.equals("r"))scorea+=5;
else if(s.equals("n"))scorea+=3;
else if(s.equals("b"))scorea+=3;
else if(s.equals("q"))scorea+=9;
}
}
public boolean freeHorizontalPath(Location from, Location to)
{
return (to.getRow() == from.getRow());
}
public int movePawn(Location from, Location to)
{//kapoioi apo tous elegxous gia th kinhshs tou pioniou sthn katallhlh kateuthunsh
if (freeVerticalPath(from, to)){
//if(pieces[from.getRow()][7-from.getCol()]!=null)
if(pieces[from.getRow()][7-from.getCol()].color==a){
if (from.getRow()==1||from.getRow()==6){
if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){
for(int i=(to.getRow());i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){
for(int j=(7-from.getCol());j>=(7-to.getCol());j--){
if (pieces[i][j].toString().equals("e")){
}
else{
System.out.println("\n--There is another piece in this position\n");
return -1;
}
}
}
return 1;
}
}
else if ((to.getRow()-from.getRow())==1){
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else{
System.out.println("\n--There is another piece in this position\n");
return -1;
}
}
else{
return -1;
}
}
else {
if (abs(to.getRow()-from.getRow())>=1 && abs(to.getRow()-from.getRow())<=2){
try{
for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){
for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){
if (pieces[i][j].toString().equals("e")){
}
else{
System.out.println("\n--There is another piece in this position\n");
return -1;
}
}
}
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("\n--There is another piece in this position\n");
return -1;
}
return 1;
}
else if ((to.getRow()-from.getRow())==-1){
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else{
System.out.println("\n--There is another piece in this position\n");
return -1;
}
}
else{
return -1;
}
}
}
else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){
if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){
if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
}
return -1;
}
public int moveRook(Location from, Location to)
{//elegxoi gia kinhshs tou purgou ekei pou prepei
if (freeVerticalPath(from, to)){
if(to.getRow()>from.getRow()){
for(int i=(to.getRow())-1;i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){
for(int j=(7-from.getCol());j>=(7-to.getCol());j--){/*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs
**afou to komati den mporei na perasei an uparxei allo komati ekei*/
if (pieces[i][j].toString().equals("e")){
}
else return -1;
}
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
else{
for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){
for(int j=abs(7-to.getCol());j>=abs(7-to.getCol());j--){
if (pieces[i][j].toString().equals("e")){
}
else return -1;
}
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
return 1;
}
else if (freeHorizontalPath(from, to)){
if(to.getCol()>from.getCol()){
for(int i=abs(to.getRow());i>=abs(to.getRow());i--){
for(int j=(to.getCol())-1;j>(to.getCol())-abs(to.getCol()-from.getCol());j--){
/*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs
**afou to komati den mporei na perasei an uparxei allo komati ekei*/
if (pieces[to.getRow()][7-j].toString().equals("e")){
}
else return -1;
}
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
else{
for(int i=abs(to.getRow());i>=abs(to.getRow());i--){
for(int j=abs(7-(to.getCol())-1);j>(7-from.getCol());j--){
if (pieces[i][j].toString().equals("e")){
}
else return -1;
}
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
return 1;
}
return -1;
}
public int moveBishop(Location from, Location to)
{//kapoioi apo tous elegxous gia th kinhshs tou axiomatikou stis katallhles kateuthunseis
if(to.getRow()>from.getRow()){
if (freeDiagonalPath(from, to)){
int j=(to.getCol()-1);
for(int i=(to.getRow()-1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){
/*elegxos gia kena sta endiamesa tetragona tou komatiou kai ths telikhs theshs
**afou to komati den mporei na perasei an uparxei allo komati ekei*/
if (j>(to.getCol())-abs(to.getCol()-from.getCol())){
if (pieces[i][7-j].toString().equals("e")){
}
else return -1;
}
j--;
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
return 1;
}
else if (freeAntidiagonalPath(from, to)){
int j=abs(7-(to.getCol()+1));
for(int i=(to.getRow()-1);i>(to.getRow()-abs(to.getRow()-from.getRow()));i--){
if(j>(7-from.getCol())){
if (pieces[i][j].toString().equals("e")){
System.out.println(i+" "+j);
}
else return -1;
}
j--;
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
return 1;
}
else System.out.println("Bishops can only move diagonally or antidiagonally");
return -1;
}
else{
if (freeDiagonalPath(from, to)){
int j=(7-from.getCol());
for(int i=abs(from.getRow()-1);i>=abs(to.getRow());i--){
if(j<=abs(7-(to.getCol()))){
if (pieces[i][j].toString().equals("e")){
}
else return -1;
}
j++;
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
return 1;
}
else if (freeAntidiagonalPath(from, to)){
int j=(to.getCol()-1);
for(int i=(to.getRow()+1);i>(to.getRow())-abs(to.getRow()-from.getRow());i--){
if (j>(to.getCol())-abs(to.getCol()-from.getCol())){
if (pieces[i][7-j].toString().equals("e")){
}
else return -1;
}
j--;
}
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
return 1;
}
else System.out.println("Bishops can only move diagonally or antidiagonally");
return -1;
}
}
public int moveKnight(Location from, Location to)
{// kinhsh tou ippou
if (freeKnightsPath(from, to)){
/*elegxos mono an to tetragono sto opoio paei einai keno*/
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
//an einai idiou xromatos den mporei na paei
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;/*an einai diaforetikou epistrefei ton katallhlo arithmo sto knight etsi oste na kalestei
h movepiececapturing apo ekei kai na 'faei'-apomakrunei to antipalo kommati*/
}
}
return -1;
}
int moveKing(Location from, Location to)
{//kinhsh tou basilia
if (freeVerticalPath(from, to)){
if ((to.getRow()-from.getRow())==1){
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
}
if (freeHorizontalPath(from, to)){
if (abs(7-to.getCol()-(7-from.getCol()))==1){
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
}
else if (freeDiagonalPath(from, to)||freeAntidiagonalPath(from, to)){
if (abs(to.getRow()-from.getRow())==1||abs(to.getCol()-from.getCol())==1){
if (pieces[to.getRow()][7-to.getCol()].toString().equals("e")){
return 1;
}
else if(pieces[to.getRow()][7-to.getCol()].color==pieces[from.getRow()][7-from.getCol()].color){
return -1;
}
else if (!pieces[to.getRow()][7-to.getCol()].toString().equals("e")&&pieces[to.getRow()][7-to.getCol()].color!=pieces[from.getRow()][7-from.getCol()].color){
return 2;
}
}
}
return -1;
}
public boolean freeVerticalPath(Location from, Location to)
{
return (to.getCol() == from.getCol());
}
public boolean freeDiagonalPath(Location from, Location to)
{
return (to.getRow() - from.getRow() == to.getCol() - from.getCol());
}
public boolean freeAntidiagonalPath(Location from, Location to)
{
return (abs(to.getRow() - from.getRow()) == abs((7-to.getCol()) - (7-from.getCol())));
}
public boolean freeKnightsPath(Location from, Location to)
{
boolean knight;
knight = (to.getRow() == from.getRow() - 2 || to.getRow() == from.getRow() + 2);
if (knight)
knight = (to.getCol() == from.getCol() - 1 || to.getCol() == from.getCol() + 1 );
if (knight) return true;
knight = (to.getRow() == from.getRow() - 1 || to.getRow() == from.getRow() + 1);
if (knight)
knight = (to.getCol() == from.getCol() - 2 || to.getCol() == from.getCol() + 2 );
return knight;
}
}
| NasosG/cmd-chess-java | cmdChess/src/project2/Board.java |
1,674 | package thesis;
// 1) When I insert a course into another course above it, I have to check the availability of the new course and if thats okay, I can add the course into the timeslot BUT for the course
// that was already there, I have to make sure to remove it from the table and add it back to the CoursesPanel
// 2) When I inesrt a course into the table, it adds the courseclassroomspanel. But, if i double click to remove it, it wont do anything.
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DateFormatSymbols;
import java.text.Normalizer;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.TransferHandler;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableCellRenderer;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.gmele.general.sheets.XlsxSheet;
import org.gmele.general.sheets.exception.SheetExc;
/**
* Η κλάση ScheduleManager κληρονομείται από την κλάση JFrame και είναι υπεύθυνη
* για την διαχείριση του παραθύρου της δημιουργίας του προγράμματος εξεταστικής.
*
* @author Nektarios Gkouvousis
* @author ice18390193
*/
public class ScheduleManager extends JFrame {
private String[] weekdays = { "ΚΥΡΙΑΚΗ", "ΔΕΥΤΕΡΑ", "ΤΡΙΤΗ", "ΤΕΤΑΡΤΗ", "ΠΕΜΠΤΗ", "ΠΑΡΑΣΚΕΥΗ", "ΣΑΒΒΑΤΟ" };
private Map<Character, Integer> coursesSemesters = new HashMap<>();
char[] greekSemesters = {'Α', 'Β', 'Γ', 'Δ', 'Ε', 'Ζ', 'Η'};
private JTable table;
private ExcelManager excelManager1;
private Map<Course, CourseClassroomsPanel> courseToPanelMap;
Definitions def;
private List<Professor> professors;
private List<Course> courses;
private List<Classroom> classrooms;
private List<String> dates;
private List<String> timeslots;
private DefaultTableModel model;
private int excelRows, excelCols;
private Logs logs;
private List<ScheduledCourse> scheduledCourses;
private Unscheduled unscheduled;
private List<ExamCoursesFromFinalSchedule> crsList;
private String finalExcelSheet;
private String regex;
private JPanel coursesClassroomsPanel;
private Utilities utils;
private LoadingPanel lp;
public ScheduleManager(ExcelManager excelManager) {
initComponents();
excelManager1 = excelManager;
initOtherComponents();
}
public void initOtherComponents() {
lp = new LoadingPanel();
utils = new Utilities();
courses = new ArrayList<>(excelManager1.getCourses());
classrooms = new ArrayList<>(excelManager1.getClassrooms());
dates = new ArrayList<>(excelManager1.getDates());
timeslots = new ArrayList<>(excelManager1.getTimeslots());
scheduledCourses = new ArrayList<>();
courseToPanelMap = new HashMap<>();
unscheduled = new Unscheduled(excelManager1.getCourses());
crsList = new ArrayList<>();
excelRows = dates.size();
excelCols = timeslots.size();
logs = new Logs();
def = excelManager1.getDefinitions();
professors = new ArrayList<>(excelManager1.getProfs());
finalExcelSheet = def.getSheet7();
regex = "\\b\\d{2}/\\d{2}/\\d{4}\\b";
modelPanel.setLayout(new BorderLayout());
coursesPanel.setLayout(new GridLayout(0, 3));
JScrollBar verticalScrollBar = coursesScrollPane.getVerticalScrollBar();
verticalScrollBar.setUnitIncrement(20);
coursesClassroomsPanel = new JPanel();
coursesClassroomsPanel.setLayout(new BoxLayout(coursesClassroomsPanel, BoxLayout.Y_AXIS));
jScrollPaneClassrooms.setViewportView(coursesClassroomsPanel);
Dimension jScrollPaneDimensions = new Dimension(200,800);
jScrollPaneClassrooms.setSize(jScrollPaneDimensions);
jScrollPaneClassrooms.setPreferredSize(jScrollPaneDimensions);
jScrollPaneClassrooms.setMaximumSize(jScrollPaneDimensions);
model = new DefaultTableModel(excelRows + 1, excelCols + 1) {
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
public boolean isCellSelected(int row, int column) {
return false;
}
};
initTable();
for (int i = 0; i < greekSemesters.length; i++) {
coursesSemesters.put(greekSemesters[i], i + 1);
}
}
public void startProcess(boolean isNew) {
modelPanel.add(populateTable());
populateCourses();
if (!isNew) {
fillCoursesWithReadExcelScheduleData();
createScheduledCourseClassroomsPanels();
sortAndReorderPanels(coursesClassroomsPanel);
} else {
}
this.setVisible(true);
this.setSize(1450, 900);
this.setLocationRelativeTo(null);
}
public void initTable() {
prepareTableRenderer();
this.table.setDropTarget(new DropTarget() {
@Override
public synchronized void drop(DropTargetDropEvent evt) {
Point dropLocation = evt.getLocation();
int row = table.rowAtPoint(dropLocation);
int col = table.columnAtPoint(dropLocation);
handleDroppedCourse(row, col, evt);
}
});
this.table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
if (e.getClickCount() == 2) {
int selectedRow = table.getSelectedRow();
int selectedColumn = table.getSelectedColumn();
removeCourseFromTable(selectedRow, selectedColumn);
}
}
});
this.table.setCellSelectionEnabled(false);
this.table.setTableHeader(new JTableHeader());
this.table.getTableHeader().setReorderingAllowed(false);
//this.table.setShowGrid(true);
//this.table.setGridColor(Color.BLACK);
}
/**
* Η μέθοδος χρησιμοποιείται για την συμπλήρωση των headers των ημερομηνιών και
* των χρονικών διαστημάτων.
*
* @return Ένα παράθυρο με εμπεριέχει τον πίνακα που δημιουργήσαμε (JScrollPane).
*/
public JScrollPane populateTable() {
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
for (int j = 0; j < excelCols; j++) {
model.setValueAt(timeslots.get(j), 0, j + 1);
}
for (int i = 0; i < excelRows; i++) {
LocalDate date = LocalDate.parse(dates.get(i), dateFormatter);
String greekDayName = date.getDayOfWeek().getDisplayName(TextStyle.FULL, Locale.forLanguageTag("el-GR"))
.toUpperCase();
String greekDayNameWithoutAccents = Normalizer.normalize(greekDayName, Normalizer.Form.NFD)
.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");
model.setValueAt(dates.get(i) + " " + greekDayNameWithoutAccents, i + 1, 0);
}
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
return scrollPane;
}
/**
* Η μέθοδος χρησιμοποιείται για την δημιουργία των αντικειμένων των μαθημάτων
* στο panel στο κάτω μέρος του κεντρικού παραθύρου.
*/
public void populateCourses() {
List<Course> notSettled = new ArrayList<>(unscheduled.getCourses());
for (Course course : notSettled) {
// Create a custom component (e.g., JPanel or JButton) for each course
JButton courseButton = new JButton();
courseButton = createCourseBtn(course);
coursesPanel.add(courseButton);
}
}
/**
* Η μέθοδος χρησιμοποιείται για την δημιουργία ενός JButton που αντιστοιχεί
* σε ένα μάθημα.
*
* @param crs Αντικείμενο μαθήματος (Course).
* @return Ένα κουμπί για το μάθημα (JButton).
*/
private JButton createCourseBtn(Course crs) {
JButton courseButton = new JButton(crs.getCourseName());
courseButton.setPreferredSize(new Dimension(270, 40)); // Set preferred size as needed
courseButton.setTransferHandler(new ButtonTransferHandler(crs.getCourseName()));
courseButton.addMouseListener(new java.awt.event.MouseAdapter() {
public void mousePressed(java.awt.event.MouseEvent evt) {
JComponent comp = (JComponent) evt.getSource();
TransferHandler handler = comp.getTransferHandler();
handler.exportAsDrag(comp, evt, TransferHandler.COPY);
}
});
if (crs.getCourseSeason().equals("ΧΕΙΜΕΡΙΝΟ")) {
// courseButton.setBackground(Color.red);
courseButton.setBackground(new Color(102, 178, 255)); // RGB values for light blue
} else {
// courseButton.setBackground(Color.blue);
courseButton.setBackground(new Color(255, 178, 102)); // RGB values for light blue
}
courseButton.setFont(new Font("Segoe UI", Font.PLAIN, 10));
return courseButton;
}
/**
* Η μέθοδος χρησιμοποιείται για την εύρεση του αντικειμένου μαθήματος (Course)
* με βάση το όνομα ή την συντομογραφία του μαθήματος.
*
* @param courseName Το όνομα του μαθήματος (String).
* @return Το αντικείμενο του μαθήματος (εφόσον βρεθεί) ή null (Course).
*/
public Course findCourses(String courseName) {
for (Course course : this.courses) {
if (course.getCourseName().equals(courseName) || course.getCourseShort().equals(courseName)) {
return course;
}
}
return null;
}
/**
* Η μέθοδος χρησιμοποιείται για την δημιουργία και την αρχική παραμετροποίηση
* του πίνακα table.
*/
public void prepareTableRenderer() {
model.setValueAt("ΗΜΕΡΟΜΗΝΙΑ / ΗΜΕΡΑ", 0, 0);
this.table = new JTable(model){
@Override
public Component prepareRenderer(TableCellRenderer renderer, int row, int column) {
Component comp = super.prepareRenderer(renderer, row, column);
Color headerCells = Color.decode("#A9A9A9");
Color firstCell = Color.decode("#3333FF");
Color otherCells = Color.decode("#FFFFFF");
// Πρώτο κελί πρώτη στήλη
if (column == 0 && row == 0) {
comp.setBackground(firstCell);
// Οποιδήποτε κελί στην 1η στήλη
} else if (column == 0) {
comp.setBackground(headerCells);
// Οποιδήποτε κελί στην 1η γραμμή (από την 2η στήλη και μετά)
} else if (row == 0 && column > 0) {
comp.setBackground(headerCells);
// Όλα τα υπόλοιπα κελιά
} else {
comp.setBackground(otherCells);
}
return comp;
}
};
table.setRowHeight(80);
table.setShowGrid(true); // to show the grid
table.setGridColor(Color.GRAY); // you can choose any color
table.getColumnModel().getColumn(0).setPreferredWidth(30); // Example for the first column
table.getColumnModel().getColumn(0).setCellRenderer(new MultiLineCellRenderer());
for (int i = 1; i < table.getColumnCount(); i++) {
table.getColumnModel().getColumn(i).setPreferredWidth(90); // Example for the first column
table.getColumnModel().getColumn(i).setCellRenderer(new MultiLineCellRenderer());
}
table.setFont(new Font("Segoe UI", Font.PLAIN, 11)); // Change the font size to 18
table.repaint();
table.revalidate();
}
public void handleDroppedCourse(int row, int col, DropTargetDropEvent evt) {
try {
// To dropCellContents παίρνει το string από το πεδίο που αφήσαμε το μάθημα
String dropCellContents = (String) table.getValueAt(row, col);
evt.acceptDrop(DnDConstants.ACTION_MOVE);
Transferable transferable = evt.getTransferable();
String buttonText = "";
// buttonText = Το string του Μαθήματος του button
buttonText = (String) transferable.getTransferData(DataFlavor.stringFlavor);
if (row > 0 & col > 0) {
Course tmpCourse = findCourse(buttonText);
String rowValue = (String) table.getValueAt(row, 0);
String colValue = (String) table.getValueAt(0, col);
rowValue = utils.getDateWithGreekFormat(weekdays, rowValue);
boolean check1 = checkExaminersConflict(tmpCourse, rowValue, colValue);
if (check1) {
boolean added = false;
model.setValueAt(buttonText, row, col);
Component[] components = coursesPanel.getComponents();
for (Component component : components) {
if (component instanceof JButton) {
JButton button = (JButton) component;
if (buttonText.equals(button.getText())) {
coursesPanel.remove(button);
coursesPanel.revalidate();
coursesPanel.repaint();
ScheduledCourse sc = new ScheduledCourse(tmpCourse, rowValue, colValue, classrooms);
addCourseToClassroomsPanel(sc, rowValue, colValue);
scheduledCourses.add(sc);
unscheduled.removeCourseFromUnscheduledList(tmpCourse);
added = true;
break;
}
}
}
if (dropCellContents != null && added) {
Course cellCourse = findCourse(dropCellContents);
ScheduledCourse courseToBeRemoved = null;
for (ScheduledCourse tmp : scheduledCourses) {
if (tmp.getCourse().getCourseName() == cellCourse.getCourseName()) {
for (Professor prf : tmp.getCourse().getExaminers()) {
prf.changeSpecificAvailability(rowValue, colValue,1);
}
//System.out.println("------------------------------------------------------ Unscheduled Before: " + tmpCourse.getCourseName());
//unscheduled.printCourses();
//unscheduled.addCourseToUnscheduledList(tmpCourse);
//System.out.println("------------------------------------------------------ Unscheduled After:");
//unscheduled.printCourses();
courseToBeRemoved = tmp;
removeCourseFromClassroomsPanel(cellCourse);
JButton courseButton = new JButton();
courseButton = createCourseBtn(cellCourse);
coursesPanel.add(courseButton);
coursesPanel.revalidate();
coursesPanel.repaint();
break;
}
if(courseToBeRemoved != null){
scheduledCourses.remove(courseToBeRemoved);
}
evt.dropComplete(true);
}
// Μετατροπή της ημερομηνίας από την μορφή 'ηη/μμ/εεεε Ημέρα' to simply
// 'ηη/μμ/εεεε'
}
} else {
JOptionPane.showMessageDialog(this, "Δεν υπάρχουν διαθέσιμοι οι καθηγητές του μαθήματος"
+ " για εκείνη την ημέρα.", "Σφάλμα", JOptionPane.ERROR_MESSAGE);
evt.rejectDrop();
}
}
} catch (UnsupportedFlavorException ex) {
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
} catch (java.awt.dnd.InvalidDnDOperationException ex) {
} catch (IOException ex) {
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
}catch (java.util.ConcurrentModificationException ex){
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}catch (Exception ex){
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
}
}
public void removeCourseFromTable(int selectedRow, int selectedColumn) {
try{
String date = table.getValueAt(selectedRow, 0).toString();
date = utils.getDateWithGreekFormat(weekdays, date);
String timeslot = table.getValueAt(0, selectedColumn).toString();
Object cellValue = model.getValueAt(selectedRow, selectedColumn);
ScheduledCourse courseToDelete = null;
if (utils.checkDate(dates, date) && utils.checkTimeslot(timeslots, timeslot)) {
if (cellValue != null && cellValue instanceof String && selectedRow > 0 && selectedColumn != 0) {
String buttonText = (String) cellValue;
for (ScheduledCourse sc : scheduledCourses) {
if (sc.getScheduledCourse().getCourseName().equals(buttonText)
|| sc.getScheduledCourse().getCourseShort().equals(buttonText)) {
for (Professor prf : sc.getScheduledCourse().getExaminers()) {
prf.changeSpecificAvailability(date, timeslot, 1);
}
courseToDelete = sc;
}
}
if (courseToDelete != null) {
unscheduled.addCourseToUnscheduledList(courseToDelete.getScheduledCourse());
scheduledCourses.remove(courseToDelete);
removeCourseFromClassroomsPanel(courseToDelete.getScheduledCourse());
} else {
try {
String msg = "Πρόβλημα κατά την αφαίρεση του μαθήματος από το κελί. Παρακαλώ πολύ ελέγξτε τα δεδομένα σας και προσπαθήστε ξανά.";
throw new CustomErrorException(ScheduleManager.this, msg);
} catch (CustomErrorException ex) {
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
// Προσθήκη του κουμπιού πίσω στο coursesPanel
JButton courseButton = new JButton();
courseButton = createCourseBtn(courseToDelete.getCourse());
coursesPanel.add(courseButton);
coursesPanel.revalidate();
coursesPanel.repaint();
model.setValueAt(null, selectedRow, selectedColumn);
}
} else {
if (selectedRow == 0 || selectedColumn == 0) {
} else {
try {
String msg = "Πρόβλημα κατά την αφαίρεση του μαθήματος από το κελί. Παρακαλώ πολύ ελέγξτε τα δεδομένα σας και προσπαθήστε ξανά.";
throw new CustomErrorException(ScheduleManager.this, msg);
} catch (CustomErrorException ex) {
Logger.getLogger(ScheduleManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}catch (Exception ex){
System.out.println(ex);
}
}
/**
* Η μέθοδος είναι υπεύθυνη για τον εντοπισμό του μαθήματος από ένα string
*
* @param courseName Το όνομα του μαθήματος προς αναζήτηση
* @return Αντικείμενο Course ή null ανάλογα με το εάν εντοπίστηκε το μάθημα
* από το string ή όχι (Course)
*/
public Course findCourse(String courseName) {
for (Course crs : courses) {
if (crs.getCourseName().equals(courseName) || crs.getCourseShort().equals(courseName)) {
return crs;
}
}
return null;
}
public boolean existsInExamCourses(Course crs){
for(ExamCoursesFromFinalSchedule tmp : crsList){
if(tmp.getCourse().getCourseName().equals(crs.getCourseName())){
return true;
}
}
return false;
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
modelScrollPane = new javax.swing.JScrollPane();
modelPanel = new javax.swing.JPanel();
lblScheduleDesigner = new javax.swing.JLabel();
lblCourses = new javax.swing.JLabel();
lblCoursesClassrooms = new javax.swing.JLabel();
btnExportXlsx = new javax.swing.JButton();
jScrollPaneClassrooms = new javax.swing.JScrollPane();
jLayeredPane1 = new javax.swing.JLayeredPane();
coursesScrollPane = new javax.swing.JScrollPane();
coursesPanel = new javax.swing.JPanel();
autoAddProfessorsToSchedulebtn = new javax.swing.JButton();
btnClear = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Φόρμα Δημιουργίας Προγράμματος");
setResizable(false);
modelScrollPane.setPreferredSize(new java.awt.Dimension(800, 450));
modelPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
modelPanel.setLayout(null);
modelScrollPane.setViewportView(modelPanel);
lblScheduleDesigner.setFont(new java.awt.Font("Franklin Gothic Book", 0, 18)); // NOI18N
lblScheduleDesigner.setText("Σχεδιαστής Προγράμματος Εξεταστικής");
lblCourses.setFont(new java.awt.Font("Franklin Gothic Book", 0, 18)); // NOI18N
lblCourses.setText("Μαθήματα");
lblCoursesClassrooms.setFont(new java.awt.Font("Franklin Gothic Book", 0, 18)); // NOI18N
lblCoursesClassrooms.setText("Μαθήματα - Αίθουσες");
btnExportXlsx.setText("Εξαγωγή");
btnExportXlsx.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
createExcelFromTable(evt);
}
});
jScrollPaneClassrooms.setMaximumSize(new java.awt.Dimension(200, 800));
jScrollPaneClassrooms.setMinimumSize(new java.awt.Dimension(200, 800));
coursesScrollPane.setPreferredSize(new java.awt.Dimension(1000, 300));
coursesPanel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
coursesPanel.setLayout(null);
coursesScrollPane.setViewportView(coursesPanel);
jLayeredPane1.setLayer(coursesScrollPane, javax.swing.JLayeredPane.DEFAULT_LAYER);
javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
jLayeredPane1.setLayout(jLayeredPane1Layout);
jLayeredPane1Layout.setHorizontalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(coursesScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
jLayeredPane1Layout.setVerticalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jLayeredPane1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(coursesScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 324, Short.MAX_VALUE))
);
autoAddProfessorsToSchedulebtn.setText("Αυτόματη Αντιστοίχιση Μαθημάτων");
autoAddProfessorsToSchedulebtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
autoAddProfessorsToSchedulebtncreateExcelFromTable(evt);
}
});
btnClear.setText("Καθαρισμός");
btnClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnClearCreateExcelFromTable(evt);
}
});
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.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addGap(365, 365, 365)
.addComponent(lblScheduleDesigner))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(modelScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 990, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
.addGap(467, 467, 467)
.addComponent(lblCourses)
.addGap(18, 18, 18)
.addComponent(autoAddProfessorsToSchedulebtn, javax.swing.GroupLayout.PREFERRED_SIZE, 222, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnClear)
.addGap(18, 18, 18)
.addComponent(btnExportXlsx)))
.addGap(8, 8, 8)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(lblCoursesClassrooms)
.addGap(89, 89, 89))
.addGroup(layout.createSequentialGroup()
.addGap(23, 23, 23)
.addComponent(jScrollPaneClassrooms, javax.swing.GroupLayout.PREFERRED_SIZE, 320, 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()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblScheduleDesigner)
.addComponent(lblCoursesClassrooms, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(modelScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCourses)
.addComponent(btnExportXlsx)
.addComponent(autoAddProfessorsToSchedulebtn)
.addComponent(btnClear))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLayeredPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jScrollPaneClassrooms, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(32, 32, 32))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void autoAddProfessorsToSchedulebtncreateExcelFromTable(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_autoAddProfessorsToSchedulebtncreateExcelFromTable
try{
JOptionPane.showMessageDialog(null, "Ενημέρωση: Η διαδικασία θα διαρκέσει μερικά δευτερόλεπτα.", "Μήνυμα εφαρμογής", JOptionPane.OK_OPTION );
showLoading();
Unscheduled copy = new Unscheduled(unscheduled);
for(Course course : copy.getCourses()){
boolean placedCourse = false;
List<Availability> professorsAvailability = new ArrayList<>();
List<String> nonAvailableDates = new ArrayList<>(getInvalidExaminationDates(course.getCourseName(), course.getCourseSem()));
professorsAvailability = initAvailabilityForValidDatesWithNoCourse(course, nonAvailableDates);
for(Availability a : professorsAvailability){
String date = a.getDate();
String timeslot = a.getTimeSlot();
if(course.checkIfProfessorsAreAvailable(date, timeslot)){
int row = getRowFromDate(date);
int col = getColFromTimeslot(timeslot);
if(row == 0 && col == 0){
break;
}
model.setValueAt(course.getCourseName(), row, col);
Component[] components = coursesPanel.getComponents();
for (Component component : components) {
if (component instanceof JButton) {
JButton button = (JButton) component;
if (course.getCourseName().equals(button.getText())){
coursesPanel.remove(button);
coursesPanel.revalidate();
coursesPanel.repaint();
ScheduledCourse sc = new ScheduledCourse(course, date, timeslot, classrooms);
scheduledCourses.add(sc);
addCourseToClassroomsPanel(sc, date, timeslot);
coursesPanel.repaint();
placedCourse = true;
unscheduled.removeCourseFromUnscheduledList(course);
}
}
}
}
if(placedCourse == true){
break;
}
}
}
hideLoading();
}catch (Exception ex){
System.out.println(ex);
}
}//GEN-LAST:event_autoAddProfessorsToSchedulebtncreateExcelFromTable
private void btnClearCreateExcelFromTable(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnClearCreateExcelFromTable
/*
ScheduleManager b = new ScheduleManager(excelManager1);
System.out.println(evt);
b.startProcess(false);
this.dispose();
*/
if (JOptionPane.showConfirmDialog(this, "Είστε σίγουρος ότι επιθυμείτε καθαρισμό όλων των δεδομένων;", "Σφάλμα εφαρμογής", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
try{
ExcelManager newExcelManager = new ExcelManager(this, def);
if(newExcelManager.readGenericExcel()){
if (newExcelManager.readAvailabilityTemplates()){
ScheduleManager b = new ScheduleManager(newExcelManager);
b.startProcess(false);
this.dispose();
}
}
clearTable();
courses = new ArrayList<>(excelManager1.getCourses());
classrooms = new ArrayList<>(excelManager1.getClassrooms());
professors = new ArrayList<>(excelManager1.getProfs());
unscheduled = new Unscheduled(excelManager1.getCourses());
for(Course crs : courses){
JButton courseButton = new JButton();
courseButton = createCourseBtn(crs);
coursesPanel.add(courseButton);
}
for(Component comp : coursesClassroomsPanel.getComponents()){
coursesClassroomsPanel.remove(comp);
}
coursesClassroomsPanel.repaint();
coursesClassroomsPanel.revalidate();
coursesPanel.repaint();
coursesPanel.revalidate();
scheduledCourses = new ArrayList<>();
}catch (Exception ex){
System.out.println(ex);
}
}
}//GEN-LAST:event_btnClearCreateExcelFromTable
public CourseClassroomsPanel findScheduledCourse(Course course) {
Component[] components = coursesClassroomsPanel.getComponents();
for (Component component : components) {
if (component instanceof CourseClassroomsPanel) {
CourseClassroomsPanel ccp = (CourseClassroomsPanel) component;
if (ccp.getScheduledCourse().getCourse().getCourseName().equals(course.getCourseName())) {
return ccp;
}
}
}
return null;
}
private void clearTable(){
for(int i = 1; i < table.getRowCount(); i++){
for(int j = 1; j < table.getColumnCount(); j++){
table.setValueAt("", i, j);
}
}
}
public List<String> getInvalidExaminationDates(String courseName, String courseSemester){
List<String> list = new ArrayList<>();
for (int i = 1; i < table.getRowCount(); i++){
for (int j = 1; j < table.getColumnCount(); j++){
if(table.getValueAt(i,j) != null){
Course crs = new Course(findCourse((String) table.getValueAt(i, j)));
if (crs != null && !crs.equals(courseName) && crs.getCourseSem().equals(courseSemester)){
String date = getDateFromTableRow(i);
List<String> tmp = new ArrayList<>(getPrevCurrNextInvalidDates(date));
for(String s : tmp){
if(!list.contains(s)){
list.add(s);
}
}
}
}
}
}
return list;
}
public List<Availability> initAvailabilityForValidDatesWithNoCourse(Course crs, List<String> invalidDates){
List<Availability> professorAvailability = new ArrayList<>();
for (int i = 1; i < table.getRowCount(); i++){
for (int j = 1; j < table.getColumnCount(); j++){
if(table.getValueAt(i,j) == null){
String timeslot = table.getValueAt(0, j).toString();
String date = getDateFromTableRow(i);
// Προσθήκη μόνο των ημερομηνιών που όλοι οι καθηγητές του μαθήματος
// είναι διαθέσιμοι.
if(!invalidDates.contains(date) && crs.checkIfProfessorsAreAvailable(date, timeslot)){
professorAvailability.add(new Availability(date, timeslot, 1));
}
}
}
}
return professorAvailability;
}
public List<String> getPrevCurrNextInvalidDates(String date){
List<String> list = new ArrayList<>();
String dt2 = utils.modifyDate(date, 1, '+');
String dt3 = utils.modifyDate(date, 1, '-');
String dt4 = utils.modifyDate(date, 2, '+');
String dt5 = utils.modifyDate(date, 2, '-');
if(dates.contains(date)){
list.add(date);
}
if(dates.contains(dt2)){
list.add(dt2);
}
if(dates.contains(dt3)){
list.add(dt3);
}
if(dates.contains(dt4)){
list.add(dt4);
}
if(dates.contains(dt5)){
list.add(dt5);
}
return list;
}
public String getDateFromTableRow(int row){
String strDate = (String) table.getValueAt(row, 0);
String date = utils.getDateWithGreekFormat(weekdays, strDate);
return date;
}
public String getDateFromTableCol(int col){
String strTimeslot = (String) table.getValueAt(0, col);
return strTimeslot;
}
public int getRowFromDate(String date){
for(int i = 1; i < table.getRowCount(); i++){
String tmp = (String) table.getValueAt(i, 0);
tmp = utils.getDateWithGreekFormat(weekdays, tmp);
if(tmp.equals(date)){
return i;
}
}
return 0;
}
public int getColFromTimeslot(String timeslot){
for(int j = 1; j < table.getColumnCount(); j++){
if(table.getValueAt(0, j).equals(timeslot)){
return j;
}
}
return 0;
}
/**
*
* @param date
* @param timeslot
* @return
*/
private List<Classroom> getClassroomsAvailableOn(String date, String timeslot) {
// This method should return a list of classrooms that are available on the
// specified date and timeslot
// Implement the logic based on how the availability data is stored and
// retrieved
List<Classroom> availableClassrooms = new ArrayList<>();
// ... logic to populate availableClassrooms ...
return availableClassrooms;
}
/**
* Τοποθέτηση των αναγνωσμένων μαθημάτων στο πάνελ με τα μαθήματα και τις
* αίθουσες.
* (Εάν έχει βρεθεί αρχείο προγράμματος εξεταστικής και εάν είναι ορθά όλα τα
* δεδομένα)
*/
private void createScheduledCourseClassroomsPanels() {
for (ScheduledCourse sc : scheduledCourses) {
CourseClassroomsPanel ccp = new CourseClassroomsPanel(sc, sc.getClassrooms(), sc.getDate(),
sc.getTimeslot());
//ccp.setSize(100,100);
coursesClassroomsPanel.add(ccp);
}
coursesClassroomsPanel.revalidate();
coursesClassroomsPanel.repaint();
}
/**
* Μέθοδος που χρησιμοποιείται για την αφαίρεση ενός μαθήματος
* από το πάνελ των μαθημάτων - αιθουσών.
*
* @param crs Το αντικείμενο του μαθήματος για προσθήκη (Course).
* @param date Το λεκτικό της ημερομηνίας που έχει τοποθετηθεί το μάθημα για
* εξέταση (String).
* @param timeslot Το λεκτικό της χρονικής περιόδου που έχει τοποθετηθεί το
* μάθημα για εξέταση (String).
*/
private void addCourseToClassroomsPanel(ScheduledCourse sc, String date, String timeslot) {
CourseClassroomsPanel ccp = new CourseClassroomsPanel(sc, classrooms, date, timeslot);
//ccp.setSize(100,100);
coursesClassroomsPanel.add(ccp);
coursesClassroomsPanel.revalidate();
coursesClassroomsPanel.repaint();
sortAndReorderPanels(coursesClassroomsPanel);
}
public void sortAndReorderPanels(JPanel container) {
// Step 1: Remove panels and add them to a list
List<CourseClassroomsPanel> panels = new ArrayList<>();
for (Component comp : container.getComponents()) {
if (comp instanceof CourseClassroomsPanel) {
panels.add((CourseClassroomsPanel) comp);
}
}
// Remove all components from the container
container.removeAll();
// Step 2: Sort the list based on the Greek semester
panels.sort(new Comparator<CourseClassroomsPanel>() {
@Override
public int compare(CourseClassroomsPanel o1, CourseClassroomsPanel o2) {
String sem1 = o1.getScheduledCourse().getCourse().getCourseSem();
String sem2 = o2.getScheduledCourse().getCourse().getCourseSem();
return Integer.compare(getGreekCharOrder(sem1.charAt(0)), getGreekCharOrder(sem2.charAt(0)));
}
});
// Step 3: Re-add the panels to the container in sorted order
for (CourseClassroomsPanel panel : panels) {
container.add(panel);
}
// Refresh the container UI
container.revalidate();
container.repaint();
}
private int getGreekCharOrder(char greekChar) {
String greekAlphabet = "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ";
// Για να μην γυρίσουμε ποτέ το -1 για χαρακτήρες που δεν βρέθηκαν
return greekAlphabet.indexOf(greekChar) + 1;
}
/**
* Μέθοδος που χρησιμοποιείται για την αφαίρεση ενός μαθήματος
* από το πάνελ των μαθημάτων - αιθουσών.
*
* @param crs Το αντικείμενο του μαθήματος προς αφαίρεση (Course).
*/
private void removeCourseFromClassroomsPanel(Course crs) {
for (Component comp : coursesClassroomsPanel.getComponents()) {
if (comp instanceof CourseClassroomsPanel) {
((CourseClassroomsPanel) comp).getScheduledCourse().getCourse().getCourseName();
String tmp = ((CourseClassroomsPanel) comp).getScheduledCourse().getCourse().getCourseName();
if (tmp.equals(crs.getCourseName()) || tmp.equals(crs.getCourseShort())) {
coursesClassroomsPanel.remove(comp);
coursesClassroomsPanel.revalidate();
coursesClassroomsPanel.repaint();
break; // Assuming each course only has one panel associated with it
}
}
}
}
/**
* Συνάρτηση που χρησιμοποιείται για την τοποθέτηση των προγραμματισμένων
* μαθημάτων στις κατάλληλες θέσεις στον πίνακα της φόρμας.
*/
private void fillCoursesWithReadExcelScheduleData() {
model = (DefaultTableModel) table.getModel();
try {
for (ExamCoursesFromFinalSchedule data : crsList) {
int row = data.getRowIndex();
int col = data.getColIndex();
model.setValueAt(data.getCourse().getCourseName(), row, col - 1);
}
// Ανανέωση για την απεικόνιση των δεδομένων.
table.revalidate();
table.repaint();
} catch (Exception ex) {
JOptionPane.showMessageDialog(this,
"Πρόβλημα κατά την συμπλήρωση των μαθημάτων από το διαβασμένο αρχείο προγράμματος εξεταστικής.",
"Σφάλμα εφαρμογής", JOptionPane.ERROR_MESSAGE);
}
}
/**
* Μέθοδος που αποθηκεύει το τελικό πρόγραμμα της εξεταστικής που απεικονίζεται
* στο παράθυρο JForm.
*
* @param evt Το event που προκάλεσε την κλήση της μεθόδου.
*/
private void createExcelFromTable(java.awt.event.ActionEvent evt) {
int rowIndex = 0;
int colIndex = 0;
String path = def.getFolderPath() + "\\" + def.getExamScheduleFile();
try (XSSFWorkbook workbook = new XSSFWorkbook()) {
XSSFSheet sheet1 = workbook.createSheet("ΠΡΟΓΡΑΜΜΑ ΕΞΕΤΑΣΤΙΚΗΣ");
XSSFSheet sheet2 = workbook.createSheet("ΠΡΟΓΡΑΜΜΑ ΑΙΘΟΥΣΩΝ");
utils.fillHeaders(workbook, sheet1, timeslots, dates);
utils.fillHeaders(workbook, sheet2, timeslots, dates);
int tableRows = table.getRowCount() - 1;
int tableColumns = table.getColumnCount() - 1;
for (rowIndex = 1; rowIndex <= tableRows; rowIndex++) {
for (colIndex = 1; colIndex <= tableColumns; colIndex++) {
try {
String cellValue = (String) table.getValueAt(rowIndex, colIndex);
Course course = utils.getCourse(courses, cellValue);
if (course != null) {
Cell excelCell1 = (Cell) sheet1.getRow(rowIndex).createCell(colIndex + 1);
excelCell1.setCellValue(course.getCourseName());
excelCell1.getCellStyle().setWrapText(true);
CourseClassroomsPanel tmp;
tmp = utils.findPanelForCourse(course, coursesClassroomsPanel);
if(tmp != null){
Cell excelCell2 = (Cell) sheet2.getRow(rowIndex).createCell(colIndex + 1);
excelCell2.getCellStyle().setWrapText(true);
String cellValue2 = course.getCourseName() + "\n(";
boolean firstValueEntered = false;
for(Classroom clr : tmp.getSelectedClassrooms()){
if(firstValueEntered == false){
cellValue2 = cellValue2 + clr.getClassroomName();
firstValueEntered = true;
}else{
cellValue2 = cellValue2 + ", " + clr.getClassroomName();
}
}
cellValue2 = cellValue2 + ")";
excelCell2.setCellValue(cellValue2);
}
} else {
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Exception thrown:" + rowIndex + " " + colIndex + e,
"Μήνυμα Λάθους", JOptionPane.ERROR_MESSAGE);
}
}
}
utils.autoSizeColumns(sheet1, tableColumns + 1);
utils.applyCellStyles(workbook, sheet1);
utils.autoSizeColumns(sheet2, tableColumns + 1);
utils.applyCellStyles(workbook, sheet2);
JOptionPane.showMessageDialog(this,
"Η δημιουργία του αρχείου προγράμματος εξεταστικής ολοκληρώθηκε επιτυχώς!", "Μήνυμα Λάθους",
JOptionPane.INFORMATION_MESSAGE);
// Αποθήκευση αρχείου προς συμπλήρωση για τους καθηγητές
try (FileOutputStream outputStream = new FileOutputStream(path.toString())) {
workbook.write(outputStream);
}
} catch (Exception e) {
System.out.println("Η δημιουργία του template για τους καθηγητές απέτυχε." + rowIndex + " " + colIndex);
}
}
/**
* Η συνάρτηση χρησιμοποιείται για να προτρέψει τον χρήστη στο να επιλέξει την
* τοποθεσία
* αλλά και το όνομα αποθήκευσης του τελικού αρχείου προγράμματος σε .xlsx
* μορφή.
*
* @return Το πλήρες μονοπάτι του αρχείου (String) ή null εάν ο χρήστης ακυρώσει
* την διαδικασία.
*/
public String askUserToSaveFile() {
JFileChooser fileChooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel Files (*.xlsx, *.xls)", "xlsx");
fileChooser.setFileFilter(filter);
int result = fileChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
java.io.File selectedFile = fileChooser.getSelectedFile();
String fullPath = selectedFile.getAbsolutePath();
if (!fullPath.contains(".xlsx")) {
fullPath = fullPath + ".xlsx";
return fullPath;
} else {
return fullPath;
}
}
return null;
}
public boolean readExamScheduleExcel() {
int rowIndex = 0;
int colIndex = 0;
String courseCell = "";
String fileName = def.getFolderPath() + "\\" + def.getExamScheduleFile();
String sheetName = def.getSheet7();
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("el", "GR"));
symbols.setWeekdays(weekdays);
// + 2 για τις 2 πρώτες στήλες
int lastCol = timeslots.size() + 2;
try (FileInputStream file = new FileInputStream(new File(fileName))) {
XlsxSheet sheet = new XlsxSheet(fileName);
sheet.SelectSheet(sheetName);
int lastRow = sheet.GetLastRow();
String header1 = sheet.GetCellString(0, 0);
String header2 = sheet.GetCellString(0, 1);
if (!header1.equals("ΗΜ/ΝΙΑ") || !header2.equals("ΗΜΕΡΑ")) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Εντοπίστηκαν διαφορετικά headers στην 1η γραμμή στις πρώτες"
+ " 2 στήλες. Παρακαλώ πολύ ελέγξτε ότι τα δεδομένα για"
+ " το 1ο και το 2ο κελί είναι 'ΗΜ/ΝΙΑ' και 'ΗΜΕΡΑ' αντίστοιχα.";
throw new CustomErrorException(this, msg);
}
String timeslot = "";
for (int x = 2; x < lastCol; x++) {
timeslot = sheet.GetCellString(rowIndex, x);
if (!timeslots.contains(timeslot)) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Το χρονικό διάστημα '" + timeslot + "' δεν υπάρχει καταχωρημένο"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
}
}
String date;
String dateName;
for (rowIndex = 1; rowIndex < lastRow; rowIndex++) {
date = "";
dateName = "";
date = sheet.GetCellString(rowIndex, 1);
dateName = utils.getGreekDayName(date);
if (dateName == null || !dates.contains(date)) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Η ημερομηνία'" + date + "' δεν υπάρχει καταχωρημένη"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
}
}
for (rowIndex = 1; rowIndex < lastRow; rowIndex++) {
for (colIndex = 2; colIndex < lastCol; colIndex++) {
courseCell = utils.getSafeCellString(sheet, rowIndex, colIndex);
if (courseCell.equals("") || courseCell.equals(" ")) {
} else {
if (findCourse(courseCell) == null) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Το μάθημα '" + courseCell + "' δεν υπάρχει καταχωρημένο"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
} else {
String courseTimeslot = sheet.GetCellString(0, colIndex);
String courseDate = sheet.GetCellString(rowIndex, 1);
Course crs = new Course(findCourse(courseCell));
boolean check = checkExaminersConflict(crs, courseDate, courseTimeslot);
if (check) {
if(!existsInExamCourses(crs)){
ExamCoursesFromFinalSchedule courseDet = new ExamCoursesFromFinalSchedule(crs, rowIndex, colIndex);
this.crsList.add(courseDet);
}
} else {
logs.appendLogger(logs.getIndexString() + "Πρόβλημα με το μάθημα '" + courseCell + "' και \n"
+ "την διαθεσιμότητα των καθηγητών. Το μάθημα θα αγνοηθεί.");
}
}
}
}
}
file.close();
return true;
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Το αρχείο '" + fileName + "' δεν βρέθηκε.",
"Μήνυμα Λάθους", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Σφάλμα κατά το άνοιγμα"
+ " του αρχείου '" + fileName + "'.", "Μήνυμα Λάθους", JOptionPane.ERROR_MESSAGE);
} catch (SheetExc ex) {
JOptionPane.showMessageDialog(this,
"Στο αρχείο '" + def.getExamScheduleFile() + "' στην γραμμή και στήλη " + (rowIndex + 1) + ":"
+ colIndex
+ "' με περιεχόμενο κελιού '" + courseCell
+ "' δεν μπόρεσε να αντιστοιχηθεί με κάποιο μάθημα." + ex,
"Μήνυμα λάθους", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
System.out.println(ex);
}
return false;
}
public boolean readClassroomsScheduleExcel() {
int rowIndex = 0;
int colIndex = 0;
String courseCell = "";
String fileName = def.getFolderPath() + "\\" + def.getExamScheduleFile();
String sheetName = def.getSheet7();
DateFormatSymbols symbols = new DateFormatSymbols(new Locale("el", "GR"));
symbols.setWeekdays(weekdays);
// + 2 για τις 2 πρώτες στήλες
int lastCol = timeslots.size() + 2;
try (FileInputStream file = new FileInputStream(new File(fileName))) {
XlsxSheet sheet = new XlsxSheet(fileName);
sheet.SelectSheet(sheetName);
int lastRow = sheet.GetLastRow();
String header1 = sheet.GetCellString(0, 0);
String header2 = sheet.GetCellString(0, 1);
if (!header1.equals("ΗΜ/ΝΙΑ") || !header2.equals("ΗΜΕΡΑ")) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Εντοπίστηκαν διαφορετικά headers στην 1η γραμμή στις πρώτες"
+ " 2 στήλες. Παρακαλώ πολύ ελέγξτε ότι τα δεδομένα για"
+ " το 1ο και το 2ο κελί είναι 'ΗΜ/ΝΙΑ' και 'ΗΜΕΡΑ' αντίστοιχα.";
throw new CustomErrorException(this, msg);
}
String timeslot = "";
for (int x = 2; x < lastCol; x++) {
timeslot = sheet.GetCellString(rowIndex, x);
if (!timeslots.contains(timeslot)) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Το χρονικό διάστημα '" + timeslot + "' δεν υπάρχει καταχωρημένο"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
}
}
String date;
String dateName;
for (rowIndex = 1; rowIndex < lastRow; rowIndex++) {
date = "";
dateName = "";
date = sheet.GetCellString(rowIndex, 1);
dateName = utils.getGreekDayName(date);
if (dateName == null || !dates.contains(date)) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Η ημερομηνία'" + date + "' δεν υπάρχει καταχωρημένη"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
}
}
for (rowIndex = 1; rowIndex < lastRow; rowIndex++) {
for (colIndex = 2; colIndex < lastCol; colIndex++) {
courseCell = utils.getSafeCellString(sheet, rowIndex, colIndex);
if (courseCell.equals("") || courseCell.equals(" ")) {
} else {
if (findCourse(courseCell) == null) {
file.close();
String msg = "Πρόβλημα με τα δεδομένα του αρχείου '" +
fileName + "' στην γραμμή " + (rowIndex + 1) +
". Το μάθημα '" + courseCell + "' δεν υπάρχει καταχωρημένο"
+ " στο βασικό αρχείο πληροφοριών (" + def.getGenericFile() + ").";
throw new CustomErrorException(this, msg);
} else {
String courseTimeslot = sheet.GetCellString(0, colIndex);
String courseDate = sheet.GetCellString(rowIndex, 1);
Course crs = new Course(findCourse(courseCell));
boolean check = checkExaminersConflict(crs, courseDate, courseTimeslot);
if (check) {
if(!existsInExamCourses(crs)){
ExamCoursesFromFinalSchedule courseDet = new ExamCoursesFromFinalSchedule(crs, rowIndex, colIndex);
this.crsList.add(courseDet);
}
} else {
logs.appendLogger(logs.getIndexString() + "Πρόβλημα με το μάθημα '" + courseCell + "' και \n"
+ "την διαθεσιμότητα των καθηγητών. Το μάθημα θα αγνοηθεί.");
}
}
}
}
}
file.close();
return true;
} catch (FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Το αρχείο '" + fileName + "' δεν βρέθηκε.",
"Μήνυμα Λάθους", JOptionPane.ERROR_MESSAGE);
} catch (IOException ex) {
JOptionPane.showMessageDialog(this, "Σφάλμα κατά το άνοιγμα"
+ " του αρχείου '" + fileName + "'.", "Μήνυμα Λάθους", JOptionPane.ERROR_MESSAGE);
} catch (SheetExc ex) {
JOptionPane.showMessageDialog(this,
"Στο αρχείο '" + def.getExamScheduleFile() + "' στην γραμμή και στήλη " + (rowIndex + 1) + ":"
+ colIndex
+ "' με περιεχόμενο κελιού '" + courseCell
+ "' δεν μπόρεσε να αντιστοιχηθεί με κάποιο μάθημα." + ex,
"Μήνυμα λάθους", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
System.out.println(ex);
}
return false;
}
public boolean checkExaminersConflict(Course course, String date, String timeslot) {
List<Professor> newCourseExaminers = null;
boolean found = false;
String errorMsg = course.getCourseName();
boolean allAvailable = true;
for (Course crs : unscheduled.getCourses()) {
if (crs.getCourseName().equals(course.getCourseName())) {
found = true;
newCourseExaminers = new ArrayList<>(course.getExaminers());
for (Professor prf1 : newCourseExaminers) {
int res1 = prf1.isAvailable(date, timeslot);
if (res1 == 0 || res1 == 2) {
logs.appendLogger(logs.getIndex() + ") Πρόβλημα με την διαθεσιμότητα καθηγητών για το μάθημα: '"
+ crs.getCourseName() + "')");
errorMsg = errorMsg + "\nΟ καθηγητής " + prf1.getProfSurname() + " " + prf1.getProfFirstname() +
" δεν είναι διαθέσιμος την ημερομηνία " + date + " και ώρα " + timeslot + ".";
allAvailable = false;
}
}
if (allAvailable) {
for (Professor prf2 : newCourseExaminers) {
prf2.changeSpecificAvailability(date, timeslot, 2);
}
ScheduledCourse sc = new ScheduledCourse(crs, date, timeslot, classrooms);
scheduledCourses.add(sc);
unscheduled.removeCourseFromUnscheduledList(crs);
return true;
}
}
}
if(found){
logs.appendLogger("Το μάθημα " + course.getCourseName() + " θα αγνοηθεί καθώς έχει ήδη"
+ "τοποθετηθεί στο πρόγραμμα εξεταστικής.");
}
return false;
}
/**
* Η μέθοδος ευθύνεται για τον έλεγχο διαθεσιμότητας των καθηγητών ενός
* μαθήματος για μία συγκεκριμενη ημερομηνία και χρονικό πλαίσιο
*
* @param course Αντικείμενο της κλάσης Course όπου από αυτό θα αντλήσουμε
* τους εξεταστές καθηγητές
* @param dateStr Η ημερομηνία προς έλεγχο
* @param timeslotStr Το χρονικό πλαίσιο προς έλεγχο
* @return true ή false ανάλογα με το εάν όλοι οι καθηγητές του μαθήματος θα
* ήταν διαθέσιμοι εκείνη την συγκεκριμένη χρονική περίοδο ή όχι
*/
public boolean checkAvailabilityForProfessors(Course course, String dateStr, String timeslotStr) {
List<Professor> profs = new ArrayList<>(course.getExaminers());
List<Integer> results = new ArrayList<>();
String date = utils.getDateWithGreekFormat(weekdays, dateStr);
for (Professor prof : profs) {
int tmp = prof.isAvailable(date, timeslotStr);
results.add(tmp);
}
for (Integer i : results) {
if (i == 0 || i == 2) {
return false;
}
}
return true;
}
private void showLoading(){
this.getContentPane().add(lp);
this.getContentPane().setComponentZOrder(lp, 0);
this.repaint();
this.revalidate();
}
private void hideLoading(){
this.remove(lp);
this.revalidate();
this.repaint();
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton autoAddProfessorsToSchedulebtn;
private javax.swing.JButton btnClear;
private javax.swing.JButton btnExportXlsx;
private javax.swing.JPanel coursesPanel;
private javax.swing.JScrollPane coursesScrollPane;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JScrollPane jScrollPaneClassrooms;
private javax.swing.JLabel lblCourses;
private javax.swing.JLabel lblCoursesClassrooms;
private javax.swing.JLabel lblScheduleDesigner;
private javax.swing.JPanel modelPanel;
private javax.swing.JScrollPane modelScrollPane;
// End of variables declaration//GEN-END:variables
} | Gouvo7/Exam-Schedule-Creator | src/thesis/ScheduleManager.java |
1,675 | package gr.aueb.softeng.view.Chef.OrderDetails;
import gr.aueb.softeng.team08.R;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
* Η κλάση αυτή εμφανίζει τα στοιχεία της επιλεγμένης παραγγελίας στην οθόνη του σέφ
*/
public class OrderDetailsActivity extends AppCompatActivity implements OrderDetailsView {
public int OrderId;
RecyclerView recyclerView;
OrderDetailsViewModel viewModel;
Button setCompletedButton;
boolean isCustomer;
/**
* Δημιουργεί to layout και αρχικοποιεί
* το activity.
* Αρχικοποιεί το view model και περνάει στον presenter το view
* Δίνει στον presenter το ownerId και αρχικοποιεί τα στοιχεία του layout
* @param savedInstanceState το Instance state
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_order_details);
viewModel = new ViewModelProvider(this).get(OrderDetailsViewModel.class);
viewModel.getPresenter().setView(this);
if (savedInstanceState == null) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
OrderId = extras.getInt("OrderId");
isCustomer = extras.getBoolean("IsCustomer");
}
viewModel.getPresenter().setOrder(OrderId);
viewModel.getPresenter().setOrderLineList();
viewModel.getPresenter().setOrderDetails();
// ui initialization
recyclerView = findViewById(R.id.OrderLinesRecyclerView);
setCompletedButton = findViewById(R.id.SetCompletedButton);
//changeLayout depending on who is using it(chef or customer)
viewModel.getPresenter().chooseLayout(isCustomer);
findViewById(R.id.SetCompletedButton).setOnClickListener(new View.OnClickListener() { //Το κουμπί που πατιέται όταν μια παραγγελία πατηθεί ότι είναι completed
public void onClick(View v) {
viewModel.getPresenter().onCompleted();
}
});
findViewById(R.id.GoBack3).setOnClickListener(new View.OnClickListener(){ // To κουμπί επιστροφής στην αρχική οθόνη
@Override
public void onClick(View v){viewModel.getPresenter().OnBack();}
});
}
/**
* Η μέθοδος αυτή εμφανίζει μήνυμα επιτυχίας στην οθόνη και καλείται όταν η παραγγελία γίνεται Completed από τον μάγειρα
* Επίσης , δημιουργεί μία onClick listener η οποία όταν πατηθεί το OK στην οθόνη , μας
* επιστρέφει στο προηγούμενο activity που μας κάλεσε
*/
public void showOrderCompletedMessage()
{
new AlertDialog.Builder(OrderDetailsActivity.this)
.setCancelable(true)
.setTitle("Επιτυχής ολοκλήρωση της παραγγελίας")
.setMessage("Η παραγγελία προστέθηκε στην λίστα των ολοκληρωμένων παραγγελιών!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
finish();
}
}).create().show();
}
/**
* Κρύβει το κουμπί του SetCompletedButton που είναι για τις περιπτώσεις που το activity καλείται απο τον customer
*/
@Override
public void hideCompletionButton() {
setCompletedButton.setVisibility(View.GONE);
}
/**
* Εμφανίζει το κουμπί του SetCompletedButton που είναι για τις περιπτώsεις του μάγειρα ώστε να μπορεί να την αλλάξει
*/
@Override
public void showCompletedButton() {
setCompletedButton.setVisibility(View.VISIBLE);
}
/**
* Καλείται όταν επιστρέφουμε στην οθόνη αυτού του activity
* Ενημερώνει την λίστα με τα Order Lines μήπως προστέθηκε κάποιο για να εμφανιστεί στο Recycler View, αλλά και τον adapter του recycler view
* Καλεί την μέθοδο changeLyaout του presenter
*/
@Override
protected void onResume() {
super.onResume();
viewModel.getPresenter().setOrderLineList();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new OrderDetailsRecyclerViewAdapter(viewModel.getPresenter().getOrderLineList()));
}
/**
* Εμφανίζει στην οθόνη το id της παραγγελίας που έχει πατηθεί
* @param orderId το μοναδικό id της παραγγελίας
*/
public void setOrderId(String orderId){
((TextView)findViewById(R.id.OrderIdText)).setText("Id:"+orderId);
}
/**
* Εμφανίζει στην οθόνη την κατάσταση της τρέχουσας επιλεγμένης παραγγελίας
* @param state η κατάσταση της παραγγελίας
*/
public void setOrderState(String state){
((TextView)findViewById(R.id.OrderStateText)).setText("State:"+state);
}
/**
* Εμφανίζει στην οθόνη τον αριθμό τραπεζιού όπου έγινε η παραγγελία
* @param num ο αριθμός του τραπεζιού
*/
public void setTableNumber(String num){
((TextView)findViewById(R.id.TableNumberText)).setText("Table:"+num);
}
/**
* Εμφανιζει στην οθόνη την ώρα και λεπτό που έγινε η παραγγελία
* @param date η ώρα και το λεπτό σε μορφή ενωμένου String
*/
public void setDate(String date){
((TextView)findViewById(R.id.DateText)).setText(date);
}
/**
* Καλείται όταν θέλουμε να επιστρέψουμε στο προηγούμενο Activity , δηλαδή στο login Page στην περίπτωσή μας(αυτό καλεί το activity μας)
*
*/
public void goBack(){
finish();
}
} | vleft02/Restaurant-Application | app/src/main/java/gr/aueb/softeng/view/Chef/OrderDetails/OrderDetailsActivity.java |
1,676 | import java.util.ArrayList;
public class Main {
private static Tree Rtree = new Tree(new TreeNode(Double.MAX_VALUE, Double.MIN_VALUE, Double.MAX_VALUE, Double.MIN_VALUE));
//Δεδομένα στοιχείου που θα κάνουμε εισαγωγή διαγραφή αλλά και των queries
private static final int k = 5;
private static final double range = 10;
private static final long id = 35836525;
private static final double lat = 38.444235;
private static final double lon = 23.853263;
/**
* Η μέθοδος αυτή είναι υπεύθυνη για τη δημιουργία του R*tree
* @param fileManager Αντικείμενο της κλάσης FileManager που μας επιτρέπει να προσπελάσουμε μεθόδους της
* @return Το R*tree που διαβάζεται από το indexfile
*/
private static void MakeIndex(FileManager fileManager) {
Rtree = fileManager.read_tree_from_indexfile();
}
private static void InsertNewLocation(ArrayList<Location> locations, Location newLocation) {
System.out.println("\n---------------->\tΕισαγωγή νέου στοιχείου\t<---------------------- \n\t" + newLocation);
long start = System.currentTimeMillis();
int size = locations.size();
FileManager osm = new FileManager();
osm.add_location(newLocation, locations);
Data data2 = new Data();
locations = data2.read_datafile();
if(size !=locations.size())
System.out.println("Η νέα τοποθεσία προστέθηκε επιτυχώς!");
else
System.out.println("Πρόβλημα στην προσθήκη της νέας τοποθεσίας!");
long finish = System.currentTimeMillis() - start;
System.out.println("Ο χρόνος που χρειάστηκε: " + finish + "ms");
System.out.println("-------------------------------------------------------------------\n");
}
public static void DeleteLocation(ArrayList<Location> locations, Location newLocation, long id) {
System.out.println("\n---------------->\tΔιαγραφή του στοιχείου\t<---------------------- \n\t" + newLocation);
long start = System.currentTimeMillis();
int size = locations.size();
Rtree.delete_from_tree(id,locations);
if(size != locations.size())
System.out.println("Η τοποθεσία διαγράφηκε επιτυχώς!");
else
System.out.println("Πρόβλημα κατά τη διαγραφή της τοποθεσίας!");
long finish = System.currentTimeMillis() - start;
System.out.println("Ο Χρόνος που χρειάστηκε: " + finish + "ms");
System.out.println("-------------------------------------------------------------------\n");
}
public static void RangeQueryWithoutIndex(double lat, double lon, ArrayList<Location> locations) {
System.out.println("\n---------------->\tΕρώτημα περιοχής χωρίς χρήση καταλόγου!\t<---------------------- \n\t" + "range: " + range + " lat: " + lat + " lon: " + lon );
long start = System.currentTimeMillis();
ArrayList<Location> locations_in_range = QueriesWithoutIndex.range_query_without_index(new Location(-1, lat, lon), range, locations);
// Εμφάνιση Αποτελεσμάτων
for (Location neighbor : locations_in_range)
System.out.println(neighbor.toString());
long finish = System.currentTimeMillis() - start;
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void RangeQueryWithIndex(QueriesWithIndex qwi, double lat, double lon) {
System.out.println("\n---------------->\tΕρώτημα περιοχής με χρήση καταλόγου!\t<---------------------- \n\t\t" + "range: " + range + " lat: " + lat + " lon: " + lon );
long start= System.currentTimeMillis();
ArrayList<Location> locations_in_range = qwi.range_query_with_index(new Point(lat, lon), range);
long finish = System.currentTimeMillis() - start;
// Εμφάνιση αποτελεσμάτων
for (Location neighbor : locations_in_range)
System.out.println(neighbor.toString());
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void KnnWithoutIndex(QueriesWithoutIndex sKNN, int k , ArrayList<Location> locations) {
System.out.println("\n------------------->\tΕρώτημα εύρεσης k κοντινότερων γειτόνων χωρίς κατάλογο για k: " + k + " lat: " + lat + " lon: " + lon + "\t<----------------");
Location middle = new Location(-1, lat, lon);
long start = System.currentTimeMillis();
ArrayList<Location> distances = sKNN.knn_without_index(locations, middle, k);
for (Location neighbor : distances)
System.out.println(neighbor.toString());
long finish = System.currentTimeMillis() - start;
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void KnnWithIndex(QueriesWithIndex qwi) {
System.out.println("\n------------------->\tΕρώτημα εύρεσης k κοντινότερων γειτόνων με κατάλογο για k: " + k + " lat: " + lat + " lon: " + lon + "\t<----------------");
Point point = new Point(lat, lon);
long start = System.currentTimeMillis();
ArrayList<Location> result_list = qwi.knn_with_index(point, k);
for (Location neighbor : result_list)
System.out.println(neighbor.toString());
long finish = System.currentTimeMillis() - start;
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void Skyline() {
System.out.println("\n--------------------------->\tΕρώτημα κορυφογραμμής!\t<---------------------------");
long start = System.currentTimeMillis();
Skyline skl = new Skyline();
ArrayList<SkylineNode> results = skl.calculateSkyline(Rtree);
for (SkylineNode node : results)
System.out.println(node);
long finish = System.currentTimeMillis() - start;
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void BottomUp() throws Exception {
System.out.println("\n---------------------->\tΥλοποίηση μαζικής κατασκευής δέντρου ΒottomUp\t<------------------");
long start= System.currentTimeMillis();
BottomUp bottomUp = new BottomUp();
bottomUp.execute_bottom_up();
long finish= System.currentTimeMillis() - start ;
System.out.println("Ο χρόνος που χρειάστηκε το ερώτημα: " + finish + "ms");
}
public static void main(String[] args) throws Exception {
Location newLocation = new Location(id, lat, lon);
FileManager file_mngr = new FileManager();
Data data = new Data();
ArrayList<Location> locations;
QueriesWithoutIndex sKNN = new QueriesWithoutIndex();
file_mngr.create_datafile(); //OSM management
locations = data.read_datafile(); //Εισαγωγές στο datafile.txt
MakeIndex(file_mngr); // Κλήση συνάρτησης δημιουργίας του καταλόγου
InsertNewLocation(locations, newLocation); // Κλήση της μεθόδου εισαγωγής νέου στοιχείου
DeleteLocation(locations, newLocation, id); // Κλήση της μεθόδου διαγραφής στοιχείου
RangeQueryWithoutIndex(lat, lon, locations); // Κλήση της μεθόδου για ερωτήματα περιοχής χωρίς κατάλογο
QueriesWithIndex qwi = new QueriesWithIndex(Rtree.getRoot());
RangeQueryWithIndex(qwi, lat, lon); // Κλήση της μεθόδου για ερωτήματα περιοχής με κατάλογο
KnnWithoutIndex(sKNN, k, locations); // Κλήση της μεθόδου εύρεσης Κ-κοντινότερων γειτόνων χωρίς κατάλογο
KnnWithIndex(qwi); // Κλήση της μεθόδου εύρεσης Κ-κοντινότερων γειτόνων με κατάλογο
Skyline(); // Κλήση μεθόδου για Skyline
BottomUp(); // Κλήση μεθόδου για BottomUp
}
}
| NikosVogiatzis/UniProjects | java Rstartree/Rstartree/Rtree/src/Main.java |
1,678 | package com.mgiandia.library.domain;
import com.mgiandia.library.LibraryException;
import com.mgiandia.library.util.SystemDate;
/**
* Το αντίτυπο ενός βιβλίου.
* @author Νίκος Διαμαντίδης
*
*/
public class Item {
private int itemNumber = 0;
private Book book;
private ItemState state = ItemState.NEW;
/**
* Προκαθορισμένος κατασκευαστής.
*/
public Item() { }
/**
* Βοηθητικός κατασκευαστής που δέχεται τον αριθμό εισαγωγής ως παράμετρο.
* @param itemNumber Ο αριθμός εισαγωγής
*/
public Item(int itemNumber) {
this.itemNumber = itemNumber;
}
/**
* Θέτει τον αριθμό εισαγωγής του αντιτύπου.
* Ο αριθμός εισαγωγής προσδιορίζει μοναδικά κάθε αντίτυπο.
* @param itemNumber Ο αριθμός εισαγωγής.
*/
public void setItemNumber(int itemNumber) {
this.itemNumber = itemNumber;
}
/**
* Επιστρέφει τον αριθμό εισαγωγής του αντιτύπου.
* Ο αριθμός εισαγωγής προσδιορίζει μοναδικά κάθε αντίτυπο.
* @return Ο αριθμός εισαγωγής
*/
public int getItemNumber() {
return itemNumber;
}
/**
* Θέτει το βιβλίο του αντιτύπου.
* @param book Το βιβλίο του αντιτύπου
* @see Book#addItem(Item)
*/
public void setBook(Book book) {
if (this.book != null) {
this.book.friendItems().remove(this);
}
this.book = book;
if (this.book != null) {
this.book.friendItems().add(this);
}
}
/**
* Επιστρέφει το βιβλίο του αντιτύπου.
* @return Το βιβλίο του αντιτύπου
*/
public Book getBook() {
return book;
}
/**
* Επιστρέφει την κατάσταση του αντιτύπου.
* @return Η κατάσταση του αντιτύπου
*/
public ItemState getState() {
return state;
}
/**
* θέτει την κατάσταση του αντιτύπου.
* Προσοχή στην ορατότητα.
* Δεν είναι δημόσια και δεν μπορεί οποιαδήποτε
* κλάση να αλλάξει την κατάσταση
* του αντιτύπου.
* @param state Η κατάσταση του αντιτύπου.
*/
protected void setState(ItemState state) {
this.state = state;
}
/**
* Πραγματοποιεί το δανεισμό του αντιτύπου για
* κάποιο δανειζόμενο και επιστρέφει το δανεισμό.
* Εάν ο δανειζόμενος είναι {@code null} τότε επιστρέφει{@code null}.
* Εάν ο δανειζόμενος δεν δικαιούται να δανειστεί
* κάποιο αντίτυπο τότε δεν πραγματοποιείται ο δανεισμός
* και επιστρέφει {@code null}.
* Επιστρέφει {@code null} εάν η κατάσταση του
* αντιτύπου δεν είναι {@code AVAILABLE}
* Η κατάσταση του αντιτύπου γίνεται {@code LOANED}
* @param borrower Ο δανειζόμενος
* @return Το αντικείμενο του δανεισμού.
*/
public Loan borrow(Borrower borrower) {
if (borrower == null) {
return null;
}
if (!borrower.canBorrow()) {
return null;
}
if (getState() != ItemState.AVAILABLE) {
return null;
}
Loan loan = new Loan();
loan.setItem(this);
loan.setBorrower(borrower);
loan.setLoanDate(SystemDate.now());
setState(ItemState.LOANED);
return loan;
}
/**
* Αλλάζει την κατάσταση του αντιτύπου σε διαθέσιμο ({@code AVAILABLE}).
*/
public void available() {
if (getState().equals(ItemState.LOST)) {
throw new LibraryException();
}
if (getState().equals(ItemState.WITHDRAWN)) {
throw new LibraryException();
}
setState(ItemState.AVAILABLE);
}
/**
* Το αντίτυπο αποσύρεται και δεν είναι διαθέσιμο για δανεισμό.
*/
public void withdraw() {
if (! getState().equals(ItemState.AVAILABLE)) {
throw new LibraryException();
}
setState(ItemState.WITHDRAWN);
}
/**
* Το αντίτυπο έχει χαθεί και δεν είναι διαθέσιμο για δανεισμό.
*/
public void lost() {
if (! getState().equals(ItemState.LOANED)) {
throw new LibraryException();
}
setState(ItemState.LOST);
}
@Override
public String toString() {
return String.valueOf(itemNumber);
}
}
| diamantidakos/Library | src/main/java/com/mgiandia/library/domain/Item.java |
1,679 | package com.example.tecktrove.dao;
import com.example.tecktrove.contacts.Email;
import com.example.tecktrove.contacts.Telephone;
import com.example.tecktrove.domain.Customer;
import com.example.tecktrove.domain.Employer;
import com.example.tecktrove.domain.Order;
import com.example.tecktrove.domain.OrderLine;
import com.example.tecktrove.domain.Synthesis;
import com.example.tecktrove.domain.Component;
import com.example.tecktrove.util.Pair;
import com.example.tecktrove.util.Port;
import com.example.tecktrove.util.Money;
import com.example.tecktrove.util.SimpleCalendar;
import java.math.BigDecimal;
import java.util.ArrayList;
public abstract class Initializer {
/**
* Erases all the data from the database
*/
protected abstract void eraseData();
/**
* Returns the object for the interface {@link CustomerDAO}
*
* @return the DAO object
*/
public abstract CustomerDAO getCustomerDAO();
/**
* Returns the object for the interface {@link EmployerDAO}
*
* @return the DAO object
*/
public abstract EmployerDAO getEmployerDAO();
/**
* Returns the object for the interface {@link ComponentDAO}
*
* @return the DAO object
*/
public abstract ComponentDAO getComponentDAO();
/**
* Returns the object for the interface {@link SynthesisDAO}
*
* @return the DAO object
*/
public abstract SynthesisDAO getSynthesisDAO();
/**
* Returns the object for the interface {@link OrderDAO}
*
* @return the DAO object
*/
public abstract OrderDAO getOrderDAO();
/**
* Initializes all objects in the daos
* as soon as the application starts
*/
public void prepareData(){
eraseData();
//Customers
Customer c1 = new Customer(5673, "george", "ok123456", "George", "Johnson", new Email("[email protected]"), new Telephone("6898909678"), new ArrayList<Synthesis>(), new ArrayList<OrderLine>());
getCustomerDAO().save(c1);
Customer c2 = new Customer(7859, "maria5", "31m@ria5", "Maria", "Papadaki", new Email("[email protected]"), new Telephone("6984596936"), new ArrayList<Synthesis>(), new ArrayList<OrderLine>());
getCustomerDAO().save(c2);
Customer c3 = new Customer(2598, "chris", "chr!s598", "Christos", "Papaioanou", new Email("[email protected]"), new Telephone("6985369825"), new ArrayList<Synthesis>(), new ArrayList<OrderLine>());
getCustomerDAO().save(c3);
//Employers
Employer em1 = new Employer(1252, "eleni3", "elen!562", "Eleni", "Georgali", new Email("[email protected]"), new Telephone("6988745961"));
getEmployerDAO().save(em1);
Employer em2 = new Employer(5698, "faihh1", "faihskoni1", "Foteini", "Soultatou", new Email("[email protected]"), new Telephone("6978451236"));
getEmployerDAO().save(em2);
Employer em3 = new Employer(8596, "kostas34", "13k023m32", "Konstantinos", "Glitsas", new Email("[email protected]"), new Telephone("6945259875"));
getEmployerDAO().save(em3);
//Components
Component com1 = new Component(4191, Money.euros(BigDecimal.valueOf(59.99)), "Box Kolink VOID RGB Midi Tower", "Το VOID Midi-Tower Case αντιπροσωπεύει ένα συναρπαστικό νέο κεφάλαιο στην ιστορία της Kolink, με εντυπωσιακό εφέ «απείρου» καθρεπτισμού σε σχήμα V, ανεμιστήρα 120mm ARGB και πληθώρα χαρακτηριστικών.","Kolink" , new Port(), new Port(), 80);
getComponentDAO().save(com1);
Pair<String, Integer> pair2_1 = new Pair<String, Integer>("ATX Power Port",1);
Pair<String, Integer> pair2_2 = new Pair<String, Integer>("ATX 12V Power Port",1);
Pair<String, Integer> pair2_3 = new Pair<String, Integer>("SATA Power Port",1);
Pair<String, Integer> pair2_4 = new Pair<String, Integer>("Molex Connector",1);
Pair<String, Integer> pair2_5 = new Pair<String, Integer>("PCI Express Connector",1);
Pair<String, Integer> pair2_6 = new Pair<String, Integer>("PCI Floppy Drive Connector",1);
Pair<String, Integer> pair2_7 = new Pair<String, Integer>("AC Adapter",1);
Port port2 = new Port();
Port port2_1 = new Port();
port2.add(pair2_1);
port2.add(pair2_2);
port2.add(pair2_3);
port2.add(pair2_4);
port2.add(pair2_5);
port2.add(pair2_6);
port2_1.add(pair2_7);
Component com2 = new Component(2936, Money.euros(BigDecimal.valueOf(36.90)), "Turbo-X PSU Value III Series 550 W", "Προσιτό αλλά αξιόπιστο τροφοδοτικό, με ισχύ 550W, προηγμένες δικλείδες ασφαλείας και αθόρυβο ανεμιστήρα 120mm.", "Turbo-X", port2, new Port(), 75);
getComponentDAO().save(com2);
Pair<String, Integer> pair3_1 = new Pair<String, Integer>("socket AM4",1);
Port port3 = new Port();
port3.add(pair3_1);
Component com3 = new Component(3260, Money.euros(BigDecimal.valueOf(119.90)), "AMD CPU Ryzen 3 3200G", "Με τέσσερις πυρήνες Zen σε Socket AM4, μέγιστη συχνότητα λειτουργίας 4GHz, μνήμη cache 6MB και Radeon Vega 8 iGPU για αξεπέραστες επιδόσεις γραφικών.", "AMD",new Port(),port3, 60);
getComponentDAO().save(com3);
Pair<String, Integer> pair4_1 = new Pair<String, Integer>("socket AM4,",1);
Port port4 = new Port();
port4.add(pair4_1);
Component com4 = new Component(3888, Money.euros(BigDecimal.valueOf(32.90)), "Alpenföhn Cooler Ben Nevis", "Ψύκτρα με ανεμιστήρα 130mm συμβατή με τα sockets 2066, 2011, 2011-v3, 1366, 115X, 1200, AM4, 775, AM4, AM3(+), AM3, AM2(+), AM2 και FM1.", "Alpenföhn", new Port(), port4, 20);
getComponentDAO().save(com4);
Pair<String, Integer> pair5_1 = new Pair<String, Integer>("socket AM4",1);
Pair<String, Integer> pair5_2 = new Pair<String, Integer>("socket DDR4",1);
Pair<String, Integer> pair5_3 = new Pair<String, Integer>("PCI Express x16 3.0",1);
Pair<String, Integer> pair5_4 = new Pair<String, Integer>("SATA III",1);
Port port5 = new Port();
port5.add(pair5_1);
port5.add(pair5_2);
port5.add(pair5_3);
port5.add(pair5_4);
Component com5 = new Component(4188, Money.euros(BigDecimal.valueOf(129.90)), "Gigabyte Motherboard A520I AC", "Βασίζεται στο AMD® A520 Chipset και δέχεται επεξεργαστές AMD Ryzen™ 5000 και 3000 Series καθώς και 4000 G-Series. Υποστηρίζει DDR4 RAM ως 64GB, NVMe PCIe 3.0 M.2 και Intel® Dual Band 802.11ac Wi-Fi.", "AMD",port5, new Port(), 57);
getComponentDAO().save(com5);
Pair<String, Integer> pair6 = new Pair<String, Integer>("socket DDR4",1);
Port port6 = new Port();
port6.add(pair6);
Component com6 = new Component(3935, Money.euros(BigDecimal.valueOf(44.90)), "Crucial Desktop RAM Value 16GB 3200MHz DDR4", "Μνήμη DDR4-3200 UDIMM χωρητικότητας 16GB από την Crucial® με συχνότητα λειτουργίας 3.200 MHz και CL22.", "Micron",new Port(),port6, 44);
getComponentDAO().save(com6);
Pair<String, Integer> pair7_1 = new Pair<String, Integer>("PCI Express x16 3.0",1);
Pair<String, Integer> pair7_2 = new Pair<String, Integer>("HDMI",1);
Pair<String, Integer> pair7_3 = new Pair<String, Integer>("DVI-D",1);
Port port7 = new Port();
Port port7_1 = new Port();
port7.add(pair7_3);
port7.add(pair7_2);
port7_1.add(pair7_1);
Component com7 = new Component(4311, Money.euros(BigDecimal.valueOf(69.90)), "Asus VGA GPU GeForce GT 730 Evo Low Profile BRK 2 GB", "Είναι ιδανική για υπολογιστές γραφείου, Small Form Factor (SFF) ή Home Theater PCs (HTPC). Είναι χαμηλής κατανάλωσης, με παθητική ψύξη και διαθέτει 3x εξόδους εικόνας.", "ASUS", port7,port7_1, 28);
getComponentDAO().save(com7);
Pair<String, Integer> pair8 = new Pair<String, Integer>("SATA III",1);
Port port8 = new Port();
port8.add(pair8);
Component com8 = new Component(2489, Money.euros(BigDecimal.valueOf(26.90)), "SanDisk Disk SSD Plus 240GB", "Η τεχνολογία SSD 2,5” στο φορητό ή το σταθερό σου υπολογιστή, με χωρητικότητα 240GB, γρήγορες ταχύτητες λειτουργίας και σύνδεση SATA III.", "SanDisk",new Port(),port8, 35);
getComponentDAO().save(com8);
Component com11 = new Component(3604, Money.euros(BigDecimal.valueOf(69.90)), "Sharkoon Midi ATX Box VS4-V Midi Tower", "Μινιμαλιστική σχεδίαση, ευρύχωρο εσωτερικό και άφθονες θέσεις για SSDs/HDDs, προεγκατεστημένος ανεμιστήρας και φίλτρο σκόνης, πρακτικό πάνελ και συμβατότητα με συστήματα υδρόψυξης.", "Sharkoon", new Port(), new Port(), 10);
getComponentDAO().save(com11);
Pair<String, Integer> pair12_1 = new Pair<String, Integer>("ATX Power Port",1);
Pair<String, Integer> pair12_2 = new Pair<String, Integer>("ATX 12V Power Port",1);
Pair<String, Integer> pair12_3 = new Pair<String, Integer>("SATA Power Port",1);
Pair<String, Integer> pair12_4 = new Pair<String, Integer>("PCI Express Connector",1);
Port port12 = new Port();
port12.add(pair12_1);
port12.add(pair12_2);
port12.add(pair12_3);
port12.add(pair12_4);
Component com12 = new Component(3740, Money.euros(BigDecimal.valueOf(69.90)), "Sharkoon PSU Series 500 W 80+ Bronze", "Τροφοδοτικό υπολογιστή Sharkoon 500W με πιστοποίηση 80+ Bronze, active PFC, αθόρυβη λειτουργεία με ανεμιστήρα 120mm και διακριτική μαύρη εμφάνιση.", "Sharkoon", port12 ,new Port(), 17);
getComponentDAO().save(com12);
Pair<String, Integer> pair13_1 = new Pair<String, Integer>("socket AM4+",1);
Port port13 = new Port();
port13.add(pair13_1);
Component com13 = new Component(3741, Money.euros(BigDecimal.valueOf(84.90)), "AMD CPU Ryzen 5 4500", "Με πυρήνες αρχιτεκτονικής Zen 2 και υψηλότερους χρονισμούς, περισσότερο bandwidth, υποστήριξη PCIe 3.0 και αποκλειστικές τεχνολογίες AMD, επαναπροσδιορίζουν την απόδοση των Gaming PCs.", "AMD",new Port(),port13,33);
getComponentDAO().save(com13);
Pair<String, Integer> pair14_1 = new Pair<String, Integer>("4-Pin PWM",1);
Port port14 = new Port();
port14.add(pair14_1);
Component com14 = new Component(4198, Money.euros(BigDecimal.valueOf(34.90)), "Be Quiet! Be Quiet Light Wings Cooler 140mm PWM", "Ανεμιστήρας 140mm με PWM, 7 ειδικά βελτιστοποιημένα για χαμηλό θόρυβο και υψηλή απόδοση πτερύγια, rifle-bearing και δύο φωτιζόμενους δακτυλίους ARGB.", "Be Quiet!", new Port(),new Port(), 54);
getComponentDAO().save(com14);
Pair<String, Integer> pair15_1 = new Pair<String, Integer>("socket AM4+",1);
Pair<String, Integer> pair15_2 = new Pair<String, Integer>("DDR5",1);
Pair<String, Integer> pair15_3 = new Pair<String, Integer>("PCI Express x16 3.0",1);
Pair<String, Integer> pair15_4 = new Pair<String, Integer>("M.2",1);
Port port15 = new Port();
port15.add(pair15_1);
port15.add(pair15_2);
port15.add(pair15_3);
port15.add(pair15_4);
Component com15 = new Component(3639, Money.euros(BigDecimal.valueOf(69.90)), "MSI Motherboard A520M-A PRO", "Βασίζεται στο AMD® A520 Chipset και δέχεται επεξεργαστές AMD Ryzen™ 5000 και 3000 Series καθώς και 4000 G-Series. Υποστηρίζει μνήμη DDR5 ως 64GB και έχει υποδοχές Μ.2 και PCI Express Gen3 x16.", "AMD", port15, new Port(), 85);
getComponentDAO().save(com15);
Pair<String, Integer> pair16 = new Pair<String, Integer>("DDR5",1);
Port port16 = new Port();
port16.add(pair16);
Component com16 = new Component(3290, Money.euros(BigDecimal.valueOf(69.90)), "Corsair Desktop RAM Vengeance PRO RGB 16GB Kit 3000MHz DDR5", "16GB μνήμης RAM DDR5 για υψηλές επιδόσεις και χρονισμούς, με built-in heat spreaders και multi-zone RGB φωτισμό που συμπληρώνει το στυλ κάθε gamer.", "Corsair", new Port(), port16, 29);
getComponentDAO().save(com16);
Pair<String, Integer> pair17_2 = new Pair<String, Integer>("HDMI",1);
Pair<String, Integer> pair17_3 = new Pair<String, Integer>("DVI-D",1);
Pair<String, Integer> pair17_4 = new Pair<String, Integer>("DisplayPort",1);
Pair<String, Integer> pair17_5 = new Pair<String, Integer>("PCI Express Connector",1);
Pair<String, Integer> pair17_6 = new Pair<String, Integer>("PCI Express x16 3.0",1);
Port port17 = new Port();
Port port17_1 = new Port();
port17.add(pair17_3);
port17.add(pair17_2);
port17.add(pair17_4);
port17_1.add(pair17_5);
port17_1.add(pair17_6);
Component com17 = new Component(4312, Money.euros(BigDecimal.valueOf(189.90)), "Asus VGA GPU GeForce GTX 1630 Phoenix EVO 4 GB", "Προσφέρει υψηλές επιδόσεις στα παιχνίδια χάρη στην αρχιτεκτονική NVIDIA Turing™. Διαθέτει 512 πυρήνες CUDA® και 4GB μνήμης GDDR6.", "Asus", port17, port7_1, 45);
getComponentDAO().save(com17);
Pair<String, Integer> pair18 = new Pair<String, Integer>("M.2",1);
Port port18 = new Port();
port18.add(pair18);
Component com18 = new Component(3748, Money.euros(BigDecimal.valueOf(94.90)), "Samsung Disk SSD 980 NVMe M.2 1TB", "Το Samsung NVMe SSD χρησιμοποιεί τεχνολογία μνήμης V-NAND και υποστηρίζει ταχύτητες ανάγνωσης και εγγραφής (sequential) έως 3.500MB/s και 3.000MB/s αντίστοιχα. Έχει χωρητικότητα 1TB", "Samsung", new Port() , port18, 66);
getComponentDAO().save(com18);
//Synthesis
Synthesis s1 = new Synthesis(9787, Money.euros(BigDecimal.valueOf(0)), "Synthesis1");
s1.setPublishState(true);
s1.add(com1);
s1.add(com2);
s1.add(com3);
s1.add(com4);
s1.add(com5);
s1.add(com6);
s1.add(com7);
s1.add(com8);
s1.setSubRating(3, c2);
s1.setSubRating(4, c3);
getSynthesisDAO().save(s1);
Synthesis s2 = new Synthesis(9485, Money.euros(BigDecimal.valueOf(0)), "Synthesis2");
s2.setPublishState(true);
s2.add(com11);
s2.add(com12);
s2.add(com13);
s2.add(com14);
s2.add(com15);
s2.add(com16);
s2.add(com17);
s2.add(com18);
s2.setSubRating(4, c1);
s2.setSubRating(5, c2);
getSynthesisDAO().save(s2);
//OrderLines-Orders
OrderLine ol1 = new OrderLine(5, com1);
OrderLine ol2 = new OrderLine(2, com2);
OrderLine ol3 = new OrderLine(4, com3);
OrderLine ol4 = new OrderLine(2, com8);
OrderLine ol5 = new OrderLine(1, s1);
ArrayList<OrderLine> orderLines1 = new ArrayList<OrderLine>();
orderLines1.add(ol1);
orderLines1.add(ol2);
orderLines1.add(ol3);
orderLines1.add(ol4);
orderLines1.add(ol5);
Order o1 = new Order(new SimpleCalendar(2023, 11, 24), 9999999999999999L, new Telephone("6977584156"), new Email("[email protected]"), orderLines1);
o1.setId(1324);
o1.setCustomer(c1);
getOrderDAO().save(o1);
//-----------------------------------------------//
OrderLine ol11 = new OrderLine(5, com15);
OrderLine ol12 = new OrderLine(2, com12);
OrderLine ol13 = new OrderLine(4, com17);
OrderLine ol14 = new OrderLine(1, com14);
OrderLine ol15 = new OrderLine(1, s2);
ArrayList<OrderLine> orderLines2 = new ArrayList<OrderLine>();
orderLines2.add(ol11);
orderLines2.add(ol12);
orderLines2.add(ol13);
orderLines2.add(ol14);
orderLines2.add(ol15);
Order o2 = new Order(new SimpleCalendar(2023, 12, 12), 1111111111111111L, new Telephone("6947512635"), new Email("[email protected]"), orderLines2);
o2.setId(1144);
o2.setCustomer(c3);
getOrderDAO().save(o2);
//-----------------------------------------------//
OrderLine ol21 = new OrderLine(5, com11);
OrderLine ol22 = new OrderLine(2, com15);
OrderLine ol23 = new OrderLine(4, com18);
OrderLine ol24 = new OrderLine(1, s1);
OrderLine ol25 = new OrderLine(1, s2);
ArrayList<OrderLine> orderLines3 = new ArrayList<OrderLine>();
orderLines3.add(ol21);
orderLines3.add(ol22);
orderLines3.add(ol23);
orderLines3.add(ol24);
orderLines3.add(ol25);
Order o3 = new Order(new SimpleCalendar(2023, 12, 25), 1234567891234567L, new Telephone("6955352569"), new Email("[email protected]"), orderLines3);
o3.setId(1225);
o3.setCustomer(c3);
getOrderDAO().save(o3);
}
} | MariaSchoinaki/TechTrove-App | app/src/main/java/com/example/tecktrove/dao/Initializer.java |
1,681 | package gr.aueb.softeng.view.Chef.HomePage;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import gr.aueb.softeng.domain.Order;
import gr.aueb.softeng.team08.R;
import gr.aueb.softeng.view.Chef.OrderDetails.OrderDetailsActivity;
/**
* H κλάση αυτή καλείται για να εμφανιστεί η αρχική σελίδα του μάγειρα με τις παραγγελίες του
*/
public class ChefHomePageActivity extends AppCompatActivity implements ChefHomePageView,
ChefHomePageRecyclerViewAdapter.ItemSelectionListener{
public int chefId;
RecyclerView recyclerView;
TextView emptyView;
ChefHomePageViewModel viewModel;
/**
* Δημιουργεί to layout και αρχικοποιεί
* το activity.
* Αρχικοποιεί το view model και περνάει στον presenter το view
* Δίνει στον presenter το chefId και αρχικοποιεί τα στοιχεία του layout
* @param savedInstanceState το Instance state
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_chef_home_page);
viewModel = new ViewModelProvider(this).get(ChefHomePageViewModel.class);
viewModel.getPresenter().setView(this);
if (savedInstanceState == null) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
chefId = extras.getInt("ChefId");
}
viewModel.getPresenter().setChef(chefId);
viewModel.getPresenter().setOrderList();
// ui initialization
recyclerView = findViewById(R.id.recyclerViewChef);
emptyView = findViewById(R.id.emptyOrdersChefText); // το TextView που εμφανίζεται όταν είναι άδεια η λίστα με τις παραγγελίες
viewModel.getPresenter().onChangeLayout();
findViewById(R.id.gobackButton4).setOnClickListener(new View.OnClickListener(){ // Το κουμπί επιστροφής στην προηγούμενη σελίδα
@Override
public void onClick(View v){
viewModel.getPresenter().onBack();
}
});
}
/**
* Καλείται όταν επιστρέφουμε στην οθόνη αυτού του activity
* Ενημερώνει την λίστα με τις παραγγελίες μήπως προστέθκε κάποιο για να εμφανιστεί στο Recycler View, αλλά και τον adapter του recycler view
* Καλεί την μέθοδο changeLyaout του presenter
*/
@Override
protected void onResume(){
super.onResume();
viewModel.getPresenter().setOrderList();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new ChefHomePageRecyclerViewAdapter(viewModel.getPresenter().getOrderList(), this));
viewModel.getPresenter().onChangeLayout();
}
/**
*Καλεί το activity για την εμφάνιση των στοιχείων της παραγγελίας που περάστηκε σαν παράμετρος
* @param order η παραγγελία που έχει επιλεχθεί στο Recycler View απο τον μάγειρα
*/
@Override
public void selectOrder(Order order) {
Intent intent = new Intent(ChefHomePageActivity.this, OrderDetailsActivity.class);
intent.putExtra("IsCustomer", false);
intent.putExtra("OrderId", order.getId());
startActivity(intent);
}
/**
* Η μέθοδος αυτή καλείται όταν η λίστα των παραγγελιών του μάγειρα είναι άδεια , ώστε να εμφανιστεί το μήνυμα
* στην οθόνη ότι η λίστα είναι άδεια.
*/
@Override
public void ShowNoOrders() {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
/**
* Η μέθοδος αυτή καλείται όταν η λίστα με τις παραγγελίες ΔΕΝ είναι άδεια και εμφανίζεται στην οθόνη το recycler view με τα αντικείμενα του.
* σετάροντας παράλληλα τον adapter και το layout manager του recycler view
*/
@Override
public void ShowOrders() {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new ChefHomePageRecyclerViewAdapter(viewModel.getPresenter().getOrderList(), this));
}
/**
* Καλείται όταν θέλουμε να επιστρέψουμε στο προηγούμενο Activity , δηλαδή στο login Page στην περίπτωσή μας(αυτό καλεί το activity μας)
*/
public void goBack(){
finish();
}
} | vleft02/Restaurant-Application | app/src/main/java/gr/aueb/softeng/view/Chef/HomePage/ChefHomePageActivity.java |
1,684 | package gr.aueb.softeng.view.Owner.HomePage;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import gr.aueb.softeng.domain.Restaurant;
import gr.aueb.softeng.team08.R;
import gr.aueb.softeng.view.Customer.ChooseRestaurant.ChooseRestaurantRecyclerViewAdapter;
import gr.aueb.softeng.view.Owner.AddRestaurant.AddRestaurantActivity;
import gr.aueb.softeng.view.Owner.RestaurantDetails.RestaurantDetailsActivity;
/**
* Η κλάση αυτή καλείται όταν συνδεθεί ο ιδιοκτήτης και εμφανίζει τα εστιατόριά του
*/
public class OwnerHomePageActivity extends AppCompatActivity implements OwnerHomePageView,
OwnerHomePageRecyclerViewAdapter.ItemSelectionListener{
public int ownerId;
RecyclerView recyclerView;
TextView emptyView;
OwnerHomePageViewModel viewModel;
/**
* Δημιουργεί to layout και αρχικοποιεί
* το activity.
* Αρχικοποιεί το view model και περνάει στον presenter το view
* Δίνει στον presenter το ownerId και αρχικοποιεί τα στοιχεία του layout
* @param savedInstanceState το Instance state
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_owner_home_page);
viewModel = new ViewModelProvider(this).get(OwnerHomePageViewModel.class);
viewModel.getPresenter().setView(this);
if (savedInstanceState == null) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
ownerId = extras.getInt("OwnerId");
}
viewModel.getPresenter().setOwner(ownerId);
viewModel.getPresenter().setRestaurantList();
// ui initialization
recyclerView = findViewById(R.id.RestaurantRecyclerView);
emptyView = findViewById(R.id.emptyView);
viewModel.getPresenter().onChangeLayout();
findViewById(R.id.AddRestaurantButton).setOnClickListener(new View.OnClickListener() { //Όταν πατηθεί το κουμπί προσθήκης εστιατορίου
public void onClick(View v) {
viewModel.getPresenter().onAddRestaurant();
}
});
findViewById(R.id.gobackButton5).setOnClickListener(new View.OnClickListener(){ //Όταν πατηθεί το κουμπί επιστροφής στην προηγούμενη σελίδα
@Override
public void onClick(View v){
viewModel.getPresenter().onBack();
}
});
}
/**
* Καλείται όταν επιστρέφουμε στην οθόνη αυτού του activity
* Ενημερώνει την λίστα με τα Restaurant μήπως προστέθκε κάποιο για να εμφανιστεί στο Recycler View, αλλά και τον adapter του recycler view
* Καλεί την μέθοδο changeLyaout του presenter
*/
@Override
protected void onResume(){
super.onResume();
viewModel.getPresenter().setRestaurantList();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new OwnerHomePageRecyclerViewAdapter(viewModel.getPresenter().getRestaurantList(), this));
viewModel.getPresenter().onChangeLayout();
}
/**
*Καλεί το activity για την εμφάνιση των στοιχείων του εστιατορίου που περάστηκε σαν παράμετρος
* @param restaurant το εστιατόριο που έχει επιλεχθεί στο Recycler View απο τον χρήστη
*/
@Override
public void selectRestaurant(Restaurant restaurant) {
Intent intent = new Intent(OwnerHomePageActivity.this, RestaurantDetailsActivity.class);
intent.putExtra("RestaurantId", restaurant.getId());
startActivity(intent);
}
/**
* Καλεί το activity στο οποίο θα περαστούν τα στοιχεία του νέου εστιατορίου που θέλουμε να προσθέσουμε στον ιδιοκτήτη
*/
public void AddRestaurant(){
Intent intent = new Intent(OwnerHomePageActivity.this, AddRestaurantActivity.class);
intent.putExtra("OwnerId",ownerId);
startActivity(intent);
}
/**
* Καλείται όταν η λίστα με τα εστιατόρια του ιδιοκτήτη είναι άδεια , ώστε να εμφανιστεί το μήνυμα ειδοποίησης στην
* οθόνη και να κρυφτεί το recycler view που θα είναι άδειο ούτως ή αλλος
*/
@Override
public void ShowNoRestaurants() {
recyclerView.setVisibility(View.GONE);
emptyView.setVisibility(View.VISIBLE);
}
/**
* Καλείται όταν η λίστα με τα εστιατόρια του ιδιοκτήτη ΔΕΝ είναι άδεια , και εμφανίζει τα αντικείμενα
* του recycler view , και παράλληλα κρύβει το μήνυμα που θα εμφανιζόταν εάν ήταν άδεια η λίστα
*/
@Override
public void ShowRestaurants() {
recyclerView.setVisibility(View.VISIBLE);
emptyView.setVisibility(View.GONE);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(new OwnerHomePageRecyclerViewAdapter(viewModel.getPresenter().getRestaurantList(), this));
}
/**
* Καλείται όταν θέλουμε να επιστρέψουμε στο προηγούμενο Activity , δηλαδή στο login Page στην περίπτωσή μας(αυτό καλεί το activity μας)
*
*/
public void goBack(){
finish();
}
}
| vleft02/Restaurant-Application | app/src/main/java/gr/aueb/softeng/view/Owner/HomePage/OwnerHomePageActivity.java |
1,685 | package sample;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.effect.GaussianBlur;
import javafx.scene.input.KeyCombination;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* <h1>Η κλάση των Settings</h1>
*/
public class SettingsPane {
public MenuItem x66;
public MenuItem x86;
@FXML
private MenuButton resolution;
@FXML
private MenuItem fullScreen,x1280;
@FXML
private ToggleButton sounds;
@FXML
private Button clearProgress;
@FXML
private Label settingsLabel,resolutionLabel,soundsLabel,clearProgressLabel;
@FXML
private Slider volume;
private Properties properties = new Properties();
private Properties properties2 = new Properties();
private OutputStream output = null;
private InputStream input = null;
private MediaPlayer mediaPlayer;
@FXML
private Button close;
private String fs;
/**
* Κατασκευαστής της κλάσης
*/
public SettingsPane(){
Media buttonSound = new Media(getClass().getClassLoader().getResource("Sounds/buttonSound.wav").toExternalForm());
mediaPlayer = new MediaPlayer(buttonSound);
}
/**
* Φορτώνει τις τιμές απο το αρχείο.
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο config.
*/
@FXML
private void initialize() throws IOException {
File f = new File("config.properties");
properties.setProperty("width","800");
properties.setProperty("height","600");
properties.setProperty("fullScreen","false");
if(f.exists()) {
input = new FileInputStream("config.properties");
properties.load(input);
String lang = properties.getProperty("flag");
loadLang(lang);
resolution.setText(properties.getProperty("resolution"));
if(properties.getProperty("resolution").equals("FullScreen")){
resolution.setText(fs);
}
if(properties.getProperty("sound").equals("enabled")){
sounds.setSelected(true);
}
else if(properties.getProperty("sound").equals("disabled")){
sounds.setSelected(false);
}
}
//volume slider
MediaPlayer mp = Main.mediaPlayer;
volume.setValue(mp.getVolume() * 100); // 1.0 = max 0.0 = min
volume.valueProperty().addListener(event -> mp.setVolume(volume.getValue() / 100));
}
/**
* Αλλάζει την ανάλυση σε πλήρης οθόνη.
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο FXML.
*/
@FXML
private void fullScreenSelected() throws IOException{
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
resolution.setText(fs);
output = new FileOutputStream("config.properties");
properties.setProperty("fullScreen","true");
properties.setProperty("width","999");
properties.setProperty("height","999");
properties.setProperty("resolution","FullScreen");
properties.store(output,null);
Parent root = FXMLLoader.load(getClass().getResource("../../resources/fxml/MainMenu.fxml"));
Stage settingsPane = (Stage) resolution.getScene().getWindow();
Stage stage = (Stage) settingsPane.getOwner().getScene().getWindow();
stage.setScene(new Scene(root));
stage.setFullScreen(true);
stage.setFullScreenExitHint("");
stage.setFullScreenExitKeyCombination(KeyCombination.NO_MATCH);
double centerXPosition = stage.getX() + stage.getWidth()/2d;
double centerYPosition = stage.getY() + stage.getHeight()/2d;
settingsPane.setWidth(stage.getWidth()/2);
settingsPane.setHeight(stage.getHeight()/2);
settingsPane.setX(centerXPosition - settingsPane.getWidth()/2d);
settingsPane.setY(centerYPosition - settingsPane.getHeight()/2d);
settingsPane.show();
}
/**
* Αλλάζει την ανάλυση σε "1280x720".
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο FXML.
*/
@FXML
private void x1280Selected() throws IOException{
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
resolution.setText("1280x720");
output = new FileOutputStream("config.properties");
properties.setProperty("resolution","1280x720");
properties.setProperty("fullScreen","false");
properties.setProperty("width","1280");
properties.setProperty("height","720");
properties.store(output,null);
Parent root = FXMLLoader.load(getClass().getResource("../../resources/fxml/MainMenu.fxml"));
Stage settingsPane = (Stage) resolution.getScene().getWindow();
Stage stage = (Stage) settingsPane.getOwner().getScene().getWindow();
stage.setScene(new Scene(root,1280,720));
GaussianBlur blur = new GaussianBlur(3);
Parent settings = settingsPane.getOwner().getScene().getRoot();
settings.setEffect(blur);
double centerXPosition = stage.getX() + stage.getWidth()/2d;
double centerYPosition = stage.getY() + stage.getHeight()/2d;
settingsPane.setWidth(stage.getWidth()/2);
settingsPane.setHeight(stage.getHeight()/2);
settingsPane.setX(centerXPosition - settingsPane.getWidth()/2d);
settingsPane.setY(centerYPosition - settingsPane.getHeight()/2d);
settingsPane.show();
}
/**
* Αλλάζει την ανάλυση σε "800x600".
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο FXML.
*/
@FXML
private void x86Selected() throws IOException {
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
resolution.setText("800x600");
output = new FileOutputStream("config.properties");
properties.setProperty("resolution","800x600");
properties.setProperty("fullScreen","false");
properties.setProperty("width","800");
properties.setProperty("height","600");
properties.store(output,null);
Parent root = FXMLLoader.load(getClass().getResource("../../resources/fxml/MainMenu.fxml"));
Stage settingsPane = (Stage) resolution.getScene().getWindow();
Stage stage = (Stage) settingsPane.getOwner().getScene().getWindow();
stage.setScene(new Scene(root,800,600));
GaussianBlur blur = new GaussianBlur(3);
Parent settings = settingsPane.getOwner().getScene().getRoot();
settings.setEffect(blur);
double centerXPosition = stage.getX() + stage.getWidth()/2d;
double centerYPosition = stage.getY() + stage.getHeight()/2d;
settingsPane.setWidth(stage.getWidth()/2);
settingsPane.setHeight(stage.getHeight()/2);
settingsPane.setX(centerXPosition - settingsPane.getWidth()/2d);
settingsPane.setY(centerYPosition - settingsPane.getHeight()/2d);
settingsPane.show();
}
/**
* Αλλάζει την ανάλυση σε "600x600".
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο FXML.
*/
@FXML
private void x66Selected() throws IOException{
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
resolution.setText("600x600");
output = new FileOutputStream("config.properties");
properties.setProperty("resolution","600x600");
properties.setProperty("fullScreen","false");
properties.setProperty("width","600");
properties.setProperty("height","600");
properties.store(output,null);
Parent root = FXMLLoader.load(getClass().getResource("../../resources/fxml/MainMenu.fxml"));
Stage settingsPane = (Stage) resolution.getScene().getWindow();
Stage stage = (Stage) settingsPane.getOwner().getScene().getWindow();
stage.setScene(new Scene(root,600,600));
GaussianBlur blur = new GaussianBlur(3);
Parent settings = settingsPane.getOwner().getScene().getRoot();
settings.setEffect(blur);
double centerXPosition = stage.getX() + stage.getWidth()/2d;
double centerYPosition = stage.getY() + stage.getHeight()/2d;
settingsPane.setWidth(stage.getWidth()/2);
settingsPane.setHeight(stage.getHeight()/2);
settingsPane.setX(centerXPosition - settingsPane.getWidth()/2d);
settingsPane.setY(centerYPosition - settingsPane.getHeight()/2d);
settingsPane.show();
}
/**
* Ο Event Handler του κουμιού εξόδου από τις ρυθμίσεις.
*/
@FXML
private void closeSettings(){
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
Stage settingsPane = (Stage) close.getScene().getWindow();
Parent mainMenu = settingsPane.getOwner().getScene().getRoot();
mainMenu.setEffect(null);
settingsPane.close();
}
/**
* Κάνει πλήρης εκκαθάριση των επιδόσεων του παίχτη, ορίζοντας κάποιες αρχικές τιμές.
* @throws IOException εάν αποτύχει να φορτώσει το αρχείο.
*/
@FXML
private void clearProgressClicked() throws IOException{
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
File f2 =new File("score.properties");
if(f2.exists()){
input = new FileInputStream("score.properties");
properties.load(input);
OutputStream output2 = new FileOutputStream("score.properties");
properties2.setProperty("MultiplayerWins1","0");
properties2.setProperty("MultiplayerWins2","0");
properties2.setProperty("MultiplayerWins3","0");
properties2.setProperty("SingleModeHighScore1","99999");
properties2.setProperty("SingleModeHighScore2","99999");
properties2.setProperty("SingleModeHighScore3","99999");
properties2.setProperty("BattleWins","0");
properties2.store(output2,null);
}
}
/**
* Φορτώνει τη γλώσσα που εμφανίζονται οι επιλογές των ρυθμίσεων.
* @param lang {@code String}
*/
private void loadLang(String lang) {
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("lang", locale);
settingsLabel.setText(bundle.getString("settings"));
soundsLabel.setText(bundle.getString("sounds"));
clearProgressLabel.setText(bundle.getString("clearProgressLabel"));
resolutionLabel.setText(bundle.getString("resolutionLabel"));
sounds.setText(bundle.getString("sounds"));
resolution.setText(bundle.getString("resolutionLabel"));
clearProgress.setText(bundle.getString("clearProgressLabel"));
x1280.setText(bundle.getString("x1280"));
fullScreen.setText(bundle.getString("fullScreen"));
fs = bundle.getString("fullScreen");
}
public void soundsClicked() throws IOException{
output = new FileOutputStream("config.properties");
if(sounds.isSelected()){
Main.mediaPlayer.play();
properties.setProperty("sound","enabled");
}
else{
Main.mediaPlayer.pause();
properties.setProperty("sound","disabled");
}
properties.store(output,null);
}
}
| TommysG/memory-card-game | src/main/java/sample/SettingsPane.java |
1,686 | package accommodations;
import accommodations.reservervations.Date;
import accommodations.reservervations.Reservation;
import accommodations.reservervations.Reserve;
import users.Customers;
import java.util.ArrayList;
import java.util.List;
/**
* Η κλάση HotelRooms υλοποιεί τα ξενοδοχειακά δωμάτια. Κληρονομεί απο την
* {@link Accommodations} τα βασικά χαρακτηριστικά της και προσθέτει επιπλέον χαρακτηριστικά
* όπως το όνομα του ξενοδοχείου ,τη διεύθυνση του ξενοδοχείου (Πόλη ΟΧΙ ειδική διεύθυνση), αριθμό δωματίου , όροφο
* ,χωρητικότητα ατόμων, λίστα με τα ειδικά χαρακτηριστικά
* και τον ειδικό αναγνωριστικό αριθμό
*
*/
public class HotelRooms extends Accommodations implements Reserve
{
private final String hotelName;
private final String address; //Δεν αφορά συγκεκριμένη οδό αλλά πόλη
protected ArrayList<Reservation> reservedDates = new ArrayList<>();
private final int id;
private int roomNumber;
private int floor;
/**
* Ορίζει, με βάση τις παραμέτρους του κατασκευαστή, αρχικές
* τιμές στο δωμάτιο που καλείται να δημιουργηθεί.
*
* @param roomNumber Αριθμός δωματίου.
* @param squareMetres Τετραγωνικά μέτρα δωματίου.
* @param price Τιμή δωματίου (σε ευρώ).
* @param hotelName Όνομα ξενοδοχείου.
* @param address Διεύθυνση ξενοδοχείου.
* @param floor Όροφος δωματίου.
* @param id Αναγνωριστικό δωματίου (Δίνεται από το σύστημα).
* @param capacity Χωρητικότητα ατόμων στο δωμάτιο
* @param characteristics Λίστα με τα ειδικά χαρακτηριστικά του δωματίου
*/
public HotelRooms(int roomNumber, int squareMetres, int price,
String hotelName, String address, int floor, int id,
int capacity, List<String> characteristics, String imageName) {
super(squareMetres, price, capacity, characteristics, imageName);
this.hotelName = hotelName;
this.address = address;
this.floor = floor;
this.roomNumber = roomNumber;
this.id = id;
}
public String getHotelName() { return hotelName; }
public int getId() { return id; }
public int getFloor() { return floor; }
public void setFloor(int floor) { this.floor = floor; }
public String getAddress() { return address; }
public int getRoomNumber() { return roomNumber; }
public void setRoomNumber(int roomNumber) { this.roomNumber = roomNumber; }
@Override
public boolean Reserve(Customers customer, Date date) {
if (this.reservedDates.contains(date))
return false;
ArrayList<Date> temp = new ArrayList<>();
temp.add(date);
int x = reservationsIdentifierManager();
this.reservedDates.add(new Reservation(customer, temp, x));
return true;
}
@Override
public boolean Reserve(Customers customer, ArrayList<Date> dates) {
if (dates != null) {
for (Date wantedDate : dates) {
for (Date reservedDates : this.getUserReservations()) {
if (reservedDates.getDay() == wantedDate.getDay()
&& reservedDates.getMonth() == wantedDate.getMonth()
&& reservedDates.getYear() == wantedDate.getYear()) {
return false;
}
}
}
this.reservedDates.add(new Reservation(customer, dates, reservationsIdentifierManager()));
return true;
}
return false;
}
@Override
public ArrayList<Date> getUserReservations(Customers customer) {
ArrayList<Date> dates = new ArrayList<>();
for (Reservation ignored : reservedDates) {
if (ignored.getCustomer().getUsername().equals(customer.getUsername())) {
dates.addAll(ignored.getReservationPeriod());
}
}
return dates;
}
@Override
public ArrayList<Date> getUserReservations() {
ArrayList<Date> dates = new ArrayList<>();
for (Reservation ignored : reservedDates) {
dates.addAll(ignored.getReservationPeriod());
}
return dates;
}
@Override
public ArrayList<Reservation> getReservations()
{
return reservedDates;
}
}
| NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/accommodations/HotelRooms.java |
1,691 | /*
* The MIT License
*
* Copyright 2010 Georgios Migdos <[email protected]>.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package glossa.interpreter.symboltable.symbols;
import glossa.interpreter.core.InterpreterUtils;
import glossa.messages.Messages;
import glossa.statictypeanalysis.scopetable.symbols.Constant;
/**
*
* @author cyberpython
*/
public class RuntimeConstant extends RuntimeSimpleSymbol implements ValueContainer {
public RuntimeConstant(Constant c) {
super(c);
}
@Override
public String toString() {
return Messages.CONSTS_STR_CONSTANT+" "+super.toString()+" = "+InterpreterUtils.toPrintableString(super.getValue());
}
@Override
public void setValue(Object value) {
if(isInitialized()){
throw new RuntimeException("Η τιμή της σταθεράς "+getName()+" δε μπορεί να αλλάξει!");
}else{
super.setValue(value);
}
}
}
| cyberpython/glossa-interpreter | src/glossa/interpreter/symboltable/symbols/RuntimeConstant.java |
1,694 | package manage;
import entities.Photos;
import helpers.DateTime;
import helpers.SlugName;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.Part;
import javax.validation.constraints.NotNull;
import org.apache.log4j.Logger;
import sessionsBeans.UploadImageFacade;
@ManagedBean
@RequestScoped
public class UploadImageController implements Serializable {
final static Logger logger = Logger.getLogger(UploadImageController.class);
private List<Photos> photos;
// TODO Chnage image path
private String path = "C:/Users/user/Documents/NetBeansProjects/PrimeFaces/web/resources/images/";
@NotNull(message = "At can't be null")
private Part file;
@EJB
UploadImageFacade uploadImageFacade;
@PostConstruct
public void init() {
if (logger.isDebugEnabled()) { logger.debug("Init Upload Image Manage"); }
}
public String doUpload() throws IOException {
@NotNull(message = "Επιλέξτε ένα αρχείο") String filename = getFilename(file);
if (filename == null) {
return "";
}
//if the filenameis allready exists
File f = new File(path + filename);
if (f.exists() && !f.isDirectory()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Το αρχείο υπάρχει. Αλλάξτε το όνομα του αρχείου"));
return "";
} else {
file.write(path + getFilename(file));
Photos ph = new Photos();
ph.setUrl(filename);
String mimeType = new MimetypesFileTypeMap().getContentType(f);
if (!"image/png".equals(mimeType) && !"image/jpg".equals(mimeType) && !"image/jpeg".equals(mimeType)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Μη αποδεχτή μορφή αρχείου. Αποδεκτές Μορφές Αρχείων: PNG JPG JPEG"));
return "";
}
ph.setMIMEtype(mimeType);
uploadImageFacade.insertFilePathToDB(ph);
}
return "/photosAll.xhtml?faces-redirect=true";
}
private static String getFilename(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
filename = SlugName.convertToSlugName(filename);
return DateTime.getDateTime() + filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1);
}
}
return null;
}
public void deleteImage(String filename, int photosid) {
try {
uploadImageFacade.deletePhotoFromDatabase(photosid);
File fd = new File(path + filename);
if (fd.delete()) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Το αρχείο " + file.getName() + " διαγράφτηκε επιτυχώς!"));
} else {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Το αρχείο " + file.getName() + " ΔΕΝ διαγράφτηκε επιτυχώς!"));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public List<Photos> getPhotos() {
return photos = uploadImageFacade.getAllfiles();
}
public void setPhotos(List<Photos> photos) {
this.photos = photos;
}
public Part getFile() {
return file;
}
public void setFile(Part file) {
this.file = file;
}
}
| mixaverros88/dockerized-java-e-commerce-app | src/main/java/manage/UploadImageController.java |
1,700 | package accommodations;
import accommodations.reservervations.Date;
import accommodations.reservervations.Reservation;
import accommodations.reservervations.Reserve;
import users.Customers;
import java.util.ArrayList;
import java.util.List;
/**
* Η κλάση PrivateAccommodation υλοποιεί τα ιδιωτικά καταλύματα (Airbnb, House , Maisonette).
* Κληρονομεί απο την {@link Accommodations} τα βασικά χαρακτηριστικά και προσθέτει επιπλέον
* την επωνυμία του καταλύματος που ταυτίζεται με την επωνυμία του παρόχου που έχει καταχωρήσει το κατάλυμα,
* τον αναγνωριστικό αριθμό, τη διεύθυνση, τον τύπο του καταλύματος, την χωρητικότητα ατόμων, τη λίστα με
* τα ειδικά χαρακτηριστικά του καταλύματος
*/
public class PrivateAccommodation extends Accommodations implements Reserve {
private final String companyName;
private final int id;
private final String address; //Δεν αφορά συγκεκριμένη οδό αλλά πόλη
protected ArrayList<Reservation> reservedDates = new ArrayList<>();
private String type;
/**
* Ορίζει, με βάση τις παραμέτρους του κατασκευαστή, αρχικές
* τιμές στο κατάλυμα που καλείται να δημιουργηθεί.
*
* @param squareMetres Τετραγωνικά μέτρα δωματίου.
* @param price Τιμή δωματίου (σε ευρώ).
* @param type Τύπος καταλύματος.
* @param address Διεύθυνση καταλύματος.
* @param companyName Διεύθυνση καταλύματος.
* @param id Αναγνωριστικό καταλύματος (Δίνεται από το σύστημα).
* @param capacity Χωρητικότητα ατόμων στο κατάλυμα
* @param characteristics Λίστα με τα ειδικά χαρακτηριστικά του καταλύματος
*/
public PrivateAccommodation(int squareMetres, int price, String type,
String address, String companyName, int id, int capacity,
List<String> characteristics, String imagePath) {
super(squareMetres, price, capacity, characteristics, imagePath);
this.type = type;
this.address = address;
this.companyName = companyName;
this.id = id;
}
public String getCompanyName() { return companyName; }
public String getAddress() { return address; }
public String getType() { return type; }
public void setType(String type) { this.type = type; }
public int getId() { return id; }
@Override
public boolean Reserve(Customers customer, Date date)
{
if (this.reservedDates.contains(date))
return false;
ArrayList<Date> temp = new ArrayList<>();
temp.add(date);
this.reservedDates.add(new Reservation(customer, temp, reservationsIdentifierManager()));
return true;
}
@Override
public boolean Reserve(Customers customer, ArrayList<Date> dates) {
if (dates != null) {
for (Date wantedDate : dates) {
for (Date reservedDates : this.getUserReservations()) {
if (reservedDates.getDay() == wantedDate.getDay()
&& reservedDates.getMonth() == wantedDate.getMonth()
&& reservedDates.getYear() == wantedDate.getYear()) {
return false;
}
}
}
this.reservedDates.add(new Reservation(customer, dates, reservationsIdentifierManager()));
return true;
}
return false;
}
@Override
public ArrayList<Date> getUserReservations() {
ArrayList<Date> dates = new ArrayList<>();
for (Reservation ignored : reservedDates) {
dates.addAll(ignored.getReservationPeriod());
}
return dates;
}
@Override
public ArrayList<Date> getUserReservations(Customers customer) {
ArrayList<Date> dates = new ArrayList<>();
for (Reservation ignored : reservedDates) {
if (customer.getUsername().equals(ignored.getCustomer().getUsername())) {
dates.addAll(ignored.getReservationPeriod());
}
}
return dates;
}
@Override
public ArrayList<Reservation> getReservations() {
return reservedDates;
}
}
| NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/accommodations/PrivateAccommodation.java |
1,702 | package gr.aueb.cf.ch2;
// Γράφουμε εντολές import.
import java.math.BigInteger; // Πλήρες όνομα της BigInteger. Δημιουργείται αυτόματα.
public class AddBigIntsApp {
public static void main(String[] args) {
BigInteger bigNum1 = new BigInteger("1234567895555555555555555555555555555555555"); // Βγάζει το import java.math.BigInteger
BigInteger bigNum2 = new BigInteger("12345678999994");
BigInteger result = bigNum1.add(bigNum2);
System.out.printf("%,d%n", result); // "\n" Αλλάζει γραμμή (Linux). Windows: "\r\n". %n compatible και στα δυο.
/**
* %d
* %4d
* %04d
* %,04d
*/
}
}
| MytilinisV/codingfactorytestbed | ch2/AddBigIntsApp.java |
1,704 | package com.mgiandia.library.domain;
import java.time.LocalDate;
import java.util.HashSet;
import java.util.Set;
import com.mgiandia.library.contacts.Address;
import com.mgiandia.library.contacts.EmailAddress;
import com.mgiandia.library.contacts.TelephoneNumber;
import com.mgiandia.library.util.Money;
/**
* Ο δανειζόμενος.
* @author Νίκος Διαμαντίδης
*
*/
public class Borrower {
private int borrowerNo;
private TelephoneNumber telephone;
private EmailAddress eMail;
private Address address;
private BorrowerCategory category;
private Person person = new Person();
private Set<Loan> loans = new HashSet<Loan>();
/**
* Ο προκαθορισμένος κατασκευαστής.
*/
public Borrower() { }
/**
* Βοηθητικός κατασκευαστής που αρχικοποιεί
* τα βασικά στοιχεία του δανειζόμενου.
* @param borrowerNo Αριθμός δανειζομένου
* @param firstName Όνομα
* @param lastName Επώνυμο
* @param address Ταχυδρομική διεύθυνση
* @param eMail Διεύθυνση ηλεκτρονικού ταχυδρομείου
* @param telephone Αριθμός Τηλεφώνου
*/
public Borrower(int borrowerNo, String firstName,
String lastName, Address address,
EmailAddress eMail,
TelephoneNumber telephone) {
this.borrowerNo = borrowerNo;
person.setFirstName(firstName);
person.setLastName(lastName);
this.address = address == null ? null : new Address(address);
this.eMail = eMail;
this.telephone = telephone;
}
/**
* Επιστρέφει τον αριθμό δανειζομένου. Ο αριθμός δανειζομένου
* προσδιορίζει μοναδικά κάθε δανειζόμενο.
* @return Τον αριθμό δανειζομένου
*/
public int getBorrowerNo() {
return borrowerNo;
}
/**
* Θέτει τον αριθμό δανειζομένου. Ο αριθμός δανειζομένου
* προσδιορίζει μοναδικά κάθε δανειζόμενο
* @param borrowerNo Ο αριθμός δανειζομένου
*/
public void setBorrowerNo(int borrowerNo) {
this.borrowerNo = borrowerNo;
}
/**
* Θέτει το όνομα του δανειζομένου.
* @param firstName Το όνομα του δανειζομένου
*/
public void setFirstName(String firstName) {
person.setFirstName(firstName);
}
/**
* Επιστρέφει το όνομα του δανειζομένου.
* @return Το όνομα του δανειζομένου
*/
public String getFirstName() {
return person.getFirstName();
}
/**
* Θέτει το επώνυμο του δανειζομένου.
* @param lastName Το επώνυμο του δανειζομένου
*/
public void setLastName(String lastName) {
person.setLastName(lastName);
}
/**
* Επιστρέφει το επώνυμο του δανειζομένου.
* @return Το επώνυμο του δανειζομένου
*/
public String getLastName() {
return person.getLastName();
}
/**
* Θέτει τον αριθμό τηλεφώνου του δανειζομένου.
* @param telephone Ο αριθμός τηλεφώνου
*/
public void setTelephone(TelephoneNumber telephone) {
this.telephone = telephone;
}
/**
* Επιστρέφει τον αριθμό τηλεφώνου του δανειζομένου.
* @return Ο αριθμός τηλεφώνου
*/
public TelephoneNumber getTelephone() {
return telephone;
}
/**
* Θέτει το e-mail του δανειζομένου.
* @param eMail Το e-mail του δανειζομένου
*/
public void setEmail(EmailAddress eMail) {
this.eMail = eMail;
}
/**
* Επιστρέφει το e-mail του δανειζομένου.
* @return Το e-mail του δανειζομένου
*/
public EmailAddress getEmail() {
return eMail;
}
/**
* Θέτει την κατηγορία δανειζομένου.
* @param category Η κατηγορία δανειζομένου
*/
public void setCategory(BorrowerCategory category) {
this.category = category;
}
/**
* Επιστρέφει την κατηγορία δανειζομένου.
* @return Η κατηγορία δανειζομένου
*/
public BorrowerCategory getCategory() {
return category;
}
/**
* Θέτει την ταχυδρομική διεύθυνση του δανειζομένου.
* Αποθηκεύεται αντίγραφο της διεύθυνση. Για να αλλάξετε τη διεύθυνση
* δημιουργήστε ένα νέο αντικείμενο της κλάσης {@link Address}
* @param address Η ταχυδρομική διεύθυνση
*/
public void setAddress(Address address) {
this.address = address == null ? null : new Address(address);
}
/**
* Επιστρέφει την ταχυδρομική διεύθυνση του δανειζομένου
* Επιστρέφει αντίγραφο της διεύθυνσης. Για να αλλάξετε τη διεύθυνση
* Δημιουργήστε ένα αντικείμενο της κλάσης {@link Address}
* και χρησιμοποιήστε τη μέθοδο {@link Borrower#setAddress(Address)}
* @return Η διεύθυνση του δανειζομένου
*/
public Address getAddress() {
return address == null ? null : new Address(address);
}
/**
* Επιστέφει τη συλλογή των δανεισμών του δανειζομένου.
* Η συλλογή είναι αντίγραφο της συλλογής των δανεισμών.
* @return Η συλλογή των δανεισμών
*/
public Set<Loan> getLoans() {
return new HashSet<Loan>(loans);
}
/**
* Μη ενθυλακωμένη συλλογή των δανεισμών.
* @return Η συλλογή των δανεισμών
*/
Set<Loan> friendLoans() {
return loans;
}
/**
* Επιστρέφει τον αριθμό των αντιτύπων που έχει δανειστεί ο
* δανειζόμενος και δεν έχει επιστρέψει.
* @return Ο αριθμός των αντιτύπων που δεν έχουν επιστραφεί.
*/
private int countPendingItems() {
int pendingItems = 0;
for (Loan loan : loans) {
if (loan.isPending()) {
pendingItems++;
}
}
return pendingItems;
}
/**
* Επιστέφει {@code true} αν ο δανειζόμενος μπορεί
* να δανειστεί κάποιο αντίτυπο.
* Το αν ο δανειζόμενος μπορεί να δανειστεί κάποιο
* αντίτυπο εξαρτάται από το μέγιστο αριθμό αντιτύπων
* που μπορεί να δανειστεί και από τον αριθμό των
* αντιτύπων που έχει δανειστεί και δεν έχει επιστρέψει
* Επιστρέφει {@code false} εάν η κατηγορία δανειζομένου
* είναι {@code null}
* @return {@code true} εάν ο δανειζόμενος μπορεί
* να δανειστεί κάποιο αντίτυπο.
*/
public boolean canBorrow() {
int pendingItems;
if (getCategory() == null) {
return false;
}
pendingItems = countPendingItems();
return getCategory().canBorrow(pendingItems);
}
/**
* Επιστρέφει την προθεσμία επιστροφής για κάποια ημερομηνία δανεισμού.
* Η προθεσμία επιστροφής εκτός από την ημερομηνία δανεισμού
* εξαρτάται και το μέγιστο
* αριθμό ημερών που μπορεί να δανειστεί ο δανειζόμενος κάποιο αντίτυπο.
* Επιστρέφει {@code null} αν δεν υπάρχει
* κατηγορία δανειζομένου ({@link BorrowerCategory}).
* @param loanDate Η ημερομηνία δανεισμού.
* @return Η προθεσμία επιστροφής.
*/
public LocalDate getLoanDue(LocalDate loanDate) {
if (loanDate == null) {
return null;
}
if (getCategory() == null) {
return loanDate;
}
return category.getLoanDue(loanDate);
}
/**
* Επιστρέφει ο ημερήσιο πρόστιμο για το δανειζόμενο.
* Επιστρέφει {@code null} αν δεν υπάρχει
* κατηγορία δανειζομένου ({@link BorrowerCategory})
* @return Το ημερήσιο πρόστιμο
*/
public Money getDailyFine() {
if (getCategory() == null) {
return null;
}
return getCategory().getDailyFine();
}
}
| diamantidakos/Library | src/main/java/com/mgiandia/library/domain/Borrower.java |
1,705 | package gr.cti.eslate.base.container.internalFrame;
import java.util.ListResourceBundle;
/**
* User: yiorgos
* Date: 17 Δεκ 2007
* Time: 11:54:38 πμ
*/
public class ESlateInternalFrameResourceBundle_el_GR extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents={
{"Maximize", "Μεγιστοποίηση"},
{"Iconify", "Απόκρυψη"},
{"Close", "Διαγραφή"},
{"Restore", "Αποκατάσταση"},
{"ShowComponentMenu", "Προβολή μενού ψηφίδας"},
{"frame", "Πλαίσιο"},
{"north", "Βόρεια περιοχή"},
{"south", "Νότια περιοχή"},
{"east", "Ανατολική περιοχή"},
{"west", "Δυτική περιοχή"},
{"northOverWest", "Βόρειο πάνω από Δυτικό"},
{"eastOverNorth", "Ανατολικό πάνω από Βόρειο"},
{"southOverEast", "Νότιο πάνω από Ανατολικό"},
{"westOverSouth", "Δυτικό πάνω από Νότιο"},
{"northVisible", "Ορατή Βόρεια περιοχή"},
{"southVisible", "Ορατή Νότια περιοχή"},
{"eastVisible", "Ορατή Ανατολική περιοχή"},
{"westVisible", "Ορατή Δυτική περιοχή"},
{"draggableFromNorth", "Μετακίνηση από Βόρεια"},
{"draggableFromSouth", "Μετακίνηση από Νότια"},
{"draggableFromEast", "Μετακίνηση από Ανατολικά"},
{"draggableFromWest", "Μετακίνηση από Δυτικά"},
{"ok", "Εντάξει"},
{"layoutcustomizer", "Τροποποίηση διάταξης"},
{"fooLayoutCustomizer", "Διάταξη"},
{"fooLayoutCustomizertip", "Ελέγχει τη διάταξη των περιφερειακών περιοχών."},
{"change", "Αλλαγή"},
{"closeButtonVisible", "Κουμπί κλεισίματος ορατό"},
{"minMaxButtonVisible", "Κουμπιά μεγιστο/ελαχιστο-ποίησης ορατά"},
{"helpButtonVisible", "Κουμπί βοήθειας ορατό"},
{"infoButtonVisible", "Κουμπί πληροφοριών ορατό"},
{"plugButtonVisible", "Κουμπί συνδέσμων ορατό"},
{"maxSizeRespected", "Χρήση μεγίστου δυνατού μεγέθους ψηφίδας"},
{"minSizeRespected", "Χρήση ελαχίστου δυνατού μεγέθους ψηφίδας"},
{"maxSizeRespectedTip", "Το μέγιστο μέγεθος ψηφίδας καθορίζει και το μέγιστο μέγεθος του παραθύρου"},
{"minSizeRespectedTip", "Το ελάχιστο μέγεθος ψηφίδας καθορίζει και το ελάχιστο μέγεθος του παραθύρου"},
{"modal", "Modal"},
{"modalTip", "Η ψηφίδα είναι \"modal\", δηλ. πάνω από τις υπόλοιπες και συνεχώς ενεργή"},
// {"borderActivationInsets", "Ευαισθησία περιγράμματος αλλαγής μεγέθους"},
// {"borderActivationInsetsTip","Ρυθμίζει την περιοχή της ψηφίδας που προκαλεί την εμφάνιση του περιγράμματος"},
{"FrameMsg1", "Είστε σίγουροι ότι θέλετε να αφαιρέσετε την ψηφίδα \""},
{"FrameMsg2", "Αφαίρεση ψηφίδας"},
{"FrameMsg3", "\";"},
//SkinPane
{"background", "Υπόβαθρο: Χρώμα"},
{"backgroundImage", "Υπόβαθρο: Εικόνα"},
{"preferredSize", "Επιθυμητό μέγεθος"},
{"opaque", "Αδιαφανές"},
{"centered", "ΣΤΟ ΚΕΝΤΡΟ"},
{"stretched", "ΕΚΤΕΤΑΜΕΝΗ"},
{"tiled", "ΣΕ ΠΑΡΑΘΕΣΗ"},
{"customSize", "Προσαρμοσμένο μέγεθος"},
{"customSizeTip", "Το μέγεθος της περιοχής όταν το προσαρμοσμένο μέγεθος είναι ενεργό"},
{"useCustomSize", "Προσαρμοσμένο μέγεθος ενεργό"},
{"useCustomSizeTip", "Όταν είναι ενεργό το μέγεθος δεν είναι το προτιμώμενο αλλά αυτό που δίνεται"},
{"MicroworldLockedException", "O μικρόκοσμος είναι κλειδωμένος και δεν είναι δυνατή η αλλαγή των ρυθμίσεών του"},
{"setEffect", "Εφέ"},
{"setEffectTip", "Επιλέξτε το εφέ που θα πραγματοποιηθεί στην ψηφίδα"},
{"noneEffect", "Κανένα"},
{"alphaCompositeEffect", "Alpha composite"},
{"clippingEffect", "Clipping"},
{"intersectionEffect", "Intersection"},
{"edit", "Διαμόρφωση"},
{"effectsDialogTitle", "Διαμόρφωση εφέ"},
{"okButton", "Εντάξει"},
{"cancelButton", "Άκυρο"},
{"antiAliasingCheck", "Antialiasing"},
{"renderingQualityCheck", "Ποιότητα rendering"},
{"numberOfSteps", "Αριθμός βημάτων"},
{"direction", "Κατεύθυνση"},
{"heightDecrease", "Μείωση ύψους"},
{"heightIncrease", "Αύξηση ύψους"},
{"widthDecrease", "Μείωση πλάτους"},
{"widthIncrease", "Αύξηση πλάτους"},
{"clipShapeType", "Σχήμα παραθύρου"},
{"clipShapeTypeTip", "Ορισμός του σχήματος του παραθύρου της ψηφίδας"},
};
}
| vpapakir/myeslate | widgetESlate/src/gr/cti/eslate/base/container/internalFrame/ESlateInternalFrameResourceBundle_el_GR.java |
1,706 | package api;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
/**
* Η κλάση αυτή διαχειρίζεται τις πληροφορίες/χαρακτηριστικά ενός καταλύματος.
*/
public class Accommodation implements Serializable {
private float avgRating;
private int totalEvaluations; //avgRating και totalEvaluations αλλάζουν κάθε φορά που προστίθεται αξιολόγηση στο κατάλυμα
private long singularId; //Για να αποφευχθούν προβλήματα συνωνυμίας !!!!!!
private final Provider provider;
private String name;
private String description;
private String stayType; //ξενοδοχείο, διαμέρισμα, μεζονέτα --> hotel, apartment, maisonette
private Location place;
private ArrayList<Utility> typesOfUtilities;
/**
* Κατασκευαστής της κλάσης των καταλυμάτων. Αρχικοποιεί τα πεδία name, description, stayType και provider σύμφωνα
* με τα ορίσματα που δίνονται. Τα πεδία avgRating και totalEvaluations αρχικοποιούνται στο μηδέν. Επίσης, υπολογίζεται
* ο κωδικός του καταλύματος ως το άθροισμα του hashCode() του username του παρόχου του καταλύματος και του ονόματος
* του ίδιου καταλύματος. Τέλος, αρχικοποιείται η λίστα των παροχών με 9 αντικείμενα για να αποφευχθούν exceptions
* του τύπου ArrayIndexOutOfBoundsException σε διάφορα σημεία του προγράμματος.
* @param name Το όνομα του καταλύματος
* @param description Περιγραφή του καταλύματος
* @param stayType Τύπος καταλύματος: 1. Ξενοδοχείο, 2. Διαμέρισμα, 3. Μεζονέτα
* @param location Αντικείμενο της κλάσης Location για την αποθήκευση της τοποθεσίας του καταλύματος (πόλη, διεύθυνση
* και Τ.Κ.)
* @param provider Ο πάροχος του καταλύματος (αντικείμενο της κλάσης Provider)
*/
public Accommodation(String name, String description, String stayType, Location location, Provider provider) {
this.name = name;
this.description = description;
this.stayType = stayType;
totalEvaluations = 0;
place = location;
this.provider = provider;
singularId = provider.getUserName().hashCode() + name.hashCode(); //Μοναδικό id καταλύματος --> Απαγορεύω στον provider να κάνει δύο καταλύματα με το ίδιο όνομα
//Μοναδικός κωδικός καταλύματος ακόμα και αν ο ίδιος πάροχος έχει δύο καταλύματα με το ίδιο όνομα
avgRating = 0;
typesOfUtilities = new ArrayList<>(); //Για λόγους debugging
Utility view = new Utility();
typesOfUtilities.add(view);
Utility bath = new Utility();
typesOfUtilities.add(bath);
Utility washingClothes = new Utility();
typesOfUtilities.add(washingClothes);
Utility entertainment = new Utility();
typesOfUtilities.add(entertainment);
Utility temperatureControl = new Utility();
typesOfUtilities.add(temperatureControl);
Utility internet = new Utility();
typesOfUtilities.add(internet);
Utility foodArea = new Utility();
typesOfUtilities.add(foodArea);
Utility outsideSpace = new Utility();
typesOfUtilities.add(outsideSpace);
Utility parkingSpace = new Utility();
typesOfUtilities.add(parkingSpace);
}
/**
* Επιστρέφει το όνομα του καταλύματος
* @return το όνομα του καταλύματος
*/
public String getName() {
return name;
}
/**
* Αλλάζει το όνομα του καταλύματος σε ό,τι δίνεται ως όρισμα
* @param name το νέο όνομα του καταλύματος
*/
public void setName(String name) {
this.name = name;
}
/**
* Επιστρέφει την περιγραφή του καταλύματος
* @return η περιγραφή του καταλύματος
*/
public String getDescription() {
return description;
}
/**
* Αλλάζει την περιγραφή του καταλύματος σε ό,τι δίνεται ως όρισμα
* @param description η νέεα περιγραφή του καταλύματος
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Επιστρέφει τον τύπο του καταλύματος που για την ώρα πρέπει να είναι 1. Ξενοδοχείο, 2. Διαμέρισμα, 3. Μεζονέτα
* @return τύπος καταλύματος
*/
public String getStayType() {
return stayType;
}
/**
* Αλλάζει την περιγραφή του καταλύματος σε ό,τι δίνεται ως όρισμα
* @param stayType ο νέος τύπος καταλύματος
*/
public void setStayType(String stayType) {
this.stayType = stayType;
}
/**
* Επιστρέφει το αντικείμενο της τοποθεσίας του καταλύματος
* @return τοποθεσία καταλύματος (πόλη, διεύθυνση και Τ.Κ.)
*/
public Location getLocation() { return place; }
/**
* Αλλάζει την τοποθεσία του καταλύματος σε ό,τι δίνεται ως όρισμα
* @param place το νέο αντικείμενο τοποθεσίας του καταλύματος
*/
public void setPlace(Location place) {
this.place = place;
}
/**
* Επιστρέφει το αντικείμενο του παρόχου του καταλύματος
* @return τον πάροχο του καταλύματος
*/
public Provider getProvider() {
return provider;
}
/**
* Επιστρέφει το μοναδικό id του καταλύματος που αρχικοποιείται στον κατασκευαστή
* @return μοναδικό id του καταλύματος
*/
public long getSingularId() {
return singularId;
}
/**
* Η μέθοδος αυτή χρησιμοποιείται για την ανανέωση του μοναδικού κωδικού καταλύματος σε περίπτωση
* μετονομασίας του. Έτσι, διατηρείται η μοναδικότητα του id αν ο πάροχος μετονομάσει αυτό το κατάλυμα και μετά
* δημιουργήσει άλλο με το αρχικό όνομα του πρώτου.
*/
public void updateSingularId() {
singularId = provider.getUserName().hashCode() + name.hashCode();
}
/**
* Επιστρέφει τη μέση βαθμολογία του καταλύματος
* @return μέση βαθμολογία του καταλύματος
*/
public float getAvgRating() {
return avgRating;
}
/**
* Επιστρέφει τον αριθμό των αξιολογήσεων του καταλύματος
* @return αριθμός των αξιολογήσεων του καταλύματος
*/
public int getTotalEvaluations() {
return totalEvaluations;
}
/**
* Επιστρέφει τη λίστα με τα αντικείμενα παροχών του καταλύματος
* @return λίστα με τα αντικείμενα παροχών του καταλύματος
*/
public ArrayList<Utility> getTypesOfUtilities() {
return typesOfUtilities;
}
/**
* Αλλάζει τη λίστα των παροχών σε περίπτωση μεταγενέστερης επεξεργασίας τους από τον πάροχο.
* @param typesOfUtilities η νέα λίστα παροχών
*/
public void setTypesOfUtilities(ArrayList<Utility> typesOfUtilities) {
this.typesOfUtilities = typesOfUtilities;
}
/**
* Η μέθοδος αυτή ενημερώνει τον μέσο όρο βαθμολογίας ενός καταλύματος και τον αριθμό των αξιολογήσεων για αυτό.
* @param evaluations Όλες οι βαθμολογίες για όλα τα καταλύματα
*/
public void updateAvgRatingOfAccommodation(ArrayList<Evaluation> evaluations) {
if (evaluations.size() == 0) { //μηδενισμός των μεταβλητών αν δεν έχουν προστεθεί αξιολογήσεις ή αν διαγραφούν αργότερα όλες
avgRating = 0;
totalEvaluations = 0;
return;
}
float totalSum = 0;
int numOfEvaluations = 0;
for (Evaluation evaluation : evaluations) {
if (evaluation.getAccommodation().equals(this)) { //αν η αξιολόγηση απευθύνεται στο συγκεκριμένο κατάλυμα
totalSum += evaluation.getGrade();
numOfEvaluations++;
}
}
if (numOfEvaluations == 0) {
avgRating = 0;
totalEvaluations = 0;
return;
}
totalEvaluations = numOfEvaluations;
avgRating = totalSum / numOfEvaluations;
}
/**
* Ελέγχει την ισότητα δύο αντικειμένων Accommodation. Η ισότητα τους αν οι θέσεις μνήμης διαφέρουν και πρόκειται για
* αντικείμενο τύπου Accommodation έγκειται στην ισότητα των id των δύο καταλυμάτων.
* @param o το αντικείμενο που θέλουμε να συγκρίνουμε με το this
* @return true αν ισχύει η ισότητα των δύο αντικειμένων
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Accommodation that)) return false;
return getSingularId() == that.getSingularId();
}
/**
* Επιστρέφει τη συμβολοσειρά που αντιστοιχεί στο κατάλυμα ως "[όνομα], [πόλη], [τύπος καταλύματος],
* [μέση βαθμολογία] ([αριθμός αξιολογήσεων])".
* @return συμβολοσειρά που αντιστοιχεί στο κατάλυμα
*/
@Override
public String toString() {
return name + ", " + getLocation().getTown() + ", " + stayType + ", " + avgRating +"(" + totalEvaluations+")";
}
}
| patiosga/myreviews | src/api/Accommodation.java |
1,708 | package accommodations;
import accommodations.reservervations.Date;
import accommodations.reservervations.Reservation;
import users.Customers;
import users.Providers;
import java.io.*;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
/**
* Η κλάση Accommodations υλοποιεί τα καταλύματα. Λειτουργεί ως πρόγονος κλάση για τις
* {@link HotelRooms} και {@link PrivateAccommodation} και περιέχει βασικά χαρακτηριστικά
* τους όπως τα τετραγωνικά μέτρα, την τιμή,την χωρητικότητα ατόμων,τη λίστα
* με τα ειδικά χαρακτηριστικά του καταλύματος και το ειδικό αναγνωριστικό καταλύματος. Ακόμα περιέχει
* δύο λίστες για την αποθήκευση όλων τον καταχωρημένων καταλυμάτων (δωματίων, ιδιωτικών καταλυμάτων)
* <p>
* Υλοποιεί: Αναζήτηση ιδιωτικού καταλύματος με κριτήρια -> {@link #SearchPrivateAccommodations(String, int, ArrayList, List)},
* αναζήτηση ξενοδοχειακού δωματίου με κριτήρια -> {@link #SearchHotelRooms(String, int, ArrayList, List)},
* ακύρωση κράτησης για ιδιωτικό κατάλυμα -> {@link #CancelReservationPrivateAccommodation(int, Customers)},
* ακύρωση κράτησης για ξενοδοχειακό δωμάτιο -> {@link #CancelReservationHotelRoom(int, Customers)},
* εύρεση και επιστροφή κρατήσεων σε ξενοδοχειακά δωμάτια για έναν συγκεκριμένο χρήστη -> {@link #UserHotelReservations(Customers)},
* εύρεση και επιστροφή κρατήσεων σε ιδιωτικά καταλύματα για έναν συγκεκριμένο χρήστη -> {@link #UserPrivateReservations(Customers)},
*
* </p>
*/
public class Accommodations implements Serializable {
private static ArrayList<HotelRooms> rooms;
private static ArrayList<PrivateAccommodation> airbnb;
private static int baseIdentifier;
private static int reservationsBaseIdentifier;
private static int imageIdentifier;
private int squareMetres;
private int price;
private int capacity;
private String imageName;
private List<String> characteristics;
public Accommodations() {
rooms = new ArrayList<>();
airbnb = new ArrayList<>();
baseIdentifier = 1000;
reservationsBaseIdentifier = 100;
imageIdentifier = 0;
this.squareMetres = 0;
this.capacity = 0;
characteristics = new ArrayList<>();
CreateDefaultAccommodation();
}
public Accommodations(int squareMetres, int price, int capacity, List<String> characteristics, String imageName) {
this.squareMetres = squareMetres;
this.price = price;
this.capacity = capacity;
this.characteristics = characteristics;
this.imageName = imageName;
}
public int getNumberOfAccommodations() {
return rooms.size() + airbnb.size();
}
public List<String> getCharacteristics() {
return characteristics;
}
public int getSquareMetres() {
return squareMetres;
}
public static void setBaseIdentifier(int baseIdentifier) {
Accommodations.baseIdentifier = baseIdentifier;
}
public static void setReservationsBaseIdentifier(int reservationsBaseIdentifier) {
Accommodations.reservationsBaseIdentifier = reservationsBaseIdentifier;
}
public static void setImageIdentifier(int imageIdentifier) {
Accommodations.imageIdentifier = imageIdentifier;
}
public void setSquareMetres(int squareMetres) {
this.squareMetres = squareMetres;
}
public ArrayList<HotelRooms> getRooms() {
return rooms;
}
public ArrayList<PrivateAccommodation> getAirbnb()
{
return airbnb;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void setCharacteristics(List<String> characteristics) {
this.characteristics = characteristics;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public String getImageName() {
return imageName;
}
/**
* Η μέθοδος αυτή φιλτράρει τα ιδιωτικά καταλύματα και επιστρέφει αυτά με οποία τα κριτήρια αναζήτησης
* που έδωσε ο χρήστης ταυτίζονται
*
* @param address Διεύθυνση ξενοδοχείου .Υποχρεωτικό πεδίο για την αναζήτηση δωματίου
* @param capacity Χωρητικότητα
* @param ranges Λίστα με το εύρος τετραγωνικών/τιμής
* @param characteristics Λίστα με τα χαρακτηριστικά του δωματίου
* @return Λίστα με τα ιδιωτικά καταλύματα που βρέθηκαν βάσει των κριτηρίων που δώθηκαν
* ως παράμετροι. null Αν το πεδίο της διεύθυνσης είναι κενό
*/
public ArrayList<PrivateAccommodation> SearchPrivateAccommodations(String address, int capacity,
ArrayList<ArrayList<Integer>> ranges,
List<String> characteristics) {
HashSet<PrivateAccommodation> filtered = new HashSet<>();
for (PrivateAccommodation accommodation : airbnb) {
if (accommodation.getAddress().equals(address) && capacity <= 0 && ranges.get(0).get(0) <= 0
&& ranges.get(1).get(0) <= 0 && characteristics == null) {
filtered.add(accommodation);
}
if (accommodation.getAddress().equalsIgnoreCase(address) && capacity > 0) {
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (capacity == accommodation.getCapacity())
filtered.add(accommodation);
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (capacity == accommodation.getCapacity() && accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (capacity == accommodation.getCapacity() && accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1) &&
accommodation.getPrice() >= ranges.get(1).get(0) && accommodation.getPrice() <= ranges.get(1).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (capacity == accommodation.getCapacity() && accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1) &&
accommodation.getPrice() >= ranges.get(1).get(0) && accommodation.getPrice() <= ranges.get(1).get(1) &&
accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (accommodation.getCapacity() == capacity && accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(1).get(0)
&& accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (capacity == accommodation.getCapacity() && accommodation.getPrice() >= ranges.get(1).get(0)
&& accommodation.getPrice() <= ranges.get(1).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (capacity == accommodation.getCapacity() && accommodation.getPrice() >= ranges.get(1).get(0)
&& accommodation.getPrice() <= ranges.get(1).get(1)
&& accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (capacity == accommodation.getCapacity() && accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics))
filtered.add(accommodation);
}
}
if (accommodation.getAddress().equals(address) && capacity < 0) {
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1) &&
accommodation.getPrice() >= ranges.get(1).get(0) && accommodation.getPrice() <= ranges.get(1).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(0).get(1) &&
accommodation.getPrice() >= ranges.get(1).get(0) && accommodation.getPrice() <= ranges.get(1).get(1) &&
accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (accommodation.getSquareMetres() >= ranges.get(0).get(0)
&& accommodation.getSquareMetres() <= ranges.get(1).get(0)
&& accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (accommodation.getPrice() >= ranges.get(1).get(0)
&& accommodation.getPrice() <= ranges.get(1).get(1)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (accommodation.getPrice() >= ranges.get(1).get(0)
&& accommodation.getPrice() <= ranges.get(1).get(1)
&& accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics)) {
filtered.add(accommodation);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (accommodation.ContainsAtLeastOneCharacteristicPrivate(characteristics))
filtered.add(accommodation);
}
}
}
return new ArrayList<>(filtered);
}
/**
* Μέθοδος που χρησιμοποιείται στην αναζήτηση δωματίου. Βρίσκει και επιστρέφει αν έστω ένα χαρακτηριστικό
* από τη λίστα που δίνεται ως όρισμα περιέχεται σε κάποιο από τα δωμάτια των ξενοδοχείων
*
* @param characteristics Λίστα με τα χαρακτηριστικά του δωματίου για το οποίο ο χρήστης κάνει αναζήτηση
* @return true/false ανάλογα με το αν περιέχεται ή όχι έστω ένα χαρακτηριστικό σε κάποιο δωμάτιο
*/
public boolean ContainsAtLeastOneCharacteristicRoom(List<String> characteristics) {
boolean contains = false;
if (characteristics != null) {
for (String has : characteristics) {
for (String index : this.getCharacteristics()) {
if (index.equalsIgnoreCase(has)) {
contains = true;
break;
}
}
}
}
return contains;
}
/**
* Μέθοδος που χρησιμοποιείται στην αναζήτηση ιδιωτικού καταλύματος. Βρίσκει και επιστρέφει αν έστω ένα χαρακτηριστικό
* από τη λίστα που δίνεται ως όρισμα περιέχεται σε κάποιο από τα ιδιωτικά καταλύματα
*
* @param characteristics Λίστα με τα χαρακτηριστικά του ιδιωτικού καταλύματος για το οποίο ο χρήστης κάνει αναζήτηση
* @return true/false ανάλογα με το αν περιέχεται ή όχι έστω ένα χαρακτηριστικό σε κάποιο ιδιωτικό κατάλυμα
*/
public boolean ContainsAtLeastOneCharacteristicPrivate(List<String> characteristics) {
boolean contains = false;
if (characteristics != null) {
for (String has : characteristics) {
for (String index : this.getCharacteristics()) {
if (index.equalsIgnoreCase(has)) {
contains = true;
break;
}
}
}
}
return contains;
}
/**
* Η μέθοδος αυτή φιλτράρει τα ξενοδοχειακά δωμάτια και επιστρέφει αυτά με οποία τα κριτήρια αναζήτησης
* που έδωσε ο χρήστης ταυτίζονται
* @param address Διεύθυνση ξενοδοχείου .Υποχρεωτικό πεδίο για την αναζήτηση δωματίου
* @param capacity Χωρητικότητα
* @param ranges Λίστα με το εύρος τετραγωνικών/τιμής
* @param characteristics Λίστα με τα χαρακτηριστικά του δωματίου
* @return Λίστα με τα δωμάτια που βρέθηκαν βάσει των κριτηρίων που δώθηκαν
* ως παράμετροι. null Αν το πεδίο της διεύθυνσης είναι κενό
*/
public ArrayList<HotelRooms> SearchHotelRooms(String address, int capacity,
ArrayList<ArrayList<Integer>> ranges,
List<String> characteristics) {
ArrayList<HotelRooms> filtered = new ArrayList<>();
if (address.equals("")) {
System.out.println("fsfd");
return null;
}
for (HotelRooms room : rooms) {
if (room.getAddress().equalsIgnoreCase(address) && capacity <= 0 && ranges.get(0).get(0) <= 0
&& ranges.get(1).get(0) <= 0 && characteristics == null) {
filtered.add(room);
}
if (room.getAddress().equals(address) && capacity > 0) {
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (capacity == room.getCapacity())
filtered.add(room);
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (capacity == room.getCapacity() && room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (capacity == room.getCapacity() && room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1) &&
room.getPrice() >= ranges.get(1).get(0) && room.getPrice() <= ranges.get(1).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (capacity == room.getCapacity() && room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1) &&
room.getPrice() >= ranges.get(1).get(0) && room.getPrice() <= ranges.get(1).get(1) &&
room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (room.getCapacity() == capacity && room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(1).get(0)
&& room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (capacity == room.getCapacity() && room.getPrice() >= ranges.get(1).get(0)
&& room.getPrice() <= ranges.get(1).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (capacity == room.getCapacity() && room.getPrice() >= ranges.get(1).get(0)
&& room.getPrice() <= ranges.get(1).get(1)
&& room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (capacity == room.getCapacity() && room.ContainsAtLeastOneCharacteristicRoom(characteristics))
filtered.add(room);
}
}
if (room.getAddress().equals(address) && capacity < 0) {
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics == null) {
if (room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1) &&
room.getPrice() >= ranges.get(1).get(0) && room.getPrice() <= ranges.get(1).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(0).get(1) &&
room.getPrice() >= ranges.get(1).get(0) && room.getPrice() <= ranges.get(1).get(1) &&
room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) > 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (room.getSquareMetres() >= ranges.get(0).get(0)
&& room.getSquareMetres() <= ranges.get(1).get(0)
&& room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics == null) {
if (room.getPrice() >= ranges.get(1).get(0)
&& room.getPrice() <= ranges.get(1).get(1)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) > 0 && characteristics != null) {
if (room.getPrice() >= ranges.get(1).get(0)
&& room.getPrice() <= ranges.get(1).get(1)
&& room.ContainsAtLeastOneCharacteristicRoom(characteristics)) {
filtered.add(room);
}
}
if (ranges.get(0).get(0) <= 0 && ranges.get(1).get(0) <= 0 && characteristics != null) {
if (room.ContainsAtLeastOneCharacteristicRoom(characteristics))
filtered.add(room);
}
}
}
return new ArrayList<>(filtered);
}
/**
* Αναζήτηση δωματίου με κριτήριο τον
* αναγνωριστικό του αριθμό.
*
* @param id Αναγνωριστικό δωματίου.
* @return Τη θέση (στη λίστα) του δωματίου
* αν υπάρχει, διαφορετικά -1.
*/
public int FindRoom(int id)
{
int positionFound = -1;
int position = 0;
for (HotelRooms room : this.getRooms())
{
if (room.getId() == id)
{
positionFound = position;
}
position++;
}
return positionFound;
}
/**
* Αναζήτηση ιδιωτικού καταλύματος με κριτήριο
* τον αναγνωριστικό του αριθμό.
*
* @param id Αναγνωριστικό καταλύματος.
* @return Τη θέση (στη λίστα) του ιδιωτικού
* καταλύματος αν υπάρχει, διαφορετικά -1.
*/
public int FindAccommodation(int id)
{
int positionFound = -1;
int position = 0;
for (PrivateAccommodation accommodation : this.getAirbnb())
{
if (accommodation.getId() == id)
{
positionFound = position;
}
position++;
}
return positionFound;
}
/**
* Μέθοδος ακύρωσης κράτησης του χρήστη τύπου πελάτη
* ({@link Customers}) για ιδιωτικά καταλύματα.
*
* @param id Αναγνωριστικό κράτησης η οποία
* θα ακυρωθεί.
* @param customer Τύπος χρήστη πελάτης: Γίνεται χρήση
* για να προσεγγιστούν όλες (μόνο)
* κρατήσεις του εκάστοτε χρήστη.
* @return Αν ακυρωθεί η επιθυμητή κράτηση τότε επιστρέφετε
* true, διαφορετικά false.
*/
public boolean CancelReservationPrivateAccommodation(int id, Customers customer)
{
boolean isCanceled = false;
ArrayList<Reservation> needsCancel = new ArrayList<>();
for (PrivateAccommodation accomm : airbnb) {
for (Reservation reservation : accomm.getReservations()) {
if (reservation.getId() == id && reservation.getCustomer().getUsername().equals(customer.getUsername())) {
needsCancel.add(reservation);
isCanceled = true;
}
}
if (needsCancel.size() != 0) {
for (Reservation x : needsCancel) {
accomm.getReservations().remove(x);
}
}
}
return isCanceled;
}
/**
* Μέθοδος ακύρωσης κράτησης του χρήστη τύπου πελάτη
* ({@link Customers}) για δωμάτια ξενοδοχείων.
*
* @param id Αναγνωριστικό κράτησης η οποία θα
* ακυρωθεί.
* @param customer Τύπος χρήστη πελάτης: Γίνεται χρήση
* για να προσεγγιστούν όλες (μόνο)
* κρατήσεις του εκάστοτε χρήστη.
* @return Αν ακυρωθεί η επιθυμητή κράτηση τότε επιστρέφετε
* true, διαφορετικά false.
*/
public boolean CancelReservationHotelRoom(int id, Customers customer)
{
boolean isCanceled = false;
ArrayList<Reservation> needsCancel = new ArrayList<>();
for (HotelRooms room : rooms) {
for (Reservation reservation : room.getReservations()) {
if (reservation.getId() == id && reservation.getCustomer().getUsername().equals(customer.getUsername())) {
needsCancel.add(reservation);
isCanceled = true;
}
}
if (needsCancel.size() != 0) {
for (Reservation x : needsCancel) {
room.getReservations().remove(x);
}
}
}
return isCanceled;
}
/**
* Η μέθοδος αυτή βρίσκει και επιστρέφει όλες τις κρατήσεις στα ξενοδοχειακά δωμάτια για έναν συγκεκριμένο χρήστη
* @param customer Ο πελάτης για τον οποίο βρίσκονται και επιστρέφονται οι κρατήσεις ιδιωτικών καταλυμάτων
* @return HashMap με όλα τα δωμάτια και τις ημερομηνίες κράτησης που του χρήστη customer
*/
public HashMap<HotelRooms, ArrayList<Date>> UserHotelReservations(Customers customer) {
boolean hasReservations = false;
HashMap<HotelRooms, ArrayList<Date>> hotelRooms = new HashMap<>();
ArrayList<Date> allReservedDates;
for (HotelRooms ignored : rooms) {
if (ignored.getReservations() != null) {
for (Reservation reservation : ignored.getReservations()) {
allReservedDates = new ArrayList<>();
for (Date date : ignored.getUserReservations(customer)) {
allReservedDates.add(date);
hotelRooms.put(ignored, allReservedDates);
hasReservations = true;
}
}
}
}
if (hasReservations)
return hotelRooms;
return null;
}
/**
* Η μέθοδος αυτή βρίσκει και επιστρέφει όλες τις κρατήσεις στα ιδιωτικά καταλύματα για έναν συγκεκριμένο χρήστη
*
* @param customer Ο πελάτης για τον οποίο βρίσκονται και επιστρέφονται οι κρατήσεις ιδιωτικών καταλυμάτων
* @return HashMap με όλα τα ιδιωτικά καταλύματα και τις ημερομηνίες κράτησης που του χρήστη customer
*/
public HashMap<PrivateAccommodation, ArrayList<Date>> UserPrivateReservations(Customers customer) {
boolean hasReservations = false;
HashMap<PrivateAccommodation, ArrayList<Date>> privateAccommodations = new HashMap<>();
ArrayList<Date> allReservedDates;
for (PrivateAccommodation ignored : airbnb) {
for (Reservation reservation : ignored.getReservations()) {
if (reservation.getCustomer().getUsername().equals(customer.getUsername())) {
allReservedDates = new ArrayList<>();
for (Date date : ignored.getUserReservations(customer)) {
allReservedDates.add(date);
privateAccommodations.put(ignored, allReservedDates);
hasReservations = true;
}
}
}
}
if (hasReservations)
return privateAccommodations;
return null;
}
/**
* Αυξάνει κάθε φορά, ανεξάρτητα το είδος καταλύματος, κατά μια
* μονάδα τη γενική μεταβλητή στην κλάση {@link Accommodations}
* έτσι ώστε κάθε κατάλυμα που προστίθεται να έχει διαφορετικό
* αναγνωριστικό.
*/
public int identifierManager() {
return baseIdentifier++;
}
public int reservationsIdentifierManager() {
return reservationsBaseIdentifier++;
}
public int getImageIdentifier() {
return imageIdentifier++;
}
/**
* Μέθοδος που αρχικοποεί τα καταλύματα και τις κρατήσεις των καταλυμάτων
*/
public void CreateDefaultAccommodation() {
//------Δωμάτια ξενοδοχείου Lucy απο τον πάροχο "Dimitris"
// ArrayList<String> characteristics = new ArrayList<>();
// characteristics.add("City View");
// characteristics.add("Wi-fi");
// characteristics.add("3 meals");
// HotelRooms lucy1 = new HotelRooms(125, 34, 42, "Lucy", "Kavala",
// 1, identifierManager(), 3, characteristics, "room" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics1 = new ArrayList<>();
// characteristics1.add("Sea View");
// characteristics1.add("Pool");
// HotelRooms lucy2 = new HotelRooms(127, 48, 55, "Lucy", "Kavala", 1, identifierManager(),
// 5, characteristics1, "room" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics2 = new ArrayList<>();
// characteristics2.add("Movie cinema");
// characteristics2.add("Television");
// characteristics2.add("2 Beds");
// HotelRooms lucy3 = new HotelRooms(223, 55, 60, "Lucy",
// "Kavala", 2, identifierManager(), 7, characteristics2, "room" + getImageIdentifier() + ".png");
// this.getRooms().add(lucy1);
// this.getRooms().add(lucy2);
// this.getRooms().add(lucy3);
//
//
// ArrayList<String> characteristics3 = new ArrayList<>();
// characteristics3.add("3 meals");
// characteristics3.add("Wi-Fi");
// characteristics3.add("Parking");
// HotelRooms titania1 = new HotelRooms(112, 20, 45, "Titania", "Athens", 1, identifierManager(),
// 2, characteristics3, "room" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics4 = new ArrayList<>();
// characteristics4.add("One day trip to Acropolis museum");
// characteristics4.add("Wi-Fi");
// characteristics4.add("Breakfast");
// HotelRooms titania2 = new HotelRooms(132, 25, 50, "Titania", "Athens",
// 1, identifierManager(), 2, characteristics4, "room" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics5 = new ArrayList<>();
// characteristics5.add("Big balcony");
// characteristics5.add("2 meals");
// HotelRooms titania3 = new HotelRooms(245, 27, 50, "Titania", "Athens",
// 2, identifierManager(), 2, characteristics5, "room" + getImageIdentifier() + ".png");
// this.getRooms().add(titania1);
// this.getRooms().add(titania2);
// this.getRooms().add(titania3);
//
// lucy1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(2, 6, 2032));
// lucy1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(3, 3, 2023));
// lucy1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(4, 3, 2030));
// lucy1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(5, 6, 2022));
// lucy1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(6, 6, 2022));
// lucy2.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(6, 6, 2022));
//
// //lucy5.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(8,3,2022));
// //lucy7.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(4,8,2022));
//
// //-------------------------------------------
//
//
// //--------Ιδιωτικά καταλύματα από τον πάροχο "Giorgos" με την επωνυμία "Vogiatzis"
// ArrayList<String> characteristics6 = new ArrayList<>();
// characteristics6.add("2 floors");
// characteristics6.add("Personal bar");
// PrivateAccommodation Maisonette1 = new PrivateAccommodation(45, 600, "Airbnb", "Thessaloniki", "Vogiatzis",
// identifierManager(), 2, characteristics6, "accommodation" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics7 = new ArrayList<>();
// characteristics7.add("4 rooms");
// characteristics7.add("2 floors");
// characteristics7.add("City view");
// ArrayList<String> characteristics8 = new ArrayList<>();
// characteristics8.add("Big balcony");
// characteristics8.add("Garden");
// characteristics8.add("Interior parking");
// PrivateAccommodation House1 = new PrivateAccommodation(98, 160, "Airbnb", "Kozani", "Vogiatzis",
// identifierManager(), 5, characteristics8, "accommodation" + getImageIdentifier() + ".png");
//
//
// PrivateAccommodation House2 = new PrivateAccommodation(65, 120, "Airbnb", "Kozani", "Vogiatzis",
// identifierManager(), 6, characteristics7, "accommodation" + getImageIdentifier() + ".png");
//
// this.getAirbnb().add(Maisonette1);
// this.getAirbnb().add(House1);
// this.getAirbnb().add(House2);
// Maisonette1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(6, 9, 2022));
// Maisonette1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(7, 9, 2022));
// Maisonette1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(8, 9, 2022));
// House1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(5, 6, 2022));
// House1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(6, 6, 2022));
// House1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(7, 6, 2022));
// House1.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(8, 6, 2022));
//
// titania1.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(4, 5, 2022));
// titania2.Reserve(new Customers("Maria", "Maria12345", "Customer", "female"), new Date(1, 7, 2022));
// titania3.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(9, 5, 2022));
// titania2.Reserve(new Customers("Makis", "Makis12345", "Customer", "male"), new Date(11, 9, 2022));
//
// // ----------------------------------------------------
//
//
// //---------Ιδιωτικά καταλύματα στην Κρήτη από τον πάροχο "Takis"
//
// ArrayList<String> characteristics9 = new ArrayList<>();
// characteristics9.add("Sea view");
// characteristics9.add("boat");
// PrivateAccommodation Airbnb1 = new PrivateAccommodation(55, 50, "Airbnb", "Kriti", "Papadopoulos",
// identifierManager(), 2, characteristics9, "accommodation" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics10 = new ArrayList<>();
// characteristics10.add("2 floors");
// characteristics10.add("Big living room");
// characteristics10.add("Wifi");
// PrivateAccommodation Airbnb2 = new PrivateAccommodation(60, 60, "Airbnb", "Kriti",
// "Papadopoulos", identifierManager(), 2, characteristics10, "accommodation" + getImageIdentifier() + ".png");
//
// ArrayList<String> characteristics11 = new ArrayList<>();
// characteristics11.add("Big balcony");
// characteristics11.add("Garden");
// PrivateAccommodation Airbnb3 = new PrivateAccommodation(47, 48, "Airbnb", "Kriti", "Papadopoulos",
// identifierManager(), 2, characteristics11, "accommodation" + getImageIdentifier() + ".png");
//
// this.getAirbnb().add(Airbnb1);
// this.getAirbnb().add(Airbnb2);
// this.getAirbnb().add(Airbnb3);
//
//
// try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("accommodationsIdentifier.bin")))
// {
// out.writeObject(identifierManager());
// } catch (IOException e){
// e.printStackTrace();
// }
//
// try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("imageIdentifier.bin")))
// {
// out.writeObject(getImageIdentifier());
// } catch (IOException e){
// e.printStackTrace();
// }
//
// try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("hotelRooms.bin")))
// {
// out.writeObject(this.getRooms());
// } catch( IOException e)
// {
// e.printStackTrace();
// }
//
// try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("privateAccommodation.bin")))
// {
// out.writeObject(this.getAirbnb());
// } catch( IOException e)
// {
// e.printStackTrace();
// }
//
// try(ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("reservationsID.bin")))
// {
// out.writeObject(reservationsIdentifierManager());
// } catch (IOException e){
// e.printStackTrace();
// }
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("privateAccommodation.bin"))) {
airbnb = (ArrayList<PrivateAccommodation>) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("hotelRooms.bin"))) {
rooms = (ArrayList<HotelRooms>) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("accommodationsIdentifier.bin"))) {
int x = (Integer) in.readObject();
setBaseIdentifier(x);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("imageIdentifier.bin"))) {
int x = (Integer) in.readObject();
setImageIdentifier(x);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("reservationsID.bin"))) {
int x = (Integer) in.readObject();
setReservationsBaseIdentifier(x);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* Η μέθοδος αυτή εισάγει την εικόνα που πήραμε από το path μέσω του JFileChooser
* στο directory "uploads" όπου αποθηκεύονται όλες οι φωτογραφίες των default καταλυμάτων αλλά
* και αυτών που εισάγονται αργότερα
*
* @param path Όνομα διαδρομής
* @param imageIdentifier1 Μεταβλητή που βοηθά στο να ξεχωρίσουμε τα ονόματα των φωτογραφιών μέσα στο directory
*/
public void addImageToDirectory(String path, int imageIdentifier1, int type) {
File file = new File(path);
String path1 = "uploads/";
File newDirectory = new File(path1);
if (!newDirectory.exists())
newDirectory.mkdirs();
File sourceFile = null;
File destinationFile = null;
sourceFile = new File(file.getAbsolutePath());
if (type == 0)
destinationFile = new File(path1 + "room" + imageIdentifier1 + ".png");
else
destinationFile = new File(path1 + "accommodation" + imageIdentifier1 + ".png");
try {
Files.copy(sourceFile.toPath(), destinationFile.toPath());
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* Η μέθοδος αυτή φιλτράρει τη λίστα με τα δωμάτια ξενοδοχείων και επιστρέφει αυτά
* τα οποία ανήκουν στον πάροχο που περνιέται ως όρισμα.
*
* @param provider Ο πάροχος για τον οποίο τα δωμάτια θα βρεθούν και θα επιστρεφούν
* @return Λίστα με τα ξενοδοχειακά δωμάτια που έχει στην κατοχή του ο πάροχος
*/
public ArrayList<HotelRooms> getProvidersRooms(Providers provider) {
ArrayList<HotelRooms> roomsToReturn = new ArrayList<>();
for (HotelRooms room : rooms) {
if (room.getHotelName().equals(provider.getProvidersBrandName())) {
roomsToReturn.add(room);
}
}
return roomsToReturn;
}
/**
* Η μέθοδος αυτή φιλτράρει τη λίστα με τα ιδιωτικά καταλύματα και επιστρέφει αυτά
* τα οποία ανήκουν στον πάροχο που περνιέται ως όρισμα.
*
* @param provider Ο πάροχος για τον οποίο τα καταλύματα θα βρεθούν και θα επιστρεφούν
* @return Λίστα με τα ιδιωτικά καταλύματα που έχει στην κατοχή του ο πάροχος
*/
public ArrayList<PrivateAccommodation> getProvidersPrivateAccommodations(Providers provider) {
ArrayList<PrivateAccommodation> accommodationsToReturn = new ArrayList<>();
for (PrivateAccommodation accommodation : airbnb) {
if (accommodation.getCompanyName().equals(provider.getProvidersBrandName())) {
accommodationsToReturn.add(accommodation);
}
}
return accommodationsToReturn;
}
} | NikosVogiatzis/UniProjects | java mybooking/mybooking-main/src/accommodations/Accommodations.java |
1,709 | package refugeoly;
import java.util.*;
public class Square
{
private String text;
private int number;
private final int board=1; //Δεν αλλάζει ποτέ - Υπάρχει μόνο ένα ταμπλό
ArrayList <Action> actions = new ArrayList<Action>();
public void setText(String s)
{
text=s;
}
public String getText()
{
return text;
}
public void setNumber(int n)
{
number=n;
}
public int getNumber()
{
return number;
}
public void setAction(Action act)
{
actions.add(act); //Το Action μπαίνει στο ArrayList
}
}
| anatheodor/Refugeoly | Refugeoly/src/refugeoly/Square.java |
1,710 |
import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
public class CheckBoxGUI {
JFrame frmInitScreen;
/**
* Launch occurs in class Main
*/
private HashSet<String> hashcourses = new HashSet<String>(); //contains distinct courses
private ArrayList<String> arrcourses = new ArrayList<String>(); //contains selected courses
private ArrayList<JCheckBox> arcboxes = new ArrayList<JCheckBox>(); //contains all checkboxes
public CheckBoxGUI() {
XlsReader re = new XlsReader();
re.read(); //read variables from Excel
frmInitScreen = new JFrame();
frmInitScreen.setTitle("Select Courses");
frmInitScreen.getContentPane().setBackground(Color.WHITE);
frmInitScreen.setSize(1024, 504);
frmInitScreen.setLocationRelativeTo(null);
JScrollPane BoxscrollPane = new JScrollPane();
BoxscrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
BoxscrollPane.getVerticalScrollBar().setUnitIncrement(10);
JLayeredPane panel = new JLayeredPane();
BoxscrollPane.setViewportView(panel);
//Set Up ComboBoxes
JComboBox<String> comboBoxS = new JComboBox<String>(); //semester combobox
comboBoxS.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
comboBoxS.setToolTipText("Επιλέξτε Εξάμηνο");
comboBoxS.setFont(new Font("Arial", Font.BOLD, 11));
comboBoxS.setModel(new DefaultComboBoxModel<String>(new String[] {"Εξάμηνο 2ο", "Εξάμηνο 4ο", "Εξάμηνο 6ο ", "Εξάμηνο 8ο"}));
JComboBox<String> comboBoxD = new JComboBox<String>(); //direction combobox
comboBoxD.setFont(new Font("Arial", Font.BOLD, 11));
comboBoxD.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
comboBoxD.setModel(new DefaultComboBoxModel<String>(new String[] {"ΔΙΟΙΚΗΣΗ ΤΕΧΝΟΛΟΓΙΑΣ", "ΕΦΑΡΜΟΣΜΕΝΗ ΠΛΗΡΟΦΟΡΙΚΗ"}));
comboBoxD.setMaximumRowCount(2);
comboBoxD.setToolTipText("Επιλέξτε την κατεύθυνση σας. Μόλις επιλέξετε δεν έχετε δικαίωμα να αλλάξετε\r\n");
/*
* set up checkboxes
*/
JCheckBox checkBox1 = new JCheckBox(re.getCoursesStats().get(0).getName());
checkBox1.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox(re.getCoursesStats().get(1).getName());
checkBox2.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox2);
JCheckBox checkBox3 = new JCheckBox(re.getCoursesStats().get(2).getName());
checkBox3.setHorizontalAlignment(SwingConstants.LEFT);
arcboxes.add(checkBox3);
JCheckBox checkBox4 = new JCheckBox(re.getCoursesStats().get(3).getName());
checkBox4.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox4);
JCheckBox checkBox5 = new JCheckBox(re.getCoursesStats().get(4).getName());
checkBox5.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox5);
JCheckBox checkBox6 = new JCheckBox(re.getCoursesStats().get(5).getName());
checkBox6.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox6);
JCheckBox checkBox7 = new JCheckBox((String) null);
checkBox7.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox7);
JCheckBox checkBox8 = new JCheckBox((String) null);
checkBox8.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox8);
JCheckBox checkBox9 = new JCheckBox((String) null);
checkBox9.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox9);
JCheckBox checkBox10 = new JCheckBox((String) null);
checkBox10.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox10);
JCheckBox checkBox11 = new JCheckBox((String) null);
checkBox11.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox11);
JCheckBox checkBox12 = new JCheckBox((String) null);
checkBox12.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox12);
JCheckBox checkBox13 = new JCheckBox((String) null);
checkBox13.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox13);
JCheckBox checkBox14 = new JCheckBox((String) null);
checkBox14.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox14);
JCheckBox checkBox15 = new JCheckBox((String) null);
checkBox15.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox15);
JCheckBox checkBox16 = new JCheckBox((String) null);
checkBox16.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox16);
JCheckBox checkBox17 = new JCheckBox((String) null);
checkBox17.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox17);
JCheckBox checkBox18 = new JCheckBox((String) null);
checkBox18.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox18);
JCheckBox checkBox19 = new JCheckBox((String) null);
checkBox19.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox19);
JCheckBox checkBox20 = new JCheckBox((String) null);
checkBox20.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox20);
JCheckBox checkBox21 = new JCheckBox((String) null);
checkBox21.setVerticalAlignment(SwingConstants.TOP);
arcboxes.add(checkBox21);
GroupLayout gl_panel = new GroupLayout(panel); //graphics stuff
gl_panel.setHorizontalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox1, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox2, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox3, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox4, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox5, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox6, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox7, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox8, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox9, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox10, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox11, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox12, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox13, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox14, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox15, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox16, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox17, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox18, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox19, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox20, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addGap(10)
.addComponent(checkBox21, GroupLayout.PREFERRED_SIZE, 400, GroupLayout.PREFERRED_SIZE))
.addGroup(gl_panel.createSequentialGroup()
.addContainerGap()
.addComponent(comboBoxD, 0, 139, Short.MAX_VALUE)
.addGap(10)
.addComponent(comboBoxS, 0, 97, Short.MAX_VALUE)
.addGap(154))
);
gl_panel.setVerticalGroup(
gl_panel.createParallelGroup(Alignment.LEADING)
.addGroup(gl_panel.createSequentialGroup()
.addGap(6)
.addGroup(gl_panel.createParallelGroup(Alignment.LEADING, false)
.addComponent(comboBoxD, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE)
.addComponent(comboBoxS, GroupLayout.PREFERRED_SIZE, 22, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.UNRELATED)
.addComponent(checkBox1)
.addGap(3)
.addComponent(checkBox2)
.addGap(3)
.addComponent(checkBox3)
.addGap(3)
.addComponent(checkBox4)
.addGap(3)
.addComponent(checkBox5)
.addGap(3)
.addComponent(checkBox6)
.addGap(3)
.addComponent(checkBox7)
.addGap(3)
.addComponent(checkBox8)
.addGap(3)
.addComponent(checkBox9)
.addGap(3)
.addComponent(checkBox10)
.addGap(3)
.addComponent(checkBox11, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox12, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox13, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox14, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox15, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox16, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox17, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox18, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox19, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox20, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE)
.addGap(3)
.addComponent(checkBox21, GroupLayout.PREFERRED_SIZE, 23, GroupLayout.PREFERRED_SIZE))
);
panel.setLayout(gl_panel);
JScrollPane infoscrollpane = new JScrollPane();
JScrollPane scrollPane = new JScrollPane();
/*
* set up buttons
*/
JButton addbutton = new JButton("Προσθήκη");
addbutton.setFont(new Font("Tahoma", Font.PLAIN, 13));
JButton clearbutton = new JButton("Καθαρισμός");
clearbutton.setFont(new Font("Tahoma", Font.PLAIN, 13));
JButton nextframebutton;
nextframebutton = new JButton("Υποβολή");
GroupLayout groupLayout = new GroupLayout(frmInitScreen.getContentPane());
groupLayout.setHorizontalGroup(
groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(BoxscrollPane, GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addGroup(groupLayout.createSequentialGroup()
.addComponent(addbutton, GroupLayout.DEFAULT_SIZE, 172, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(clearbutton, GroupLayout.DEFAULT_SIZE, 173, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 351, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)))
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGap(18)
.addComponent(infoscrollpane, GroupLayout.DEFAULT_SIZE, 312, Short.MAX_VALUE))
.addGroup(groupLayout.createSequentialGroup()
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(nextframebutton)
.addContainerGap())))
);
groupLayout.setVerticalGroup(
groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createSequentialGroup()
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addComponent(scrollPane, GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
.addComponent(infoscrollpane, GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE))
.addGap(18)
.addGroup(groupLayout.createParallelGroup(Alignment.TRAILING)
.addGroup(groupLayout.createParallelGroup(Alignment.LEADING)
.addComponent(clearbutton, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE)
.addComponent(addbutton, GroupLayout.PREFERRED_SIZE, 34, GroupLayout.PREFERRED_SIZE))
.addComponent(nextframebutton))
.addGap(26))
.addComponent(BoxscrollPane, GroupLayout.DEFAULT_SIZE, 465, Short.MAX_VALUE)
);
/*
* set up information fields
*/
JLabel label_1 = new JLabel("Επιλεγμένα Μαθήματα");
label_1.setHorizontalAlignment(SwingConstants.CENTER);
scrollPane.setColumnHeaderView(label_1);
JTextArea textcourses = new JTextArea();
textcourses.setEditable(false);
scrollPane.setViewportView(textcourses);
textcourses.setFont(new Font("Tahoma", Font.PLAIN, 15));
JLabel label = new JLabel("Πληροφορίες Μαθήματος");
label.setHorizontalAlignment(SwingConstants.CENTER);
infoscrollpane.setColumnHeaderView(label);
JTextArea infotext = new JTextArea();
infotext.setEditable(false);
infotext.setFont(new Font("Monospaced", Font.PLAIN, 13));
label.setLabelFor(infotext);
infotext.setText("Κάντε κλικ σε ένα μάθημα για\nνα εμφανίσετε τις πληροφορίες του.");
infoscrollpane.setViewportView(infotext);
frmInitScreen.getContentPane().setLayout(groupLayout);
for(int i=6; i<arcboxes.size();i++) { //hide checkboxes that are empty
arcboxes.get(i).hide();
}
frmInitScreen.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
class ItemHandler implements ItemListener {
@Override
public void itemStateChanged(ItemEvent event) { //fire up actions when comboboxes state is changed
if(comboBoxD.getSelectedIndex()==0) {
Dioikisi(Semester(comboBoxS.getSelectedIndex()));
}
else if(comboBoxD.getSelectedIndex()==1){
Efarmosmeni(Semester(comboBoxS.getSelectedIndex()));
}
comboBoxD.setEnabled(false); //prevent user to select courses with different directions
}
private int Semester(int sem_index) { //convert semester index to real number
int x=0;
if(sem_index==0)
{
x=2;
}
else if(sem_index==1)
{ x=4;
}
else if(sem_index==2)
{
x=6;
}
else if(sem_index==3)
{
x=8;
}
return x;
}
private void Efarmosmeni(int S){ // receives semester number, sets up the needed names for the current semester for ΚΕΠ direction
if(S==2) { //IDIA MATHIMATA EFARM KAI DIOIKHSH STO 2o EKSAMINO
setCheckBoxes(0,5);
}
else if(S==4) {
setCheckBoxes(6,11);
}
else if(S==6) {
setCheckBoxes(12,17);
}
else if(S==8) { //ep
setCheckBoxes(18,38);
}
}
private void Dioikisi(int S) { // receives semester number, sets up the needed names for the current semester for ΚΔΤ direction
if(S==2) {
setCheckBoxes(0,5);
}
else if(S==4) {
setCheckBoxes(41,46);
}
else if(S==6) {
setCheckBoxes(47,52);
}
else if(S==8) {
setCheckBoxes(53,63);
}
}
private void setCheckBoxes(int start, int end) { //Enable needed checkbox and hide others according to Semester and Direction
int checkboxcounter=0;
for(int cindex = start; cindex<=end;cindex++) {
arcboxes.get(checkboxcounter).show();
arcboxes.get(checkboxcounter).setSelected(false);
arcboxes.get(checkboxcounter).setText(re.getCoursesStats().get(cindex).getName());
checkboxcounter++;
}
for(int i=checkboxcounter; i<arcboxes.size();i++) {
arcboxes.get(i).hide();
arcboxes.get(i).setSelected(false);
}
}
}//itemlistener
class ActionHandler implements ActionListener{
@Override
public void actionPerformed(ActionEvent ae) {
if(ae.getSource()==nextframebutton) { //when Υποβολή is clicked
if (arrcourses.size()>0 && arrcourses.size()<=10) { //prevent faulty number of selected courses
int dirindex = comboBoxD.getSelectedIndex();
String dirstr=""; //Saves selected Direction from User
if(dirindex ==0)
dirstr = "ΚΔΤ";
else if(dirindex ==1)
dirstr ="ΚΕΠ";
String username = "";
while(username.trim().length()==0 && username!=null) { //while username is only white spaces
try {
username = JOptionPane.showInputDialog("Enter Username"); //ask for username
if (username == null) {//user might cancel or close the dialog. Null will be assigned to username
System.exit(0); //program will shut down.
}
} catch (Exception e ) {
break;
}
}
if (username.trim().length()!=0) { //if username is given
try (Writer writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream("username.txt"), "UTF-8"))) {
writer.write(username);
/*write username into file */
} catch (IOException ex) {
System.out.println("username entering failed");
ex.printStackTrace();
}
re.setArrayString(arrcourses); //transfer array to XlsReader
re.setSelectedDirection(dirstr);
re.writeSelectedCourses();
}
EventQueue.invokeLater(new Runnable() { //Open MainFrame
public void run() {
try {
MainFrame window = new MainFrame();
window.frmMainframe.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
frmInitScreen.setVisible(false);
}
else {
//error Pop up
JOptionPane.showMessageDialog(null, "Πρέπει να δηλώσετε μέχρι 10 μαθήματα", "ΕRROR", JOptionPane.ERROR_MESSAGE);
}
}
setupSelectedBoxes(ae);
if(ae.getSource()==clearbutton) //deletes all selected courses
{
hashcourses.clear(); //flushes hashset
arrcourses.clear(); //flushes string array with selected courses
textcourses.setText(null);
}
}//actionPerformed
private void setupSelectedBoxes(ActionEvent ae){
for(JCheckBox selectedcb :arcboxes) { //scan all checkboxes that are selected
if(selectedcb.isSelected()) {
if (ae.getSource()==selectedcb) { //show current selected course's info
readInfoFile(selectedcb.getText(), infotext);
}
if(ae.getSource()==addbutton) { //add all selected courses to the Selected Panel
hashcourses.add(selectedcb.getText());
printAll(hashcourses, textcourses);
}
}
}
}//setupselectedboxes
private void printAll(HashSet<String> courses, JTextArea textcourses) { //print selected courses
Iterator<String> it= courses.iterator();
arrcourses.clear(); //flush previously selected courses
while(it.hasNext()) {
String arcS = ((String) it.next()+"\n");
arrcourses.add(arcS);
}
Collections.sort(arrcourses);
textcourses.setText(toString2(arrcourses));
}
public String toString2(ArrayList<String> arrcourses) { //line up nicely selected courses and return an entire String that contains them all
String strOutput ="";
for(int i = 0; i < arrcourses.size(); i++){
strOutput += arrcourses.get(i) ;
}
return strOutput;
}
private void readInfoFile(String course, JTextArea field) { //Uses Courses name to find the necessary text file containing all course's information
String fileName = course + "info.txt";
Path path = Paths.get(fileName);
BufferedReader reader = null;
String line = "";
String them = "";
if(Files.exists(path)) {
String input = path.toString();
File file = new File(input);
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(input), "UTF-8"));
try {
while((line = reader.readLine()) != null) {
them += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
field.setText(them);
}
else {
field.setText("Δεν βρέθηκαν πληροφορίες");
}
}
} //actionListener
/*
* add all action listeners
*/
ActionListener checkboxListener = new ActionHandler();
ActionListener addbuttonListener = new ActionHandler();
ActionListener clearbuttonListener = new ActionHandler();
ActionListener nextframebuttonListener = new ActionHandler();
for(int i=0;i<arcboxes.size();i++)
arcboxes.get(i).addActionListener(checkboxListener);
addbutton.addActionListener(addbuttonListener);
clearbutton.addActionListener(clearbuttonListener);
nextframebutton.addActionListener(nextframebuttonListener);
ItemHandler Sboxhandler = new ItemHandler();
ItemHandler Dboxhandler = new ItemHandler();
comboBoxD.addItemListener(Dboxhandler);
comboBoxS.addItemListener(Sboxhandler);
}//constructor
} //CheckBoGUI class
| GeorgeMichos13/MyUom | src/CheckBoxGUI.java |
1,713 | package refugeoly;
public class Refugee extends Game
{
private String name;
private double money=10000;
private final int board=1; //Δεν αλλάζει ποτέ - Υπάρχει μόνο ένα ταμπλό
private int square=0; //Κάθε παίκτης ξεκινάει από το τετράγωνο 0
private double expenses=0;
public void setName(String n)
{
name=n;
}
public String getName()
{
return name;
}
public void setMoney(double m)
{
money=m;
}
public double getMoney()
{
return money;
}
public void receiveMoney(double m)
{
money=money+m;
}
public void setSquare(int s)
{
square=s;
}
public void moveTo(int s)
{
if (square+s<=39)
{
square=square+s;
}
else
{
int goback=0;
for (int i=1 ; i<=s ; i++)
{
if (square+1<=39 && goback==0)
{
square=square+1;
}
else
{
square=square-1;
goback=1;
}
}
}
}
public int getSquare()
{
return square;
}
public void setExpenses(double e)
{
expenses=e;
}
public void incExpenses(double e)
{
expenses=expenses+e;
}
public double getExpenses()
{
return expenses;
}
public double giveMoney(double exp)
{
if (exp>money)
{
System.out.printf("You have gone bankrupted! You lost! The other refugees shall continue living without you...\n");
System.out.printf("Total money spent: %f\n\n", expenses);
return -1;
}
else
{
money=money-exp;
return exp;
}
}
}
| anatheodor/Refugeoly | Refugeoly/src/refugeoly/Refugee.java |
1,714 | package api;
import java.io.Serializable;
import java.text.*;
import java.util.Calendar;
/**
* Η κλάση αυτή αφορά την αξιολόγηση κάποιου καταλύματος.
*/
public class Evaluation implements Serializable {
private final String currentDate;
private final SimpleUser user;
private final Accommodation accommodation;
private String evaluationText;
private float grade; //1 έως 5
private final long singularId;
/**
* Κατασκευαστής της κλάσης των αξιολογήσεων. Αρχικοποιεί τα πεδία evaluationText, grade, user, και Accommodation
* σύμφωνα με τα ορίσματα που δίνονται. Επίσης, ορίζεται η ημερομηνία που δημιουργήθηκε το αντικείμενο της
* αξιολόγησης ως η ημερομηνία της ίδιας της αξιολόγησης. Τέλος, υπολογίζεται το id της αξιολόγησης ως το άθροισμα
* του hashCode() του username του χρήστη που έκανε την αξιολόγηση και του hashCode() του καταλύματος υπό
* αξιολόγηση. Είναι μοναδικό καθώς δεν επιτρέπεται στον ίδιο χρήστη να αξιολογήσει ένα κατάλυμα πάνω απο μία φορά.
* @param evaluationText Κείμενο αξιολόγησης του εκάστοτε καταλύματος
* @param grade Βαθμός αξιολόγησης
* @param user Αντικείμενο απλού χρήστη που έκανε την αξιολόγηση
* @param accommodation Το κατάλυμα που αξιολογείται
*/
public Evaluation(String evaluationText, float grade, SimpleUser user, Accommodation accommodation) {
this.evaluationText = evaluationText;
this.grade = grade;
this.user = user;
this.accommodation = accommodation;
//Ορισμός της ημερομηνίας που προστίθεται η αξιολόγηση
DateFormat Date = DateFormat.getDateInstance();
Calendar cals = Calendar.getInstance();
currentDate = Date.format(cals.getTime());
singularId = user.getUserName().hashCode() + accommodation.hashCode();
}
/**
* Επιστρέφει το κείμενο της αξιολόγησης
* @return κείμενο της αξιολόγησης
*/
public String getEvaluationText() {
return evaluationText;
}
/**
* Αλλάζει το κείμενο της αξιολόγησης σε περίπτωση μεταγενέστερης επεξεργασίας της από τον χρήστη που την έκανε.
* @param evaluationText νέο κείμενο της αξιολόγησης
*/
public void setEvaluationText(String evaluationText) {
this.evaluationText = evaluationText;
}
/**
* Επιστρέφει τον βαθμό της αξιολόγησης
* @return βαθμός της αξιολόγησης
*/
public float getGrade() {
return grade;
}
/**
* Αλλάζει τον βαθμό της αξιολόγησης σε περίπτωση μεταγενέστερης επεξεργασίας της από τον χρήστη που την έκανε.
* @param grade νέος βαθμός αξιολόγησης
*/
public void setGrade(float grade) {
this.grade = grade;
}
/**
* Επιστρέφει το αντικείμενο του απλού χρήστη που έκανε την αξιολόγηση
* @return αντικείμενο του απλού χρήστη που έκανε την αξιολόγηση
*/
public SimpleUser getUser() {
return user;
}
/**
* Επιστρέφει το αντικείμενο του καταλύματος που αξιολογείται
* @return κατάλυμα που αξιολογείται
*/
public Accommodation getAccommodation() {
return accommodation;
}
/**
* Επιστρέφει τη συμβολοσειρά της ημερομηνίας που έγινε η αξιολόγηση.
* @return συμβολοσειρά ημερομηνίας
*/
public String getCurrentDate() {
return currentDate;
}
/**
* Επιστρέφει το id της αξιολόγησης
* @return id αξιολόγησης
*/
public long getSingularId() {
return singularId;
}
/**
* Ελέγχει την ισότητα δύο αντικειμένων Evaluation. Η ισότητα τους αν οι θέσεις μνήμης διαφέρουν και πρόκειται για
* αντικείμενο τύπου Evaluation έγκειται στην ισότητα των id των δύο αξιολογήσεων.
* @param o το αντικείμενο που θέλουμε να συγκρίνουμε με το this
* @return true αν ισχύει η ισότητα των δύο αντικειμένων
*/
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Evaluation that)) return false;
return getSingularId() == that.getSingularId();
}
/**
* Επιστρέφει τη συμβολοσειρά που αντιστοιχεί στην αξιολόγηση ως "[μικρό όνομα χρήστη], [ημερομηνία αξιολόγησης],
* Βαθμολογία: [βαθμός αξιολόγησης]"
* @return συμβολοσειρά που αντιστοιχεί στην αξιολόγηση
*/
@Override
public String toString() {
return user.getFirstName() + ", " + currentDate + ", Βαθμολογία: " + grade;
}
}
| patiosga/myreviews | src/api/Evaluation.java |
1,716 | package CarOps;
import java.util.ArrayList;
public class RepairFolder {
private Registry aRegistry;
private Session aSession;
private Repair aRepair;
private int RepairFolderid;
private String status;
private int estTime;
private int totalCost;
private ArrayList<RepairTask> RepairTaskCatalog = new ArrayList<RepairTask>();
//Έγκριση του φακέλου επισκευής απο την γραμματεία και δημιουργία επικευής που αντιστοιχεί στον φάκελο
public Repair ApprovedRepairFolder() {
this.status = "Approved";
Repair newRepair=new Repair(this,"wait");
this.aRepair=newRepair;
return newRepair;
}
//Second Constructor for use in the HostEngineer Class
//Με τη χρήση αυτού του Constructor δημιουργείται ένας φάκελος που εκκρεμεί(stats="Pending") και για να αλλάξει πρέπει να εγκριθεί από την Γραμματεία
public RepairFolder(Session aSession,int estTime,int totalCost,ArrayList<Task> aListOfTasks){
this.RepairFolderid=Registry.RepairFolders.size()+1;
this.status = "Pending";
this.aSession=aSession;
this.estTime=estTime;
this.totalCost=totalCost;
for(int i=0;i<aListOfTasks.size();i++) {
this.RepairTaskCatalog.add(new RepairTask(aListOfTasks.get(i),this));
//this.aAppointmentID= aAppointmentID; //What is this?
}
Registry.RepairFolders.add(this);
}
public void PrintDetails() {
System.out.println("Repair Folder Details:");
System.out.println("ID: "+ RepairFolderid);
System.out.println("Status: "+ status);
System.out.println("Estimated Time: "+ estTime);
System.out.println("TotalCost: "+ totalCost);
System.out.println("It contains these tasks:");
//for(int i=0; i<TaskCatalog.size(); i++) {
//System.out.println("Task: "+ i+1);
//TaskCatalog.get(i).PrintDetails();
}
//}
public void addRepairTask(RepairTask aRepairTask) {
RepairTaskCatalog.add(aRepairTask);
}
//public int getSessionID() {
//return SessionID;
//}
public void setSessionID(int sessionID) {
//SessionID = sessionID;
}
public int getRepairFolderid() {
return RepairFolderid;
}
public void setRepairFolderid(int repairFolderid) {
RepairFolderid = repairFolderid;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status=status;
}
public int getEstTime() {
return estTime;
}
public void setEstTime(int estTime) {
this.estTime = estTime;
}
public int getTotalCost() {
return totalCost;
}
public void setTotalCost(int totalCost) {
this.totalCost = totalCost;
}
//public ArrayList<Task> getTaskCatalog() {
//return TaskCatalog;
//}
public void setTaskCatalog(ArrayList<Task> taskCatalog) {
//TaskCatalog = taskCatalog;
}
public ArrayList<RepairTask> getRepairTaskCatalog() {
return RepairTaskCatalog;
}
public void setRepairTaskCatalog(ArrayList<RepairTask> repairTaskCatalog) {
RepairTaskCatalog = repairTaskCatalog;
}
public Session getaSession() {
return aSession;
}
public void setaSession(Session aSession) {
this.aSession = aSession;
}
public Repair getaRepair() {
return aRepair;
}
public void setaRepair(Repair aRepair) {
this.aRepair = aRepair;
}
} | TonyGnk/carops-information-system | code/src/CarOps/RepairFolder.java |
1,720 | import java.util.Scanner;
public class GetUserInfo_NB
{
public static void main(String[] args)
{
String name;
int age;
Scanner inputDevice = new Scanner(System.in);
System.out.print("Please enter your age >> ");
age = inputDevice.nextInt();
// Δείτε τι συμβαίνει αν παραληφθεί η επόμενη εντολή:
inputDevice.nextLine();
System.out.print("Please enter your name >> ");
name = inputDevice.nextLine();
System.out.println("Your name is " + name +
" and you are " + age + " years old.");
}
}
| riggas-ionio/java | lecture-examples/02-essentials/GetUserInfo_NB.java |
1,724 | import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class GUI extends JFrame {
private JPanel panel = new JPanel(); // Πάνελ
private JButton openFileButton = new JButton("Open File"); // Κουμπί
private JFileChooser fc = new JFileChooser(); // Γραφικό συστατικό επιλογής αρχείου
public GUI(){
panel.add(openFileButton);
this.setContentPane(panel);
//Δημιουργώ ανώνυμη κλάση και το interface που την υλοποιεί...
openFileButton.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
//Ανοίγει το παράθυρο του FileChooser
//Μητρικό παράθυρο panel
//Επιστρεφόμενη ακέραια τιμή στο returnValue
int returnValue = fc.showOpenDialog(panel);
// Αν επέλεξε το open, τότε επέλεξα να ανοίξει το αρχείο
if(returnValue == JFileChooser.OPEN_DIALOG){
//κώδικας για ανάγνωση αρχείο κειμένου
// Λήψη αρχείου
File file = fc.getSelectedFile();
//Περιτυλίγει το FileReader που περιτυλίγει το file
//Αποδοτικό. Παίρνει μεγάλα κομμάτια από το αρχείο και η προσπέλαση στο δίσκο γίνεται πιο αραιά (γρήγορος)
// Παράγεται εξαίρεση (διότι έχουμε αρχείο)
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
//Διαβάζω και μπορεί να εμφανίσει εξαίρεση. Προσθέτω ένα catch ακόμα
String line = reader.readLine(); // Διαβάζει γραμμή ολόκληρη...
while(line!=null){
System.out.println(line);
line = reader.readLine();
}
reader.close(); // κλείνω το ρεύμα
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
this.setVisible(true);
this.setSize(300, 300);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/Files_v2/src/GUI.java |
1,728 | package com.fivasim.antikythera;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Build;
import static com.fivasim.antikythera.Initial.*;
public class OpenGLRenderer implements Renderer {
private Gear gears[] = new Gear[num_gears];
private Gear axles[] = new Gear[num_axles];
private Pointer pointers[] = new Pointer[num_pointers];
private Gear pointerbase = new Gear( new float[]{0f, 1.5f, 1f, 50f, 0f, 0f} );
private Plate plates[] = new Plate[2];
private static int framecount = 0;
public static float curX = 0f;
public static float curY = 0f;
public static float curX1 = 0f;
public static float curY1 = 0f;
public static float curDist = 0f;
public static int touchmode = 0;
public static float fullrotate_x = 0f;
public static float fullrotate_y = 0f;
public static float fullrotate_z = 0f;
public static float position_x = 0f;
public static float position_y = 0f;
public static float zoomfac = 0f;
public static long timestamp = System.currentTimeMillis();
private Bitmap bitmap;
public OpenGLRenderer() {
int i;
// Initialize our gears.
for (i=0;i<num_gears;i++) {
gears[i] = new Gear(geardata[i]);
}
for (i=0;i<num_axles;i++) {
axles[i] = new Gear(axledata[i]);
}
for (i=0;i<num_pointers;i++) {
pointers[i] = new Pointer( pointer_len[i], pointer_pos[i]);
}
plates[0] = new Plate(60.0f, 40.0f, 25.0f);
plates[1] = new Plate(60.0f, 40.0f,-41.0f);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition
* .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background color to black ( rgba ).
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Enable Smooth Shading, default not really needed.
gl.glShadeModel(GL10.GL_SMOOTH);
// Depth buffer setup.
gl.glClearDepthf(1.0f);
// Enables depth testing.
gl.glEnable(GL10.GL_DEPTH_TEST);
// The type of depth testing to do.
gl.glDepthFunc(GL10.GL_LEQUAL);
// Really nice perspective calculations.
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
//gl.glEnable(GL10.GL_DITHER);
}
public void onDrawFrame(GL10 gl) {
if( Build.VERSION.SDK_INT >= 7 ){
framecount++;
if (framecount == 10) {
antikytherap.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp);
timestamp = System.currentTimeMillis();
framecount = 0;
} else if (antikytherap.fps == 0f) {
if (timestamp == 0) {
timestamp = System.currentTimeMillis();
} else {
framecount = 0;
antikytherap.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) );
timestamp = System.currentTimeMillis();
}
}
} else {
framecount++;
if (framecount == 10) {
antikytherap_nomulti.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp);
timestamp = System.currentTimeMillis();
framecount = 0;
} else if (antikytherap.fps == 0f) {
if (timestamp == 0) {
timestamp = System.currentTimeMillis();
} else {
framecount = 0;
antikytherap_nomulti.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) );
timestamp = System.currentTimeMillis();
}
}
}
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
// Clears the screen and depth buffer.
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// Replace the current matrix with the identity matrix
gl.glLoadIdentity();
// Translates 4 units into the screen.
if (position_x > 100f) { position_x = 100f;}
if (position_x <-100f) { position_x =-100f;}
if (position_y > 100f) { position_y = 100f;}
if (position_y <-100f) { position_y =-100f;}
gl.glTranslatef(position_x, position_y, -120f + zoomfac);
gl.glRotatef( fullrotate_x, 1f, 0f, 0f);
gl.glRotatef( fullrotate_y, 0f, 1f, 0f);
gl.glRotatef( fullrotate_z, 0f, 0f, 1f);
// Draw our gears
int i;
for (i=0;i<num_gears;i++) {
gl.glPushMatrix();
if(differential[i]!=0) { //Αν το γρανάζι είναι ένα από τα διαφορικά του μηχανισμού Περιστροφή διαφορικού γραναζιού
gl.glTranslatef( gearpos[10][0], gearpos[10][1], 0.0f); //Κέντρο κύκλου περιστροφής
if (Preferences.rotate_backwards) {
differential_angle[i] -= Preferences.rotation_speed * differential[i];
} else {
differential_angle[i] += Preferences.rotation_speed * differential[i];
}
gl.glRotatef( differential_angle[i] , 0.0f, 0.0f, 1.0f);
}
gl.glTranslatef(gearpos[i][0],gearpos[i][1], gearpos[i][2]); //Κέντρο γραναζιού
if(i==num_gears-1) { //Αν το γρανάζι είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα)
gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f);
}
if (Preferences.rotate_backwards) {
startangle[i] -= Preferences.rotation_speed * gearpos[i][3];
} else {
startangle[i] += Preferences.rotation_speed * gearpos[i][3];
}
gl.glRotatef( startangle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού
gears[i].draw(gl, (int)gearpos[i][4]);
gl.glPopMatrix();
}
//axles
for (i=0;i<num_axles;i++) {
gl.glPushMatrix();
if(axle_differential[i]!=0) { //Αν ανήκει στα διαφορικά γρανάζια του μηχανισμού Περιστροφή διαφορικού
if(i==num_axles-1) {//Αν είναι το χερούλι της μανιβέλας
gl.glTranslatef( axlepos[i-1][0], axlepos[i-1][1], axlepos[i-1][2]); //Κέντρο κύκλου περιστροφής
if (Preferences.rotate_backwards) {
axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i];
} else {
axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i];
}
gl.glRotatef( axle_differential_angle[i], 1.0f, 0.0f, 0.0f);
} else { //Οποιόσδήποτε άλλος άξονας γραναζιού
gl.glTranslatef( gearpos[10][0], gearpos[10][1], 0.0f); //Κέντρο κύκλου περιστροφής
if (Preferences.rotate_backwards) {
axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i];
} else {
axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i];
}
gl.glRotatef( axle_differential_angle[i], 0.0f, 0.0f, 1.0f);
}
}
gl.glTranslatef(axlepos[i][0],axlepos[i][1], axlepos[i][2]); //Κέντρο γραναζιού
if(i>=num_axles-3) { //Αν είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα)
gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f);
}
if (Preferences.rotate_backwards) {
axle_angle[i] -= Preferences.rotation_speed * axlepos[i][3];
} else {
axle_angle[i] += Preferences.rotation_speed * axlepos[i][3];
}
gl.glRotatef( axle_angle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού
axles[i].draw(gl, (int)axlepos[i][4]);
gl.glPopMatrix();
}
//pointers
for (i=0;i<num_pointers;i++) {
gl.glPushMatrix();
gl.glTranslatef( pointer_pos[i][0], pointer_pos[i][1], pointer_pos[i][2]); //Κέντρο δείκτη
//Περιστροφή δείκτη γύρω απ' τον άξονά του. Ο συντελεστής του angle είναι η ταχύτητα περιστροφής
if (Preferences.rotate_backwards) {
pointer_angle[i] -= Preferences.rotation_speed * pointer_pos[i][3];
} else {
pointer_angle[i] += Preferences.rotation_speed * pointer_pos[i][3];
}
gl.glRotatef(pointer_angle[i], 0.0f, 0.0f, 1.0f);
pointers[i].draw(gl, (int)pointer_pos[i][4]);
pointerbase.draw(gl, (int)pointer_pos[i][4]);
gl.glPopMatrix();
}
//plates
if (Preferences.plate_visibility) {
for (i=0;i<2;i++) {
gl.glPushMatrix();
plates[i].draw(gl);
gl.glPopMatrix();
}
}
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition
* .khronos.opengles.GL10, int, int)
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
if (Preferences.plate_visibility) {
if( Build.VERSION.SDK_INT >= 7 ){
bitmap = antikytherap.bitmap;
} else {
bitmap = antikytherap_nomulti.bitmap;
}
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
// Sets the current view port to the new size.
gl.glViewport(0, 0, width, height);
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 75.0f, (float) width / (float) height, 0.1f, 750.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
}
| fivasim/Antikythera-Simulation | Antikythera/src/com/fivasim/antikythera/OpenGLRenderer.java |
1,729 | package sample;
import javafx.animation.KeyFrame;
import javafx.animation.ScaleTransition;
import javafx.animation.Timeline;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;
import javafx.util.Duration;
import java.io.*;
import java.util.*;
/**
* <h1>Η κλάση Battle</h1>
*/
public class Battle extends Multiplayer {
@FXML
private Button back,nextButton;
@FXML
private GridPane gridTable1,gridTable2;
private Image theme;
private ArrayList<ImageView> imageViews2;
private ArrayList<Card> cards2;
private int clicks;
private ImageView playerImageview,botImageView;
private Card playerCard,botCard;
private boolean flag,boolRan;
private GameMode gameMode;
private int botScore,playerScore,wins;
private Properties properties = new Properties();
private Properties properties2 = new Properties();
private InputStream input2 = null;
private OutputStream output = null;
private String t,nt,pl1,pl2,you,playerTurn1,p2,win,botWin,draw;
@FXML
private Label player1,player2,turn,nextTurn,winLabel,noteLabel;
private boolean oneTime;
private MediaPlayer mediaPlayer;
/**
* Φορτώνει τα αρχεία και θέτει αρχικές τιμές
* @throws IOException εαν αποτύχει να ανοίξει κάποιο αρχείο
*/
@Override
public void initialize() throws IOException {
oneTime = false;
nextButton.setDisable(true);
File f =new File("score.properties");
File f2 =new File("config.properties");
if(f2.exists()) {
input2 = new FileInputStream("config.properties");
properties2.load(input2);
String lang = properties2.getProperty("flag");
loadLang(lang);
}
if(f.exists()){
InputStream input = new FileInputStream("score.properties");
properties.load(input);
wins = Integer.parseInt(properties.getProperty("BattleWins"));
}
}
/**
* Ο κατασκευαστής της κλάσης
*/
public Battle(){
imageViews2 = new ArrayList<>();
foundCards = new ArrayList<>();
cards2 = new ArrayList<>();
gameMode = new GameMode();
flag = false;
clicks = 0;
boolRan = false;
oneTime = false;
Media buttonSound = new Media(getClass().getClassLoader().getResource("Sounds/buttonSound.wav").toExternalForm());
mediaPlayer = new MediaPlayer(buttonSound);
}
/**
* Θέτει το GameMode ανάλογα με το τι έχει επιλέξει ο χρήστης, δημιουργεί τα ImageViews και τις κάρτες και για τα δύο πλέγματα.
* @param gameMode {@code GameMode}
* @param theme {@code Image}
* @throws IOException -
*/
@Override
public void setMode(GameMode gameMode, Image theme) throws IOException {
super.setMode(gameMode, theme);
this.theme = theme;
this.gameMode = gameMode;
gameMode.gameResolution();
createImageViews(gridTable1,imageViews);
createImages(cards);
// shuffleCards(imageViews);
setImages(imageViews,cards);
player();
createImageViews(gridTable2,imageViews2);
createImages(cards2);
// shuffleCards(imageViews2);
setImages(imageViews2,cards2);
}
/**
* Φτιάχνει τα ονόματα των παιχτών ανάλογα με την γλώσσα και ορίζει στα Labels την σειρά.
* @throws IOException -
*/
public void battleStart() throws IOException{
playersLang();
turn.setText(t+ playerTurn1+you);
nextTurn.setText(nt + p2 );
}
/**
* Ελέγχει την κάρτα που πάτησε ο χρήστης και την γυρνάει. Επίσης με βρίσκεται και ο Event Handler του κουμπιού ΕΠΟΜΕΝΟ που καθορίζει την σειρά με την οποία θα παίξουν οι παίχτες.
* @param imageView {@code ImageView}
* @param card {@code Card}
*/
@Override
public void clickEvent(ImageView imageView, Card card) {
if(foundCards.size() == gameMode.getSize()*2) {
findWinner();
nextButton.setDisable(true);
return;
}
clicks++;
flipAnimation(imageView, card);
playerImageview = imageView;
playerCard = card;
if(clicks == 1){
nextButton.setDisable(false);
}
nextButton.setOnAction(event -> {
if (clicks==0 ) {
turn.setText(t+ playerTurn1+you);
nextTurn.setText(nt + p2 );
enableAll();
}
else if (clicks==1 ) {
turn.setText(nt + p2 );
nextTurn.setText(t+ playerTurn1+you);
if(gameMode.getRival1().equals("Goldfish")){
this.goldfish();
compareGoldfish(playerImageview,playerCard);
clicks++;
}
else if(gameMode.getRival1().equals("Elephant")){
this.elephant(playerCard);
if(!flag){
this.goldfish();
compareGoldfish(playerImageview,playerCard);
}
else{
compareElephant(playerImageview);
}
clicks++;
}
else if(gameMode.getRival1().equals("Kangaroo")){
this.kangaroo(playerCard);
if(!flag){
this.goldfish();
compareGoldfish(playerImageview,playerCard);
}
else{
compareKangaroo(playerImageview);
}
clicks++;
}
}
else if (clicks==2) {
if(gameMode.getRival1().equals("Goldfish")){
this.goldfish();
clicks++;
}
else if(gameMode.getRival1().equals("Elephant")){
this.elephant(playerCard);
if(!flag){
this.goldfish();
}
clicks++;
}
else if(gameMode.getRival1().equals("Kangaroo")){
this.kangaroo(playerCard);
if(!flag){
this.goldfish();
}
clicks++;
}
}
else if(clicks == 3) {
turn.setText(t+ playerTurn1+you);
nextTurn.setText(nt + p2 );
enableAll();
}
else{
if(gameMode.getRival1().equals("Goldfish")){
compareGoldfish(playerImageview, playerCard);
clicks = 0;
}
else if(gameMode.getRival1().equals("Elephant")){
if(!flag){
compareGoldfish(playerImageview,playerCard);
}
else{
compareElephant(playerImageview);
}
clicks = 0;
}
else if(gameMode.getRival1().equals("Kangaroo")){
if(!flag){
compareGoldfish(playerImageview,playerCard);
}
else{
compareKangaroo(playerImageview);
}
clicks = 0;
}
if(foundCards.size() == gameMode.getSize()*2) {
findWinner();
nextButton.setDisable(true);
}
}
});
disableAll();
}
/**
* Το Animation του ImageView οταν πατηθεί.
* @param imageView {@code ImageView}
* @param card {@code Card}
*/
private void flipAnimation(ImageView imageView,Card card){
imageView.setDisable(true);
ScaleTransition scaleTransition = new ScaleTransition(Duration.seconds(0.4),imageView);
scaleTransition.setFromX(1);
scaleTransition.setToX(-1);
scaleTransition.play();
scaleTransition.setOnFinished(event -> {imageView.setScaleX(1);imageView.setImage(card.getValue());});
}
/**
* Ο Event Handler του κουμπιού που σε πηγαίνει στην προηγούμενη σκηνή.
* @throws IOException εαν αποτύχει να φορτώσει το αρχείο FXML
*/
public void backClicked() throws IOException {
mediaPlayer.seek(Duration.ZERO);
mediaPlayer.setVolume(0.3f);
mediaPlayer.play();
Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("fxml/BattleSettings.fxml"));
Stage stage = (Stage) back.getScene().getWindow();
stage.getScene().setRoot(root);
}
/**
* Δημιουργεί τις εικόνες
* @param cards {@code ArrayList<Card>}
*/
@Override
public void createImages(ArrayList<Card> cards) {
for(int i =1; i<=gameMode.getSize();i++) {
Image value = new Image("Images/Cards/" + i + ".png");
Card image2 = new Card(value,theme,i);
cards.add(image2);
}
}
/**
* Το μποτάκι Goldfish το διαλέγει έναν τυχαίο αριθμό στο μέγεθος του ArrayList με τα ImageView επιλέγει έναν επιτρεπτό αριθμό και γυρνάει αυτή την κάρτα.
*/
public void goldfish() {
if(foundCards.size() == gameMode.getSize()*2) {
findWinner();
nextButton.setDisable(true);
return;
}
nextButton.setDisable(true);
Random random = new Random();
int random1 = random.nextInt(imageViews2.size());
boolRan = random.nextBoolean();
while(foundCards.contains(imageViews2.get(random1)))
random1 = random.nextInt(imageViews2.size());
botImageView = imageViews2.get(random1);
botCard = cards2.get(random1);
if(boolRan){
if(!seenImageViewsKangaroo.contains(botImageView)){
seenImageViewsKangaroo.add(botImageView);
seenCardsKangaroo.add(botCard);
}
}
if(!seenImageViewsElephant.contains(botImageView)){
seenImageViewsElephant.add(botImageView);
seenCardsElephant.add(botCard);
}
flipAnimation(botImageView,botCard);
nextButton.setDisable(false);
}
/**
* Το μποτάκι Elephant που δέχεται την κάρτα που έχει σηκώσει εκείνη την στιγμή ο χρήστης και ελέγχει αν την έχει δει στο δίκο του πλέγμα.
* @param card {@code Card}
*/
private void elephant(Card card){
if(foundCards.size() == gameMode.getSize()*2) {
findWinner();
nextButton.setDisable(true);
return;
}
nextButton.setDisable(true);
flag = false;
ImageView seenImageView1 = imageViews2.get(0);
Card seenCard1 = cards2.get(0);
for(int i = 0;i<seenCardsElephant.size();i++){
if(seenCardsElephant.get(i).getId() == card.getId()){
seenImageView1 = seenImageViewsElephant.get(i);
seenCard1 = seenCardsElephant.get(i);
flag = true;
break;
}
}
System.out.printf("SIZE IS: %d\n",seenCardsElephant.size());
botImageView = seenImageView1;
botCard = seenCard1;
nextButton.setDisable(false);
}
/**
* Το μποτάκι Kangaroo το οποίο δέχεται την κάρτα που έχει σηκώσει ο χρήστης και ελέγχει αν την έχει δει στο δίκο του πλέγμα.
* @param card {@code Card}
*/
private void kangaroo(Card card){
if(foundCards.size() == gameMode.getSize()*2) {
findWinner();
nextButton.setDisable(true);
return;
}
nextButton.setDisable(true);
flag = false;
ImageView seenImageView1 = imageViews2.get(0);
Card seenCard1 = cards2.get(0);
for(int i = 0;i<seenCardsKangaroo.size();i++){
if(seenCardsKangaroo.get(i).getId() == card.getId()){
seenImageView1 = seenImageViewsKangaroo.get(i);
seenCard1 = seenCardsKangaroo.get(i);
flag = true;
break;
}
}
System.out.printf("SIZE IS: %d\n",seenCardsElephant.size());
botImageView = seenImageView1;
botCard = seenCard1;
nextButton.setDisable(false);
}
/**
* Σύγκριση των καρτών του παίχτη και του Kangaroo
* @param playerImageview {@code ImageView}
*/
private void compareKangaroo(ImageView playerImageview){
nextButton.setDisable(true);
if(flag){
if(clicks == 1){
botScore++;
player2.setText(pl2+botScore);
}
else if(clicks == 4){
playerScore++;
player1.setText(pl1+playerScore);
}
foundCards.add(botImageView);
foundCards.add(playerImageview);
seenImageViewsKangaroo.remove(botImageView);
seenCardsKangaroo.remove(botCard);
seenImageViewsElephant.remove(botImageView);
seenCardsElephant.remove(botCard);
flipAnimation(botImageView,botCard);
new Timeline(new KeyFrame(Duration.seconds(0.6),event -> {
botImageView.setDisable(true);
playerImageview.setDisable(true);
botImageView.setOpacity(0.6);
playerImageview.setOpacity(0.6);
nextButton.setDisable(false);
})).play();
}
}
/**
* Σύγκριση των καρτών του παίχτη και του Goldfish
* @param playerImageview {@code ImageView}
* @param playerCard {@code Card}
*/
private void compareGoldfish(ImageView playerImageview,Card playerCard){
nextButton.setDisable(true);
if(botCard.getId() == playerCard.getId()){
if(clicks == 1){
botScore++;
player2.setText(pl2+botScore);
}
else if(clicks == 4){
playerScore++;
player1.setText(pl1+playerScore);
}
foundCards.add(botImageView);
foundCards.add(playerImageview);
seenImageViewsElephant.remove(botImageView);
seenCardsElephant.remove(botCard);
seenCardsKangaroo.remove(botCard);
seenImageViewsKangaroo.remove(botImageView);
new Timeline(new KeyFrame(Duration.seconds(0.6), event -> {
botImageView.setDisable(true);
playerImageview.setDisable(true);
botImageView.setOpacity(0.6);
playerImageview.setOpacity(0.6);
nextButton.setDisable(false);
})).play();
}
else {
new Timeline(new KeyFrame(Duration.seconds(1.5), event -> {
botImageView.setImage(botCard.getBackground());
playerImageview.setImage(playerCard.getBackground());
nextButton.setDisable(false);
})).play();
}
}
/**
* Σύγκριση των καρτών του παίχτη και του Elephant
* @param playerImageview {@code ImageView}
*/
private void compareElephant(ImageView playerImageview){
nextButton.setDisable(true);
if(flag){
if(clicks == 1){
botScore++;
player2.setText(pl2+botScore);
}
foundCards.add(botImageView);
foundCards.add(playerImageview);
seenImageViewsElephant.remove(botImageView);
seenCardsElephant.remove(botCard);
seenImageViewsKangaroo.remove(botImageView);
seenCardsKangaroo.remove(botCard);
flipAnimation(botImageView,botCard);
new Timeline(new KeyFrame(Duration.seconds(0.6),event -> {
botImageView.setDisable(true);
playerImageview.setDisable(true);
botImageView.setOpacity(0.6);
playerImageview.setOpacity(0.6);
nextButton.setDisable(false);
})).play();
}
}
/**
* Ελέγχει ποιος είναι ο νικητής
*/
private void findWinner(){
if (playerScore>botScore && !oneTime){
oneTime = true;
wins++;
try {
output = new FileOutputStream("score.properties");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
properties.setProperty("BattleWins",Integer.toString(wins));
try {
properties.store(output,null);
} catch (IOException e) {
e.printStackTrace();
}
winLabel.setText(win);
nextButton.setDisable(true);
}
else if(playerScore == botScore){
winLabel.setText(draw);
nextButton.setDisable(true);
}
else{
winLabel.setText(p2 + " "+botWin);
nextButton.setDisable(true);
}
}
/**
* Φορτώνει την γλώσσα
* @param lang {@code String}
*/
private void loadLang(String lang) {
Locale locale = new Locale(lang);
ResourceBundle bundle = ResourceBundle.getBundle("lang", locale);
t = (bundle.getString("turn"));
nt = bundle.getString("nextTurn");
pl1 = bundle.getString("player1");
pl2 = bundle.getString("player2");
playerTurn1 = bundle.getString("player1T");
you = bundle.getString("you");
player1.setText(bundle.getString("player1") + "0");
player2.setText(bundle.getString("player2") + "0");
win = bundle.getString("win");
botWin = bundle.getString("botWin");
nextButton.setText(bundle.getString("next"));
noteLabel.setText(bundle.getString("noteLabel"));
draw = bundle.getString("draw");
}
/**
* Φορτώνει τα ονόματα των παιχτών
* @throws IOException -
*/
private void playersLang() throws IOException{
File f2 =new File("config.properties");
if(f2.exists()) {
input2 = new FileInputStream("config.properties");
properties2.load(input2);
String lang = properties2.getProperty("flag");
loadLang(lang);
if (lang.equals("el")) {
if (gameMode.getRival1().equals("Goldfish")) {
p2 = "Χρυσόψαρο";
} else if (gameMode.getRival1().equals("Kangaroo")) {
p2 = "Καγκουρό";
} else if (gameMode.getRival1().equals("Elephant")) {
p2 = "Ελέφαντας";
}
}
else if(lang.equals("en")){
if(gameMode.getRival1().equals("Goldfish")){
p2 = "Goldfish";
}
else if(gameMode.getRival1().equals("Kangaroo")){
p2 = "Kangaroo";
}
else if(gameMode.getRival1().equals("Elephant")){
p2 = "Elephant";
}
}
}
}
}
| TommysG/memory-card-game | src/main/java/sample/Battle.java |
1,750 | 404: Not Found | AggelosMps/ProjectTest | Savefile.java |
1,751 | package api;
import java.io.Serializable;
import java.util.Objects;
/**
* Η κλάση αυτή αναπαριστά ένα χρήστη
* @author trifon
*/
public class User implements Serializable {
private String name;
private String surname;
private String username;
private String password;
private String type;
public User(String name, String surname, String username, String password, String type){
this.name = name;
this.surname = surname;
this.username = username;
this.password = password;
this.type = type;
}
// Getters
public String getName() {
return name;
}
public String getSurname() {
return surname;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public String getType() {
return type;
}
/**
* Ελέγχει την ισότητα δύο αντεικιμένων
* @param user
* @return true αν τα αντεικίμενα είναι ίσα, false αντίθετα
*/
public boolean equals(User user) {
return Objects.equals(this.name, user.name) &&
Objects.equals(this.type, user.type) &&
Objects.equals(this.surname, user.surname) &&
Objects.equals(this.username, user.username) &&
Objects.equals(this.password, user.password);
}
}
| AnestisZotos/Accommodations-rating-platform | api/User.java |
1,755 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Λαμβάνει ως είσοδο true/false σπό το
* stdin, για δυο δεξαμενές καυσίμων ενός
* αεροπλάνου εάν τα καύσιμα είναι κάτω
* από 1/4. Επεξεργάζεται και αν η μία
* δεξαμενή είναι < 1/4 ανάβει η πορτοκαλή
* ένδειξη, αν και οι δύο είναι < 1/4 ανάβει
* η κόκκινη ένδειξη
*/
public class TankApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean isEmptyTank1 = false;
boolean isEmptyTank2 = false;
boolean isOrange = false;
boolean isRed = false;
System.out.println("Please insert tank1 status (true/false)");
isEmptyTank1 = scanner.nextBoolean();
System.out.println("Please insert tank2 status (true/false)");
isEmptyTank2 = scanner.nextBoolean();
isOrange = isEmptyTank1 ^ isEmptyTank2;
isRed = isEmptyTank1 && isEmptyTank2;
System.out.println("Orange: " + isOrange + ", Red: " + isRed);
}
}
| MytilinisV/codingfactorytestbed | ch3/TankApp.java |
1,758 | package MemoryGame;
import java.io.*;
import java.util.ArrayList;
/**
* Η κλάση διαχειρίζεται το αρχείο που αποθηκεύονται τα δεδομένα.
*
* @author Δημήτριος Παντελεήμων Γιακάτος
* @version 1.0.0
*/
public class FileManager {
private String file;
private String path;
/**
* Ο μέθοδος δημιουργεί το φάκελο που θα αποθηκευτεί το αρχείο δεδομένων.
*
* @param file Το όνομα του αρχείου.
* @param path Τη διεύθυνση που θα αποθηκευτεί το αρχείο.
*/
public FileManager(String file, String path) {
this.file = file;
this.path = path;
new File(this.path).mkdir();
}
/**
* Η μέθοδος αποθηκεύει τα δεδομένα στο αρχείο, αφού ελέγξει πρώτα αν τα δεδομένα που πρόκειται να αποθηκευτούν
* είναι πολλαπλάσια του δύο. Αυτό συμβαίνει επειδή η παράμετρος που δέχεται η μέθοδος είναι ένας πίνακας
* χαρακτήρων που περιλαμβάνει το όνομα και τα βήματα που έκανε ένα παίχτης. Αν ο παίχτης παίζει για πρώτη φορά
* τότε οι νίκες αρχικοποιούνται σε 1, αλλιώς αυξάνονται κατά 1. Τα αποθηκεύει σε μία δομή
* δεδομένων και τέλος εξάγει τη δομή στο αρχείο.
*
* @param str Πίνακας χαρακτήρων που προλαμβάνει το όνομα και τα βήματα, δηλαδή str[0]=”name” και str[1]=”2”.
*/
void SetData(String[] str) {
if(str.length%2 != 0) {
return;
}
boolean flag;
ArrayList<FileForm> contents = Input();
FileForm[] listContents = new FileForm[str.length / 2];
String[][] subStr = new String[str.length / 2][2];
for(int i = 0; i < subStr.length; i++) {
subStr[i][0] = str[2*i];
subStr[i][1] = str[2*i+1];
}
for(int i = 0; i < subStr.length; i++) {
flag = true;
for (FileForm content : contents) {
if (subStr[i][0].equals(content.getName())) {
content.increaseWins();
content.setSteps(subStr[i][1]);
flag = false;
break;
}
}
if(flag) {
listContents[i] = new FileForm();
listContents[i].setName(subStr[i][0]);
listContents[i].setWins("1");
listContents[i].setSteps(subStr[i][1]);
contents.add(listContents[i]);
}
}
Output(contents);
}
/**
* Η μέθοδος δέχεται ένα όνομα, ελέγχει αν υπάρχει στο αρχείο και επιστρέφει το όνομα, τις νίκες και τα βήματα του.
*
* @param str Το όνομα.
* @return Ένα πίνακα χαρακτήρων μίας διάστασης που περιλαμβάνει το όνομα, τις νίκες και τα βήματα.
*/
String[] GetSpecificData(String str) {
ArrayList<FileForm> contents = Input();
String[] data = new String[3];
for (FileForm content : contents) {
if (str.equals(content.getName())) {
data[0] = content.getName();
data[1] = content.getWins();
data[2] = content.getSteps();
break;
}
}
return data;
}
/**
* Η μέθοδος εξάγει τα δεδομένα που είναι αποθηκευμένα στο αρχείο σε ένα πίνακα μίας διάστασης.
* Πιο συγκεκριμένα εξάγει τα ονόματα και τις νίκες των παιχτών.
*
* @return Πίνακα μιας διάστασης με τα ονόματα και τις νίκες των παιχτών.
*/
public String[] ExportWinsToStringMatrix() {
ArrayList<FileForm> contents = SortForWins(Input());
String[] str = new String[contents.size() * 2];
int j = 0;
for (FileForm content : contents) {
str[j] = content.getName();
j++;
str[j] = content.getWins();
j++;
}
return str;
}
/**
* Η μέθοδος εξάγει τα δεδομένα που είναι αποθηκευμένα στο αρχείο σε ένα πίνακα μίας διάστασης.
* Πιο συγκεκριμένα εξάγει τα ονόματα και τα βήματα των παιχτών.
*
* @return Πίνακα μιας διάστασης με τα ονόματα και τα βήματα των παιχτών.
*/
public String[] ExportStepsToStringMatrix() {
ArrayList<FileForm> contents = SortForSteps(Input());
String[] str = new String[contents.size() * 2];
int j = 0;
for (FileForm content : contents) {
str[j] = content.getName();
j++;
str[j] = content.getSteps();
j++;
}
return str;
}
/**
* Η μέθοδος εξάγει τη δομή δεδομένων που περιλαμβάνει τα ονόματα, τις νίκες και τα βήματα των παιχτών στο αρχείο.
*
* @param str Δομή δεδομένων που περιλαμβάνει τα ονόματα, τις νίκες και τα βήματα των παιχτών
*/
private void Output(ArrayList<FileForm> str){
try(DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(path + file, false)))) {
for (FileForm fileForm : str) {
out.writeUTF(fileForm.getName());
out.writeUTF(fileForm.getWins());
out.writeUTF(fileForm.getSteps());
}
} catch (Exception ignored) {
}
}
/**
* Η μέθοδος μετράει το μέγεθος τους αρχείου.
*
* @return Το μέγεθος τους αρχείου.
*/
private int FileSize() {
int lines = 0;
try(DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(path + file)))) {
while((in.readUTF()) != null) {
lines++;
}
} catch (Exception ignored) {
}
return lines;
}
/**
* Η μέθοδος διαβάζει το αρχείο και εισάγει τα δεδομένα, δηλαδή τα ονόματα, τις νίκες και τα βήματα των παιχτών
* σε μία δομή.
*
* @return Τη δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών
*/
private ArrayList<FileForm> Input() {
int count = 0;
String str;
FileForm[] form = new FileForm[FileSize() / 3];
ArrayList<FileForm> contents = new ArrayList<>();
try(DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream(path + file)))) {
while((str = in.readUTF()) != null) {
form[count] = new FileForm();
form[count].setName(str);
if((str = in.readUTF()) != null) {
form[count].setWins(str);
} else {
break;
}
if((str = in.readUTF()) != null) {
form[count].setSteps(str);
} else {
break;
}
contents.add(form[count]);
count++;
}
} catch(Exception ignored) {
}
return contents;
}
/**
* Η μέθοδος ταξινομεί τη δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών κατά φθίνουσα σειρά με
* βάση τις νίκες.
*
* @param str Δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών.
* @return Τη ταξινομημένη δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών.
*/
private ArrayList<FileForm> SortForWins(ArrayList<FileForm> str) {
for(int i = 0; i < str.size(); i++) {
for(int j = 1; j < str.size() - i; j++) {
if(Integer.valueOf(str.get(j-1).getWins()) < Integer.valueOf(str.get(j).getWins())) {
Swap(str, j-1, j);
}
}
}
return str;
}
/**
* Η μέθοδος ταξινομεί τη δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών κατά αύξουσα σειρά με
* βάση τα βήματα.
*
* @param str Δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών.
* @return Τη ταξινομημένη δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών.
*/
private ArrayList<FileForm> SortForSteps(ArrayList<FileForm> str) {
for(int i = 0; i < str.size(); i++) {
for(int j = 1; j < str.size() - i; j++) {
if(Integer.valueOf(str.get(j-1).getSteps()) > Integer.valueOf(str.get(j).getSteps())) {
Swap(str, j-1, j);
}
}
}
return str;
}
/**
* Η μέθοδος υλοποιεί την αντιμετάθεση μεταξύ δύο στοιχείων.
*
* @param str Δομή δεδομένων με τα ονόματα, τις νίκες και τα βήματα των παιχτών.
* @param i Τη θέση του πρώτου στοιχείου στη δομή.
* @param j Τη θέση του δεύτερου στοιχείου στη δομή.
*/
private void Swap(ArrayList<FileForm> str, int i, int j) {
String tempN;
String tempW;
String tempS;
tempN = str.get(i).getName();
str.get(i).setName(str.get(j).getName());
str.get(j).setName(tempN);
tempW = str.get(i).getWins();
str.get(i).setWins(str.get(j).getWins());
str.get(j).setWins(tempW);
tempS = str.get(i).getSteps();
str.get(i).setSteps(str.get(j).getSteps());
str.get(j).setSteps(tempS);
}
}
| dpgiakatos/MemoryGame | MemoryGame/FileManager.java |
1,766 | import java.util.HashMap;
import java.util.Iterator;
/**
* Η κλάση αυτή αφορά μια συναλλαγή ενός πελάτη με ένα supermarket. Με άλλα
* λόγια αντιπροσωπεύει το καλάθι με τα προϊόντα που αγόρασε σε μια επίσκεψη.
* This class represents a transaction of a super market customer. In other words,
* the basket with the products of a visit to the supermarket.
*
* @author Grigorios Tsoumakas
*/
public class Transaction {
private HashMap<String, Integer> items;
public Transaction() {
items = new HashMap<>();
}
/**
* Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα ενός προϊόντος και άρα στην
* προσθήκη του στην τρέχουσα συναλλαγή ενός πελάτη.
* This method represents the scanning process in a supermarket. It adds the product
* to the current transaction.
*
* @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of
* the product e.g. milk
*/
public void scanItem(String product) {
scanItems(product, 1);
}
/**
* Η μέθοδος αυτή αντιστοιχεί στο σκανάρισμα πολλών προϊόντων του ίδιου
* είδους και προσθήκη τους στην τρέχουσα συναλλαγή ενός πελάτη.
* <p>
* This method represents the scanning of the same product multiple times
* and adds them to the customers transactions.
*
* @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of
* the product e.g. milk
* @param amount ποσότητα προϊόντος. The amount of the products
*/
public void scanItems(String product, int amount) {
if (items.containsKey(product)) {
items.put(product, items.get(product) + amount);
} else {
items.put(product, amount);
}
}
/**
* Η μέθοδος αυτή επιστρέφει τo πλήθος εμφάνισης ενός προϊόντος στο
* καλάθι ενός πελάτη.
* The number of times a product appears in the basket.
*
* @param product συμβολοσειρά με το όνομα του προϊόντος, π.χ. γάλα. String containing the name of
* the product e.g. milk
*/
public int getAmountOfProduct(String product) {
//return items.getOrDefault(product, 0);
if (items.containsKey(product)) {
return items.get(product);
} else {
return 0;
}
}
/**
* Η μέθοδος αυτή επιστέφει έναν πίνακα με τα ονόματα των προϊόντων που
* υπάρχουν στο καλάθι του πελάτη. Αν το ίδιο προϊόν υπάρχει πάνω από μία
* φορές στο καλάθι, θα πρέπει στον επιστρεφόμενο πίνακα να εμφανίζεται μία
* φορά μόνο.
* <p>
* This method returns a table with the names of the products that exist in the basket.
* The returning table should not contain duplicate items and each product should appear only once.
*
* @return ο πίνακας με τα ονόματα των προϊόντων. The table with the names of the products purchased.
*/
public String[] getProducts() {
String[] products = new String[items.keySet().size()];
Iterator<String> it = items.keySet().iterator();
for (int i = 0; i < products.length; i++) {
products[i] = it.next();
}
return products;
// String[] products = new String[items.keySet().size()];
// return items.keySet().toArray(products);
}
}
| auth-csd-oop-2022/lab-advancedBehavior-Supermarket-solved | src/Transaction.java |
1,768 | package gr.aueb.cf.ch3;
import java.util.Scanner;
/**
* Αν η θερμοκρασία είναι < 0 τότε
* η isTempBelowZero γίνεται true,
* αλλιώς γίνεται false.
*/
public class TemperatureApp {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int temperature = 0;
boolean isTempBelowZero = false;
System.out.println("Please insert temperature");
temperature = scanner.nextInt();
isTempBelowZero = (temperature < 0);
System.out.println("Temp is below zero: " + isTempBelowZero);
}
}
| a8anassis/codingfactory5-java | src/gr/aueb/cf/ch3/TemperatureApp.java |
1,770 |
import // <editor-fold defaultstate="collapsed">
java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Base64;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.ColorUIResource;
public class Main {
public static final String MAIN_DIR_PATH = "data";
public static final String DIGESTS_FILE_PATH = MAIN_DIR_PATH + "/digests.data";
public static final String APP_PUBLIC_KEY_FILE_PATH = MAIN_DIR_PATH + "/public.key";
public static final String USER_FILES_DIR_PATH = MAIN_DIR_PATH + "/user_files";
//Κωδικες Σφαλματων
public static final int USERNAME_EXISTS = 1;
public static final int CORRUPTED_KEY_FILE = 2;
public static final int CORRUPTED_DIGESTS_FILE = 3;
public static final int ENCRYPTION_ERROR = 4;
public static final int ILLEGAL_USERNAME = 5;
public static final int ILLEGAL_PASSWORD = 6;
public static final int UNKNOWN_ERROR = 7;
public static final int USER_NOT_EXISTS = 1;
public static final int WRONG_PASSWORD = 2;
public static final int CORRUPTED_DATA_FILES = 1;
public static final int USER_FILES_INFRIGMENT = 10;
private static final String usernameREGEX
= "^\\w(?:\\w*(?:[.-]\\w+)?)*(?<=^.{4,22})$";
/**
* Στην αρχη χρησιμοποιησα regex kai για το password αλλα τελικα το κανα σε
* μεθοδο για καλυτερη ασφαλεια αλλαξα το τροπο υλοποιησης και τωρα δεν
* αποθηκευεται ποτε ο κωδικος μεσα σε String (δηλαδη στη μνημη)*
*/
// private static final String passwordREGEX
// = "^(?=.*\\d)(?=.*[\\[\\]\\^\\$\\.\\|\\?\\*\\+\\(\\)\\\\~`\\!@#%&\\-_+={}'\"\"<>:;, ])(?=.*[a-z])(?=.*[A-Z]).{8,32}$";
public static final String separator = ":=:";
private static UserInfo currentUserInfo;
private static ArrayList<TransactionEntry> currentUserEntries = new ArrayList<>();
//Μεθοδος για την εγγραφη των νεων χρηστων
public static int register(String name, String username, char[] password) {
if (!username.matches(usernameREGEX)) { //Ελγχος για σωστη μορφη username
return ILLEGAL_USERNAME;
}
if (!passwordStrengthCheck(password)) { //Ελεγχος και για σωστη μορφη κωδικου
return ILLEGAL_PASSWORD;
}
try {
if (getUserInfo(username) == null) { //Ελεγχος αν υπαρχει το username
//Δημιουργια salts
byte[] salt = SHA256.generateSalt();
String saltEncoded = Base64.getEncoder().encodeToString(salt);
//Δημιουργια συνοψης με salts
byte[] hash = SHA256.HashWithSalt(toBytes(password), salt);
//Ασσυμετρη κρυπτογραφηση συνοψης και μετατροπη σε Base64 String για αποθηκευση σε αρχειο
String encryptedHashEncoded = Base64.getEncoder().encodeToString(
RSA2048.encrypt(hash, RSA2048.constructPublicKey(AppKeyPair.getPublic())));
//Δημιουργια τυχαιου συμμετρικου κλειδιου για τον χρηστη και μετατροπη σε Base64 String για αποθηκευση σε αρχειο
String randomKeyEncoded = Base64.getEncoder().encodeToString(AES256.getRandomKey().getEncoded());
//Αποθηκευση στο αρχειο με τις συνοψεις
appendContentToFile(name + separator + username + separator + saltEncoded
+ separator + encryptedHashEncoded + separator + randomKeyEncoded + "\n",
new File(DIGESTS_FILE_PATH));
return 0;
} else {
return USERNAME_EXISTS;
}
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (InvalidKeyException ex) {
ex.printStackTrace();
return CORRUPTED_KEY_FILE;
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (BadPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (IOException ex) {
ex.printStackTrace();
return CORRUPTED_DIGESTS_FILE;
} catch (InvalidKeySpecException ex) {
ex.printStackTrace();
return CORRUPTED_KEY_FILE;
} catch (Exception ex) {
ex.printStackTrace();
return UNKNOWN_ERROR;
}
}
//Μεθοδος για Συνδεση Χρηστη
public static int login(String username, char[] password) {
try {
currentUserInfo = getUserInfo(username);
if (!(currentUserInfo == null)) { //Ελεγχος αν υπαρχει το username
//Παιρνω τα αποθηκευμενα salt και τη κρυπτογραφημενη συνοψη
String encodedSalt = currentUserInfo.getSaltEncoded();
String digestEncoded = currentUserInfo.getEncryptedDigestEncoded();
//Μετατροπη και παλι σε byte array
byte[] salt = Base64.getDecoder().decode(encodedSalt);
byte[] hash = SHA256.HashWithSalt(toBytes(password), salt);
//Ασυμμετρη αποκωδικοποιηση συνοψης
byte[] decryptedHash = RSA2048.decrypt(
Base64.getDecoder().decode(digestEncoded),
RSA2048.constructPrivateKey(AppKeyPair.getPrivate()));
//Συγκριση των συνοψεων για επιβεβαιωση
if (Arrays.equals(hash, decryptedHash)) {
return 0;
} else {
return WRONG_PASSWORD;
}
} else {
return USER_NOT_EXISTS;
}
} catch (IOException ex) {
ex.printStackTrace();
return CORRUPTED_DIGESTS_FILE;
} catch (InvalidKeyException ex) {
ex.printStackTrace();
return CORRUPTED_DIGESTS_FILE;
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (BadPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (InvalidKeySpecException ex) {
ex.printStackTrace();
return CORRUPTED_DIGESTS_FILE;
} catch (Exception ex) {
ex.printStackTrace();
return UNKNOWN_ERROR;
}
}
//Μεθοδος για αποθηκευση νεας λογιστικης εγγραφης στο καταλληλο αρχειο
public static int saveNewEntry(TransactionEntry entry) {
String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname();
File udir = new File(user_dir);
if (!(udir.exists() && udir.isDirectory())) {
udir.mkdir();
}
try {
//Συμμετρικη κωδικοποιηση με το κλειδι του χρηστη
String encryptedEntry = AES256.Encrypt(entry.getId() + separator + entry.getDate()
+ separator + entry.getAmmount() + separator + entry.getDescription(),
AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n";
//Αποθηκευση στο καταλληλο αρχειο (αναλογα το ειδος της συνναλαγης)
if (entry.getType() == TransactionEntry.INCOME) {
File user_income_file = new File(udir.getPath() + "/" + "income.data");
appendContentToFile(encryptedEntry, user_income_file);
} else {
File user_outcome_file = new File(udir.getPath() + "/" + "outcome.data");
appendContentToFile(encryptedEntry, user_outcome_file);
}
//Προσθηκη στο ArrayList με τις αλλες εγγραφες
currentUserEntries.add(entry);
return 0;
} catch (IOException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (InvalidKeyException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (BadPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (Exception ex) {
ex.printStackTrace();
return UNKNOWN_ERROR;
}
}
//Μεθοδος για την αντικατασταση μιας εγγραφης μετα απο αλλαγη των στοιχειων της και αποθηκευση
public static int replaceEntryAndSave(TransactionEntry entry) {
//Αντικατασταση της εγγραφης
for (int i = 0; i < currentUserEntries.size(); i++) {
if (currentUserEntries.get(i).getId().equals(entry.getId())) {
currentUserEntries.remove(i);
currentUserEntries.add(i, entry);
}
}
String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname();
File user_income_file = new File(user_dir + "/" + "income.data");
File user_outcome_file = new File(user_dir + "/" + "outcome.data");
//Αποθηκευση παλι των εγγραφων στο αρχειο
try {
FileWriter fw;
if (entry.getType() == TransactionEntry.INCOME) {
fw = new FileWriter(user_income_file);
} else {
fw = new FileWriter(user_outcome_file);
}
BufferedWriter buff = new BufferedWriter(fw);
for (TransactionEntry e : currentUserEntries) {
if (e.getType() == entry.getType()) {
String encryptedEntry = AES256.Encrypt(e.getId() + separator + e.getDate()
+ separator + e.getAmmount() + separator + e.getDescription(),
AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded()))) + "\n";
buff.write(encryptedEntry);
}
}
buff.close();
fw.close();
return 0;
} catch (IOException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (InvalidKeyException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (BadPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (Exception ex) {
ex.printStackTrace();
return UNKNOWN_ERROR;
}
}
//Μεθοδος για τη φορτωση των εγγραφων του χρηστη απο τα αρχεια (γινεται στην αρχη)
public static int getCurrentUserEntries() {
String user_dir = USER_FILES_DIR_PATH + "/" + currentUserInfo.getUname();
File user_income_file = new File(user_dir + "/" + "income.data");
File user_outcome_file = new File(user_dir + "/" + "outcome.data");
try {
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(user_income_file)));
String encryptedEntry;
//Καθε γραμμη ειναι μια εγγραφη, αποκωδικοποιειται και επειτα τη σπαω σε κομματια (με το separator που ορισα)
//παιρνω τα στοιχεια της, τη δημιουργω και τη βαζω στη λιστα με τις εγγραφες του χρηστη
//Αυτο γινεται κια στα δυο αρχεια του χρηστη
while ((encryptedEntry = br.readLine()) != null) {
String decryptedEntryStr = AES256.Decrypt(encryptedEntry,
AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded())));
String[] entryDetails = decryptedEntryStr.split(separator);
TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1],
entryDetails[2], entryDetails[3], TransactionEntry.INCOME);
currentUserEntries.add(entry);
}
br.close();
br = new BufferedReader(new InputStreamReader(
new FileInputStream(user_outcome_file)));
while ((encryptedEntry = br.readLine()) != null) {
String decryptedEntryStr = AES256.Decrypt(encryptedEntry,
AES256.getKeyFromBytes(Base64.getDecoder().decode(currentUserInfo.getKeyEncoded())));
String[] entryDetails = decryptedEntryStr.split(separator);
TransactionEntry entry = new TransactionEntry(entryDetails[0], entryDetails[1],
entryDetails[2], entryDetails[3], TransactionEntry.OUTCOME);
currentUserEntries.add(entry);
}
return 0;
} catch (FileNotFoundException ex) {
return 0;
} catch (IOException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (NoSuchPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (InvalidKeyException ex) {
ex.printStackTrace();
return CORRUPTED_DATA_FILES;
} catch (InvalidAlgorithmParameterException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (IllegalBlockSizeException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (BadPaddingException ex) {
ex.printStackTrace();
return ENCRYPTION_ERROR;
} catch (Exception ex) {
ex.printStackTrace();
return UNKNOWN_ERROR;
}
}
//Μεθοδος για Επιστροφη λιστας συνναλαγων οι οποιες εγιναν σε μια συγκεκριμενη ημερομηνια
public static ArrayList<TransactionEntry> getEntriesWithSelectedDate(String selectedDate) {
ArrayList<TransactionEntry> entries = new ArrayList<>();
for (TransactionEntry e : currentUserEntries) {
if (e.getDate().equals(selectedDate)) {
entries.add(e);
}
}
return entries;
}
//Μεθοδος για επιστροφη συνναλαγης βαση του κωδικου της
public static TransactionEntry getEntryByID(String id) {
for (TransactionEntry e : currentUserEntries) {
if (e.getId().equals(id)) {
return e;
}
}
return null;
}
//Μεθοδος για επιστροφη λιστας με τους μηνες οι οποιοι εχουν συνναλαγες (η δευτερη λιστα ειναι για
//να κρατασει εναν αριθμο για τον μηνα και ενα για τη χρονια του μηνα. Και επειδη ειναι και αυτο
//ειναι λιστα μπορω να χρησιμοποιησω την μεθοδο contains που με γλυτωσε απο κοπο
public static ArrayList<ArrayList<Integer>> getMonthsWithEntries() {
ArrayList<ArrayList<Integer>> months = new ArrayList<>();
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat(GUI.dateFormat);
for (TransactionEntry entry : currentUserEntries) {
try {
java.util.Date d = formatter.parse(entry.getDate());
ArrayList<Integer> temp = new ArrayList<>(Arrays.asList(
Integer.parseInt(new java.text.SimpleDateFormat("MM").format(d)) - 1,
Integer.parseInt(new java.text.SimpleDateFormat("yyyy").format(d))));
if (!months.contains(temp)) {
months.add(temp);
}
} catch (ParseException ex) {
ex.printStackTrace();
}
}
return months;
}
//Μεθοδοσ γι την επιστροφη λιστας με εγγραφες που εχουν γινει σε ενα συγκεκριμενο μηνα
public static ArrayList<TransactionEntry> getEntriesWithSelectedMonth(String selectedMonth) {
ArrayList<TransactionEntry> entries = new ArrayList<>();
for (TransactionEntry e : currentUserEntries) {
java.util.Date entryDate = null;
try {
entryDate = new java.text.SimpleDateFormat(GUI.dateFormat).parse(e.getDate());
} catch (ParseException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}
if (new java.text.SimpleDateFormat(GUI.monthYearFormat).format(entryDate)
.equals(selectedMonth)) {
entries.add(e);
}
}
return entries;
}
//Η main στην αρχη αλλαζει την εμφανιση των γραφικων της java. Προσοχη χρειαζεται να προσθεσετε τη βιβλιοθηκη που υπαρχει
//στον φακελο lib του project αλλιως τα γραφικα δε θα φαινονται καλα
//Επισης φτιαχνει τους απαραιτητους φακελους αν δεν υπαρχουν και καλει τα γραφικα
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
try {
UIManager.setLookAndFeel("com.jtattoo.plaf.hifi.HiFiLookAndFeel");
UIManager.put("ComboBox.selectionBackground", new ColorUIResource(new Color(80, 80, 80)));
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
System.out.println("JTatto not found.");
// System.exit(1);
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
}
File mdir = new File(MAIN_DIR_PATH);
if (!(mdir.exists() && mdir.isDirectory())) {
mdir.mkdir();
}
File kdir = new File(USER_FILES_DIR_PATH);
if (!(kdir.exists() && kdir.isDirectory())) {
kdir.mkdir();
}
File appkeyfile = new File(APP_PUBLIC_KEY_FILE_PATH);
if (!appkeyfile.exists()) {
try (PrintStream out = new PrintStream(new FileOutputStream(appkeyfile))) {
out.print(AppKeyPair.getPublic());
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
File digestsfile = new File(DIGESTS_FILE_PATH);
if (!digestsfile.exists()) {
try {
digestsfile.createNewFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
new GUI();
});
}
//Μεθοδος για τον ελεγχο την ασφαλειας του κωδικου (να εχει ενα πεζο ενα κεφαλαιο εναν ειδικο χαρακτηρα
//και ενα ψηφιο τουλαχιστον και να ειναι απο 8 εως 32 χαρακτρηρες)
private static boolean passwordStrengthCheck(char[] pass) {
boolean special = false, uppercase = false, lowercase = false, digit = false,
whitespace = false, illegal = false, length = pass.length > 8 && pass.length < 32;
for (int i = 0; i < pass.length; i++) {
if (Character.isUpperCase(pass[i])) {
uppercase = true;
} else if (Character.isLowerCase(pass[i])) {
lowercase = true;
} else if (Character.isDigit(pass[i])) {
digit = true;
} else if (Character.isWhitespace(pass[i])) {
whitespace = true;
} else if (!Character.isAlphabetic(i)) {
special = true;
} else {
illegal = true;
}
}
return (special && uppercase && lowercase && length && !whitespace && !illegal);
}
//Βρισκει τα στοιχεια ενος χρηστη που εχουν αποθηκευτει στο αρχειο των συνοψεων
private static UserInfo getUserInfo(String username) throws IOException {
UserInfo user = null;
FileInputStream fstream = new FileInputStream(DIGESTS_FILE_PATH);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String line;
while ((line = br.readLine()) != null) {
String[] separated = line.split(separator);
if (username.equals(separated[2])) {
user = new UserInfo(separated[0], separated[1], separated[2],
separated[3], separated[4], separated[5]);
}
}
br.close();
return user;
}
public static UserInfo getCurrentUserInfo() {
return currentUserInfo;
}
private static void appendContentToFile(String content, File file) throws IOException {
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter buff = new BufferedWriter(fw);
buff.write(content);
buff.close();
fw.close();
}
//μετατροπη πινακα χαρακτηρων σε πινακα byte
private static byte[] toBytes(char[] chars) {
CharBuffer charBuffer = CharBuffer.wrap(chars);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
byteBuffer.position(), byteBuffer.limit());
Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
return bytes;
}
}
| icsd12015/projects_security | Cash Flow X/Project/src/Main.java |
1,773 | /**
* Αυτή η κλάση αναπαριστά έναν τρόπο υπολογισμού φόρου. Ο υπολογισμός του φόρου για τα αυτοκίνητα γίνεται βάση τριών
* συντελεστών ενός για κάθε ένα από τα 3 χαρακτηριστικά του. Ο τελικός φόρος είναι το άθροισμα των τριών
* χαρακτηριστικών πολλαπλασιασμένα με τον συντελεστή τους. Επιπλέον, αν το αυτοκίνητο είναι πολυτελές προστίθεται μια
* επιπλέον σταθερή χρέωση πολυτελείας. Για τα σπίτια ο υπολογισμός του φόρου γίνεται αθροίζοντας τα 4 χαρακτηριστικά
* του κάθε σπιτιού πολλαπλασιασμένα το καθένα με έναν σταθερό συντελεστή 0.25. Επιπλέον, αν το σπίτι είναι πολυτελές
* προστίθεται δύο φορές η σταθερή χρέωση πολυτελείας.
* <p>
* This class represents a way of calculating the tax. The tax for a car is calculated based on 3 factors one for each
* one of its characteristics. The final tax is the sum of those three characteristics multiplied by its factor. If the
* car is luxurious a constant luxury factor is added. The tax for a house is calculated by summing its 4
* characteristics each one multiplied by a constant factor 0.25. If the house is luxurious the constant luxury factor
* is added 2 times.
*/
public class LuxuryFactorTax implements Tax {
private double cubic_capacity_factor;
private double consumption_factor;
private double horse_power_factor;
private double luxury_factor;
/**
* Κατασκευαστής/constructor
*
* @param factor1 συντελεστής του κυβισμού/ factor for cubic capacity
* @param factor2 συντελεστής της κατανάλωσης/ factor for consumption
* @param factor3 συντελεστής της υποδύναμης/ factor for horse power
* @param luxury_factor Επιπλέον χρέωση πολυτελείας/ extra luxury factor
*/
public LuxuryFactorTax(double factor1, double factor2, double factor3, double luxury_factor) {
this.cubic_capacity_factor = factor1;
this.consumption_factor = factor2;
this.horse_power_factor = factor3;
this.luxury_factor = luxury_factor;
}
@Override
public double carTax(Car car) {
double tax = cubic_capacity_factor * car.getCubic_capacity() +
consumption_factor * car.getConsumption() + horse_power_factor * car.getHorse_power();
if (car.isLuxurious()) {
tax += luxury_factor;
}
return tax;
}
@Override
public double houseTax(House house) {
double tax = 0.25 * (house.getFloors() + house.getHouse_age() + house.getRooms() + house.getSquare_meters());
if (house.isLuxurious()) {
tax += (2 * luxury_factor);
}
return tax;
}
}
| auth-csd-oop-2023/lab-abstraction-TaxSystem-solved | src/LuxuryFactorTax.java |
1,777 | package gr.aueb.cf.solutions.ch3;
import java.util.Scanner;
/** Ελέγχει αν ένα έτος είναι δίσεκτο.
* Δίσεκτο είναι ένα έτος αν διαιρείται με το 4
* και είτε δε διαιρείται με το 100 ή διαιρείται με το 100 και το 400.
*/
public class LeapYearApp {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int year = 0;
boolean isLeap = false;
System.out.println("Please insert the year");
year = in.nextInt();
/*if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
isLeap = true;
}*/
isLeap = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
System.out.println("Year: " + year + " is leap: " + isLeap);
}
}
| a8anassis/codingfactory5-java | src/gr/aueb/cf/solutions/ch3/LeapYearApp.java |
1,785 | package api;
import api.Media.Category;
import api.Media.Content;
import java.io.Serializable;
import java.util.ArrayList;
/**
* Κλάση που υλοποιεί την αναζήτηση ενός μέσου και από τους δύο τύπους χρηστών.
* Δημιουργεί ένα αντικείμενο με τα κριτήρια που επέλεξε ο χρήστης και επιστρέφει τα αντίστοιχα αποτελέσματα μέσω μιας λίστας.
*/
public class Search implements Serializable {
private String title;
private String type;
private String ageRestriction;
private String stars;
private Category category;
private Double rating;
private Data data;
private boolean titleCheck;
private boolean typeCheck;
private boolean ageCheck;
private boolean starsCheck;
private boolean categoryCheck;
private boolean ratingCheck;
private ArrayList<Content> content;
/**
* Κατασκευαστής που δημιουργεί το αντικείμενο αναζήτησης και αρχικοποιεί όλα τα μέλη του
* @param data η βάση δεδομένων
* @param title ο τίτλος που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param type ο τύπος του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param ageRestriction ο περιορισμός της ηλικίας που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param stars ο πρωταγωνιστής που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param category η κατηγορία του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
* @param rating η ελάχιστη μέση βαθμολογία αξιολογήσεων του μέσου που δήλωσε ο χρήστης (μπορεί να μη δηλώσει)
*/
public Search(Data data,String title,String type,String ageRestriction,String stars,Category category,Double rating) {
this.title = title;
this.type = type;
this.ageRestriction = ageRestriction;
this.stars = stars;
this.category = category;
this.rating = rating;
this.data = data;
content = new ArrayList<>();
content.addAll(data.getMovies());
content.addAll(data.getSeries());
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
}
/**
* Μέθοδος που υλοποιεί την αναζήτηση των μέσων με βάση τα κριτήρια που έδωσε ο χρήστης.
* @return Μια λίστα με τα αποτελέσματα. Αν δε δοθεί κάποιο κριτήριο επιστρέφονται όλα τα μέσα.
*/
public ArrayList<Content> results() {
ArrayList<Content> searchResults = new ArrayList<>();
for (Content media : content) {
titleCheck = typeCheck = ageCheck = starsCheck = categoryCheck = ratingCheck = false;
if (title.equals("") || media.getTitle().equalsIgnoreCase(title)) titleCheck = true;
if (type == null) {
typeCheck = true;
} else if (type.equals(media.getType())) {
typeCheck =true;
}
if (ageRestriction == null) {
ageCheck = true;
} else if (ageRestriction.equals(media.getAgeRestriction())) {
ageCheck = true;
}
if (stars.isEmpty()) {
starsCheck = true;
} else {
for (String star : media.getStars().split(",")) {
if (stars.equalsIgnoreCase(star)) {
starsCheck = true;
break;
}
}
}
if (category == null) {
categoryCheck = true;
} else if (category == media.getCategory()) {
categoryCheck = true;
}
if (rating == null) {
ratingCheck = true;
} else if (Double.compare(rating,-1)==0 || Double.compare(rating, media.AverageRating())<0) {
ratingCheck = true;
}
if (titleCheck && typeCheck && ageCheck && starsCheck && categoryCheck && ratingCheck) {
searchResults.add(media);
}
}
return searchResults;
}
}
| zaxlois/streaming-tv-platform | src/api/Search.java |
1,786 | package view;
import POJOs.Content;
import POJOs.ContentPK;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.element.Text;
import com.itextpdf.layout.properties.Leading;
import com.itextpdf.layout.properties.Property;
import com.itextpdf.layout.properties.TextAlignment;
import com.itextpdf.layout.properties.UnitValue;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import model.AddDataController;
import model.QueriesSQL;
import static view.Helper.getJsonStrFromApiURL;
import static view.Helper.getUrlStrForDateRange;
import static view.Helper.jokerJsonSingleDrawToObject;
/**
* @author Athanasios Theodoropoulos
* @author Alexandros Dimitrakopoulos
* @author Odysseas Raftopoulos
* @author Xristoforos Ampelas
*/
public class WindowShowData
{
// Variables declaration
private String lastDrawDate;
private final JDialog dialog;
private final JComboBox comboBoxGameSelect;
private final JComboBox comboBoxYearSelect;
private final JRadioButton radioButtonApi;
private final JTable dataViewTable;
// Methods
/**
* Populates comboBoxYearSelect with the years the selected game is active.
* This method is called when the window is first opened and every time a different
* game is selected.
*/
private void populateComboBoxYearSelect()
{
// Remove all items from comboBoxYearSelect
comboBoxYearSelect.removeAllItems();
// Current local date
int yearNow = LocalDate.now().getYear();
// First year of the selected game
int firstYear = 1999;
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": firstYear = yearNow-2; break;
case "Powerspin": firstYear = 2020; break;
case "Super3": firstYear = 2002; break;
case "Πρότο": firstYear = 2000; break;
case "Λόττο": firstYear = 2000; break;
case "Τζόκερ": firstYear = 2000; break;
case "Extra5": firstYear = 2002; break;
}
// Populate combobox
for (int i = yearNow; i >= firstYear; i--)
{
comboBoxYearSelect.addItem(i);
}
}
/**
* Uses the API "https://api.opap.gr/draws/v3.0/{gameId}/last-result-and-active" to
* find the date of the latest draw of the selected game and stores it in the variable
* lastDrawDate. This method is called when the window is first opened and every time
* a different game is selected.
*/
private void findLastDrawDate()
{
// Get selected game id
String gId = null;
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": gId = "1100"; break;
case "Powerspin": gId = "1110"; break;
case "Super3": gId = "2100"; break;
case "Πρότο": gId = "2101"; break;
case "Λόττο": gId = "5103"; break;
case "Τζόκερ": gId = "5104"; break;
case "Extra5": gId = "5106"; break;
}
// URL string
String urlStr = "https://api.opap.gr/draws/v3.0/"+gId+"/last-result-and-active";
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
try
{
// Get json string from the API
String jsonStr = getJsonStrFromApiURL(urlStr);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the last draw object
JsonObject lastDraw = jObject.getAsJsonObject("last");
// Get the drawTime
Long drawTime = lastDraw.get("drawTime").getAsLong();
LocalDateTime ldt = Instant.ofEpochMilli(drawTime).atZone(ZoneId.systemDefault()).toLocalDateTime();
lastDrawDate = formatter.format(ldt);
}
catch (Exception ex) { /* Silently continue */ }
}
/**
* Gather data for the selected game and year using the api.
*/
private void getDataFromApi(String gameId, String year)
{
// Variables
String date1;
String date2;
List<String> urlStrList = new ArrayList<>(); // List with all the url we'll call
List<String> jsonStrList = new ArrayList<>(); // List with the json strings
BigDecimal bd; // BigDecimal - used for rounding
int drawCount;
double moneySum;
int jackpotCount;
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Create the 12 date pairs and the urlStrList
date1 = year + "-01-01";
date2 = year + "-01-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-02-01";
date2 = formatter.format(LocalDate.parse(date1, formatter).plusMonths(1).minusDays(1));
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-03-01";
date2 = year + "-03-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-04-01";
date2 = year + "-04-30";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-05-01";
date2 = year + "-05-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-06-01";
date2 = year + "-06-30";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-07-01";
date2 = year + "-07-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-08-01";
date2 = year + "-08-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-09-01";
date2 = year + "-09-30";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-10-01";
date2 = year + "-10-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-11-01";
date2 = year + "-11-30";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
date1 = year + "-12-01";
date2 = year + "-12-31";
urlStrList.add("https://api.opap.gr/draws/v3.0/"+gameId+"/draw-date/"+date1+"/"+date2+"/?limit=180");
// Number of threads (simultaneous calls to the API)
int threadNum = 12;
// --- Create the threads to do the job ---
GetJsonStrListFromUrlStrListMT[] threadArray = new GetJsonStrListFromUrlStrListMT[threadNum];
int taskNum = urlStrList.size(); // Total number of tasks to do
for (int i=0; i<threadNum; i++)
{
int index1 = i*taskNum/threadNum; // Each thread does index2-index1
int index2 = (i+1)*taskNum/threadNum; // tasks, from index1 to index2-1
threadArray[i] = new GetJsonStrListFromUrlStrListMT(index1, index2, urlStrList);
threadArray[i].start();
}
// Wait for all threads to finish
for (int i=0; i<threadNum; i++)
{
try
{
threadArray[i].join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
// Merge results from all threads
for (GetJsonStrListFromUrlStrListMT thread : threadArray)
{
// Merge jsonStrList
thread.getJsonStrList().forEach((jsonStr) ->
{
jsonStrList.add(jsonStr);
});
}
// Parce all json strings in jsonStrList
for (int i = 0; i < jsonStrList.size(); i++)
{
// Set the counters and sum to 0
drawCount = 0;
moneySum = 0;
jackpotCount = 0;
// Json string
String jsonStr = jsonStrList.get(i);
// First empty the table cells for this month.
// They'll remain empty if json has no draw data.
dataViewTable.setValueAt("", i, 1);
dataViewTable.setValueAt("", i, 2);
dataViewTable.setValueAt("", i, 3);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the "content" json array
JsonArray content = jObject.getAsJsonArray("content");
for (JsonElement drawElement : content)
{
// Get the json object from this content json element
JsonObject drawObject = drawElement.getAsJsonObject();
// Create a JokerDrawData object from the json object
JokerDrawData jokerDraw = jokerJsonSingleDrawToObject(drawObject);
// Update the counters and sum
drawCount++;
moneySum += jokerDraw.getPrizeTier5_1dividend() + jokerDraw.getPrizeTier5dividend() +
jokerDraw.getPrizeTier4_1dividend() + jokerDraw.getPrizeTier4dividend() +
jokerDraw.getPrizeTier3_1dividend() + jokerDraw.getPrizeTier3dividend() +
jokerDraw.getPrizeTier2_1dividend() + jokerDraw.getPrizeTier1_1dividend();
if (jokerDraw.getPrizeTier5_1winners() == 0) {jackpotCount++;}
}
// Round the moneySum and make it BigDecimal
bd = BigDecimal.valueOf(moneySum);
BigDecimal moneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
// Put the data for this month to dataViewTable
dataViewTable.setValueAt(drawCount, i, 1);
dataViewTable.setValueAt(moneySumBD, i, 2);
dataViewTable.setValueAt(jackpotCount, i, 3);
}
// Calculate the "total" row
int totalDrawCount = 0;
double totalMoneySum = 0;
int totalJackpotCount = 0;
for (int i = 0; i < 12; i++)
{
totalDrawCount += (int) dataViewTable.getValueAt(i, 1);
totalMoneySum += ((BigDecimal) dataViewTable.getValueAt(i, 2)).doubleValue();
totalJackpotCount += (int) dataViewTable.getValueAt(i, 3);
}
bd = BigDecimal.valueOf(totalMoneySum);
BigDecimal totalMoneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
dataViewTable.setValueAt(totalDrawCount, 12, 1);
dataViewTable.setValueAt(totalMoneySumBD, 12, 2);
dataViewTable.setValueAt(totalJackpotCount, 12, 3);
}
/**
* Gather data for the selected game and year using the DB.
*/
private void getDataFromDB(String gameId, String year) throws Exception {
// Check if Java DB server is started
try
{
DriverManager.getConnection("jdbc:derby://localhost/opapGameStatistics");
}
catch (SQLException ex)
{
String errorMsg = "Ο server της βάσης δεδομένων δεν είναι ενεργοποιημένος.";
JOptionPane.showMessageDialog(null, errorMsg, "Σφάλμα σύνδεσης στη ΒΔ", 0);
return;
}
for(int i = 0; i < 12; i++) {
//variables declaration
int drawCount;
double moneySum;
int jackpotCount;
BigDecimal bd;
String startDate;
String endDate;
// First empty the table cells for this month.
dataViewTable.setValueAt("", i, 1);
dataViewTable.setValueAt("", i, 2);
dataViewTable.setValueAt("", i, 3);
//if i+1 value has one digit
if((i + 1) < 10)
startDate = year + "-0" + (i+1) + "-01";
else //if i+1 value has two digits
startDate = year + "-" + (i+1) + "-01";
//create a Content object to be used for chacking if record exists in database
Content content = new Content();
JsonObject singleDrawObj;
ContentPK contentPK = new ContentPK();
//set startign date (1st day of the month
LocalDate fromDate = LocalDate.parse(startDate, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//set finishing day (last day of the month also checking if year is a leap year)
LocalDate toDate = fromDate.withDayOfMonth(fromDate.getMonth().length(fromDate.isLeapYear()));
//convert both dates to String
endDate = toDate.toString();
//get the numbers of draws for current month from API
JsonArray monthlyDraws = model.Utilities.GET_API_ARRAY("https://api.opap.gr/draws/v3.0/5104/draw-date/" + startDate + "/" + endDate + "/draw-id");
//loop to check if record exists in the database
for(int j = 0; j < monthlyDraws.size(); j++) {
contentPK.setDrawid(monthlyDraws.get(j).getAsInt());
contentPK.setGameid(Integer.parseInt(gameId));
content.setContentPK(contentPK);
boolean control = QueriesSQL.checkIfRecordExists(content);
//if it doesn't exists, then add it so that presented statistical data are accurate
if(!control) {
singleDrawObj = model.Utilities.GET_API("https://api.opap.gr/draws/v3.0/" + gameId + "/" + content.getContentPK().getDrawid());
AddDataController.storeDrawsDataByDrawID(singleDrawObj);
}
}
//set values for number of games, total earnings and number of jackpots
drawCount = QueriesSQL.countMonthlyGames(startDate, endDate);
moneySum = QueriesSQL.sumMonthlyDivident(startDate, endDate);
jackpotCount = QueriesSQL.countJackpots(startDate, endDate);
//convert monyeSum to big decimal to format the number of decimal points shown
bd = BigDecimal.valueOf(moneySum);
BigDecimal moneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
// Put the data for this month to dataViewTable
dataViewTable.setValueAt(drawCount, i, 1);
dataViewTable.setValueAt(moneySumBD, i, 2);
dataViewTable.setValueAt(jackpotCount, i, 3);
}
// Calculate the "total" row
int totalDrawCount = 0;
double totalMoneySum = 0;
int totalJackpotCount = 0;
for (int i = 0; i < 12; i++)
{
totalDrawCount += (int) dataViewTable.getValueAt(i, 1);
totalMoneySum += ((BigDecimal) dataViewTable.getValueAt(i, 2)).doubleValue();
totalJackpotCount += (int) dataViewTable.getValueAt(i, 3);
}
BigDecimal bd = BigDecimal.valueOf(totalMoneySum);
BigDecimal totalMoneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
dataViewTable.setValueAt(totalDrawCount, 12, 1);
dataViewTable.setValueAt(totalMoneySumBD, 12, 2);
dataViewTable.setValueAt(totalJackpotCount, 12, 3);
}
// Button actions
/**
* Action of the comboBoxGameSelect.
* @param evt
*/
private void comboBoxGameSelectActionPerformed(java.awt.event.ActionEvent evt)
{
populateComboBoxYearSelect();
CompletableFuture.runAsync(() -> findLastDrawDate()); // Run asynchronously
}
/**
* Action of the buttonDownload.
* @param evt
*/
private void buttonDownloadActionPerformed(java.awt.event.ActionEvent evt)
{
// Get selected game id
String gameId = null;
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": gameId = "1100"; break;
case "Powerspin": gameId = "1110"; break;
case "Super3": gameId = "2100"; break;
case "Πρότο": gameId = "2101"; break;
case "Λόττο": gameId = "5103"; break;
case "Τζόκερ": gameId = "5104"; break;
case "Extra5": gameId = "5106"; break;
}
// Get selected year
String year = comboBoxYearSelect.getSelectedItem().toString();
// Get the data
if (radioButtonApi.isSelected())
{
getDataFromApi(gameId, year);
}
else
{
try {
getDataFromDB(gameId, year);
} catch (Exception ex) {
Logger.getLogger(WindowShowData.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* Action of the buttonExportToPdf.
* @param evt
*/
private void buttonExportToPdfActionPerformed(java.awt.event.ActionEvent evt)
{
// If lastDrawDate remains null, there's a connection error. So, show appropriate message.
if (lastDrawDate == null) {findLastDrawDate();}
if (lastDrawDate == null)
{
String message = "Σφάλμα σύνδεσης στο API του ΟΠΑΠ.";
JOptionPane.showMessageDialog(null, message, "Σφάλμα σύνδεσης", 0);
return;
}
// Create file name
String basename = "Συγκεντρωτικά δεδομένα " + comboBoxGameSelect.getSelectedItem().toString() + " έως " + lastDrawDate;
String filename = basename + ".pdf";
// Window saveAs
JFileChooser fileChooser = new JFileChooser()
{
@Override
public JDialog createDialog(Component parent)
{
JDialog dialog = super.createDialog(parent);
dialog.setMinimumSize(new Dimension(600, 400));
return dialog;
}
};
fileChooser.setCurrentDirectory(new File("."));
fileChooser.setDialogTitle("Επιλέξτε το όνομα του αρχείου pdf");
fileChooser.setSelectedFile(new File(filename));
int userSelection = fileChooser.showSaveDialog(null);
// If user doesn't click Save, do nothing
if (userSelection != JFileChooser.APPROVE_OPTION) {return;}
// Path of chosen file
File fileToSave = fileChooser.getSelectedFile();
String path = fileToSave.getAbsolutePath();
// File replace confirmation
if (fileToSave.exists())
{
int input = JOptionPane.showConfirmDialog(null,
"Το αρχείο θα αντικατασταθεί. Θέλετε να συνεχίσετε;",
"Επιβεβαίωση αντικατάστασης", JOptionPane.OK_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (input != 0) {return;}
}
// Date format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
// Get selected game id and find the date of the first draw
String gameId = null;
String date1 = "2000-01-01";
switch (comboBoxGameSelect.getSelectedItem().toString())
{
case "Κίνο": gameId = "1100"; date1 = formatter.format(LocalDate.now().minusYears(3)); break;
case "Powerspin": gameId = "1110"; date1 = "2020-06-30"; break;
case "Super3": gameId = "2100"; date1 = "2002-11-25"; break;
case "Πρότο": gameId = "2101"; date1 = "2000-01-01"; break;
case "Λόττο": gameId = "5103"; date1 = "2000-01-01"; break;
case "Τζόκερ": gameId = "5104"; date1 = "2000-01-01"; break;
case "Extra5": gameId = "5106"; date1 = "2002-11-25"; break;
}
// Variables
int maxSimConnections = 50; // Max number of simultaneous calls to the API
int threadNum; // Number of threads (simultaneous calls to the API)
List<String> urlStrList; // List with all the urls we will call
List<String> jsonStrList = new ArrayList<>(); // List with the json strings
List<JokerDrawData> JokerDrawDataList = new ArrayList<>(); // List with all the draw data
// List with the API urls
urlStrList = getUrlStrForDateRange(Integer.parseInt(gameId), date1, lastDrawDate);
// Set number of threads = urlStrList.size(), but not more that maxSimConnections
threadNum = urlStrList.size();
if (threadNum > maxSimConnections) {threadNum = maxSimConnections;}
// --- Create the threads to do the job ---
GetJsonStrListFromUrlStrListMT[] threadArray = new GetJsonStrListFromUrlStrListMT[threadNum];
int taskNum = urlStrList.size(); // Total number of tasks to do
for (int i=0; i<threadNum; i++)
{
int index1 = i*taskNum/threadNum; // Each thread does index2-index1
int index2 = (i+1)*taskNum/threadNum; // tasks, from index1 to index2-1
threadArray[i] = new GetJsonStrListFromUrlStrListMT(index1, index2, urlStrList);
threadArray[i].start();
}
// Wait for all threads to finish
for (int i=0; i<threadNum; i++)
{
try
{
threadArray[i].join();
}
catch (InterruptedException ex)
{
ex.printStackTrace();
}
}
// Merge results from all threads
for (GetJsonStrListFromUrlStrListMT thread : threadArray)
{
// Merge jsonStrList
thread.getJsonStrList().forEach((jsonStr) ->
{
jsonStrList.add(jsonStr);
});
}
// Parce all json strings in jsonStrList
for (int i = jsonStrList.size()-1; i >= 0; i--)
{
String jsonStr = jsonStrList.get(i);
// Parse jsonStr into json element and get an object structure
JsonElement jElement = new JsonParser().parse(jsonStr);
JsonObject jObject = jElement.getAsJsonObject();
// Get the totalElements
int totalElements = jObject.get("totalElements").getAsInt();
// If there are no draw data, go to the next jsonStrList element
if (totalElements == 0) {continue;}
// Get the "content" json array
JsonArray content = jObject.getAsJsonArray("content");
for (JsonElement drawElement : content)
{
// Get the json object from this content json element
JsonObject drawObject = drawElement.getAsJsonObject();
// Create a JokerDrawData object from the json object
JokerDrawData jokerDraw = jokerJsonSingleDrawToObject(drawObject);
// Add to the list
JokerDrawDataList.add(jokerDraw);
}
}
// Initialize PDFwriter
PdfWriter pdfWriter;
try
{
pdfWriter = new PdfWriter(path);
}
catch (FileNotFoundException ex)
{
String message = "Σφάλμα δημιουργίας αρχείου.\nΒεβαιωθείτε πως έχετε δικαίωμα εγγραφής στο φάκελο.";
JOptionPane.showMessageDialog(null, message, "Σφάλμα εγγραφής", 0);
return;
}
//Initialize PDF document
PdfDocument pdf = new PdfDocument(pdfWriter);
// Initialize document
Document document = new Document(pdf, PageSize.A4);
document.setProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, 1.0f));
document.setMargins(23, 36, 10, 36); // (top, right, bottom, left)
// Create PdfFonts to be used in the pdf document
PdfFont fontRegular = null;
PdfFont fontBold = null;
try
{
fontRegular = PdfFontFactory.createFont(getClass().getResource("/resources/Roboto-Regular.ttf").toString());
fontBold = PdfFontFactory.createFont(getClass().getResource("/resources/Roboto-Bold.ttf").toString());
}
catch (Exception ex)
{
ex.printStackTrace();
try
{
fontRegular = PdfFontFactory.createFont("Helvetica", "Cp1253");
fontBold = PdfFontFactory.createFont("Helvetica-Bold", "Cp1253");
}
catch (Exception ex1) {System.err.println(ex1);}
}
// Variables
BigDecimal bd; // BigDecimal - used for rounding
int drawCount = 0;
double moneySum = 0;
int jackpotCount = 0;
int drawCountTotal = 0;
double moneySumTotal = 0;
int jackpotCountTotal = 0;
int tableCounter = 0; // Used for adding a page break every 3 tables
JokerDrawData jokerDraw = JokerDrawDataList.get(JokerDrawDataList.size()-1);
String drawDate = jokerDraw.getDrawDate();
String year = drawDate.substring(0, 4);
String prevYear = drawDate.substring(0, 4);
String month = drawDate.substring(5, 7);
String prevMonth = drawDate.substring(5, 7);
// Add a title to the document
Paragraph par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-14.8f).setMarginBottom(-1f);
par.add(new Text(basename).setFont(fontBold).setFontSize(19));
document.add(par);
// Add the first year to the document
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(4f).setMarginBottom(2f);
par.add(new Text(year).setFont(fontBold).setFontSize(14));
document.add(par);
// First table
Table table = new Table(UnitValue.createPercentArray(new float[]{50f, 70f, 100f, 40f}));
table.useAllAvailableWidth();
// Column 1 header
Paragraph header1 = new Paragraph().setTextAlignment(TextAlignment.CENTER);
header1.setMarginTop(0f).setMarginBottom(0f);
header1.add(new Text("Μήνας").setFont(fontBold).setFontSize(12));
table.addHeaderCell(header1);
// Column 2 header
Paragraph header2 = new Paragraph().setTextAlignment(TextAlignment.CENTER);
header2.setMarginTop(0f).setMarginBottom(0f);
header2.add(new Text("Πλήθος κληρώσεων").setFont(fontBold).setFontSize(12));
table.addHeaderCell(header2);
// Column 3 header
Paragraph header3 = new Paragraph().setTextAlignment(TextAlignment.CENTER);
header3.setMarginTop(0f).setMarginBottom(0f);
header3.add(new Text("Χρήματα που διανεμήθηκαν (€)").setFont(fontBold).setFontSize(12));
table.addHeaderCell(header3);
// Column 4 header
Paragraph header4 = new Paragraph().setTextAlignment(TextAlignment.CENTER);
header4.setMarginTop(0f).setMarginBottom(0f);
header4.add(new Text("Τζακ-ποτ").setFont(fontBold).setFontSize(12));
table.addHeaderCell(header4);
// Start the counters and sum
drawCount++;
moneySum += jokerDraw.getPrizeTier5_1dividend() + jokerDraw.getPrizeTier5dividend() +
jokerDraw.getPrizeTier4_1dividend() + jokerDraw.getPrizeTier4dividend() +
jokerDraw.getPrizeTier3_1dividend() + jokerDraw.getPrizeTier3dividend() +
jokerDraw.getPrizeTier2_1dividend() + jokerDraw.getPrizeTier1_1dividend();
if (jokerDraw.getPrizeTier5_1winners() == 0) {jackpotCount++;}
for (int i = JokerDrawDataList.size()-2; i >= 0; i--)
{
jokerDraw = JokerDrawDataList.get(i);
drawDate = jokerDraw.getDrawDate();
year = drawDate.substring(0, 4);
month = drawDate.substring(5, 7);
// If month has changed
if (!month.equals(prevMonth))
{
// Month name
String monthName = null;
switch (prevMonth)
{
case "01": monthName = "Ιανουάριος"; break;
case "02": monthName = "Φεβρουάριος"; break;
case "03": monthName = "Μάρτιος"; break;
case "04": monthName = "Απρίλιος"; break;
case "05": monthName = "Μάιος"; break;
case "06": monthName = "Ιούνιος"; break;
case "07": monthName = "Ιούλιος"; break;
case "08": monthName = "Αύγουστος"; break;
case "09": monthName = "Σεπτέμβριος"; break;
case "10": monthName = "Οκτώβριος"; break;
case "11": monthName = "Νοέμβριος"; break;
case "12": monthName = "Δεκέμβριος"; break;
}
// Round the moneySum and make it BigDecimal
bd = BigDecimal.valueOf(moneySum);
BigDecimal moneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
// Add the data to the table
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(monthName).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(drawCount)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(moneySumBD)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(jackpotCount)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
// Add values to "Total" variables
drawCountTotal += drawCount;
moneySumTotal += moneySum;
jackpotCountTotal += jackpotCount;
// Reset the counters
drawCount = 0;
moneySum = 0;
jackpotCount = 0;
}
// If year has changed
if (!year.equals(prevYear))
{
// Round the moneySumTotal and make it BigDecimal
bd = BigDecimal.valueOf(moneySumTotal);
BigDecimal moneySumTotalBD = bd.setScale(2, RoundingMode.HALF_UP);
// Add "Total" row to the table
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text("Σύνολο").setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(drawCountTotal)).setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(moneySumTotalBD)).setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(jackpotCountTotal)).setFont(fontBold).setFontSize(11));
table.addCell(par);
// Add last table
document.add(table);
// Reset the "Total" counters
drawCountTotal = 0;
moneySumTotal = 0;
jackpotCountTotal = 0;
// Change page every 3 tables
tableCounter++;
if (tableCounter == 3)
{
document.add(new AreaBreak());
tableCounter = 0;
}
// Add new year
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(11f).setMarginBottom(2f);
par.add(new Text(year).setFont(fontBold).setFontSize(14));
document.add(par);
// Create table for the new year
table = new Table(UnitValue.createPercentArray(new float[]{50f, 70f, 100f, 40f}));
table.useAllAvailableWidth();
table.addHeaderCell(header1);
table.addHeaderCell(header2);
table.addHeaderCell(header3);
table.addHeaderCell(header4);
}
// Update the counters and sum
drawCount++;
moneySum += jokerDraw.getPrizeTier5_1dividend() + jokerDraw.getPrizeTier5dividend() +
jokerDraw.getPrizeTier4_1dividend() + jokerDraw.getPrizeTier4dividend() +
jokerDraw.getPrizeTier3_1dividend() + jokerDraw.getPrizeTier3dividend() +
jokerDraw.getPrizeTier2_1dividend() + jokerDraw.getPrizeTier1_1dividend();
if (jokerDraw.getPrizeTier5_1winners() == 0) {jackpotCount++;}
prevYear = drawDate.substring(0, 4);
prevMonth = drawDate.substring(5, 7);
}
// Month name
String monthName = null;
switch (prevMonth)
{
case "01": monthName = "Ιανουάριος"; break;
case "02": monthName = "Φεβρουάριος"; break;
case "03": monthName = "Μάρτιος"; break;
case "04": monthName = "Απρίλιος"; break;
case "05": monthName = "Μάιος"; break;
case "06": monthName = "Ιούνιος"; break;
case "07": monthName = "Ιούλιος"; break;
case "08": monthName = "Αύγουστος"; break;
case "09": monthName = "Σεπτέμβριος"; break;
case "10": monthName = "Οκτώβριος"; break;
case "11": monthName = "Νοέμβριος"; break;
case "12": monthName = "Δεκέμβριος"; break;
}
// Round the moneySum and make it BigDecimal
bd = BigDecimal.valueOf(moneySum);
BigDecimal moneySumBD = bd.setScale(2, RoundingMode.HALF_UP);
// Add the last data to the table
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(monthName).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(drawCount)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(moneySumBD)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(jackpotCount)).setFont(fontRegular).setFontSize(11));
table.addCell(par);
// Add values to "Total" variables
drawCountTotal += drawCount;
moneySumTotal += moneySum;
jackpotCountTotal += jackpotCount;
// Round the moneySumTotal and make it BigDecimal
bd = BigDecimal.valueOf(moneySumTotal);
BigDecimal moneySumTotalBD = bd.setScale(2, RoundingMode.HALF_UP);
// Add "Total" row to the table
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text("Έως " + lastDrawDate).setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(drawCountTotal)).setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(moneySumTotalBD)).setFont(fontBold).setFontSize(11));
table.addCell(par);
par = new Paragraph().setTextAlignment(TextAlignment.CENTER);
par.setMarginTop(-0.7f).setMarginBottom(-0.7f);
par.add(new Text(String.valueOf(jackpotCountTotal)).setFont(fontBold).setFontSize(11));
table.addCell(par);
// Add the last table
document.add(table);
// Close document
document.close();
pdf.close();
}
/**
* Action of the buttonClose.
* @param evt
*/
private void buttonCloseActionPerformed(java.awt.event.ActionEvent evt)
{
dialog.dispose();
}
// Constructor
public WindowShowData()
{
// Background color
Color backColor = new java.awt.Color(244, 244, 250);
// Icons list
final List<Image> icons = new ArrayList<>();
try
{
icons.add(ImageIO.read(getClass().getResource("/resources/icon_16.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_20.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_24.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_28.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_32.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_40.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_48.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_56.png")));
icons.add(ImageIO.read(getClass().getResource("/resources/icon_64.png")));
}
catch (Exception ex)
{
ex.printStackTrace();
}
// Font
Font fontRobotoRegular = null;
try
{
fontRobotoRegular = Font.createFont(Font.PLAIN, getClass().getResourceAsStream("/resources/Roboto-Regular.ttf"));
}
catch (FontFormatException | IOException ex)
{
System.err.println(ex);
fontRobotoRegular = new Font("Dialog", 0, 12); // Fallback, not suppose to happen
}
/*
* Top panel with the window title
*/
JPanel topPanel = new JPanel();
topPanel.setBorder(BorderFactory.createEmptyBorder(8, 0, 18, 0));
topPanel.setLayout(new FlowLayout(1, 0, 0));
topPanel.setBackground(backColor);
JPanel titlePanel = new JPanel();
titlePanel.setLayout(new OverlayLayout(titlePanel));
titlePanel.setBackground(backColor);
// Labels with the title
JLabel labelTitle = new JLabel("Προβολή δεδομένων");
labelTitle.setFont(new Font(null, 3, 42));
labelTitle.setForeground(Color.ORANGE);
JLabel labelTitleShadow = new JLabel("Προβολή δεδομένων");
labelTitleShadow.setBorder(BorderFactory.createEmptyBorder(5, 1, 0, 0));
labelTitleShadow.setFont(new Font(null, 3, 42));
labelTitleShadow.setForeground(Color.BLUE);
titlePanel.add(labelTitle);
titlePanel.add(labelTitleShadow);
topPanel.add(titlePanel);
/*
* Middle panel with all the functionality
*/
JPanel middlePanel = new JPanel();
middlePanel.setBorder(BorderFactory.createEmptyBorder(0, 20, 0, 20));
middlePanel.setLayout(new BoxLayout(middlePanel, BoxLayout.Y_AXIS));
middlePanel.setBackground(backColor);
// Game selection & year selection panel
JPanel gameSelectPanel = new JPanel();
gameSelectPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 0));
gameSelectPanel.setLayout(new FlowLayout(0, 0, 0)); // align,hgap,vgap (1,5,5)
gameSelectPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, gameSelectPanel.getMinimumSize().height));
gameSelectPanel.setBackground(backColor);
// Label game select
JLabel labelGameSelect = new JLabel("Επιλέξτε τυχερό παιχνίδι");
// ComboBox game select
String opapGames[] = {"Τζόκερ"};
comboBoxGameSelect = new JComboBox(opapGames);
comboBoxGameSelect.addActionListener(this::comboBoxGameSelectActionPerformed);
comboBoxGameSelect.setBackground(backColor);
// Label year
JLabel labelYear = new JLabel("Έτος");
labelYear.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 6));
// ComboBox year select
comboBoxYearSelect = new JComboBox();
comboBoxYearSelect.setBackground(backColor);
gameSelectPanel.add(labelGameSelect);
gameSelectPanel.add(Box.createRigidArea(new Dimension(10,0)));
gameSelectPanel.add(comboBoxGameSelect);
gameSelectPanel.add(Box.createRigidArea(new Dimension(50,0)));
gameSelectPanel.add(labelYear);
gameSelectPanel.add(comboBoxYearSelect);
gameSelectPanel.add(Box.createRigidArea(new Dimension(50,0)));
// Choose search method label panel
JPanel chooseMethodLabelPanel = new JPanel();
chooseMethodLabelPanel.setBorder(BorderFactory.createEmptyBorder(12, 0, 0, 0));
chooseMethodLabelPanel.setLayout(new FlowLayout(0, 0, 0));
chooseMethodLabelPanel.setBackground(backColor);
// Label choose method
JLabel labelChooseMethod = new JLabel("Επιλέξτε από που θέλετε να αντληθούν τα δεδομένα");
chooseMethodLabelPanel.add(labelChooseMethod);
chooseMethodLabelPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, chooseMethodLabelPanel.getMinimumSize().height));
// Choose search method and download panel
JPanel chooseMethodAndDLPanel = new JPanel();
chooseMethodAndDLPanel.setLayout(new BoxLayout(chooseMethodAndDLPanel, BoxLayout.X_AXIS));
chooseMethodAndDLPanel.setBackground(backColor);
// Choose search method panel
JPanel chooseMethodPanel = new JPanel();
chooseMethodPanel.setLayout(new BoxLayout(chooseMethodPanel, BoxLayout.Y_AXIS));
chooseMethodPanel.setBackground(backColor);
// API method panel
JPanel apiMethodPanel = new JPanel();
apiMethodPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0));
apiMethodPanel.setLayout(new FlowLayout(0, 0, 0));
apiMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, apiMethodPanel.getMinimumSize().height));
apiMethodPanel.setBackground(backColor);
// Radio button for API method
radioButtonApi = new JRadioButton();
radioButtonApi.setText("API");
radioButtonApi.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
radioButtonApi.setBackground(backColor);
radioButtonApi.setSelected(true);
// Label API method info
JLabel labelApiInfo = new JLabel("(Η βάση δεδομένων δε θα πειραχθεί)");
labelApiInfo.setBorder(BorderFactory.createEmptyBorder(1, 107, 0, 0));
labelApiInfo.setFont(fontRobotoRegular.deriveFont(0, 12));
labelApiInfo.setForeground(Color.DARK_GRAY);
apiMethodPanel.add(radioButtonApi);
apiMethodPanel.add(labelApiInfo);
apiMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, apiMethodPanel.getMinimumSize().height));
// DB method panel
JPanel DBMethodPanel = new JPanel();
DBMethodPanel.setBorder(BorderFactory.createEmptyBorder(6, 0, 0, 0));
DBMethodPanel.setLayout(new FlowLayout(0, 0, 0));
DBMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, DBMethodPanel.getMinimumSize().height));
DBMethodPanel.setBackground(backColor);
// Radio button for DB method
JRadioButton radioButtonDB = new JRadioButton();
radioButtonDB.setText("Βάση δεδομένων");
radioButtonDB.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
radioButtonDB.setBackground(backColor);
radioButtonDB.setSelected(false);
// Group radio butttons
ButtonGroup groupChooseMethod = new ButtonGroup();
groupChooseMethod.add(radioButtonApi);
groupChooseMethod.add(radioButtonDB);
// Label DB method info
JLabel labelDBInfo = new JLabel("(Αν τα δεδομένα δεν υπάρχουν ήδη, τότε θα προστεθούν στη βάση)");
labelDBInfo.setBorder(BorderFactory.createEmptyBorder(1, 30, 0, 0));
labelDBInfo.setFont(fontRobotoRegular.deriveFont(0, 12));
labelDBInfo.setForeground(Color.DARK_GRAY);
DBMethodPanel.add(radioButtonDB);
DBMethodPanel.add(labelDBInfo);
DBMethodPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, DBMethodPanel.getMinimumSize().height));
chooseMethodPanel.add(apiMethodPanel);
chooseMethodPanel.add(DBMethodPanel);
// Button download
JButton buttonDownload = new JButton("Προβολή συγκεντρωτικών");
buttonDownload.setPreferredSize(new Dimension(buttonDownload.getMinimumSize().width, 46));
buttonDownload.setMaximumSize(new Dimension(buttonDownload.getMinimumSize().width, 46));
buttonDownload.setText("<html><center>Προβολή συγκεντρωτικών<br>δεδομένων ανά μήνα</center></html>");
buttonDownload.addActionListener((evt) ->
{
CompletableFuture.runAsync(() -> this.buttonDownloadActionPerformed(evt));
});
chooseMethodAndDLPanel.add(chooseMethodPanel);
chooseMethodAndDLPanel.add(buttonDownload);
// Data view panel
JPanel dataViewPanel = new JPanel();
dataViewPanel.setBorder(BorderFactory.createEmptyBorder(18, 0, 0, 0));
dataViewPanel.setLayout(new BorderLayout());
dataViewPanel.setBackground(backColor);
// Columns and initial data of the JTable for data per month
String[] columns = {"Μήνας", "Πλήθος κληρώσεων",
"Χρήματα που διανεμήθηκαν (€)", "Τζακ-ποτ"};
Object[][] data = {
{"Ιανουάριος", "", "", ""},
{"Φεβρουάριος", "", "", ""},
{"Μάρτιος", "", "", ""},
{"Απρίλιος", "", "", ""},
{"Μάιος", "", "", ""},
{"Ιούνιος", "", "", ""},
{"Ιούλιος", "", "", ""},
{"Αύγουστος", "", "", ""},
{"Σεπτέμβριος", "", "", ""},
{"Οκτώβριος", "", "", ""},
{"Νοέμβριος", "", "", ""},
{"Δεκέμβριος", "", "", ""},
{"ΣΥΝΟΛΟ", "", "", ""},
};
// Center renderer for table columns
DefaultTableCellRenderer centerText = new DefaultTableCellRenderer();
centerText.setHorizontalAlignment(SwingConstants.CENTER);
// JTable for Joker single draw
dataViewTable = new JTable(data, columns);
dataViewTable.getColumnModel().getColumn(0).setCellRenderer(centerText);
dataViewTable.getColumnModel().getColumn(1).setCellRenderer(centerText);
dataViewTable.getColumnModel().getColumn(2).setCellRenderer(centerText);
dataViewTable.getColumnModel().getColumn(3).setCellRenderer(centerText);
// Make table cells unselectable and uneditable
dataViewTable.setEnabled(false);
// Disable table column re-ordering
dataViewTable.getTableHeader().setReorderingAllowed(false);
// Make the JScrollPane take the same size as the JTable
dataViewTable.setPreferredScrollableViewportSize(dataViewTable.getPreferredSize());
dataViewPanel.add(new JScrollPane(dataViewTable), BorderLayout.NORTH);
dataViewPanel.setMaximumSize(new Dimension(Integer.MAX_VALUE, dataViewPanel.getMinimumSize().height));
// Data view panel
JPanel exportToPdfPanel = new JPanel();
exportToPdfPanel.setBorder(BorderFactory.createEmptyBorder(18, 0, 0, 0));
exportToPdfPanel.setLayout(new BoxLayout(exportToPdfPanel, BoxLayout.X_AXIS));
exportToPdfPanel.setBackground(backColor);
// Button export to pdf
JButton buttonExportToPdf = new JButton("Εξαγωγή συγκεντρωτικών δεδομένων σε αρχείο pdf (API)");
buttonExportToPdf.addActionListener(this::buttonExportToPdfActionPerformed);
exportToPdfPanel.add(Box.createHorizontalGlue());
exportToPdfPanel.add(buttonExportToPdf);
middlePanel.add(gameSelectPanel);
middlePanel.add(chooseMethodLabelPanel);
middlePanel.add(chooseMethodAndDLPanel);
middlePanel.add(dataViewPanel);
middlePanel.add(exportToPdfPanel);
middlePanel.add(Box.createVerticalGlue());
// Empty expanding panel
JPanel expandingPanel = new JPanel();
expandingPanel.setLayout(new BorderLayout());
expandingPanel.setBackground(backColor);
/*
* Bottom panel with the Close button
*/
JPanel bottomPanel = new JPanel();
bottomPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 0, 20));
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.X_AXIS));
bottomPanel.setBackground(backColor);
// Close button
JButton buttonClose = new JButton("Κλείσιμο");
buttonClose.setPreferredSize(new Dimension(116, 26));
buttonClose.addActionListener(this::buttonCloseActionPerformed);
bottomPanel.add(Box.createHorizontalGlue());
bottomPanel.add(buttonClose);
/*
* Main panel
*/
JPanel mainPanel = new JPanel();
mainPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 30, 0));
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
mainPanel.setPreferredSize(new Dimension(870, 558));
mainPanel.setBackground(backColor);
mainPanel.add(topPanel);
mainPanel.add(middlePanel);
mainPanel.add(expandingPanel);
mainPanel.add(bottomPanel);
/*
* Main window
*/
dialog = new JDialog();
dialog.add(mainPanel, BorderLayout.CENTER);
dialog.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
dialog.setTitle("Show data");
dialog.setModalityType(Dialog.DEFAULT_MODALITY_TYPE);
dialog.pack();
dialog.setLocationRelativeTo(null); // Appear in the center of screen
dialog.setMinimumSize(new Dimension(880, 588));
dialog.setResizable(false);
dialog.setIconImages(icons);
// Populate comboBoxYearSelect
populateComboBoxYearSelect();
CompletableFuture.runAsync(() -> findLastDrawDate()); // Run asynchronously
dialog.setVisible(true);
}
}
| JaskJohin/JokerGame-Stats | src/view/WindowShowData.java |
1,787 | package UserClientV1;
import java.awt.Dimension;
import java.awt.Insets;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.UIManager;
import java.io.File;
import java.nio.file.Files;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.Calendar;
import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import static UserClientV1.ManageUserClient.expandAll;
/**
* Κλάση που έχει κληρονομήσει ένα JPanel και που ουσιαστικά είναι μια καρτέλα εποπτείας
* κάποιας συσκευής μέσα στο κύριο παράθυρο του User Client ({@link Fmain}).
* Μέσα από αυτό το panel μπορεί ο χρήστης να βλέπει τις καταστάσεις των μονάδων είτε
* μέσα από το δέντρο(JTree) που είναι αριστερά είτε με τα εικονίδια({@link UnitControl}) που
* βρίσκονται δεξιά .
* Επίσης με τη κλάση αυτή (καρτέλα) μπορεί ο χρήστης να κάνει και άλλες
* λειτουργίες όπως μα σταματάει ή να ξεκινάει την εποπτεία , να αλλάζει εικόνα στο
* background , να επαναφέρει τα εικονίδια των μονάδων στη περίπτωση που μετά από ένα
* resize δεν φαίνονται , να επιλέγει αν θα αποθηκεύονται οι επιλογές του χρήστη
* στον υπολογιστή για να μπορούν να ανακτηθούν όταν κλείσει και ξανά ανοίξει το
* πρόγραμμα και τέλος ο χρήστης μπορεί να κλείσει την καρτέλα.
* Ακόμη όμως κάποιος χρήστης μέσω της κλάσης αυτής μπορεί να βλέπει διάφορα μηνύματα ροής
* μέσα από τη κονσόλα όπως επίσης και να βλέπει ένα διακριτικό κλειδί ανάλογα με τα δικαιώματα
* που έχει πάνω στη συγκεκριμένη συσκευή που κάνει εκείνη την ώρα εποπτεία , καθώς επιπλέον
* μπορεί να ενημερώνεται με κάποιο μήνυμα και ένα εικονίδιο κατάστασης στο κάτω μέρος αριστερά.
* @author Michael Galliakis
*/
public class Ptab extends javax.swing.JPanel {
public Device device ;
public String devID ;
public String devName ;
public String devAccess ;
public boolean isConnected ;
JFileChooser fc ;
boolean firstTimeChangeImage = true ;
/**
* Κατασκευαστής της κλάσης μας που προετοιμάζει κατάλληλα την καρτέλα μας.
* @param devID Το ID της συσκευής για την οποία θα γίνεται εποπτεία .
* @param devName Το όνομα της συσκευής για την οποία θα γίνεται εποπτεία .
* @param devAccess Τα δικαιώματα που έχει ο χρήστης πάνω στη συσκευή η οποία θα εποπτεύεται.
*/
public Ptab(String devID,String devName,String devAccess) {
initComponents();
this.devID = devID;
this.devName = devName;
this.devAccess = devAccess;
bSaveSettings.setBackground(Globals.selectedColor);
//System.out.println(spTreeAndStatus.getSize().height - 45);
//spTreeAndStatus.setDividerLocation(spTreeAndStatus.getSize().height - 45) ;
}
/**
* Μέθοδος που αναλαμβάνει να κάνει όλα τα απαραίτητα βήματα που χρειάζονται
* για να ξεκινήσει η εποπτεία μιας συσκευής .
*/
public void startMonitoring()
{
Device locDevice ;
try {
ManageSocket ms = ManageUserClient.connectProcess(Globals.address, Globals.port);
if (ms==null)
{
Tools.Debug.print("Connect UnsuccessFully (Connect Failed)!");
JOptionPane.showMessageDialog(this,"Connect Failed","Failed",JOptionPane.PLAIN_MESSAGE);
//Globals.objDevices.setEnabled(false);
return ;
}
//Globals.objDevices.setEnabled(false);
if (!ManageUserClient.certificationProcess(ms))
{
Tools.Debug.print("Connect UnsuccessFully (Certification Failed)!");
JOptionPane.showMessageDialog(this,"Certification Failed","Failed",JOptionPane.PLAIN_MESSAGE);
return ;
}
String DBUserID = ManageUserClient.loginProcess(ms, Globals.username, Globals.password);
if (DBUserID.equals("X"))
{
Tools.Debug.print("Connect UnsuccessFully (Login Failed)!");
JOptionPane.showMessageDialog(this,"Login Failed","Failed",JOptionPane.PLAIN_MESSAGE);
return ;
}
locDevice = ManageUserClient.bringMeDeviceProcess(ms, DBUserID,devID,devName,devAccess) ;
if (locDevice==null)
{
Tools.Debug.print("InitControllers Fail!");
Tools.send("#"+DBUserID+"UD"+"@UD$Quit:1*(Bey-bey!);",ms.out);
Tools.Debug.print("bringMeDeviceProcess UnsuccessFully!");
JOptionPane.showMessageDialog(this,"bring Me Device Process Failed","Failed",JOptionPane.PLAIN_MESSAGE);
return ;
}
device = locDevice ;
loadaccessIcon(device.devAccess) ;
Globals.hmDevices.put(devName,device) ;
JTree tree = device.getTree(true) ;
this.scpDevTree.getViewport().removeAll();
this.scpDevTree.getViewport().add(tree) ;
expandAll(tree) ;
Tools.Debug.print("Connect SuccessFully!");
BackgroundPanel bp = new BackgroundPanel(device) ;
bp.setLayout(null);
this.scpScreen.getViewport().removeAll();
this.scpScreen.getViewport().add(bp) ;
bp.setVisible(true);
Insets insets = bp.getInsets();
for (UnitControl uc : device.getAllControls())
{
uc.setVisible(true);
bp.add(uc) ;
}
device.fillUnitControls(bp,insets) ;
device.setPTab(this) ;
device.clearSelection();
device.setLTForRead(new ListenThread(device,ms.clientSocket,ms.in,this)); //Logika tha fygei i teleytaia parametros!
device.ltForRead.start() ;
JTextPane tmpTextPane = new JTextPane() ;
tmpTextPane.setStyledDocument(Globals.debugDoc);
tmpTextPane.setEditable(false);
tmpTextPane.setMinimumSize(new Dimension (100,100));
tmpTextPane.setMaximumSize(new Dimension (100,100));
tmpTextPane.setSize(new Dimension (100,100));
this.scpConsole.getViewport().removeAll();
this.scpConsole.getViewport().add(tmpTextPane) ;
this.scpConsole.setVisible(Globals.objMainFrame.isConsoleReportEnable);
setIsConnected(true) ;
setStatus("Start success!",0) ;
} catch (Exception ex) {
// Logger.getLogger(Ptab.class.getName()).log(Level.SEVERE, null, ex);
setStatus("Start failed!",2) ;
JOptionPane.showMessageDialog(this,"Δεν μπόρεσε να ξεκινήσει το Monitoring",Globals.messDialTitle,JOptionPane.PLAIN_MESSAGE);
}
}
/**
* Μέθοδος που απλά εμφανίζει ένα μήνυμα κατάστασης στην κάτω μεριά της καρτέλας
* όπως επίσης και καθορίζει και το εικονίδιο κατάστασης .
* @param message Ένα μήυνμα κατάστασης που εμφανίζεται .
* @param optIcon Επιλογή για το ποια εικόνα θα εμφανιστεί σαν εικονίδιο κατάστασης.
* Είναι Ο αν θέλουμε την εικόνα με το "ΟΚ" , 1 αν θέλουμε την εικόνα με το "Disconnect"
* και 2 αν θέλουμε την εικόνα με το "Oops".
*/
public void setStatus(String message,int optIcon)
{
Globals.today = Calendar.getInstance().getTime();
String reportDate = Globals.dateFormat.format(Globals.today);
lStatusText.setText("<html>" + message +":<br>" + reportDate +"</html>");
switch (optIcon){
case 0 : //OK
lStatus.setIcon(Globals.imOK) ;
break ;
case 1 : //Stop
lStatus.setIcon(Globals.imDisconnect) ;
break ;
case 2 : //Oops
lStatus.setIcon(Globals.imOops) ;
break ;
default :
//lStatus.setIcon(Globals.imOops) ;
}
}
/**
* Μέθοδος που απλά αλλάζει την εικόνα του κουμπιού bStartStop
* ανάλογα με το αν υπάρχει ενεργή εποπτεία ή όχι όπως επίσης και
* ενημερώνει τη μεταβλητή για το αν υπάρχει σύνδεση η όχι .
* Αν είναι ενεργή η εποπτεία εμφανίζεται το κουμπί "stop" αλλιώς
* αν είναι κλειστή η εποπτεία εμφανίζεται το κουμπί "start" .
* Αλλάζει το χρώμα , για να είναι πιο εμφανές αν είναι το κουμπί "πατημένο"(πορτοκαλί)
* ή όχι (default).
* @param isConnected True αν υπάρχει σύνδεση και False αν δεν υπάρχει .
*/
public void setIsConnected(boolean isConnected) {
this.isConnected = isConnected;
if (isConnected)
{
bStartStop.setIcon(Globals.imStop);
}
else
{
bStartStop.setIcon(Globals.imStart);
}
}
/**
* Μέθοδος που απλά σταματάει ολοκληρωμένα την εποπτεία (χωρίς να κλείνει η
* καρτέλα της συσκευής).
*/
public void stopMonitoring()
{
stopMonitoring(true);
}
/**
* Μέθοδος που απλά σταματάει ολοκληρωμένα την εποπτεία (χωρίς να κλείνει η
* καρτέλα της συσκευής).
* @param byUser Παράμετρος που καθορίζει αν η εποπτεία κλείνει επειδή το
* επέλεξε ο χρήστης(true) ή αν κλείνει από απροσδόκητη αιτία(false) (πχ έπεσε ο Server).
*/
public void stopMonitoring(boolean byUser)
{
if (byUser)
setStatus("Stopped success!",1) ;
else
setStatus(" Oops !!! :<br>" + "stopped monitoring!",2) ;
try {
if (device!=null)
{
device.ms.close();
device.saveToXML();
}
} catch (IOException ex) {
Logger.getLogger(Ptab.class.getName()).log(Level.SEVERE, null, ex);
}
setIsConnected(false);
if (device.ltForRead!=null)
device.ltForRead.stop();
}
/**
* Μέθοδος που απλά αλλάζει το χρώμα στο background του κουμπιού bSaveSettings
* ανάλογα με το ποια επιλογή είναι ήδη επιλεγμένη από το χρήστη .
* Αλλάζει το χρώμα , για να είναι πιο εμφανές αν είναι το κουμπί "πατημένο"(πορτοκαλί)
* ή όχι (default).
*/
public void setSettingsButton ()
{
if (device.saveSettings)
bSaveSettings.setBackground(Globals.selectedColor);
else
bSaveSettings.setBackground(UIManager.getColor ( "Panel.background" ));
}
/**
* Μέθοδος που αναλαμβάνει με βάση τα δικαιώματα που έχει ο χρήστης πάνω σε μια
* συγκεκριμένη συσκευή να εμφανίσει την κατάλληλη εικόνα κλειδιού στο κάτω
* μέρος της καρτέλας που έχει την εποπτεία της εν λόγο συσκευής .
* @param access Ουσιαστικά είναι ένα γράμμα(O,A,F,R) για τα δικαιώματα προσπέλασης
*/
private void loadaccessIcon(String access)
{
switch(access)
{
case "O" :
lAccess.setIcon(Globals.imOwner);
break ;
case "A" :
lAccess.setIcon(Globals.imAdmin);
break ;
case "F" :
lAccess.setIcon(Globals.imFull);
break ;
case "R" :
lAccess.setIcon(Globals.imReadOnly);
break ;
default :
lAccess.setIcon(Globals.imReadOnly);
}
}
/**
* Μέθοδος που κλείνει ολοκληρωμένα μια καρτέλα μιας εποπτείας συσκευής .
*/
private void closeTab ()
{
stopMonitoring() ;
for (int i = 0 ; i< Globals.objDevices.lastArrayWithDevEnable.length;i++)
if (Globals.objDevices.lastArrayWithDevEnable[i].equals("O|"+device.getDeviceName()))
{
//Tools.Debug.print( Globals.objDevices.lastArrayWithDevEnable[i]);
Globals.objDevices.lastArrayWithDevEnable[i] = Globals.objDevices.lastArrayWithDevEnable[i].replace("O|","|") ;
//Tools.Debug.print( Globals.objDevices.lastArrayWithDevEnable[i]);
}
Globals.hmDevices.remove(devName,device) ;
Globals.objDevices.setDevicesInfo(Globals.objDevices.lastAlWithDevices) ;
device = null ;
Globals.objMainFrame.tpAllDevices.remove(this);
}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
pTabMain = new javax.swing.JPanel();
spTabMain = new javax.swing.JSplitPane();
pLeft = new javax.swing.JPanel();
spDevMenuAndTree = new javax.swing.JSplitPane();
pDevMenu = new javax.swing.JPanel();
bStartStop = new javax.swing.JButton();
bChangeMap = new javax.swing.JButton();
bFix = new javax.swing.JButton();
bClose = new javax.swing.JButton();
bSaveSettings = new javax.swing.JButton();
pTreeAndStatus = new javax.swing.JPanel();
pStatus = new javax.swing.JPanel();
lAccess = new javax.swing.JLabel();
lStatus = new javax.swing.JLabel();
lStatusText = new javax.swing.JLabel();
scpDevTree = new javax.swing.JScrollPane();
pRight = new javax.swing.JPanel();
spView = new javax.swing.JSplitPane();
scpConsole = new javax.swing.JScrollPane();
scpScreen = new javax.swing.JScrollPane();
setName(""); // NOI18N
setPreferredSize(new java.awt.Dimension(250, 716));
addComponentListener(new java.awt.event.ComponentAdapter() {
public void componentResized(java.awt.event.ComponentEvent evt) {
formComponentResized(evt);
}
});
spTabMain.setDividerLocation(240);
spTabMain.setDividerSize(2);
pLeft.setPreferredSize(new java.awt.Dimension(216, 714));
spDevMenuAndTree.setDividerLocation(42);
spDevMenuAndTree.setDividerSize(0);
spDevMenuAndTree.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
pDevMenu.setPreferredSize(new java.awt.Dimension(210, 40));
bStartStop.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/stop36.png"))); // NOI18N
bStartStop.setMargin(new java.awt.Insets(0, 0, 0, 0));
bStartStop.setMaximumSize(new java.awt.Dimension(40, 40));
bStartStop.setMinimumSize(new java.awt.Dimension(40, 40));
bStartStop.setName(""); // NOI18N
bStartStop.setPreferredSize(new java.awt.Dimension(40, 40));
bStartStop.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bStartStopMouseClicked(evt);
}
});
bChangeMap.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/map36.png"))); // NOI18N
bChangeMap.setToolTipText("");
bChangeMap.setMargin(new java.awt.Insets(0, 0, 0, 0));
bChangeMap.setMaximumSize(new java.awt.Dimension(40, 40));
bChangeMap.setMinimumSize(new java.awt.Dimension(40, 40));
bChangeMap.setName(""); // NOI18N
bChangeMap.setPreferredSize(new java.awt.Dimension(40, 40));
bChangeMap.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bChangeMapMouseClicked(evt);
}
});
bFix.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/fix36.png"))); // NOI18N
bFix.setMargin(new java.awt.Insets(0, 0, 0, 0));
bFix.setMaximumSize(new java.awt.Dimension(40, 40));
bFix.setMinimumSize(new java.awt.Dimension(40, 40));
bFix.setName(""); // NOI18N
bFix.setPreferredSize(new java.awt.Dimension(40, 40));
bFix.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bFixMouseClicked(evt);
}
});
bClose.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/close36.png"))); // NOI18N
bClose.setMargin(new java.awt.Insets(0, 0, 0, 0));
bClose.setMaximumSize(new java.awt.Dimension(40, 40));
bClose.setMinimumSize(new java.awt.Dimension(40, 40));
bClose.setName(""); // NOI18N
bClose.setPreferredSize(new java.awt.Dimension(40, 40));
bClose.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bCloseMouseClicked(evt);
}
});
bSaveSettings.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/save36.png"))); // NOI18N
bSaveSettings.setMargin(new java.awt.Insets(0, 0, 0, 0));
bSaveSettings.setMaximumSize(new java.awt.Dimension(40, 40));
bSaveSettings.setMinimumSize(new java.awt.Dimension(40, 40));
bSaveSettings.setPreferredSize(new java.awt.Dimension(40, 40));
bSaveSettings.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
bSaveSettingsMouseClicked(evt);
}
});
javax.swing.GroupLayout pDevMenuLayout = new javax.swing.GroupLayout(pDevMenu);
pDevMenu.setLayout(pDevMenuLayout);
pDevMenuLayout.setHorizontalGroup(
pDevMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pDevMenuLayout.createSequentialGroup()
.addComponent(bStartStop, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bChangeMap, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bFix, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bSaveSettings, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(bClose, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pDevMenuLayout.setVerticalGroup(
pDevMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pDevMenuLayout.createSequentialGroup()
.addGroup(pDevMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(bClose, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bFix, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bChangeMap, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bSaveSettings, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(bStartStop, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(0, 0, Short.MAX_VALUE))
);
spDevMenuAndTree.setTopComponent(pDevMenu);
pStatus.setMaximumSize(new java.awt.Dimension(0, 42));
pStatus.setMinimumSize(new java.awt.Dimension(0, 42));
pStatus.setName(""); // NOI18N
pStatus.setPreferredSize(new java.awt.Dimension(0, 42));
lAccess.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/typeDevices/full.png"))); // NOI18N
lAccess.setToolTipText("");
lAccess.setBorder(new javax.swing.border.LineBorder(java.awt.Color.blue, 1, true));
lAccess.setMaximumSize(new java.awt.Dimension(60, 30));
lAccess.setMinimumSize(new java.awt.Dimension(60, 30));
lAccess.setName(""); // NOI18N
lAccess.setPreferredSize(new java.awt.Dimension(60, 30));
lAccess.setRequestFocusEnabled(false);
lStatus.setIcon(new javax.swing.ImageIcon(getClass().getResource("/UserClientV1/Images/OK.png"))); // NOI18N
lStatus.setToolTipText("");
lStatus.setBorder(new javax.swing.border.LineBorder(java.awt.Color.blue, 1, true));
lStatus.setMaximumSize(new java.awt.Dimension(40, 40));
lStatus.setMinimumSize(new java.awt.Dimension(40, 40));
lStatus.setName(""); // NOI18N
lStatus.setPreferredSize(new java.awt.Dimension(40, 40));
lStatusText.setFont(new java.awt.Font("Dialog", 2, 10)); // NOI18N
lStatusText.setText(" 04/11/2015 & 12:12");
lStatusText.setToolTipText("");
lStatusText.setBorder(new javax.swing.border.LineBorder(java.awt.Color.blue, 1, true));
lStatusText.setMaximumSize(new java.awt.Dimension(60, 30));
lStatusText.setMinimumSize(new java.awt.Dimension(60, 30));
lStatusText.setName(""); // NOI18N
lStatusText.setPreferredSize(new java.awt.Dimension(60, 30));
lStatusText.setRequestFocusEnabled(false);
javax.swing.GroupLayout pStatusLayout = new javax.swing.GroupLayout(pStatus);
pStatus.setLayout(pStatusLayout);
pStatusLayout.setHorizontalGroup(
pStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pStatusLayout.createSequentialGroup()
.addComponent(lAccess, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lStatusText, javax.swing.GroupLayout.DEFAULT_SIZE, 113, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(lStatus, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
pStatusLayout.setVerticalGroup(
pStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pStatusLayout.createSequentialGroup()
.addGroup(pStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(lAccess, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lStatusText, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
javax.swing.GroupLayout pTreeAndStatusLayout = new javax.swing.GroupLayout(pTreeAndStatus);
pTreeAndStatus.setLayout(pTreeAndStatusLayout);
pTreeAndStatusLayout.setHorizontalGroup(
pTreeAndStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pTreeAndStatusLayout.createSequentialGroup()
.addComponent(pStatus, javax.swing.GroupLayout.PREFERRED_SIZE, 225, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 9, Short.MAX_VALUE))
.addComponent(scpDevTree)
);
pTreeAndStatusLayout.setVerticalGroup(
pTreeAndStatusLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pTreeAndStatusLayout.createSequentialGroup()
.addComponent(scpDevTree, javax.swing.GroupLayout.DEFAULT_SIZE, 623, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(pStatus, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
);
spDevMenuAndTree.setRightComponent(pTreeAndStatus);
javax.swing.GroupLayout pLeftLayout = new javax.swing.GroupLayout(pLeft);
pLeft.setLayout(pLeftLayout);
pLeftLayout.setHorizontalGroup(
pLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spDevMenuAndTree)
);
pLeftLayout.setVerticalGroup(
pLeftLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spDevMenuAndTree, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 714, Short.MAX_VALUE)
);
spTabMain.setLeftComponent(pLeft);
spView.setDividerLocation(650);
spView.setDividerSize(2);
spView.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
spView.setRightComponent(scpConsole);
spView.setLeftComponent(scpScreen);
javax.swing.GroupLayout pRightLayout = new javax.swing.GroupLayout(pRight);
pRight.setLayout(pRightLayout);
pRightLayout.setHorizontalGroup(
pRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spView)
);
pRightLayout.setVerticalGroup(
pRightLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spView)
);
spTabMain.setRightComponent(pRight);
javax.swing.GroupLayout pTabMainLayout = new javax.swing.GroupLayout(pTabMain);
pTabMain.setLayout(pTabMainLayout);
pTabMainLayout.setHorizontalGroup(
pTabMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spTabMain, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)
);
pTabMainLayout.setVerticalGroup(
pTabMainLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(spTabMain)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pTabMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pTabMain, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
}// </editor-fold>//GEN-END:initComponents
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί (bFix) για να fixάρει τα {@link ControlUnit}s.
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event το οποίο στη
* περίπτωση μας δεν χρησιμοποιείται .
*/
private void bFixMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bFixMouseClicked
device.fixUnitControlToResize();
}//GEN-LAST:event_bFixMouseClicked
/**
* Μέθοδος που εκτελείτε όταν γίνει resize της καρτέλας .
* Σκοπός είναι η καλύτερη δυνατή εμφάνηση της κονσόλας μηνυμάτων εφόσων
* έχει επιλέξει ο χρήστης να εμφανίζεται .
* @param evt
*/
private void formComponentResized(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentResized
if (scpConsole.getSize().height > 200)
spView.setDividerLocation(spView.getSize().height-200) ;
}//GEN-LAST:event_formComponentResized
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί (bSaveSettings) για να
* αποθηκεύονται ή όχι κάποιες πληροφορίες της συσκευής της καρτέλας στον υπολογιστή του χρήστη.
* Πληροφορίες εννοούνται πχ θέσεις των {@link UnitControl} στην οθόνη , τα Description τους κα .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event
* το οποίο στη περίπτωση μας δεν χρησιμοποιείται .
*/
private void bSaveSettingsMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bSaveSettingsMouseClicked
device.saveSettings = !device.saveSettings ;
setSettingsButton() ;
}//GEN-LAST:event_bSaveSettingsMouseClicked
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί (bClose) για να
* κλείσει την καρτέλα της εποπτείας .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event
* το οποίο στη περίπτωση μας δεν χρησιμοποιείται .
*/
private void bCloseMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bCloseMouseClicked
closeTab() ;
}//GEN-LAST:event_bCloseMouseClicked
/**
* Μέθοδος που προετοιμάζει το DialogOpen και εκτελείτε μόνο την πρώτη φορά
* που ο χρηστής θα πατήσει το κουμπί για να αλλάξει την εικόνα του background
* της συγκεκριμένης συσκευής .
*/
private void prepareChangeBackgroundImage()
{
fc = new JFileChooser();
fc.setSize(800, 600);
fc.setSize(new Dimension(800,600));
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
fc.setFileFilter(filter);
fc.setCurrentDirectory(new File(Globals.runFolder.getAbsolutePath() + Globals.fSep+"backgroundImages"+Globals.fSep));
}
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί (bChangeMap) για να
* αλλάξει την εικόνα του background της εποπτείας.
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event
* το οποίο στη περίπτωση μας δεν χρησιμοποιείται .
*/
private void bChangeMapMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bChangeMapMouseClicked
if (firstTimeChangeImage)
{
prepareChangeBackgroundImage() ;
firstTimeChangeImage = false ;
}
int returnVal = fc.showDialog(Globals.objMainFrame, "Change Background Icon");
if (returnVal==0)
{
File f = new File(Globals.runFolder.getAbsolutePath() + Globals.fSep+"backgroundImages"+Globals.fSep +fc.getSelectedFile().getName()) ;
try {
if (!fc.getSelectedFile().toPath().toString().equals(f.toPath().toString()))
Files.copy(fc.getSelectedFile().toPath(),f.toPath(), REPLACE_EXISTING);
device.setPathFile(f.toPath().toString());
} catch (IOException ex) {
Tools.Debug.print("Dont copy Image");
}
}
}//GEN-LAST:event_bChangeMapMouseClicked
/**
* Μέθοδος που εκτελείτε όταν "κλικάρει" ο χρήστης το κουμπί (bStartStop) για να
* σταματήσει ή να ξεκινήσει την εποπτεία σε μια συσκευή .
* @param evt Το Default MouseEvent αντικείμενο που έχει το συγκεκριμένο event
* το οποίο στη περίπτωση μας δεν χρησιμοποιείται .
*/
private void bStartStopMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bStartStopMouseClicked
if (isConnected)
stopMonitoring() ;
else
startMonitoring() ;
}//GEN-LAST:event_bStartStopMouseClicked
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton bChangeMap;
private javax.swing.JButton bClose;
private javax.swing.JButton bFix;
private javax.swing.JButton bSaveSettings;
private javax.swing.JButton bStartStop;
private javax.swing.JLabel lAccess;
public javax.swing.JLabel lStatus;
public javax.swing.JLabel lStatusText;
private javax.swing.JPanel pDevMenu;
private javax.swing.JPanel pLeft;
private javax.swing.JPanel pRight;
public javax.swing.JPanel pStatus;
private javax.swing.JPanel pTabMain;
private javax.swing.JPanel pTreeAndStatus;
public javax.swing.JScrollPane scpConsole;
public javax.swing.JScrollPane scpDevTree;
public javax.swing.JScrollPane scpScreen;
private javax.swing.JSplitPane spDevMenuAndTree;
private javax.swing.JSplitPane spTabMain;
public javax.swing.JSplitPane spView;
// 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/Ptab.java |
1,789 | package hmp_gui;
import data.*;
import java.text.SimpleDateFormat;
/**
*
* @author Theodoros Tomadakis
*/
public class Parathiro_Aithsewn extends javax.swing.JFrame {
private int app_index; //index aithshs
private Application appl = null; //to application poy pernume
private Dashboard_Headdoc dashboard; //Pairnei meso tou constructor thn timh tou prohgounmenou Dashboard
/**
* Creates new form Patient_Profile
*/
public Parathiro_Aithsewn(Dashboard_Headdoc dashboard, Application application, int appl_index) { //arxikopoihsh toy dashboard twn aithsewn
this.dashboard = dashboard;
this.appl = application;
this.app_index = appl_index;
initComponents();
}
/**
* This method is called from within the constructor to initialize the form.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
Parath_Aithsewn = new javax.swing.JPanel();
Stoixeia_Ait = new javax.swing.JPanel();
IDL = new javax.swing.JLabel();
SBL = new javax.swing.JLabel();
history_scroll = new javax.swing.JScrollPane();
patient_history_panel = new javax.swing.JPanel();
patient_history = new javax.swing.JTextArea();
HMNIAL = new javax.swing.JLabel();
OnAsthL = new javax.swing.JLabel();
status = new javax.swing.JLabel();
cond_scroll = new javax.swing.JScrollPane();
patient_conditions_panel = new javax.swing.JPanel();
patient_conditions = new javax.swing.JTextArea();
patient_history_label = new javax.swing.JLabel();
patient_cond_label = new javax.swing.JLabel();
id = new javax.swing.JTextArea();
submitted_by = new javax.swing.JTextArea();
hmnia = new javax.swing.JTextArea();
name = new javax.swing.JTextArea();
exit_button = new javax.swing.JButton();
cond = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
exit_button1 = new javax.swing.JButton();
exit_button2 = new javax.swing.JButton();
exit_button3 = new javax.swing.JButton();
exit_button4 = new javax.swing.JButton();
jLabel2 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
setTitle("Στοιχεία Αίτησης");
setLocation(new java.awt.Point(800, 400));
Parath_Aithsewn.setBackground(new java.awt.Color(153, 204, 255));
Stoixeia_Ait.setBackground(new java.awt.Color(153, 204, 255));
Stoixeia_Ait.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255), 2), "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 11), new java.awt.Color(255, 255, 255))); // NOI18N
IDL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
IDL.setForeground(new java.awt.Color(255, 255, 255));
IDL.setText("ID Αίτησης:");
SBL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
SBL.setForeground(new java.awt.Color(255, 255, 255));
SBL.setText("Υποβλήθηκε από:");
patient_history.setEditable(false);
patient_history.setColumns(20);
patient_history.setRows(5);
javax.swing.GroupLayout patient_history_panelLayout = new javax.swing.GroupLayout(patient_history_panel);
patient_history_panel.setLayout(patient_history_panelLayout);
patient_history_panelLayout.setHorizontalGroup(
patient_history_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(patient_history_panelLayout.createSequentialGroup()
.addComponent(patient_history, javax.swing.GroupLayout.PREFERRED_SIZE, 230, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
patient_history_panelLayout.setVerticalGroup(
patient_history_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(patient_history, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
);
history_scroll.setViewportView(patient_history_panel);
HMNIAL.setBackground(new java.awt.Color(255, 255, 255));
HMNIAL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
HMNIAL.setForeground(new java.awt.Color(255, 255, 255));
HMNIAL.setText("Ημ/νία υποβολής:");
OnAsthL.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
OnAsthL.setForeground(new java.awt.Color(255, 255, 255));
OnAsthL.setText("Όνομα ασθενή:");
status.setBackground(new java.awt.Color(255, 255, 255));
status.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
status.setForeground(new java.awt.Color(255, 255, 255));
status.setText("Κατάσταση Αίτησης:");
patient_conditions.setEditable(false);
patient_conditions.setColumns(20);
patient_conditions.setRows(5);
javax.swing.GroupLayout patient_conditions_panelLayout = new javax.swing.GroupLayout(patient_conditions_panel);
patient_conditions_panel.setLayout(patient_conditions_panelLayout);
patient_conditions_panelLayout.setHorizontalGroup(
patient_conditions_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, patient_conditions_panelLayout.createSequentialGroup()
.addComponent(patient_conditions, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, Short.MAX_VALUE))
);
patient_conditions_panelLayout.setVerticalGroup(
patient_conditions_panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(patient_conditions, javax.swing.GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE)
);
cond_scroll.setViewportView(patient_conditions_panel);
patient_history_label.setBackground(new java.awt.Color(255, 255, 255));
patient_history_label.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
patient_history_label.setForeground(new java.awt.Color(255, 255, 255));
patient_history_label.setText("Ιστορικό Ασθενή:");
patient_cond_label.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
patient_cond_label.setForeground(new java.awt.Color(255, 255, 255));
patient_cond_label.setText("Κατάσταση Ασθενή:");
id.setEditable(false);
id.setColumns(20);
id.setRows(5);
submitted_by.setEditable(false);
submitted_by.setColumns(20);
submitted_by.setRows(5);
hmnia.setEditable(false);
hmnia.setColumns(20);
hmnia.setRows(5);
name.setEditable(false);
name.setColumns(20);
name.setRows(5);
exit_button.setText("Έξοδος");
exit_button.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exit_buttonActionPerformed(evt);
}
});
cond.setEditable(false);
cond.setColumns(20);
cond.setRows(5);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(255, 255, 255));
jLabel1.setText("Στοιχεία αίτησης");
exit_button1.setText("Έγκριση");
exit_button1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exit_button1ActionPerformed(evt);
}
});
exit_button2.setText("Απόρριψη");
exit_button2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exit_button2ActionPerformed(evt);
}
});
exit_button3.setText("Αναίρεση έγκρισης ");
exit_button3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exit_button3ActionPerformed(evt);
}
});
exit_button4.setText("Διόρθωση");
exit_button4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exit_button4ActionPerformed(evt);
}
});
jLabel2.setForeground(new java.awt.Color(255, 0, 0));
jLabel2.setText("<html>Αν ο αριθμός των κρεβατιών της κλινικής ενημερώνεται με λάθος τρόπο, πατήστε στο πλήκτρο \"Διόρθωση\" και θα μεταβείτε στην καρτέλα των Αιτήσεων.<br> Για να διορθώσετε το σφάλμα, απλά πληκτρολογήστε τον αριθμο που επιθυμείτε, στο πεδίο των διαθέσιμων κρεβατιών. H τελευταία αίτηση που επιλέξατε<br> θα μεταβεί σε κατάσταση \"In Progress\".</html> ");
javax.swing.GroupLayout Stoixeia_AitLayout = new javax.swing.GroupLayout(Stoixeia_Ait);
Stoixeia_Ait.setLayout(Stoixeia_AitLayout);
Stoixeia_AitLayout.setHorizontalGroup(
Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addContainerGap()
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(IDL)
.addComponent(SBL)
.addComponent(HMNIAL)
.addComponent(OnAsthL)
.addComponent(status))
.addGap(18, 18, 18)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(name, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(hmnia, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(submitted_by, javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(id, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(cond, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(jLabel1)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addComponent(exit_button1)
.addGap(18, 18, 18)
.addComponent(exit_button2)
.addGap(18, 18, 18)
.addComponent(exit_button3)
.addGap(18, 18, 18)
.addComponent(exit_button4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(exit_button))
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(history_scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(patient_history_label))
.addGap(58, 58, 58)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cond_scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 231, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(patient_cond_label))))
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
Stoixeia_AitLayout.setVerticalGroup(
Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, Stoixeia_AitLayout.createSequentialGroup()
.addGap(25, 25, 25)
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(IDL, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(submitted_by, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(SBL, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
.addGap(11, 11, 11)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(hmnia, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(HMNIAL, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(OnAsthL, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
.addGap(11, 11, 11)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addComponent(cond, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
.addComponent(status, javax.swing.GroupLayout.DEFAULT_SIZE, 26, Short.MAX_VALUE))
.addGap(30, 30, 30)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addComponent(patient_history_label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(history_scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(Stoixeia_AitLayout.createSequentialGroup()
.addComponent(patient_cond_label)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(cond_scroll, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(65, 65, 65)
.addGroup(Stoixeia_AitLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(exit_button)
.addComponent(exit_button1)
.addComponent(exit_button2)
.addComponent(exit_button3)
.addComponent(exit_button4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(29, 29, 29))
);
javax.swing.GroupLayout Parath_AithsewnLayout = new javax.swing.GroupLayout(Parath_Aithsewn);
Parath_Aithsewn.setLayout(Parath_AithsewnLayout);
Parath_AithsewnLayout.setHorizontalGroup(
Parath_AithsewnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Stoixeia_Ait, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
Parath_AithsewnLayout.setVerticalGroup(
Parath_AithsewnLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Stoixeia_Ait, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Parath_Aithsewn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(Parath_Aithsewn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
//Exit button
private void exit_buttonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_buttonActionPerformed
this.dashboard.setEnabled(true);
dispose();
}//GEN-LAST:event_exit_buttonActionPerformed
//gia egkrish aithshs
private void exit_button1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_button1ActionPerformed
if (dashboard.returnTabsAit().getSelectedIndex() == 0){ //an to jtabbed pane einai stis aithseis eisitiriou
if(dashboard.getClinic().getNumOfBeds()>=1 && !(appl.getStatus().equals("Approved"))){ //an ta krevatia tis klinikis einai perissotera toy 1 kai h aithsh den einai approved
appl.setStatus(Application.Status_enum.approved); //thetume thn katastash ths aithshs ws egkekrimenh
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); //formatter gia date
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempAdms().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus(); //string gia thn enhmerwsh toy jlist
javax.swing.DefaultListModel<String> admis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEisitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eisithrioy toy dashboard_headdoc
admis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
String s2 = String.valueOf(Integer.parseInt(dashboard.getDomKlin().getText()) - 1); //string gia ta krevatia
dashboard.getClinic().setNumOfBeds(Integer.parseInt(s2)); //enhmerwnoyme ton arithmo twn krevatiwn
dashboard.getDomKlin().setText(s2); //settarume to kenurio string ston arithmo twn krevatiwn
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία έγκρισης αίτησης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else if(appl.getStatus().equals("Approved")){ //an h aithsh einai approved
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html>Η αίτηση έχει ήδη εγκριθεί!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else{ //an den arkrun ta krevatia ths klinikhs
appl.setStatus(Application.Status_enum.rejected); //kane thn aithsh rejected
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Αποτυχία έγκρισης αίτησης. Δεν υπάρχουν διαθέσιμες κρεβάτια στην κλινική!</html>");
con1.setVisible(true);
this.setEnabled(false);
}
}else if(dashboard.returnTabsAit().getSelectedIndex() == 1){ //an h aithsh einai eksithrioy
if(!(appl.getStatus().equals("Approved"))){ //an den einai approved
appl.setStatus(Application.Status_enum.approved); //thetume thn katastash ths aithshs ws egkekrimenh
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempDis().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus(); //string gia thn enhmerwsh toy jlist
javax.swing.DefaultListModel<String> dis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEksitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eksithrioy toy dashboard_headdoc
dis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
String s2 = String.valueOf(Integer.parseInt(dashboard.getDomKlin().getText()) + 1); //string gia ta krevatia
dashboard.getDomKlin().setText(s2); //settarume to kenurio string ston arithmo twn krevatiw
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία έγκρισης αίτησης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else if(appl.getStatus().equals("Approved")){ //an h aithsh einai approved
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Η αίτηση έχει ήδη εγκριθεί!</html>");
con1.setVisible(true);
this.setEnabled(false);
}
}
}//GEN-LAST:event_exit_button1ActionPerformed
//gia aporripsh aithshs
private void exit_button2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_button2ActionPerformed
if (dashboard.returnTabsAit().getSelectedIndex() == 0){ //an to jtabbed pane einai stis aithseis eisirioy
if(!(appl.getStatus().equals("Rejected"))){ //an den einai rejected
appl.setStatus(Application.Status_enum.rejected); //kanth rejected
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempAdms().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus(); //string gia to jlist
javax.swing.DefaultListModel<String> admis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEisitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eisithrioy toy dashboard_headdoc
admis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία απόρριψης αίτησης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else{ //an h aithsh eixei hdh aporriftei
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Η αίτηση έχει ήδη απορριφθεί!</html>");
con1.setVisible(true);
this.setEnabled(false);
}
}else if (dashboard.returnTabsAit().getSelectedIndex() == 1){ //an to jtabbed pane einai stis aithseis eksitirioy
if(!(appl.getStatus().equals("Rejected"))){ //an den einai rejected h aithsh
appl.setStatus(Application.Status_enum.rejected); //kanth rejected
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempDis().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus();
javax.swing.DefaultListModel<String> dis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEksitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eksithrioy toy dashboard_headdoc
dis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία απόρριψης αίτησης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else{//an h aithsh einai hdh rejected
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html>Η αίτηση έχει ήδη απορριφθεί!</html>");
con1.setVisible(true);
this.setEnabled(false);
}
}
}//GEN-LAST:event_exit_button2ActionPerformed
//gia anairesh egkrishs
private void exit_button3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_button3ActionPerformed
if ((dashboard.returnTabsAit().getSelectedIndex() == 0) && (appl.getStatus().equals("Approved"))){ //an h aithsh einai eisitiriou kai einai approved
appl.setStatus(Application.Status_enum.in_progress); //kanume thn aithsh in progress pali
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempAdms().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus(); //string gia to jlist
javax.swing.DefaultListModel<String> admis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEisitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eisithrioy toy dashboard_headdoc
admis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
String s2 = String.valueOf(Integer.parseInt(dashboard.getDomKlin().getText()) + 1); //string gia ta krevatia
dashboard.getDomKlin().setText(s2); //settarume to kenurio string ston arithmo twn krevatiw
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία αναίρεσης έγκρισης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else if ((dashboard.returnTabsAit().getSelectedIndex() == 1) && (appl.getStatus().equals("Approved"))){ //an h aithsh einai eksitiriou kai einai approved
appl.setStatus(Application.Status_enum.in_progress); //kanume thn aithsh in progress pali
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String s1 = "ID Αίτησης: " + appl.getID() +" " + "Υποβλήθηκε από: " + appl.getDoctor().getName() + " " + "Ημερομηνία: " + formatter.format(appl.getDate()) + " " + "Ασθενής: " + dashboard.returnTempDis().get(app_index).getPatient().getName() + " " + "Κατάσταση: " + appl.getStatus();
javax.swing.DefaultListModel<String> dis_jlist_model = (javax.swing.DefaultListModel<String>)dashboard.getEksitiria().getModel(); //pernume to modelo ths jlist twn aithsewn eksithrioy toy dashboard_headdoc
dis_jlist_model.set(this.app_index,s1); //thetume to string pou dhmiourhsame
String s2 = String.valueOf(Integer.parseInt(dashboard.getDomKlin().getText()) - 1); //string gia ta krevatia
dashboard.getDomKlin().setText(s2); //settarume to kenurio string ston arithmo twn krevatiw
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Επιτυχία αναίρεσης έγκρισης!</html>");
con1.setVisible(true);
this.setEnabled(false);
}else if(!(appl.getStatus().equals("Approved"))){ //an h aithsh den einai egkekrimenh
Conditional_Message con1 = new Conditional_Message(this);
con1.triggerMsg("<html> Αδυναμία αναίρεσης, η αίτηση δεν είναι εγκεκριμένη!</html>");
con1.setVisible(true);
this.setEnabled(false);
}
}//GEN-LAST:event_exit_button3ActionPerformed
//diorthwsh krevatiwn klinikhs
private void exit_button4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exit_button4ActionPerformed
this.dashboard.setEnabled(true);
dispose();
dashboard.getDomKlin().setEditable(true);
}//GEN-LAST:event_exit_button4ActionPerformed
//Methodos pou settarei ta dedomena ths aithshs eisitirioy sta pedia tou parathyrou
public void ShowAppAdmInfo(Admission_Application app){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
id.setText(Integer.toString(app.getID()));
submitted_by.setText(app.getDoctor().getName());
hmnia.setText(formatter.format(app.getDate()));
name.setText(app.getPatient().getName());
cond.setText(app.getStatus());
patient_history.setText(app.getPatient().getHistory());
patient_conditions.setText(app.getPatient().getConditions());
}
//Methodos pou settarei ta dedomena ths aithshs eksitirioy sta pedia tou parathyrou
public void ShowAppDisInfo(Discharge_Application app){
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
id.setText(Integer.toString(app.getID()));
submitted_by.setText(app.getDoctor().getName());
hmnia.setText(formatter.format(app.getDate()));
name.setText(app.getPatient().getName());
cond.setText(app.getStatus());
patient_history.setText(app.getPatient().getHistory());
patient_conditions.setText(app.getPatient().getConditions());
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* 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(Parathiro_Aithsewn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Parathiro_Aithsewn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Parathiro_Aithsewn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Parathiro_Aithsewn.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel HMNIAL;
private javax.swing.JLabel IDL;
private javax.swing.JLabel OnAsthL;
private javax.swing.JPanel Parath_Aithsewn;
private javax.swing.JLabel SBL;
private javax.swing.JPanel Stoixeia_Ait;
private javax.swing.JTextArea cond;
private javax.swing.JScrollPane cond_scroll;
private javax.swing.JButton exit_button;
private javax.swing.JButton exit_button1;
private javax.swing.JButton exit_button2;
private javax.swing.JButton exit_button3;
private javax.swing.JButton exit_button4;
private javax.swing.JScrollPane history_scroll;
private javax.swing.JTextArea hmnia;
private javax.swing.JTextArea id;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JTextArea name;
private javax.swing.JLabel patient_cond_label;
private javax.swing.JTextArea patient_conditions;
private javax.swing.JPanel patient_conditions_panel;
private javax.swing.JTextArea patient_history;
private javax.swing.JLabel patient_history_label;
private javax.swing.JPanel patient_history_panel;
private javax.swing.JLabel status;
private javax.swing.JTextArea submitted_by;
// End of variables declaration//GEN-END:variables
}
| NSkam/HMP | src/hmp_gui/Parathiro_Aithsewn.java |
1,791 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package hmp_gui;
import java.util.ArrayList;
import java.lang.NumberFormatException;
/**
*
* @author John
*/
public class Addition_Promithies_MedEq extends javax.swing.JFrame {
/**
* Creates new form Addition_Promithies_MedEq
*/
private ArrayList<String> medList = new ArrayList();
private ArrayList<String> medQuantityList = new ArrayList();
private ArrayList<String> medEqList = new ArrayList();
private ArrayList<String> medEqQuantityList = new ArrayList();
private int available_space;
public Addition_Promithies_MedEq() {
initComponents();
}
public Addition_Promithies_MedEq(int available_space,ArrayList<String> medList, ArrayList<String>medEqList, ArrayList<String> medQuantityList, ArrayList<String> medEqQuantityList) {
this.available_space = available_space;
this.medList = medList;
this.medEqList = medEqList;
this.medQuantityList = medQuantityList;
this.medEqQuantityList = medEqQuantityList;
initComponents();
}
/**
* 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() {
condMsg = new javax.swing.JPanel();
nameTag = new javax.swing.JTextField();
quantityTag = new javax.swing.JTextField();
okButton = new javax.swing.JButton();
backButton = new javax.swing.JButton();
typeTag = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
condMsg.setBackground(new java.awt.Color(153, 204, 255));
nameTag.setForeground(new java.awt.Color(153, 153, 153));
nameTag.setText("Όνομα προμήθειας");
quantityTag.setForeground(new java.awt.Color(153, 153, 153));
quantityTag.setText("Ποσότητα");
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
backButton.setText("Τέλος");
backButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
backButtonActionPerformed(evt);
}
});
typeTag.setForeground(new java.awt.Color(153, 153, 153));
typeTag.setText("Τύπος εξοπλισμού");
javax.swing.GroupLayout condMsgLayout = new javax.swing.GroupLayout(condMsg);
condMsg.setLayout(condMsgLayout);
condMsgLayout.setHorizontalGroup(
condMsgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(condMsgLayout.createSequentialGroup()
.addGap(49, 49, 49)
.addGroup(condMsgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(typeTag, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(quantityTag, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nameTag, javax.swing.GroupLayout.PREFERRED_SIZE, 313, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(38, Short.MAX_VALUE))
.addGroup(condMsgLayout.createSequentialGroup()
.addContainerGap()
.addComponent(backButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(okButton)
.addGap(28, 28, 28))
);
condMsgLayout.setVerticalGroup(
condMsgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(condMsgLayout.createSequentialGroup()
.addGap(43, 43, 43)
.addComponent(nameTag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(28, 28, 28)
.addComponent(typeTag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(quantityTag, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(34, 34, 34)
.addGroup(condMsgLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(backButton)
.addComponent(okButton))
.addContainerGap(24, Short.MAX_VALUE))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 400, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(condMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 239, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(condMsg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
Dashboard_Promithies dp = new Dashboard_Promithies(available_space,medList,medEqList,medQuantityList,medEqQuantityList);
Conditional_Message cm = new Conditional_Message(dp);
try{
String medEqName = nameTag.getText();
String type = typeTag.getText();
int quantity = Integer.parseInt(quantityTag.getText());
if (available_space - quantity < 0){
throw new java.lang.IndexOutOfBoundsException();
}
available_space = available_space - quantity;
medEqList.add("Medicine Name: " + medEqName +" Type: " + type + " Quantity: " + quantity);
medEqQuantityList.add(Integer.toString(quantity));
cm.triggerMsg("Επιτυχής προσθήκη!");
cm.setVisible(true);
} catch(java.lang.NumberFormatException exc)
{
cm.triggerMsg("<html>Η προσθήκη απέτυχε! Παρακαλώ ελέγξτε αν τα στοιχεία που δώσατε είναι σωστά και δοκιμάστε ξανά!</html>");
cm.setVisible(true);
}catch (java.lang.IndexOutOfBoundsException e){
cm.triggerMsg("Exceeded maximum space!");
cm.setVisible(true);
}
}//GEN-LAST:event_okButtonActionPerformed
private void backButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backButtonActionPerformed
Dashboard_Promithies dp = new Dashboard_Promithies(available_space,medList,medEqList,medQuantityList,medEqQuantityList);
dispose();
dp.setVisible(true);
}//GEN-LAST:event_backButtonActionPerformed
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* 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(Addition_Promithies_MedEq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Addition_Promithies_MedEq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Addition_Promithies_MedEq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Addition_Promithies_MedEq.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Addition_Promithies_MedEq().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton backButton;
private javax.swing.JPanel condMsg;
private javax.swing.JTextField nameTag;
private javax.swing.JButton okButton;
private javax.swing.JTextField quantityTag;
private javax.swing.JTextField typeTag;
// End of variables declaration//GEN-END:variables
}
| NSkam/HMP | src/hmp_gui/Addition_Promithies_MedEq.java |
1,792 | import java.util.*;
public class Node {
private LinkedList<Packet> queue; // the node's buffer
private Set<Integer> T; // channels the node can transmit to
private Set<Integer> R; // channels the node can receive from
private ArrayList<ArrayList<Integer>> A;
private ArrayList<ArrayList<Integer>> B;
private Random rand; // random number generator
private int bufferSize; // node's capacity of packets
private double l; // packet generation probability
private double[] d; // destination probabilities
private int id;
private int transmitted;
private int buffered;
private int slotsWaited;
public Node(int id, int configuration, long seed){
queue = new LinkedList<>();
T = new HashSet<>();
R = new HashSet<>();
rand = new Random(seed);
this.id = id;
d = new double[Main.getNumberOfNodes()+1];
configure(id, configuration);
}
private void configure(int id, int configuration){
// Configure Node's transmission range and receivers.
switch (configuration){
case 1:
// system configuration 1
// each transmitter can be tuned to two wavelengths
// each node has two receivers
// configure the transmission range
if (id==1 || id==2 || id==3){
T.add(1);
T.add(2);
} else if (id==4 || id==5 || id==6){
T.add(2);
T.add(3);
} else if (id==7 || id==8){
T.add(3);
T.add(4);
}
// configure the receivers
if (id==1){
R.add(2);
R.add(3);
} else if (id==2 || id==3 || id==5 || id==7){
R.add(2);
R.add(4);
} else if (id==4 || id==6 || id==8){
R.add(1);
R.add(3);
}
break;
case 2:
// system configuration 2
// each transmitter can be tuned to one wavelength
// each node has four receivers, one for each wavelength
// configure the transmission range
if (id==1 || id==2){
T.add(1);
} else if (id==3 || id==4){
T.add(2);
} else if (id==5 || id ==6){
T.add(3);
} else if (id==7 || id==8){
T.add(4);
}
// configure the receivers
R.add(1);
R.add(2);
R.add(3);
R.add(4);
break;
case 3:
// system configuration 3
// each transmitter can be tuned to all four wavelengths
// each node has one receiver
// configure the transmission range
T.add(1);
T.add(2);
T.add(3);
T.add(4);
// configure the receivers
if (id==1 || id==2){
R.add(1);
} else if (id==3 || id==4){
R.add(2);
} else if (id==5 || id==6){
R.add(3);
} else if (id==7 || id==8){
R.add(4);
}
break;
}
}
public void slotAction(int slot){
////////////////////
// PACKET ARRIVAL //
////////////////////
boolean arrives = rand.nextDouble() < l;
if (arrives && queue.size() < bufferSize){
int destination = findDestination();
if (destination==-1){
System.exit(5);
}
queue.add(new Packet(destination, slot));
}
//////////////////////////
// Creating trans table //
//////////////////////////
// Initialize the trans table
int[] trans = new int[Main.getNumberOfNodes() + 1];
for (int i = 1; i <= Main.getNumberOfNodes(); i++) {
trans[i] = 0;
}
// initialize channels ( Ω )
ArrayList<Integer> channels = new ArrayList<>();
for (int channel = 1; channel <= Main.getNumberOfChannels(); channel++) {
channels.add(channel);
}
// get a copy of A
ArrayList<ArrayList<Integer>> _A = new ArrayList<>();
for (int i = 0; i < A.size(); i++) {
_A.add((ArrayList<Integer>) A.get(i).clone());
}
// create trans table
while (!channels.isEmpty()) {
int k = channels.get(rand.nextInt(channels.size())); // get a random channel, say channel k
int i = _A.get(k).get(rand.nextInt(_A.get(k).size())); // get a random node from _A[k], say node i
trans[i] = k;
// remove i from _A
for (int j = 1; j < _A.size(); j++) {
_A.get(j).remove((Integer) i);
}
// remove k from channels (Ω)
channels.remove((Integer) k);
}
buffered += queue.size();
//////////////////
// TRANSMISSION //
//////////////////
if (trans[id] != 0) {
int channel = trans[id];
for (Packet packet : queue) {
// αν ο κόμβος του destination του <packet> έχει receiver στο <channel> κάνε το transmission
int destination = packet.destination;
if (B.get(channel).contains(destination)){
// do the transmission
slotsWaited += slot - packet.timeslot;
queue.remove(packet);
transmitted++;
break;
}
}
}
}
private int findDestination() {
double p = Math.random();
double cumulativeProbability = 0.0;
for (int m=0; m<d.length; m++){
cumulativeProbability += d[m];
if (p <= cumulativeProbability){
return m;
}
}
return -1;
}
public void reset(double systemLoad){
// changes l, resets the counters, and clears the queue
if (Main.getValidation()){
l = id * systemLoad / 36;
} else {
l = systemLoad / Main.getNumberOfNodes();
}
transmitted = 0;
buffered = 0;
slotsWaited = 0;
queue.clear();
}
public void setD(boolean validation){
int N = Main.getNumberOfNodes();
if (validation){
for (int m=1; m<=N; m++){
if (m==id){
d[m] = 0;
} else {
d[m] = (double) m / (N*(N+1)/2 - id);
}
}
} else {
for (int m=1; m<=N; m++){
if (m==id){
d[m] = 0;
} else {
d[m] = (double) 1 / (N-1);
}
}
}
}
public void setBufferSize(boolean validation){
if (validation){
bufferSize = id;
} else {
bufferSize = 4;
}
}
public void setA(ArrayList<ArrayList<Integer>> A) {
this.A = A;
}
public void setB(ArrayList<ArrayList<Integer>> B) {
this.B = B;
}
public Set<Integer> getT() {
return T;
}
public Set<Integer> getR() {
return R;
}
public int getTransmitted(){
return transmitted;
}
public int getBuffered(){ return buffered; }
public int getSlotsWaited(){ return slotsWaited; }
}
| b1ru/rtdma | src/Node.java |
1,793 | /* GENERATED SOURCE. DO NOT MODIFY. */
// © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2005-2016, International Business Machines Corporation and *
* others. All Rights Reserved. *
*******************************************************************************
*/
package android.icu.util;
import java.util.Date;
import java.util.Locale;
/**
* Implement the Coptic calendar system.
* <p>
* CopticCalendar usually should be instantiated using
* {@link android.icu.util.Calendar#getInstance(ULocale)} passing in a <code>ULocale</code>
* with the tag <code>"@calendar=coptic"</code>.</p>
*
* @see android.icu.util.Calendar
*/
public final class CopticCalendar extends CECalendar
{
// jdk1.4.2 serialver
private static final long serialVersionUID = 5903818751846742911L;
/**
* Constant for ωογτ / تﻮﺗ,
* the 1st month of the Coptic year.
*/
public static final int TOUT = 0;
/**
* Constant for Παοπι / ﻪﺑﺎﺑ,
* the 2nd month of the Coptic year.
*/
public static final int BABA = 1;
/**
* Constant for Αθορ / رﻮﺗﺎﻫ,
* the 3rd month of the Coptic year.
*/
public static final int HATOR = 2;
/**
* Constant for Χοιακ / ﻚﻬﻴﻛ;,
* the 4th month of the Coptic year.
*/
public static final int KIAHK = 3;
/**
* Constant for Τωβι / طﻮﺒﻫ,
* the 5th month of the Coptic year.
*/
public static final int TOBA = 4;
/**
* Constant for Μεϣιρ / ﺮﻴﺸﻣأ,
* the 6th month of the Coptic year.
*/
public static final int AMSHIR = 5;
/**
* Constant for Παρεμϩατ / تﺎﻬﻣﺮﺑ,
* the 7th month of the Coptic year.
*/
public static final int BARAMHAT = 6;
/**
* Constant for Φαρμοθι / هدﻮﻣﺮﺑ,
* the 8th month of the Coptic year.
*/
public static final int BARAMOUDA = 7;
/**
* Constant for Παϣαν / ﺲﻨﺸﺑ;,
* the 9th month of the Coptic year.
*/
public static final int BASHANS = 8;
/**
* Constant for Παωνι / ﻪﻧؤﻮﺑ,
* the 10th month of the Coptic year.
*/
public static final int PAONA = 9;
/**
* Constant for Επηπ / ﺐﻴﺑأ,
* the 11th month of the Coptic year.
*/
public static final int EPEP = 10;
/**
* Constant for Μεϲωρη / ىﺮﺴﻣ,
* the 12th month of the Coptic year.
*/
public static final int MESRA = 11;
/**
* Constant for Πικογϫι μαβοτ / ﺮﻴﻐﺼﻟاﺮﻬﺸﻟا,
* the 13th month of the Coptic year.
*/
public static final int NASIE = 12;
private static final int JD_EPOCH_OFFSET = 1824665;
// Eras
private static final int BCE = 0;
private static final int CE = 1;
/**
* Constructs a default <code>CopticCalendar</code> using the current time
* in the default time zone with the default locale.
*/
public CopticCalendar() {
super();
}
/**
* Constructs a <code>CopticCalendar</code> based on the current time
* in the given time zone with the default locale.
*
* @param zone The time zone for the new calendar.
*/
public CopticCalendar(TimeZone zone) {
super(zone);
}
/**
* Constructs a <code>CopticCalendar</code> based on the current time
* in the default time zone with the given locale.
*
* @param aLocale The locale for the new calendar.
*/
public CopticCalendar(Locale aLocale) {
super(aLocale);
}
/**
* Constructs a <code>CopticCalendar</code> based on the current time
* in the default time zone with the given locale.
*
* @param locale The icu locale for the new calendar.
*/
public CopticCalendar(ULocale locale) {
super(locale);
}
/**
* Constructs a <code>CopticCalendar</code> based on the current time
* in the given time zone with the given locale.
*
* @param zone The time zone for the new calendar.
* @param aLocale The locale for the new calendar.
*/
public CopticCalendar(TimeZone zone, Locale aLocale) {
super(zone, aLocale);
}
/**
* Constructs a <code>CopticCalendar</code> based on the current time
* in the given time zone with the given locale.
*
* @param zone The time zone for the new calendar.
* @param locale The icu locale for the new calendar.
*/
public CopticCalendar(TimeZone zone, ULocale locale) {
super(zone, locale);
}
/**
* Constructs a <code>CopticCalendar</code> with the given date set
* in the default time zone with the default locale.
*
* @param year The value used to set the calendar's {@link #YEAR YEAR} time field.
* @param month The value used to set the calendar's {@link #MONTH MONTH} time field.
* The value is 0-based. e.g., 0 for Tout.
* @param date The value used to set the calendar's {@link #DATE DATE} time field.
*/
public CopticCalendar(int year, int month, int date) {
super(year, month, date);
}
/**
* Constructs a <code>CopticCalendar</code> with the given date set
* in the default time zone with the default locale.
*
* @param date The date to which the new calendar is set.
*/
public CopticCalendar(Date date) {
super(date);
}
/**
* Constructs a <code>CopticCalendar</code> with the given date
* and time set for the default time zone with the default locale.
*
* @param year The value used to set the calendar's {@link #YEAR YEAR} time field.
* @param month The value used to set the calendar's {@link #MONTH MONTH} time field.
* The value is 0-based. e.g., 0 for Tout.
* @param date The value used to set the calendar's {@link #DATE DATE} time field.
* @param hour The value used to set the calendar's {@link #HOUR_OF_DAY HOUR_OF_DAY} time field.
* @param minute The value used to set the calendar's {@link #MINUTE MINUTE} time field.
* @param second The value used to set the calendar's {@link #SECOND SECOND} time field.
*/
public CopticCalendar(int year, int month, int date, int hour,
int minute, int second) {
super(year, month, date, hour, minute, second);
}
/**
* {@inheritDoc}
*/
@Override
public String getType() {
return "coptic";
}
/**
* {@inheritDoc}
* @deprecated This API is ICU internal only.
* @hide original deprecated declaration
* @hide draft / provisional / internal are hidden on Android
*/
@Override
@Deprecated
protected int handleGetExtendedYear() {
int eyear;
if (newerField(EXTENDED_YEAR, YEAR) == EXTENDED_YEAR) {
eyear = internalGet(EXTENDED_YEAR, 1); // Default to year 1
} else {
// The year defaults to the epoch start, the era to AD
int era = internalGet(ERA, CE);
if (era == BCE) {
eyear = 1 - internalGet(YEAR, 1); // Convert to extended year
} else {
eyear = internalGet(YEAR, 1); // Default to year 1
}
}
return eyear;
}
/**
* {@inheritDoc}
* @deprecated This API is ICU internal only.
* @hide original deprecated declaration
* @hide draft / provisional / internal are hidden on Android
*/
@Override
@Deprecated
protected void handleComputeFields(int julianDay) {
int era, year;
int[] fields = new int[3];
jdToCE(julianDay, getJDEpochOffset(), fields);
// fields[0] eyear
// fields[1] month
// fields[2] day
if (fields[0] <= 0) {
era = BCE;
year = 1 - fields[0];
} else {
era = CE;
year = fields[0];
}
internalSet(EXTENDED_YEAR, fields[0]);
internalSet(ERA, era);
internalSet(YEAR, year);
internalSet(MONTH, fields[1]);
internalSet(DAY_OF_MONTH, fields[2]);
internalSet(DAY_OF_YEAR, (30 * fields[1]) + fields[2]);
}
/**
* {@inheritDoc}
* @deprecated This API is ICU internal only.
* @hide original deprecated declaration
* @hide draft / provisional / internal are hidden on Android
*/
@Override
@Deprecated
protected int getJDEpochOffset() {
return JD_EPOCH_OFFSET;
}
/**
* Convert an Coptic year, month, and day to a Julian day.
*
* @param year the year
* @param month the month
* @param date the day
* @hide draft / provisional / internal are hidden on Android
*/
// The equivalent operation can be done by public Calendar API.
// This API was accidentally marked as @draft, but we have no good
// reason to keep this. For now, we leave it as is, but may be
// removed in future. 2008-03-21 yoshito
public static int copticToJD(long year, int month, int date) {
return ceToJD(year, month, date, JD_EPOCH_OFFSET);
}
}
| Reginer/aosp-android-jar | android-34/src/android/icu/util/CopticCalendar.java |
1,796 | package operatingsystem;
import static operatingsystem.Main.stats;
// Χρίστος Γκόγκος (2738), Αθανάσιος Μπόλλας (2779), Δημήτριος Σβίγγας (2618), Αναστάσιος Τεμπερεκίδης (2808)
/* Η κλάση αυτή παριστάνει τη μονάδα επεξεργασίας CPU του συστήματος */
public class CPU {
/* περιέχει τη διεργασία που χρησιμοποιεί τη CPU την τρέχουσα στιγμή */
private Process runningProcess;
/* περιέχει τη χρονική στιγμή της επόμενης διακοπής */
private int timeToNextContextSwitch;
/* περιέχει τη χρονική στιγμή έναρξης της τελευταίας διεργασίας */
private int lastProcessStartTime;
/* constructor – αρχικοποίηση των πεδίων*/
public CPU() {
this.runningProcess = null;
this.timeToNextContextSwitch = 0;
this.lastProcessStartTime = 0;
}
/* εισαγωγή της διεργασίας προς εκτέλεση στη CPU */
public void addProcess(Process process) {
if (process != null) {
process.setProcessState(ProcessState.RUNNING);
process.requestAccepted();
this.runningProcess = process;
}
}
/* εξαγωγή της τρέχουσας διεργασίας από τη CPU */
public Process removeProcessFromCpu() {
Process proc = this.runningProcess;
this.runningProcess = null;
return proc;
}
/* αλλάγη του χρόνου επόμενου context switch */
public void setTimeToNextContextSwitch(int time) {
this.timeToNextContextSwitch = time;
}
/* εκτέλεση της διεργασίας με αντίστοιχη μέιωση του χρόνου εκτέλεσής της */
public void execute() {
if (runningProcess == null) { // Δεν υπάρχει καμία διεργασία που τρέχει στην CPU
Main.clock.Time_Run();
return;
}
this.lastProcessStartTime = Main.clock.ShowTime();
// Εκτέλεση της διεργασίας μέχρι το επόμενο context-switch
while (Main.clock.ShowTime() <= this.timeToNextContextSwitch) {
if (runningProcess.getRemainingTime() == 0) { // Η διεργασία έχει τερματίσει
runningProcess.setProcessState(ProcessState.TERMINATED);
stats.processTerminated(runningProcess);
break;
}
// Εκτέλεση της διεργασίας
Main.clock.Time_Run();
runningProcess.decreaseCpuRemainingTime();
}
}
/* επιστρέφει την διεργασία που τρέχει αυτή τη στιγμή
ή null αν δεν τρέχει καμία διεργασία στην CPU */
public Process getRunningProcess() {
return this.runningProcess;
}
}
| TeamLS/Operating-System-Simulator | src/operatingsystem/CPU.java |
1,797 | package org.apache.lucene.analysis.el;
import org.apache.lucene.analysis.util.CharArraySet;
import java.util.Arrays;
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/**
* A stemmer for Greek words, according to: <i>Development of a Stemmer for the
* Greek Language.</i> Georgios Ntais
* <p>
* NOTE: Input is expected to be casefolded for Greek (including folding of final
* sigma to sigma), and with diacritics removed. This can be achieved with
* either {@link GreekLowerCaseFilter} or ICUFoldingFilter.
* @lucene.experimental
*/
public class GreekStemmer {
/**
* Stems a word contained in a leading portion of a char[] array.
* The word is passed through a number of rules that modify its length.
*
* @param s A char[] array that contains the word to be stemmed.
* @param len The length of the char[] array.
* @return The new length of the stemmed word.
*/
public int stem(char s[], int len) {
if (len < 4) // too short
return len;
final int origLen = len;
// "short rules": if it hits one of these, it skips the "long list"
len = rule0(s, len);
len = rule1(s, len);
len = rule2(s, len);
len = rule3(s, len);
len = rule4(s, len);
len = rule5(s, len);
len = rule6(s, len);
len = rule7(s, len);
len = rule8(s, len);
len = rule9(s, len);
len = rule10(s, len);
len = rule11(s, len);
len = rule12(s, len);
len = rule13(s, len);
len = rule14(s, len);
len = rule15(s, len);
len = rule16(s, len);
len = rule17(s, len);
len = rule18(s, len);
len = rule19(s, len);
len = rule20(s, len);
// "long list"
if (len == origLen)
len = rule21(s, len);
return rule22(s, len);
}
private int rule0(char s[], int len) {
if (len > 9 && (endsWith(s, len, "καθεστωτοσ")
|| endsWith(s, len, "καθεστωτων")))
return len - 4;
if (len > 8 && (endsWith(s, len, "γεγονοτοσ")
|| endsWith(s, len, "γεγονοτων")))
return len - 4;
if (len > 8 && endsWith(s, len, "καθεστωτα"))
return len - 3;
if (len > 7 && (endsWith(s, len, "τατογιου")
|| endsWith(s, len, "τατογιων")))
return len - 4;
if (len > 7 && endsWith(s, len, "γεγονοτα"))
return len - 3;
if (len > 7 && endsWith(s, len, "καθεστωσ"))
return len - 2;
if (len > 6 && (endsWith(s, len, "σκαγιου"))
|| endsWith(s, len, "σκαγιων")
|| endsWith(s, len, "ολογιου")
|| endsWith(s, len, "ολογιων")
|| endsWith(s, len, "κρεατοσ")
|| endsWith(s, len, "κρεατων")
|| endsWith(s, len, "περατοσ")
|| endsWith(s, len, "περατων")
|| endsWith(s, len, "τερατοσ")
|| endsWith(s, len, "τερατων"))
return len - 4;
if (len > 6 && endsWith(s, len, "τατογια"))
return len - 3;
if (len > 6 && endsWith(s, len, "γεγονοσ"))
return len - 2;
if (len > 5 && (endsWith(s, len, "φαγιου")
|| endsWith(s, len, "φαγιων")
|| endsWith(s, len, "σογιου")
|| endsWith(s, len, "σογιων")))
return len - 4;
if (len > 5 && (endsWith(s, len, "σκαγια")
|| endsWith(s, len, "ολογια")
|| endsWith(s, len, "κρεατα")
|| endsWith(s, len, "περατα")
|| endsWith(s, len, "τερατα")))
return len - 3;
if (len > 4 && (endsWith(s, len, "φαγια")
|| endsWith(s, len, "σογια")
|| endsWith(s, len, "φωτοσ")
|| endsWith(s, len, "φωτων")))
return len - 3;
if (len > 4 && (endsWith(s, len, "κρεασ")
|| endsWith(s, len, "περασ")
|| endsWith(s, len, "τερασ")))
return len - 2;
if (len > 3 && endsWith(s, len, "φωτα"))
return len - 2;
if (len > 2 && endsWith(s, len, "φωσ"))
return len - 1;
return len;
}
private int rule1(char s[], int len) {
if (len > 4 && (endsWith(s, len, "αδεσ") || endsWith(s, len, "αδων"))) {
len -= 4;
if (!(endsWith(s, len, "οκ") ||
endsWith(s, len, "μαμ") ||
endsWith(s, len, "μαν") ||
endsWith(s, len, "μπαμπ") ||
endsWith(s, len, "πατερ") ||
endsWith(s, len, "γιαγι") ||
endsWith(s, len, "νταντ") ||
endsWith(s, len, "κυρ") ||
endsWith(s, len, "θει") ||
endsWith(s, len, "πεθερ")))
len += 2; // add back -αδ
}
return len;
}
private int rule2(char s[], int len) {
if (len > 4 && (endsWith(s, len, "εδεσ") || endsWith(s, len, "εδων"))) {
len -= 4;
if (endsWith(s, len, "οπ") ||
endsWith(s, len, "ιπ") ||
endsWith(s, len, "εμπ") ||
endsWith(s, len, "υπ") ||
endsWith(s, len, "γηπ") ||
endsWith(s, len, "δαπ") ||
endsWith(s, len, "κρασπ") ||
endsWith(s, len, "μιλ"))
len += 2; // add back -εδ
}
return len;
}
private int rule3(char s[], int len) {
if (len > 5 && (endsWith(s, len, "ουδεσ") || endsWith(s, len, "ουδων"))) {
len -= 5;
if (endsWith(s, len, "αρκ") ||
endsWith(s, len, "καλιακ") ||
endsWith(s, len, "πεταλ") ||
endsWith(s, len, "λιχ") ||
endsWith(s, len, "πλεξ") ||
endsWith(s, len, "σκ") ||
endsWith(s, len, "σ") ||
endsWith(s, len, "φλ") ||
endsWith(s, len, "φρ") ||
endsWith(s, len, "βελ") ||
endsWith(s, len, "λουλ") ||
endsWith(s, len, "χν") ||
endsWith(s, len, "σπ") ||
endsWith(s, len, "τραγ") ||
endsWith(s, len, "φε"))
len += 3; // add back -ουδ
}
return len;
}
private static final CharArraySet exc4 = new CharArraySet(
Arrays.asList("θ", "δ", "ελ", "γαλ", "ν", "π", "ιδ", "παρ"),
false);
private int rule4(char s[], int len) {
if (len > 3 && (endsWith(s, len, "εωσ") || endsWith(s, len, "εων"))) {
len -= 3;
if (exc4.contains(s, 0, len))
len++; // add back -ε
}
return len;
}
private int rule5(char s[], int len) {
if (len > 2 && endsWith(s, len, "ια")) {
len -= 2;
if (endsWithVowel(s, len))
len++; // add back -ι
} else if (len > 3 && (endsWith(s, len, "ιου") || endsWith(s, len, "ιων"))) {
len -= 3;
if (endsWithVowel(s, len))
len++; // add back -ι
}
return len;
}
private static final CharArraySet exc6 = new CharArraySet(
Arrays.asList("αλ", "αδ", "ενδ", "αμαν", "αμμοχαλ", "ηθ", "ανηθ",
"αντιδ", "φυσ", "βρωμ", "γερ", "εξωδ", "καλπ", "καλλιν", "καταδ",
"μουλ", "μπαν", "μπαγιατ", "μπολ", "μποσ", "νιτ", "ξικ", "συνομηλ",
"πετσ", "πιτσ", "πικαντ", "πλιατσ", "ποστελν", "πρωτοδ", "σερτ",
"συναδ", "τσαμ", "υποδ", "φιλον", "φυλοδ", "χασ"),
false);
private int rule6(char s[], int len) {
boolean removed = false;
if (len > 3 && (endsWith(s, len, "ικα") || endsWith(s, len, "ικο"))) {
len -= 3;
removed = true;
} else if (len > 4 && (endsWith(s, len, "ικου") || endsWith(s, len, "ικων"))) {
len -= 4;
removed = true;
}
if (removed) {
if (endsWithVowel(s, len) || exc6.contains(s, 0, len))
len += 2; // add back -ικ
}
return len;
}
private static final CharArraySet exc7 = new CharArraySet(
Arrays.asList("αναπ", "αποθ", "αποκ", "αποστ", "βουβ", "ξεθ", "ουλ",
"πεθ", "πικρ", "ποτ", "σιχ", "χ"),
false);
private int rule7(char s[], int len) {
if (len == 5 && endsWith(s, len, "αγαμε"))
return len - 1;
if (len > 7 && endsWith(s, len, "ηθηκαμε"))
len -= 7;
else if (len > 6 && endsWith(s, len, "ουσαμε"))
len -= 6;
else if (len > 5 && (endsWith(s, len, "αγαμε") ||
endsWith(s, len, "ησαμε") ||
endsWith(s, len, "ηκαμε")))
len -= 5;
if (len > 3 && endsWith(s, len, "αμε")) {
len -= 3;
if (exc7.contains(s, 0, len))
len += 2; // add back -αμ
}
return len;
}
private static final CharArraySet exc8a = new CharArraySet(
Arrays.asList("τρ", "τσ"),
false);
private static final CharArraySet exc8b = new CharArraySet(
Arrays.asList("βετερ", "βουλκ", "βραχμ", "γ", "δραδουμ", "θ", "καλπουζ",
"καστελ", "κορμορ", "λαοπλ", "μωαμεθ", "μ", "μουσουλμ", "ν", "ουλ",
"π", "πελεκ", "πλ", "πολισ", "πορτολ", "σαρακατσ", "σουλτ",
"τσαρλατ", "ορφ", "τσιγγ", "τσοπ", "φωτοστεφ", "χ", "ψυχοπλ", "αγ",
"ορφ", "γαλ", "γερ", "δεκ", "διπλ", "αμερικαν", "ουρ", "πιθ",
"πουριτ", "σ", "ζωντ", "ικ", "καστ", "κοπ", "λιχ", "λουθηρ", "μαιντ",
"μελ", "σιγ", "σπ", "στεγ", "τραγ", "τσαγ", "φ", "ερ", "αδαπ",
"αθιγγ", "αμηχ", "ανικ", "ανοργ", "απηγ", "απιθ", "ατσιγγ", "βασ",
"βασκ", "βαθυγαλ", "βιομηχ", "βραχυκ", "διατ", "διαφ", "ενοργ",
"θυσ", "καπνοβιομηχ", "καταγαλ", "κλιβ", "κοιλαρφ", "λιβ",
"μεγλοβιομηχ", "μικροβιομηχ", "νταβ", "ξηροκλιβ", "ολιγοδαμ",
"ολογαλ", "πενταρφ", "περηφ", "περιτρ", "πλατ", "πολυδαπ", "πολυμηχ",
"στεφ", "ταβ", "τετ", "υπερηφ", "υποκοπ", "χαμηλοδαπ", "ψηλοταβ"),
false);
private int rule8(char s[], int len) {
boolean removed = false;
if (len > 8 && endsWith(s, len, "ιουντανε")) {
len -= 8;
removed = true;
} else if (len > 7 && endsWith(s, len, "ιοντανε") ||
endsWith(s, len, "ουντανε") ||
endsWith(s, len, "ηθηκανε")) {
len -= 7;
removed = true;
} else if (len > 6 && endsWith(s, len, "ιοτανε") ||
endsWith(s, len, "οντανε") ||
endsWith(s, len, "ουσανε")) {
len -= 6;
removed = true;
} else if (len > 5 && endsWith(s, len, "αγανε") ||
endsWith(s, len, "ησανε") ||
endsWith(s, len, "οτανε") ||
endsWith(s, len, "ηκανε")) {
len -= 5;
removed = true;
}
if (removed && exc8a.contains(s, 0, len)) {
// add -αγαν (we removed > 4 chars so it's safe)
len += 4;
s[len - 4] = 'α';
s[len - 3] = 'γ';
s[len - 2] = 'α';
s[len - 1] = 'ν';
}
if (len > 3 && endsWith(s, len, "ανε")) {
len -= 3;
if (endsWithVowelNoY(s, len) || exc8b.contains(s, 0, len)) {
len += 2; // add back -αν
}
}
return len;
}
private static final CharArraySet exc9 = new CharArraySet(
Arrays.asList("αβαρ", "βεν", "εναρ", "αβρ", "αδ", "αθ", "αν", "απλ",
"βαρον", "ντρ", "σκ", "κοπ", "μπορ", "νιφ", "παγ", "παρακαλ", "σερπ",
"σκελ", "συρφ", "τοκ", "υ", "δ", "εμ", "θαρρ", "θ"),
false);
private int rule9(char s[], int len) {
if (len > 5 && endsWith(s, len, "ησετε"))
len -= 5;
if (len > 3 && endsWith(s, len, "ετε")) {
len -= 3;
if (exc9.contains(s, 0, len) ||
endsWithVowelNoY(s, len) ||
endsWith(s, len, "οδ") ||
endsWith(s, len, "αιρ") ||
endsWith(s, len, "φορ") ||
endsWith(s, len, "ταθ") ||
endsWith(s, len, "διαθ") ||
endsWith(s, len, "σχ") ||
endsWith(s, len, "ενδ") ||
endsWith(s, len, "ευρ") ||
endsWith(s, len, "τιθ") ||
endsWith(s, len, "υπερθ") ||
endsWith(s, len, "ραθ") ||
endsWith(s, len, "ενθ") ||
endsWith(s, len, "ροθ") ||
endsWith(s, len, "σθ") ||
endsWith(s, len, "πυρ") ||
endsWith(s, len, "αιν") ||
endsWith(s, len, "συνδ") ||
endsWith(s, len, "συν") ||
endsWith(s, len, "συνθ") ||
endsWith(s, len, "χωρ") ||
endsWith(s, len, "πον") ||
endsWith(s, len, "βρ") ||
endsWith(s, len, "καθ") ||
endsWith(s, len, "ευθ") ||
endsWith(s, len, "εκθ") ||
endsWith(s, len, "νετ") ||
endsWith(s, len, "ρον") ||
endsWith(s, len, "αρκ") ||
endsWith(s, len, "βαρ") ||
endsWith(s, len, "βολ") ||
endsWith(s, len, "ωφελ")) {
len += 2; // add back -ετ
}
}
return len;
}
private int rule10(char s[], int len) {
if (len > 5 && (endsWith(s, len, "οντασ") || endsWith(s, len, "ωντασ"))) {
len -= 5;
if (len == 3 && endsWith(s, len, "αρχ")) {
len += 3; // add back *ντ
s[len - 3] = 'ο';
}
if (endsWith(s, len, "κρε")) {
len += 3; // add back *ντ
s[len - 3] = 'ω';
}
}
return len;
}
private int rule11(char s[], int len) {
if (len > 6 && endsWith(s, len, "ομαστε")) {
len -= 6;
if (len == 2 && endsWith(s, len, "ον")) {
len += 5; // add back -ομαστ
}
} else if (len > 7 && endsWith(s, len, "ιομαστε")) {
len -= 7;
if (len == 2 && endsWith(s, len, "ον")) {
len += 5;
s[len - 5] = 'ο';
s[len - 4] = 'μ';
s[len - 3] = 'α';
s[len - 2] = 'σ';
s[len - 1] = 'τ';
}
}
return len;
}
private static final CharArraySet exc12a = new CharArraySet(
Arrays.asList("π", "απ", "συμπ", "ασυμπ", "ακαταπ", "αμεταμφ"),
false);
private static final CharArraySet exc12b = new CharArraySet(
Arrays.asList("αλ", "αρ", "εκτελ", "ζ", "μ", "ξ", "παρακαλ", "αρ", "προ", "νισ"),
false);
private int rule12(char s[], int len) {
if (len > 5 && endsWith(s, len, "ιεστε")) {
len -= 5;
if (exc12a.contains(s, 0, len))
len += 4; // add back -ιεστ
}
if (len > 4 && endsWith(s, len, "εστε")) {
len -= 4;
if (exc12b.contains(s, 0, len))
len += 3; // add back -εστ
}
return len;
}
private static final CharArraySet exc13 = new CharArraySet(
Arrays.asList("διαθ", "θ", "παρακαταθ", "προσθ", "συνθ"),
false);
private int rule13(char s[], int len) {
if (len > 6 && endsWith(s, len, "ηθηκεσ")) {
len -= 6;
} else if (len > 5 && (endsWith(s, len, "ηθηκα") || endsWith(s, len, "ηθηκε"))) {
len -= 5;
}
boolean removed = false;
if (len > 4 && endsWith(s, len, "ηκεσ")) {
len -= 4;
removed = true;
} else if (len > 3 && (endsWith(s, len, "ηκα") || endsWith(s, len, "ηκε"))) {
len -= 3;
removed = true;
}
if (removed && (exc13.contains(s, 0, len)
|| endsWith(s, len, "σκωλ")
|| endsWith(s, len, "σκουλ")
|| endsWith(s, len, "ναρθ")
|| endsWith(s, len, "σφ")
|| endsWith(s, len, "οθ")
|| endsWith(s, len, "πιθ"))) {
len += 2; // add back the -ηκ
}
return len;
}
private static final CharArraySet exc14 = new CharArraySet(
Arrays.asList("φαρμακ", "χαδ", "αγκ", "αναρρ", "βρομ", "εκλιπ", "λαμπιδ",
"λεχ", "μ", "πατ", "ρ", "λ", "μεδ", "μεσαζ", "υποτειν", "αμ", "αιθ",
"ανηκ", "δεσποζ", "ενδιαφερ", "δε", "δευτερευ", "καθαρευ", "πλε",
"τσα"),
false);
private int rule14(char s[], int len) {
boolean removed = false;
if (len > 5 && endsWith(s, len, "ουσεσ")) {
len -= 5;
removed = true;
} else if (len > 4 && (endsWith(s, len, "ουσα") || endsWith(s, len, "ουσε"))) {
len -= 4;
removed = true;
}
if (removed && (exc14.contains(s, 0, len)
|| endsWithVowel(s, len)
|| endsWith(s, len, "ποδαρ")
|| endsWith(s, len, "βλεπ")
|| endsWith(s, len, "πανταχ")
|| endsWith(s, len, "φρυδ")
|| endsWith(s, len, "μαντιλ")
|| endsWith(s, len, "μαλλ")
|| endsWith(s, len, "κυματ")
|| endsWith(s, len, "λαχ")
|| endsWith(s, len, "ληγ")
|| endsWith(s, len, "φαγ")
|| endsWith(s, len, "ομ")
|| endsWith(s, len, "πρωτ"))) {
len += 3; // add back -ουσ
}
return len;
}
private static final CharArraySet exc15a = new CharArraySet(
Arrays.asList("αβαστ", "πολυφ", "αδηφ", "παμφ", "ρ", "ασπ", "αφ", "αμαλ",
"αμαλλι", "ανυστ", "απερ", "ασπαρ", "αχαρ", "δερβεν", "δροσοπ",
"ξεφ", "νεοπ", "νομοτ", "ολοπ", "ομοτ", "προστ", "προσωποπ", "συμπ",
"συντ", "τ", "υποτ", "χαρ", "αειπ", "αιμοστ", "ανυπ", "αποτ",
"αρτιπ", "διατ", "εν", "επιτ", "κροκαλοπ", "σιδηροπ", "λ", "ναυ",
"ουλαμ", "ουρ", "π", "τρ", "μ"),
false);
private static final CharArraySet exc15b = new CharArraySet(
Arrays.asList("ψοφ", "ναυλοχ"),
false);
private int rule15(char s[], int len) {
boolean removed = false;
if (len > 4 && endsWith(s, len, "αγεσ")) {
len -= 4;
removed = true;
} else if (len > 3 && (endsWith(s, len, "αγα") || endsWith(s, len, "αγε"))) {
len -= 3;
removed = true;
}
if (removed) {
final boolean cond1 = exc15a.contains(s, 0, len)
|| endsWith(s, len, "οφ")
|| endsWith(s, len, "πελ")
|| endsWith(s, len, "χορτ")
|| endsWith(s, len, "λλ")
|| endsWith(s, len, "σφ")
|| endsWith(s, len, "ρπ")
|| endsWith(s, len, "φρ")
|| endsWith(s, len, "πρ")
|| endsWith(s, len, "λοχ")
|| endsWith(s, len, "σμην");
final boolean cond2 = exc15b.contains(s, 0, len)
|| endsWith(s, len, "κολλ");
if (cond1 && !cond2)
len += 2; // add back -αγ
}
return len;
}
private static final CharArraySet exc16 = new CharArraySet(
Arrays.asList("ν", "χερσον", "δωδεκαν", "ερημον", "μεγαλον", "επταν"),
false);
private int rule16(char s[], int len) {
boolean removed = false;
if (len > 4 && endsWith(s, len, "ησου")) {
len -= 4;
removed = true;
} else if (len > 3 && (endsWith(s, len, "ησε") || endsWith(s, len, "ησα"))) {
len -= 3;
removed = true;
}
if (removed && exc16.contains(s, 0, len))
len += 2; // add back -ησ
return len;
}
private static final CharArraySet exc17 = new CharArraySet(
Arrays.asList("ασβ", "σβ", "αχρ", "χρ", "απλ", "αειμν", "δυσχρ", "ευχρ", "κοινοχρ", "παλιμψ"),
false);
private int rule17(char s[], int len) {
if (len > 4 && endsWith(s, len, "ηστε")) {
len -= 4;
if (exc17.contains(s, 0, len))
len += 3; // add back the -ηστ
}
return len;
}
private static final CharArraySet exc18 = new CharArraySet(
Arrays.asList("ν", "ρ", "σπι", "στραβομουτσ", "κακομουτσ", "εξων"),
false);
private int rule18(char s[], int len) {
boolean removed = false;
if (len > 6 && (endsWith(s, len, "ησουνε") || endsWith(s, len, "ηθουνε"))) {
len -= 6;
removed = true;
} else if (len > 4 && endsWith(s, len, "ουνε")) {
len -= 4;
removed = true;
}
if (removed && exc18.contains(s, 0, len)) {
len += 3;
s[len - 3] = 'ο';
s[len - 2] = 'υ';
s[len - 1] = 'ν';
}
return len;
}
private static final CharArraySet exc19 = new CharArraySet(
Arrays.asList("παρασουσ", "φ", "χ", "ωριοπλ", "αζ", "αλλοσουσ", "ασουσ"),
false);
private int rule19(char s[], int len) {
boolean removed = false;
if (len > 6 && (endsWith(s, len, "ησουμε") || endsWith(s, len, "ηθουμε"))) {
len -= 6;
removed = true;
} else if (len > 4 && endsWith(s, len, "ουμε")) {
len -= 4;
removed = true;
}
if (removed && exc19.contains(s, 0, len)) {
len += 3;
s[len - 3] = 'ο';
s[len - 2] = 'υ';
s[len - 1] = 'μ';
}
return len;
}
private int rule20(char s[], int len) {
if (len > 5 && (endsWith(s, len, "ματων") || endsWith(s, len, "ματοσ")))
len -= 3;
else if (len > 4 && endsWith(s, len, "ματα"))
len -= 2;
return len;
}
private int rule21(char s[], int len) {
if (len > 9 && endsWith(s, len, "ιοντουσαν"))
return len - 9;
if (len > 8 && (endsWith(s, len, "ιομασταν") ||
endsWith(s, len, "ιοσασταν") ||
endsWith(s, len, "ιουμαστε") ||
endsWith(s, len, "οντουσαν")))
return len - 8;
if (len > 7 && (endsWith(s, len, "ιεμαστε") ||
endsWith(s, len, "ιεσαστε") ||
endsWith(s, len, "ιομουνα") ||
endsWith(s, len, "ιοσαστε") ||
endsWith(s, len, "ιοσουνα") ||
endsWith(s, len, "ιουνται") ||
endsWith(s, len, "ιουνταν") ||
endsWith(s, len, "ηθηκατε") ||
endsWith(s, len, "ομασταν") ||
endsWith(s, len, "οσασταν") ||
endsWith(s, len, "ουμαστε")))
return len - 7;
if (len > 6 && (endsWith(s, len, "ιομουν") ||
endsWith(s, len, "ιονταν") ||
endsWith(s, len, "ιοσουν") ||
endsWith(s, len, "ηθειτε") ||
endsWith(s, len, "ηθηκαν") ||
endsWith(s, len, "ομουνα") ||
endsWith(s, len, "οσαστε") ||
endsWith(s, len, "οσουνα") ||
endsWith(s, len, "ουνται") ||
endsWith(s, len, "ουνταν") ||
endsWith(s, len, "ουσατε")))
return len - 6;
if (len > 5 && (endsWith(s, len, "αγατε") ||
endsWith(s, len, "ιεμαι") ||
endsWith(s, len, "ιεται") ||
endsWith(s, len, "ιεσαι") ||
endsWith(s, len, "ιοταν") ||
endsWith(s, len, "ιουμα") ||
endsWith(s, len, "ηθεισ") ||
endsWith(s, len, "ηθουν") ||
endsWith(s, len, "ηκατε") ||
endsWith(s, len, "ησατε") ||
endsWith(s, len, "ησουν") ||
endsWith(s, len, "ομουν") ||
endsWith(s, len, "ονται") ||
endsWith(s, len, "ονταν") ||
endsWith(s, len, "οσουν") ||
endsWith(s, len, "ουμαι") ||
endsWith(s, len, "ουσαν")))
return len - 5;
if (len > 4 && (endsWith(s, len, "αγαν") ||
endsWith(s, len, "αμαι") ||
endsWith(s, len, "ασαι") ||
endsWith(s, len, "αται") ||
endsWith(s, len, "ειτε") ||
endsWith(s, len, "εσαι") ||
endsWith(s, len, "εται") ||
endsWith(s, len, "ηδεσ") ||
endsWith(s, len, "ηδων") ||
endsWith(s, len, "ηθει") ||
endsWith(s, len, "ηκαν") ||
endsWith(s, len, "ησαν") ||
endsWith(s, len, "ησει") ||
endsWith(s, len, "ησεσ") ||
endsWith(s, len, "ομαι") ||
endsWith(s, len, "οταν")))
return len - 4;
if (len > 3 && (endsWith(s, len, "αει") ||
endsWith(s, len, "εισ") ||
endsWith(s, len, "ηθω") ||
endsWith(s, len, "ησω") ||
endsWith(s, len, "ουν") ||
endsWith(s, len, "ουσ")))
return len - 3;
if (len > 2 && (endsWith(s, len, "αν") ||
endsWith(s, len, "ασ") ||
endsWith(s, len, "αω") ||
endsWith(s, len, "ει") ||
endsWith(s, len, "εσ") ||
endsWith(s, len, "ησ") ||
endsWith(s, len, "οι") ||
endsWith(s, len, "οσ") ||
endsWith(s, len, "ου") ||
endsWith(s, len, "υσ") ||
endsWith(s, len, "ων")))
return len - 2;
if (len > 1 && endsWithVowel(s, len))
return len - 1;
return len;
}
private int rule22(char s[], int len) {
if (endsWith(s, len, "εστερ") ||
endsWith(s, len, "εστατ"))
return len - 5;
if (endsWith(s, len, "οτερ") ||
endsWith(s, len, "οτατ") ||
endsWith(s, len, "υτερ") ||
endsWith(s, len, "υτατ") ||
endsWith(s, len, "ωτερ") ||
endsWith(s, len, "ωτατ"))
return len - 4;
return len;
}
/**
* Checks if the word contained in the leading portion of char[] array ,
* ends with the suffix given as parameter.
*
* @param s A char[] array that represents a word.
* @param len The length of the char[] array.
* @param suffix A {@link String} object to check if the word given ends with these characters.
* @return True if the word ends with the suffix given , false otherwise.
*/
private boolean endsWith(char s[], int len, String suffix) {
final int suffixLen = suffix.length();
if (suffixLen > len)
return false;
for (int i = suffixLen - 1; i >= 0; i--)
if (s[len -(suffixLen - i)] != suffix.charAt(i))
return false;
return true;
}
/**
* Checks if the word contained in the leading portion of char[] array ,
* ends with a Greek vowel.
*
* @param s A char[] array that represents a word.
* @param len The length of the char[] array.
* @return True if the word contained in the leading portion of char[] array ,
* ends with a vowel , false otherwise.
*/
private boolean endsWithVowel(char s[], int len) {
if (len == 0)
return false;
switch(s[len - 1]) {
case 'α':
case 'ε':
case 'η':
case 'ι':
case 'ο':
case 'υ':
case 'ω':
return true;
default:
return false;
}
}
/**
* Checks if the word contained in the leading portion of char[] array ,
* ends with a Greek vowel.
*
* @param s A char[] array that represents a word.
* @param len The length of the char[] array.
* @return True if the word contained in the leading portion of char[] array ,
* ends with a vowel , false otherwise.
*/
private boolean endsWithVowelNoY(char s[], int len) {
if (len == 0)
return false;
switch(s[len - 1]) {
case 'α':
case 'ε':
case 'η':
case 'ι':
case 'ο':
case 'ω':
return true;
default:
return false;
}
}
}
| Samsung/KnowledgeSharingPlatform | sameas/lib/lucene-analyzers-common-5.0.0/org/apache/lucene/analysis/el/GreekStemmer.java |
1,798 | package operatingsystem;
import java.io.IOException;
// Χρίστος Γκόγκος (2738), Αθανάσιος Μπόλλας (2779), Δημήτριος Σβίγγας (2618), Αναστάσιος Τεμπερεκίδης (2808)
/* Από την κλάση αυτή ξεκινά η εκτέλεση της εφαρμογής. Δημιουργεί το αρχείο με
τις διεργασίες, φορτώνει από αυτό όλες τις διεργασίες και προσομοιώνει την
δρομολόγηση με σειρά τους εξής αλγορίθμους: SJF preemptive, SJF non-preemptive,
Round Robin quantum=50, Round Robin quantum=300. Τέλος καταγράφει τα στατιστικά
από τις παραπάνω προσομοιώσεις και τα αποθηκεύει σε αρχείο. */
public class Main {
public static Clock clock;
public static CPU cpu;
public static NewProcessTemporaryList newProcessList;
public static ReadyProcessesList readyProcessesList;
public static Statistics stats;
/* Επιστρέφει true αν η cpu δεν έχει καμία διεργασία για εκτέλεση,
δεν υπάρχει καμία διεργασία στην ουρά έτοιμων διεργασιών και η ουρά νέων διεργασιών είναι άδεια. */
public static boolean end() {
return (cpu.getRunningProcess() == null) && (readyProcessesList.isEmpty()) && (newProcessList.isEmpty());
}
public static void main(String[] args) throws IOException {
String inputFileName = "processes.txt"; //Αρχείο των στοιχείων των διεργασιών
String outputFileName = "statistics.txt"; // Αρχείο στατιστικών εκτέλεσης
ProcessGenerator processParse;
new ProcessGenerator(inputFileName, false); // Δημιουργία αρχείου εισόδου
cpu = new CPU();
newProcessList = new NewProcessTemporaryList();
stats = new Statistics(outputFileName);
clock = new Clock();
readyProcessesList = new ReadyProcessesList();
// ============== PREEMPTIVE SJF ==============//
processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών
processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών
SJFScheduler sjfs = new SJFScheduler(true); // Προεκχωρίσιμος SJFS
while (!end()) {
sjfs.SJF(); //Δρομολόγηση διεργασίας
cpu.execute(); //Εκτέλεση διεργασίας
}
//Εγγραφή των στατιστικών
stats.WriteStatistics2File("Preemptive SJF");
stats.printStatistics("Preemptive SJF");
// ============== NON-PREEMPTIVE SJF ==============//
clock.reset(); //Μηδενισμός ρολογιού
stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών
processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών
processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών
sjfs.setIsPreemptive(false); // Μη- προεκχωρίσιμος SJFS
while (!end()) {
sjfs.SJF(); //Δρομολόγηση διεργασίας
cpu.execute(); //Εκτέλεση διεργασίας
}
//Εγγραφή των στατιστικών
stats.WriteStatistics2File("Non-Preemptive SJF");
stats.printStatistics("Non-Preemptive SJF");
// ============== RR WITH QUANTUM = 200 ==============//
clock.reset(); //Μηδενισμός ρολογιού
stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών
processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών
processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών
RRScheduler rrs = new RRScheduler(200); //Round Robin με quantum = 200
while (!end()) {
rrs.RR(); //Δρομολόγηση διεργασίας
cpu.execute(); //Εκτέλεση διεργασίας
}
//Εγγραφή των στατιστικών
stats.WriteStatistics2File("Round Robin with quantum = 200");
stats.printStatistics("Round Robin with quantum = 200");
// ============== RR WITH QUANTUM = 5000 ==============//
clock.reset(); //Μηδενισμός ρολογιού
stats.reset(); // Αρχικοποίηση παραμέτρων αντικειμένου στατιστικών
processParse = new ProcessGenerator(inputFileName, true); //Παραγωγή όλων των διεργασιών
processParse.addProcessesToTemporayList(); // Προσθήκη των νέων διεργασιών στην ουρά νέων διεργασιών
rrs.setQuantum(5000); //Round Robin με quantum = 5000
while (!end()) {
rrs.RR(); //Δρομολόγηση διεργασίας
cpu.execute(); //Εκτέλεση διεργασίας
}
//Εγγραφή των στατιστικών
stats.WriteStatistics2File("Round Robin with quantum = 5000");
stats.printStatistics("Round Robin with quantum = 5000");
}
} | TeamLS/Operating-System-Simulator | src/operatingsystem/Main.java |
1,799 | package UserClientV1;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
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.Iterator;
import javax.swing.ImageIcon;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;
import static UserClientV1.ManageUserClient.expandAll;
/**
* Κλάση που μας βοηθάει να κάνουμε καλύτερη διαχείριση του περιεχομένου μιας συσκευής .
* Είναι όλες οι πληροφορίες που αφορούν μια συσκευή μαζί με μεθόδους που μας δίνουν
* την δυνατότητα να κάνουμε ομαδοποιημένα πράγματα πολύ εύκολα και στοχευμένα
* να επηρεάσουμε το περιεχόμενο της συσκευής μας .
* @author Michael Galliakis
*/
public class Device {
private static final int sumOfDifferentsTypes = 12;
private String deviceName ;
private String deviceID ;
private String senderFullID ;
private ArrayList<UnitControl> allControls ;
public BackgroundPanel backPanel ;
private HashMap<String,HashMap<String,Unit>> allUnits ;
private ManageSocketMessage msm ;
public ManageSocket ms ;
public String devAccess ;
public boolean saveSettings = true;
public ListenThread ltForRead ;
private String pathFile ="" ;
public Ptab myPTab ;
JTree tree ;
DefaultTreeModel treeModel ;
public HashMap<CustomTreeNode ,Unit> hmUnitNodes = new HashMap<>() ;
int sumOfControllers ;
public Device(String id,String sfID,String dn,ManageSocket _ms,String devAcc) {
deviceName = dn ;
deviceID = id ;
senderFullID = sfID ;
allUnits = new HashMap<>() ;
msm = new ManageSocketMessage() ;
sumOfControllers = 0 ;
allControls = new ArrayList<>() ;
ms = _ms ;
devAccess = devAcc ;
saveSettings = true ;
}
/**
* Get μέθοδος που απλά επιστρέφει το μονοπάτι την εικόνας του background
* σε συμβολοσειρά .
* @return Το μονοπάτι της εικόνας για το background της συσκευής .
*/
public String getPathFile() {
return pathFile;
}
/**
* Set μέθοδος που με βάση ένα μονοπάτι εικόνας μέσα στο δίσκο (παράμετρος)
* την φορτώνει και την εμφανίζει σαν background στην καρτέλα της συσκευής .
* @param pathFile Συμβολοσειρά με ολόκληρο το μονοπάτι της εικόνας .
*/
public void setPathFile(String pathFile) {
if (pathFile==null)
pathFile = "";
this.pathFile = pathFile;
if (!pathFile.equals(""))
backPanel.setImage(new File(pathFile));
}
/**
* Απλή set μέθοδος που ενημερώνει και συσχετίσει την εκάστοτε συσκευή με το
* αντίστοιχο ListenThread που την αφορά .
* @param lt Κάποιο {@link ListenThread} με το οποίο θα συσχετίσθει το {@link Device} .
*/
public void setLTForRead(ListenThread lt)
{
ltForRead = lt ;
}
/**
* Απλή set μέθοδος που ενημερώνει και συσχετίσει την εκάστοτε συσκευή με το
* αντίστοιχο Ptab που την αφορά .
* @param tab Κάποιο {@link Ptab} με το οποίο θα συσχετηθεί το {@link Device} .
*/
public void setPTab(Ptab tab)
{
myPTab = tab ;
}
/**
* Μέθοδος που αναλαμβάνει να στείλει το ανάλογο μήνυμα αλλαγής τιμής στον
* Server μέσω του αντίστοιχου socket .
* @param unitStrValue Μια συμβολοσειρά με το όνομα του ελεγκτή,το όνομα της
* μονάδας και την νέα τιμή .
* Μεταξύ τους έχουν μια "|" για διαχωριστικό όπως επίσης να αναφέρουμε ότι
* και όλη η συμβολοσειρά με την παραπάνω πληροφορία πρέπει να είναι μέσα
* σε παρένθεση . Πχ ένα unitStrValue θα μπορούσε να είναι : "(con1|unit1|21)" .
*/
public void changeRemoteValue(String unitStrValue)
{
String message ;
message = "#"+senderFullID+"$ChangeValues:1*"+ unitStrValue +";" ;
Tools.send(message,ms.out) ;
Tools.Debug.print(message);
}
/**
* Μέθοδος που αναλαμβάνει να στείλει το ανάλογο μήνυμα αλλαγής mode(τρόπος λειτουργίας)
* στον Server μέσω του αντίστοιχου socket .
* @param unitStrMode Μια συμβολοσειρά με το όνομα του ελεγκτή,το όνομα της
* μονάδας και το νέο mode .
* Μεταξύ τους έχουν μια "|" για διαχωριστικό όπως επίσης να αναφέρουμε ότι
* και όλη η συμβολοσειρά με την παραπάνω πληροφορία πρέπει να είναι μέσα
* σε παρένθεση . Πχ ένα unitStrMode θα μπορούσε να είναι : "(con1|unit1|3)" .
*/
public void changeRemoteMode(String unitStrMode)
{
String message ;
message = "#"+senderFullID+"$ChangeModes:1*"+ unitStrMode +";" ;
Tools.send(message,ms.out) ;
Tools.Debug.print(message);
}
/**
* Μέθοδος που "καθαρίζει" όλες τις επιλεγμένες μονάδες από δέξια που είναι
* "εικονίδια" (δηλαδή παύουν να είναι πορτοκαλί αν ήταν) όπως επίσης σταματάει
* να είναι επιλεγμένο κάποιο "κλαδί" από το "δέντρο" της εκάστοτε συσκευής .
*/
public void clearSelection()
{
UnitControl.clearSelection(allControls);
tree.clearSelection();
}
//Απλοί Get μέθοδοι - Αρχή :
public String getDeviceID() {
return deviceID;
}
public String getDeviceName() {
return deviceName;
}
//Απλοί Get μέθοδοι - Τέλος :
/**
* Μέθοδος που αναλαμβάνει να κτίσει ένας πλήρες δέντρο με όλες τις απαραίτητες
* πληροφορίες που γνωρίζει από το ίδιο το {@link Device} και στην συνέχεια να
* επιστρέφει ένα JTree .
* Σκοπός της μεθόδου είναι να μπορούμε πολύ απλά και ομαδοποιημένα να πάρουμε
* ένας πλήρες "δέντρο" και απλά να το εμφανίσουμε στην δεξιά πλευρά (όπως κοιτάμε εμείς)
* της εκάστοτε καρτέλας της συγκεκριμένης συσκευής .
* @param createTree Αν true τότε δημιουργείται εκ νέου το "δέντρο" αλλιώς απλά επιστρέφετε
* το "δέντρο" που είχε φτιαχτεί την τελευταία φορά .
* @return Ένα πλήρες JTree με κορυφή το όνομα της συσκευής και μέσα του όλους
* τους ελεγκτές με όλες τις μονάδες τους κ.α .
*/
public JTree getTree(boolean createTree)
{
if (createTree)
{
CustomTreeNode top = new CustomTreeNode(deviceName);
createNodes(top);
tree = new JTree(top);
treeModel = (DefaultTreeModel)tree.getModel();
tree.setName(deviceName);
/**
* Άμεση δημιουργία προγραμματιστικά ενός MouseListener
*/
tree.addMouseListener(new MouseListener() {
/**
* Μέθοδος που εκτελείτε όταν πατήσουμε κάποιο "κλικ" μέσα στο
* δέντρο μας .
* Πρακτικά το χρειαζόμαστε στην περίπτωση που είναι το "φύλλο" είναι
* ελεγκτής ή μονάδα για να ανοίγει ένα μενού και να έχει ο χρήστης
* την δυνατότητα να κάνει αλλαγή κάποιου description.
* @param e Ένα Default MouseEvent αντικείμενο που το χρειαζόμαστε για να
* βρούμε αν ο χρήστης πάτησε δεξί κλικ όπως επίσης για να βρούμε
* με βάση τη θέση που έγινε το κλικ , σε ποιο "φύλλο" του δέντρου
* απευθύνεται .
*/
@Override
public void mouseClicked( MouseEvent e) {
if ( SwingUtilities.isRightMouseButton ( e ) )
{
Point myPointOfScreen = e.getLocationOnScreen() ;
TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
tree.setSelectionPath(path);
Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
{
CustomTreeNode ctn = (CustomTreeNode)path.getLastPathComponent();
if (ctn.getLevel()==1 || ctn.getLevel()==3)
{
JPopupMenu menu = new JPopupMenu ();
JMenuItem jmi = new JMenuItem ( "Change Description" ) ;
/**
* Άμεση δημιουργία προγραμματιστικά ενός MouseListener
*/
jmi.addMouseListener(new MouseListener() {
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseClicked(MouseEvent me) {
//new DfChangeText(tree,ctn,myPointOfScreen) ;
// System.out.println("Mike12");
}
/**
* Μέθοδος που εκτελείτε όταν έχει πατηθεί κάποιο "κλικ" πάνω στο
* menuitem 'Change Description" .
* Και ουσιαστικά ανοίγει ένα {@link DfChangeText} για να δοθεί η δυνατότητα
* στον χρήστη να αλλάξει το description μιας μονάδας ή ενός ελεγκτή.
* @param me Ένα Default MouseEvent αντικείμενο που δεν το χρησιμοποιούμε .
*/
@Override
public void mousePressed(MouseEvent me) {
new DfChangeText(tree,(CustomTreeNode)path.getLastPathComponent(),myPointOfScreen).setVisible(true);
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseReleased(MouseEvent me) {
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseEntered(MouseEvent me) {
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseExited(MouseEvent me) {
}
});
menu.add ( jmi );
menu.show ( tree, pathBounds.x+50, pathBounds.y + pathBounds.height-20 );
}
}
}
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param e Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mousePressed ( MouseEvent e )
{
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseReleased(MouseEvent me) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseEntered(MouseEvent me) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
/**
* Μέθοδος που απλά πρέπει να γίνει override και που πρακτικά δεν κάνει τίποτα.
* @param me Ένα Default MouseEvent αντικείμενο το οποίο δεν το χρησιμοποιούμε.
*/
@Override
public void mouseExited(MouseEvent me) {
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
});
tree.setCellRenderer(new MyRenderer());
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
/**
* Άμεση δημιουργία προγραμματιστικά ενός TreeSelectionListener
*/
tree.addTreeSelectionListener(new TreeSelectionListener() {
/**
* Μέθοδος που εκτελείτε όταν αλλάξει το επιλεγμένο "φύλλο"
* του δέντρο μας .
* Πρακτικά το χρειαζόμαστε για να απο-επιλέγει τα επιλεγμένα εικονίδια
* των μονάδων (δηλαδή να παύουν να είναι πορτοκαλί) και ανάλογα
* το "φύλλο" που έχει επιλέξει να επιλέγονται (Να γίνονται πορτοκαλί)
* τα αντίστοιχα εικονίδια μονάδων(Αν επιλέξει ο χρήστης "φύλλο" μας
* μονάδας επιλέγεται[γίνεται πορτοκαλί] μόνο ένα εικονίδιο μονάδας στα δεξιά)
* @param tse Ένα Default TreeSelectionEvent αντικείμενο το οποίο
* δεν χρησιμοποιείται.
*/
@Override
public void valueChanged(TreeSelectionEvent tse) {
CustomTreeNode node = (CustomTreeNode)
tree.getLastSelectedPathComponent();
if (node != null)
{
switch(node.getLevel())
{
case 0 :
UnitControl.clearSelection(allControls);
break ;
case 1 :
UnitControl.clearSelection(allControls);
for (int j = 0 ; j< node.getChildCount();j++)
for (int i = 0 ; i< node.getChildAt(j).getChildCount();i++)
hmUnitNodes.get(node.getChildAt(j).getChildAt(i)).uc.setSelected(true);
break ;
case 2 :
if (node.getChildCount()>0)
{
UnitControl.clearSelection(allControls);
for (int i = 0 ; i< node.getChildCount();i++)
hmUnitNodes.get(node.getChildAt(i)).uc.setSelected(true);
}
break ;
case 3 :
UnitControl.clearSelection(allControls);
hmUnitNodes.get(node).uc.setSelected(true);
break ;
case 4 :
UnitControl.clearSelection(allControls);
hmUnitNodes.get(node.getParent()).uc.setSelected(true);
break ;
}
}
}
});
}
return tree ;
}
/**
* Custom Renderer για το δέντρο το οποίο έχει κληρονομήσει το DefaultTreeCellRenderer.
* Σκοπός του είναι πρακτικά να εμφανίζονται τα διάφορα εικονίδια στα "φύλλα" του
* δέντρου και όχι αυτά της προεπιλογής .
* Δηλαδή στην κορυφή το εικονίδιο του επεξεργαστή , στους ελεγκτές το εικονίδιο
* του arduino , στις μονάδες εικονίδια ανάλογα με το τύπο τους ,
* στις κατηγορίες 2(ανοικτό-κλειστό) εικονίδια πιο ξεχωριστά όπως επίσης και
* ένα πράσινο φύλλο στις πληροφορίες της κάθε μονάδας .
*/
private class MyRenderer extends DefaultTreeCellRenderer {
/**
* Κατασκευαστής που αρχικοποιεί τα εικονίδια των "φύλλων" του δέντρου.
*/
public MyRenderer() {
//backgroundSelectionColor = Globals.selectedColor ;
textSelectionColor =Globals.selectedColor ;
setClosedIcon(Globals.imTreeOpen);
setOpenIcon(Globals.imTreeClose);
setLeafIcon(Globals.imTreeLeaf);
}
/**
* Μέθοδος που εκτελείτε αυτόματα κάθε φορά που "επαναζωγραφίζεται" το δέντρο.
* @param tree Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @param value Default παράμετρος που πρακτικά είναι ένα {@link CustomTreeNode}
* και που σε επόμενη φάση θα ερευνηθεί και θα πάρει την κατάλληλη εικόνα με βάση
* το είδος του "φύλλου".
* @param sel Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @param expanded Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @param leaf Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @param row Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @param hasFocus Default παράμετρος που δεν επεμβαίνουμε προγραμματιστικά.
* @return Default Component αντικείμενο που επιστρέφεται αυτόματα κάθε
* κάποια χρονική στιγμή για να "επαναζωγραφιστεί" σε επόμενη φάση το δέντρο.
*/
@Override
public Component getTreeCellRendererComponent(
JTree tree,
Object value,
boolean sel,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus) {
super.getTreeCellRendererComponent(
tree, value, sel,
expanded, leaf, row,
hasFocus);
ImageIcon imIc = getImageIconFromTreeNode(value) ;
if (imIc!= null)
setIcon(imIc);
//CustomTreeNode node = (CustomTreeNode)value;
return this;
}}
/**
* Μέθοδος που επιστρέφει το κατάλληλο εικονίδιο με βάση το είδος του "φύλλου" .
* @param value Ένα Default Object αντικείμενο που πρακτικά είναι ένα {@link CustomTreeNode}
* το οποίο θα ερευνηθεί και θα επιστραφεί η κατάλληλη εικόνα με βάση αυτού .
* @return Ένα ImageIcon - εικόνα το οποίο θα έχει το αντίστοιχο "φύλλο" του δέντρου.
*/
protected ImageIcon getImageIconFromTreeNode(Object value) {
CustomTreeNode node = (CustomTreeNode)value;
ImageIcon tmpImIc ;
if (node.getLevel()==0)
tmpImIc = Globals.imProcessor ;
else if (node.getLevel()==1)
tmpImIc = Globals.imController ;
else
tmpImIc = (hmUnitNodes.get(node)!=null) ? hmUnitNodes.get(node).getImIc(): null ;
return tmpImIc ;
}
/**
* Μέθοδος που με βάση όλες τις απαραίτητες πληροφορίες του {@link Device}
* κτίζεται και όλο το δέντρο πάνω στο αρχικό "φύλλο" κορυφής που παίρνει
* σαν παράμετρο . Δηλαδή πρακτικά κρεμιούνται όλοι οι ελεγκτές μαζί με τις
* μονάδες τους και τα υπόλοιπα βασικά στοιχεία της κάθε μονάδας(Value,Mode).
* @param top Το αρχικό "φύλλο" κορυφής στο οποίο θα κρεμαστούν όλες οι
* υπόλοιπες βασικές πληροφορίες της συσκευής με μορφή δέντρου .
*/
private void createNodes(CustomTreeNode top) {
CustomTreeNode nodController,typeNode ;
String keyCon ;
Iterator<String> keyIterUnit ;
Iterator<String> keyIterCon = allUnits.keySet().iterator();
int conCount = 0;
int unitCount ;
while(keyIterCon.hasNext())
{
keyCon = keyIterCon.next() ;
nodController = new CustomTreeNode("["+conCount+"]"+keyCon) ;
nodController.setName(keyCon);
nodController.setID("["+conCount+"]");
top.add(nodController);
unitCount = 0 ;
for (Integer i = 0 ;i<sumOfDifferentsTypes;i++)
{
keyIterUnit = allUnits.get(keyCon).keySet().iterator() ;
typeNode = createSomeCateroryNodes(i.toString(),keyCon,keyIterUnit,conCount,unitCount) ;
if (typeNode!=null)
{
unitCount+=typeNode.getChildCount() ;
nodController.add(typeNode);
}
}
conCount++ ;
}
}
/**
* Μέθοδος που μέσω αυτής μπορούμε να έχουμε τις μονάδες που έχουν ίδιο τύπο
* σε ένα ελεγκτή όλες μαζί σαν ομάδα κάτω από ένα "φύλλο" "τύπου μονάδας" .
* Επίσης μέσα από αυτή τη μέθοδο παίρνουν οι μονάδες το αναγνωριστικό ID
* συστήματος που τους δίνει ο User Client .
* @param type Λεκτικό για τον τύπο (Πρακτικά είναι ένας αριθμός)
* @param keyCon Λεκτικό του ελεγκτή
* @param keyIterUnit Ένας iterator για το
* @param conCount Αριθμός σειράς του ελεγκτή μέσα στη συσκευή.
* @param unitCount Αριθμός σειράς της μονάδας μέσα στον ελεγκτή
* @return Ένα {@link CustomTreeNode} "τύπου μονάδας" στο οποίο από "κάτω"
* θα βρίσκονται ομαδοποιημένα όλες οι μονάδες του ίδιου τύπου στον ίδιο ελεγκτή.
*/
private CustomTreeNode createSomeCateroryNodes(String type,String keyCon,Iterator<String> keyIterUnit,int conCount,int unitCount)
{
CustomTreeNode typeNode = new CustomTreeNode() ;
CustomTreeNode nodUnit ;
String sysID ;
String keyUnit ;
int count = 0 ;
while(keyIterUnit.hasNext())
{
keyUnit = keyIterUnit.next() ;
if (allUnits.get(keyCon).get(keyUnit).getType().equals(type))
{
sysID = conCount+"/"+unitCount ;
nodUnit = new CustomTreeNode("["+sysID+"]"+keyUnit) ;
nodUnit.setName(keyUnit);
unitCount++ ;
allUnits.get(keyCon).get(keyUnit).setFullID(sysID);
nodUnit.add(allUnits.get(keyCon).get(keyUnit).getNodValue());
nodUnit.add(allUnits.get(keyCon).get(keyUnit).getNodMode());
typeNode.add(nodUnit) ;
String unType = allUnits.get(keyCon).get(keyUnit).getType() ;
//System.out.println(unType);
ImageIcon imIc = Globals.hmUnitImages.get("1"+unType.toString()) ;
if (imIc==null)
imIc = Globals.hmUnitImages.get("0"+unType.toString()) ;
allUnits.get(keyCon).get(keyUnit).setImIc(imIc) ;
hmUnitNodes.put(nodUnit, allUnits.get(keyCon).get(keyUnit)) ;
count++ ;
}
}
typeNode.setUserObject(Globals.namesOfTypes[Integer.parseInt(type)] + "("+count+")" );
if (typeNode.getChildCount()>0)
return typeNode ;
else
return null ;
}
/**
* Μέθοδος που όταν εκτελεστεί φέρνει όλα τα {@link UnitControl} μέσα στο
* οπτικό πεδίο του χρήστη .
* Μπορεί λόγου χάρη μετά από κάποιο resize του παραθύρου του UserClient
* να μην "βλέπει" ο χρήστης κάποια εικονίδια των μονάδων , οπότε με
* αυτή την μέθοδο εισέρχονται όλες οι μονάδες μέσα στο χώρο που βλέπει
* ο χρήστης .
*/
public void fixUnitControlToResize()
{
for (UnitControl uc : allControls)
uc.fixToResize() ;
}
public void fillUnitControls(BackgroundPanel bp, Insets insets)
{
//saveSettings = true ;
backPanel = bp ;
for (UnitControl uc : allControls)
{
Dimension size = uc.getPreferredSize();
uc.setBounds(insets.left,insets.top, size.width, size.height);
uc.setBackPanel(bp);
}
this.readXML() ;
}
/**
* Απλοί μέθοδος που επιστρέφει μια λίστα με όλα τα {@link UnitControl}
* της εκάστοτε συσκευής .
* @return Επιστρέφει μια λίστα με όλα τα {@link UnitControl} αυτής της συσκευής
*/
public ArrayList<UnitControl> getAllControls() {
return allControls;
}
/**
* Μέθοδος που με βάση μια λίστα από μηνύματα πρωτοκόλλου γίνεται η προετοιμασία
* της συσκευής μας και ουσιαστικά γεμίζει με περιεχόμενο το Device μας .
* @param newControllers Μια λίστα με συμβολοσειρές με μηνύματα πρωτοκόλλου
* που ουσιαστικά προσθέτουν στο Device μας ελεγκτές μαζί με τις μονάδες τους .
*/
public void prepareDevice(ArrayList<String> newControllers)
{
sumOfControllers = newControllers.size() ;
allUnits.clear();
String conName,unitName,unitType,unitValue ;
String unitMode;
String unitLimit;
String unitMax ;
String unitMin;
String unitTag ;
String sysID ;
int conCount = 0 ;
HashMap<String, Unit> hmUnits ;
for (String mess : newControllers)
{
msm.reload(mess);
conName = msm.getParameters().get(0).get(0) ;
hmUnits = new HashMap<>() ;
Tools.Debug.print(msm.getMessage()) ;
for (int i = 1 ; i<msm.getParameters().size();i++)
{
unitName = msm.getParameters().get(i).get(0) ;
unitType = msm.getParameters().get(i).get(1) ;
unitMode = msm.getParameters().get(i).get(2) ;
unitTag = msm.getParameters().get(i).get(3) ;
if (msm.getParameters().get(i).size()>2)
unitValue = msm.getParameters().get(i).get(4) ;
else
unitValue = "0" ;
unitMax = msm.getParameters().get(i).get(5) ;
unitMin = msm.getParameters().get(i).get(6) ;
unitLimit = msm.getParameters().get(i).get(7) ;
sysID = conCount +"/" +(i-1) ;
Unit newUnit = new Unit(this,conName,unitName,unitType,unitValue,unitMode,unitLimit,unitMax,unitMin,unitTag,sysID) ;
hmUnits.put(unitName, newUnit) ;
}
allUnits.put(conName,hmUnits) ;
conCount++ ;
}
}
/**
* Μέθοδος που απλά προσθέτει έναν νέο ελεγκτή στη συσκευή μας .
* @param newController Συμβολοσειρά που έχει μορφή μηνύματος πρωτοκόλλου .
* @return Μια συμβολοσειρά με το όνομα του Ελεγκτή .
*/
public String addController(String newController)
{
//sumOfControllers = newControllers.size() ;
//allUnits.clear();
String conName,unitName,unitType,unitValue ;
String unitMode;
String unitLimit;
String unitMax ;
String unitMin;
String unitTag ;
String sysID ;
int conCount = 0 ;
HashMap<String, Unit> hmUnits ;
msm.reload(newController);
conName = msm.getParameters().get(0).get(0) ;
hmUnits = new HashMap<>() ;
Tools.Debug.print(msm.getMessage()) ;
for (int i = 1 ; i<msm.getParameters().size();i++)
{
unitName = msm.getParameters().get(i).get(0) ;
unitType = msm.getParameters().get(i).get(1) ;
unitMode = msm.getParameters().get(i).get(2) ;
unitTag = msm.getParameters().get(i).get(3) ;
if (msm.getParameters().get(i).size()>2)
unitValue = msm.getParameters().get(i).get(4) ;
else
unitValue = "0" ;
unitMax = msm.getParameters().get(i).get(5) ;
unitMin = msm.getParameters().get(i).get(6) ;
unitLimit = msm.getParameters().get(i).get(7) ;
sysID = conCount +"/" +(i-1) ;
Unit newUnit = new Unit(this,conName,unitName,unitType,unitValue,unitMode,unitLimit,unitMax,unitMin,unitTag,sysID) ;
hmUnits.put(unitName, newUnit) ;
}
allUnits.put(conName,hmUnits) ;
conCount++ ;
JTree tree = this.getTree(true) ;
myPTab.scpDevTree.getViewport().removeAll();
myPTab.scpDevTree.getViewport().add(tree) ;
expandAll(tree) ;
Tools.Debug.print("Connect SuccessFully!");
BackgroundPanel bp = new BackgroundPanel(this) ;
bp.setLayout(null);
myPTab.scpScreen.getViewport().removeAll();
myPTab.scpScreen.getViewport().add(bp) ;
bp.setVisible(true);
Insets insets = bp.getInsets();
for (UnitControl uc : this.getAllControls())
{
uc.setVisible(true);
bp.add(uc) ;
}
this.fillUnitControls(bp,insets) ;
this.setPTab(myPTab) ;
this.clearSelection();
// myPTab.stopMonitoring(true);
// myPTab.startMonitoring();
return conName ;
}
/**
* Μέθοδος που απλά διαγράφει έναν ελεγκτή από τη συσκευή μας .
* @param msm Συμβολοσειρά που έχει μορφή μηνύματος πρωτοκόλλου .
*/
public void deleteController(ManageSocketMessage msm)
{
if (msm!=null)
if (msm.getCommand().equals("DeleteController"))
{
if (msm.getParameters().size()>0)
{
String conName = msm.getParameters().get(0).get(0) ;
Iterator<String> keyIterUnit = allUnits.get(conName).keySet().iterator();
String keyUnit;
while(keyIterUnit.hasNext())
{
keyUnit = keyIterUnit.next() ;
allControls.remove(allUnits.get(conName).get(keyUnit).getUc()) ;
}
allUnits.get(conName).clear();
allUnits.remove(conName) ;
}
JTree tree = this.getTree(true) ;
myPTab.scpDevTree.getViewport().removeAll();
myPTab.scpDevTree.getViewport().add(tree) ;
expandAll(tree) ;
Tools.Debug.print("Connect SuccessFully!");
BackgroundPanel bp = new BackgroundPanel(this) ;
bp.setLayout(null);
myPTab.scpScreen.getViewport().removeAll();
myPTab.scpScreen.getViewport().add(bp) ;
bp.setVisible(true);
Insets insets = bp.getInsets();
for (UnitControl uc : this.getAllControls())
{
uc.setVisible(true);
bp.add(uc) ;
}
this.fillUnitControls(bp,insets) ;
this.setPTab(myPTab) ;
this.clearSelection();
}
}
/**
* Μέθοδος που με βάση ένα μήνυμα πρωτοκόλλου (που μεταφέρετε μέσα από socket δηλαδή)
* αλλάζει στοχευμένα το value σε ένα ή περισσότερα Unit της συσκευής .
* @param valuesOfMessage Συμβολοσειρά που έχει μορφή μηνύματος πρωτοκόλλου .
*/
public void setValuesOfDevice(String valuesOfMessage)
{
String conName,unitName,unitValue ;
msm.reload(valuesOfMessage);
for (int i = 0 ; i<msm.getParameters().size();i++)
{
conName = msm.getParameters().get(i).get(0) ;
unitName = msm.getParameters().get(i).get(1) ;
unitValue = msm.getParameters().get(i).get(2) ;
allUnits.get(conName).get(unitName).setValue(unitValue);
}
}
/**
* Μέθοδος που με βάση ένα μήνυμα πρωτοκόλλου (που μεταφέρετε μέσα από socket δηλαδή)
* αλλάζει στοχευμένα το Mode σε ένα ή περισσότερα Unit της συσκευής .
* @param modesOfMessage Συμβολοσειρά που έχει μορφή μηνύματος πρωτοκόλλου .
*/
public void setModesOfDevice(String modesOfMessage)
{
String conName,unitName,modeValue ;
msm.reload(modesOfMessage);
for (int i = 0 ; i<msm.getParameters().size();i++)
{
conName = msm.getParameters().get(i).get(0) ;
unitName = msm.getParameters().get(i).get(1) ;
modeValue = msm.getParameters().get(i).get(2) ;
allUnits.get(conName).get(unitName).setMode(modeValue);
}
}
/**
* Μέθοδος που αναλαμβάνει να αποθηκεύσει όλες τις απαραίτητες πληροφορίες
* ρυθμίσεων για την εκάστοτε συσκευή .
* Σκοπός της είναι να μπορεί κάποια άλλη χρονική στιγμή ο User Client να
* ανακτήσει όλες αυτές τις πληροφορίες και πιο συγκεκριμένα οι μονάδες
* και οι ελεγκτές να πάρουν τα description που έχει καταχωρήσει ο χρήστης.
* Επίσης να μπορούν να ανακτηθούν οι θέσεις πάνω στην οθόνη που βρίσκονται τώρα
* οι μονάδες όπως επίσης και το να είναι "κλειδωμένες" ή όχι ανάλογα με την
* τώρα κατάσταση ..
* Ακόμη θα μπορεί να ανακτηθεί το path της εικόνας και κατά επέκταση η ίδια η εικόνα για το
* background της συσκευής , αν έχει αλλάξει ο χρήστης την default .
* @throws java.io.FileNotFoundException Εξαίρεση που μπορεί να υπάρψει αν για κάποιο
* λόγο δεν μπορέσει να εγγραφεί το αρχείο στον δίσκο .
*/
public void saveToXML() throws FileNotFoundException {
if (!saveSettings)
{
File f = new File(Globals.runFolder.getAbsolutePath() + Globals.fSep+"Settings"+Globals.fSep+deviceName + "_" + Globals.username+".xml") ;
f.delete();
//System.out.println(f.toPath().toAbsolutePath());
return ;
}
Document dom;
Element controllers,unit,attribute,BackImPa,descriptionCon,descriptionsOfControllers,ConSystemID;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.newDocument();
Element rootEle = dom.createElement(deviceName);
BackImPa = dom.createElement("Settings");
unit = dom.createElement("BackgroundImagePath");
unit.appendChild(dom.createTextNode(getPathFile()));
BackImPa.appendChild(unit);
//System.out.println(getPathFile());
rootEle.appendChild(BackImPa);
///////////////////////////////////
descriptionsOfControllers = dom.createElement("descriptionsOfControllers");
for (int i = 0 ; i<tree.getRowCount();i++)
{
TreePath tpath = tree.getPathForRow(i) ;
CustomTreeNode ctn = (CustomTreeNode) tpath.getLastPathComponent() ;
if (ctn.getLevel() == 1)
{
if (!ctn.getUserObject().toString().equals(ctn.getName()))
{
ConSystemID = dom.createElement("ConSystemID");
ConSystemID.appendChild(dom.createTextNode(ctn.getName()));
descriptionsOfControllers.appendChild(ConSystemID);
descriptionCon = dom.createElement("ConDescription");
String desc = Tools.getOnlyDescriptionWithoutSysID(ctn.getUserObject().toString());
descriptionCon.appendChild(dom.createTextNode((desc.equals(ctn.getName())?"":desc)));
descriptionsOfControllers.appendChild(descriptionCon);
}
}
}
rootEle.appendChild(descriptionsOfControllers);
controllers = dom.createElement("Controllers");
for (UnitControl uc : allControls)
{
unit = dom.createElement("Unit");
attribute = dom.createElement("ID");
attribute.appendChild(dom.createTextNode(uc.getUnit().fullID));
unit.appendChild(attribute);
attribute = dom.createElement("Description");
attribute.appendChild(dom.createTextNode((uc.getUnit().getDescription().equals(uc.getUnit().getName())?"":uc.getUnit().getDescription())));
unit.appendChild(attribute);
attribute = dom.createElement("Locked");
attribute.appendChild(dom.createTextNode(String.valueOf(uc.locked)));
unit.appendChild(attribute);
attribute = dom.createElement("LocationX");
attribute.appendChild(dom.createTextNode(String.valueOf(uc.getLocation().x)));
unit.appendChild(attribute);
attribute = dom.createElement("LocationY");
attribute.appendChild(dom.createTextNode(String.valueOf(uc.getLocation().y)));
unit.appendChild(attribute);
controllers.appendChild(unit);
}
rootEle.appendChild(controllers);
dom.appendChild(rootEle);
try {
Transformer tr = TransformerFactory.newInstance().newTransformer();
tr.setOutputProperty(OutputKeys.INDENT, "yes");
tr.setOutputProperty(OutputKeys.METHOD, "xml");
tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
tr.transform(new DOMSource(dom),
new StreamResult(new FileOutputStream(Globals.runFolder.getAbsolutePath() + Globals.fSep+"Settings"+ Globals.fSep +deviceName + "_" + Globals.username+".xml")));
} catch (TransformerException te) {
Tools.Debug.print(te.getMessage());
}
} catch (ParserConfigurationException pce) {
Tools.Debug.print("UsersXML: Error trying to instantiate DocumentBuilder " + pce);
}
}
/**
* Μέθοδος που αναλαμβάνει να διαβάσει όλες τις απαραίτητες πληροφορίες
* από ένα αρχείο xml (Της κατάλληλης μορφής βέβαια) για την συγκεκριμένη συσκευή
* εφόσον βέβαια υπάρχει κάποιο αρχείο "ρυθμίσεων" στον δίσκο από παλαιότερη χρήση
* του User Client και της ίδιας συσκευής.
* Σκοπός της είναι να αξιοποιηθούν όλα αυτά τα δεδομένα , δηλαδή οι μονάδες
* και οι ελεγκτές να πάρουν τα description που είχε καταχωρήσει ο χρήστης όταν
* έκλεισε για τελευταία φορά το User Client .
* Επίσης ανακτούνται οι θέσεις πάνω στην οθόνη που βρισκόντουσαν οι μονάδες
* όπως επίσης και το αν ήταν "κλειδωμένες" ή όχι .
* Ακόμη ανακτάται το path της εικόνας και κατά επέκταση η ίδια η εικόνα για το
* background της συσκευής , αν είχε αλλάξει ο χρήστης την default .
* @return Επιστρέφει True αν όλα πήγαν καλά και False αν κάτι δεν πήγα .
*/
public boolean readXML() {
String lock ,x,y ,desc;
Document dom;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
dom = db.parse(Globals.runFolder.getAbsolutePath() + Globals.fSep+"Settings"+Globals.fSep+deviceName + "_" + Globals.username+".xml");
Element doc = dom.getDocumentElement();
setPathFile(Globals.getTextValue(doc, "BackgroundImagePath", 0)) ;
int conCounter = 0 ;
for (int i = 0 ; i<tree.getRowCount();i++)
{
TreePath tpath = tree.getPathForRow(i) ;
CustomTreeNode ctn = (CustomTreeNode) tpath.getLastPathComponent() ;
if (ctn.getLevel() == 1)
{
if (ctn.getName() == null ? Globals.getTextValue(doc, "ConSystemID", conCounter) == null : ctn.getName().equals(Globals.getTextValue(doc, "ConSystemID", conCounter)))
{
desc = Globals.getTextValue(doc, "ConDescription", conCounter);
if (desc!=null && !desc.equals("") && !desc.equals(ctn.getName()))
ctn.setUserObject(ctn.getID() + desc);
((DefaultTreeModel)tree.getModel()).reload(ctn);
ManageUserClient.expandAll(tree,Tools.getPath(ctn));
conCounter ++ ;
}
}
}
int i = 0 ;
for (UnitControl uc : allControls)
{
desc = Globals.getTextValue( doc, "Description",i);
x = Globals.getTextValue( doc, "LocationX",i);
y = Globals.getTextValue( doc, "LocationY",i);
lock = Globals.getTextValue( doc, "Locked",i++);
if (desc!=null && !desc.equals("") && !desc.equals(uc.getUnit().getName()))
uc.getUnit().setDescription(desc,true);
if (lock!=null)
uc.setLocked(Boolean.parseBoolean(lock));
if ((x!=null)&& (y!=null))
uc.setLocation(Integer.parseInt(x),Integer.parseInt(y));
}
return true;
} catch (ParserConfigurationException | SAXException pce) {
Tools.Debug.print(pce.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
return false;
}
/**
* Κλάση που έχει όλη την πληροφορία για μια μονάδα μας .
*/
public class Unit
{
private CustomTreeNode nodValue,nodMode ;
private String name ;
private String myType ;
private String value ;
private String fullID ;
private String mode ;
public String limit ;
public String tag ;
public double max,min ;
private String controller ;
private UnitControl uc ;
public ImageIcon imIc ;
public Device device ;
private String description = "";
/**
* Κατασκευαστής που αρχικοποιεί πλήρως την μονάδα .
* @param d Device στο οποίο ανήκει η μονάδα .
* @param c Ελεγκτής στον οποίο ανήκει η μονάδα
* @param n Όνομα της μονάδας
* @param t Τύπος της μονάδας
* @param v Τιμή της μονάδας
* @param mo "Τρόπος λειτουργίας" της μονάδας
* @param l Το όριο που έχει η μονάδα
* @param ma Την μέγιστη τιμή που μπορεί να πάρει η μονάδα
* @param mi Την μικρότερη τιμή που μπορεί να πάρει η μονάδα
* @param ta Μια ετικέτα που μπορεί να έχει η μονάδα (Για μελλοντική χρήση)
* @param fID Το πλήρες ID που έχει η μονάδα .
*/
public Unit(Device d,String c,String n,String t,String v,String mo,String l,String ma,String mi,String ta,String fID) {
device = d ;
name = n ;
myType = t ;
value = v ;
controller = c ;
nodValue = new CustomTreeNode("Value : " + v) ;
mode =mo;
switch(mode)
{
case "2":
nodMode = new CustomTreeNode("Mode : Both") ;
break ;
case "0" :
case "3" :
nodMode = new CustomTreeNode("Mode : Auto") ;
break ;
case "1" :
case "4" :
nodMode = new CustomTreeNode("Mode : Remote") ;
break ;
default :
nodMode = new CustomTreeNode("Mode : Both") ;
}
fullID = fID ;//ELT.getOnlyDBID(c) +"/" +Tools.getOnlyDBID(n) ;
limit = l ;
tag =ta;
max= (Tools.isNumeric(ma))?Double.parseDouble(ma):255 ;
min =(Tools.isNumeric(mi))?Double.parseDouble(mi):0 ;
uc = new UnitControl(this) ;
setDescription(name) ;
allControls.add(uc) ;
}
/**
* Μέθοδος που αλλάζει το description της κλάσης (Μονάδας) όπως επίσης
* και το description του αντίστοιχου {@link UnitControl} της ίδιας μονάδας.
* @param description Το λεκτικό για το νέο description.
*/
public void setDescription(String description) {
setDescription(description,false);
}
public void setDescription(String description,boolean andNode) {
this.description = description;
uc.setDescription(description);
if (andNode)
{
((CustomTreeNode)nodValue.getParent()).setUserObject("["+fullID+"]"+description);
treeModel.reload((CustomTreeNode)nodValue.getParent());
}
}
/**
* Ενημέρωση κάποιων βασικών στοιχείων της κλάσης , δηλαδή του name,type και
* value της μονάδας .
* @param n Το λεκτικό του ονόματος
* @param t Το λεκτικό του τύπου (πρακτικά αν και συμβολοσειρά πρέπει να είναι αριθμός)
* @param v Το λεκτικό της τιμής (πρακτικά αν και συμβολοσειρά πρέπει να είναι αριθμός)
*/
public void setUnit(String n,String t,String v)
{
if (name!=null)
{
name = n ;
uc.setName(value) ;
}
if (myType!=null)
{
myType = t ;
uc.setType(value) ;
}
if (value!=null)
{
value = v.trim().toString() ;
if (nodValue!=null)
{
nodValue.setUserObject("Value : " + value);
uc.setValue(value) ;
treeModel.reload(nodValue);
}
}
}
/**
* Καταχωρείτε το νέο mode τόσο στο αντικείμενο της κλάσης {@link Unit} όσο
* και στο αντίστοιχο "φύλλο" του δέντρου της συσκευής
* αλλά και στο ανάλογο {@link UnitControl} της ίδιας μονάδας .
* @param mode Το νέο mode που θα καταχωρηθεί .
*/
public void setMode(String mode) {
this.mode = mode.trim();
uc.setMode((Tools.isNumeric(this.mode)?Integer.parseInt(this.mode):0)) ;
switch(mode)
{
case "2":
nodMode.setUserObject("Mode : Both");
break ;
case "0" :
case "3" :
nodMode.setUserObject("Mode : Auto");
break ;
case "1" :
case "4" :
nodMode.setUserObject("Mode : Remote");
break ;
default :
nodMode.setUserObject("Mode : Both");
}
treeModel.reload(nodMode);
}
/**
* Καταχωρείτε μια νέα τιμή τόσο στο αντικείμενο της κλάσης {@link Unit} όσο
* και στο αντίστοιχο "φύλλο" του δέντρου της συσκευής
* αλλά και στο ανάλογο {@link UnitControl} της ίδιας μονάδας .
* @param value Η νέα τιμή που θα καταχωρηθεί .
*/
public void setValue(String value) {
this.value = value.trim();
if (nodValue!=null)
{
nodValue.setUserObject("Value : " + value.trim());
uc.setValue(value.trim()) ;
treeModel.reload(nodValue);
}
}
/**
* Επιλέγετε (Selected) το αντίστοιχο "φύλλο" της μονάδας που βρίσκεται στο δέντρο .
*/
public void setSelectedNode()
{
TreePath tp = Tools.getPath(nodValue.getParent()) ;
tree.setSelectionPath(tp) ;
tree.scrollPathToVisible(tp);
}
/**
* Καταχωρείτε το πλήρες ID μιας μονάδας στην μεταβλητή του αντικειμένου
* αλλά και στο αντίστοιχο αντικείμενο του {@link UnitControl} της ίδιας μονάδας.
* @param fullID Το πλήρες Id μιας μονάδας .
*/
public void setFullID(String fullID) {
this.fullID = fullID;
uc.setID(fullID) ;
}
//Απλοί set μεθόδοι : - Αρχή:
public void setImIc(ImageIcon imIc) {
this.imIc = imIc;
}
//Απλοί set μεθόδοι : - Τέλος:
//Απλοί get μεθόδοι : - Αρχή:
public UnitControl getUc() {
return uc;
}
public String getDescription() {
return description;
}
public ImageIcon getImIc() {
return imIc;
}
public CustomTreeNode getNodMode() {
return nodMode;
}
public CustomTreeNode getNodValue() {
return nodValue;
}
public String getFullID() {
return fullID;
}
public String getMode() {
return mode;
}
public String getType() {
return myType;
}
public String getName() {
return name;
}
public String getFullValue()
{
return "("+controller+"|"+name+"|"+value+")" ;
}
public String getFullMode()
{
return "("+controller+"|"+name+"|"+mode+")" ;
}
public String getValue() {
return value;
}
public String getUnit()
{
return "("+name+"|"+myType+")" ;
}
//Απλοί get μεθόδοι : - Τέλος:
@Override
public String toString() {
return "("+name+"|"+myType+"|"+value+")" ;
}
}
/**
* Δικό μας custom TreeNode που έχει κληρονομήσει το DefaultMutableTreeNode.
* Ουσιαστικά φτιάχτηκε για να μπορούμε μέσα σε ένα "φύλλο" του δέντρου να
* έχουμε εκτός από το λεκτικό του , που έχει σαν τίτλο, και κάποιο Name.
* Και όλο αυτό για να μπορούμε σε επόμενη φάση , να αλλάζει ο εκάστοτε χρήστης
* το λεκτικό - description του "φύλλου" αλλά όμως να συνεχίζουμε να ξέρουμε το αρχικό Name που είχε .
*/
class CustomTreeNode extends DefaultMutableTreeNode
{
String name;
String ID ;
/**
* Κατασκευαστής που αρχικοποιεί κατάλληλα το "φύλλο" μας όπως επίσης
* δίνει αρχική τιμή στο name μας με βάση αυτό που έχει στην παράμετρο.
* @param name Το λεκτικό που θα έχει το "φύλλο" αλλά και η μεταβλητή name μας.
*/
public CustomTreeNode(String name) {
super(name) ;
this.name = name ;
}
/**
* Default κατασκευαστής
*/
public CustomTreeNode() {
super() ;
}
//Απλοί set μεθόδοι : - Αρχή:
public void setID(String ID) {
this.ID = ID;
}
public void setName(String name) {
this.name = name;
}
//Απλοί set μεθόδοι : - Τέλος:
//Απλοί get μεθόδοι : - Αρχή:
public String getID() {
return ID;
}
public String getName() {
return name;
}
//Απλοί get μεθόδοι : - Τέλος:
}
}
/*
* * * * * * * * * * * * * * * * * * * * * * *
* + + + + + + + + + + + + + + + + + + + + + *
* +- - - - - - - - - - - - - - - - - - - -+ *
* +| 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/Device.java |
1,800 | /*
* Copyright (c) 2022 Eben Howard, Tommy Ettinger, and contributors
*
* 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 squidpony;
import regexodus.MatchResult;
import regexodus.Matcher;
import regexodus.Pattern;
import regexodus.REFlags;
import regexodus.Replacer;
import squidpony.squidmath.CrossHash;
import squidpony.squidmath.GWTRNG;
import squidpony.squidmath.Hashers;
import squidpony.squidmath.IRNG;
import squidpony.squidmath.IStatefulRNG;
import squidpony.squidmath.NumberTools;
import squidpony.squidmath.OrderedMap;
import squidpony.squidmath.OrderedSet;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* A text generator for producing sentences and/or words in nonsense languages that fit a theme. This does not use an
* existing word list as a basis for its output, so it may or may not produce existing words occasionally, but you can
* safely assume it won't generate a meaningful sentence except in the absolute unlikeliest of cases.
* <br>
* This supports a lot of language styles in predefined constants. There's a registry of these constants in
* {@link #registered} and their names in {@link #registeredNames}, plus the languages that would make sense for
* real-world cultures to use (and all use the Latin alphabet, so they can be swapped around) are in
* {@link #romanizedHumanLanguages}. You can make a new language with a constructor, but it's pretty time-consuming; the
* recommended ways are generating a random language with {@link #randomLanguage(long)} (when you don't care too much
* about exactly how it should sound), or blending two or more languages with {@link #mixAll(Object...)} or
* {@link #mix(double, FakeLanguageGen, double, Object...)} (when you have a sound in mind that isn't quite met by an
* existing language).
* <br>
* Created by Tommy Ettinger on 11/29/2015.
* @see NaturalLanguageCipher NaturalLanguageCipher uses a FakeLanguageGen to reversibly translate English text to nonsense.
* @see Thesaurus Thesaurus uses this class a lot to generate things like plant names and the titles of nations.
*/
public class FakeLanguageGen implements Serializable {
private static final long serialVersionUID = -2396642435461186352L;
public final String[] openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants,
vowelSplitters, closingSyllables;
public final boolean clean;
public final double[] syllableFrequencies;
protected final double totalSyllableFrequency;
public final double syllableBias;
public final double vowelStartFrequency, vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency;
public final Pattern[] sanityChecks;
public final ArrayList<Modifier> modifiers;
public static final GWTRNG srng = new GWTRNG();
private static final OrderedMap<String, FakeLanguageGen> registry = new OrderedMap<>(64, Hashers.caseInsensitiveStringHasher);
protected String summary;
protected String name = "Nameless Language";
private static final StringBuilder sb = new StringBuilder(20);
private static final StringBuilder ender = new StringBuilder(12);
private static final StringBuilder ssb = new StringBuilder(80);
/**
* A pattern String that will match any vowel FakeLanguageGen can produce out-of-the-box, including Latin, Greek,
* and Cyrillic; for use when a String will be interpreted as a regex (as in {@link FakeLanguageGen.Alteration}).
*/
public static final String anyVowel = "[àáâãäåæāăǎąǻǽaèéêëēĕėęěeìíîïĩīĭįǐıiòóôõöøōŏőǒœǿoùúûüũūŭůǔűųuýÿŷỳyαοειυωаеёийоуъыэюя]",
/**
* A pattern String that will match one or more of any vowels FakeLanguageGen can produce out-of-the-box, including
* Latin, Greek, and Cyrillic; for use when a String will be interpreted as a regex (as in
* {@link FakeLanguageGen.Alteration}).
*/
anyVowelCluster = anyVowel + '+',
/**
* A pattern String that will match any consonant FakeLanguageGen can produce out-of-the-box, including Latin,
* Greek, and Cyrillic; for use when a String will be interpreted as a regex (as in
* {@link FakeLanguageGen.Alteration}).
*/
anyConsonant = "[bcçćĉċčdþðďđfgĝğġģhĥħjĵȷkķlĺļľŀłmnñńņňŋpqrŕŗřsśŝşšștţťțvwŵẁẃẅxyýÿŷỳzźżžρσζτκχνθμπψβλγφξςбвгдклпрстфхцжмнзчшщ]",
/**
* A pattern String that will match one or more of any consonants FakeLanguageGen can produce out-of-the-box,
* including Latin, Greek, and Cyrillic; for use when a String will be interpreted as a regex (as in
* {@link FakeLanguageGen.Alteration}).
*/
anyConsonantCluster = anyConsonant + '+';
protected static final Pattern repeats = Pattern.compile("(.)\\1+");
protected static final Pattern vowelClusters = Pattern.compile(anyVowelCluster, REFlags.IGNORE_CASE | REFlags.UNICODE);
//latin
//àáâãäåæāăąǻǽaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőœǿoùúûüũūŭůűųuýÿŷỳybcçćĉċčdþðďđfgĝğġģhĥħjĵȷkķlĺļľŀłmnñńņňŋpqrŕŗřsśŝşšștţťțvwŵẁẃẅxyýÿŷỳzźżž
//ÀÁÂÃÄÅÆĀĂĄǺǼAÈÉÊËĒĔĖĘĚEÌÍÎÏĨĪĬĮIIÒÓÔÕÖØŌŎŐŒǾOÙÚÛÜŨŪŬŮŰŲUÝŸŶỲYBCÇĆĈĊČDÞÐĎĐFGĜĞĠĢHĤĦJĴȷKĶLĹĻĽĿŁMNÑŃŅŇŊPQRŔŖŘSŚŜŞŠȘTŢŤȚVWŴẀẂẄXYÝŸŶỲZŹŻŽṚṜḶḸḌṬṄṆṢṂḤ
//greek
//αοειυρσζτκχνθμπψβλγφξς
//ΑΟΕΙΥΡΣΖΤΚΧΝΘΜΠΨΒΛΓΦΞ
//cyrillic
//аеёийоуъыэюябвгдклпрстфхцжмнзчшщ
//АЕЁИЙОУЪЫЭЮЯБВГДКЛПРСТФХЦЖМНЗЧШЩ
private static final Pattern[]
vulgarChecks = new Pattern[]
{
//17 is REFlags.UNICODE | REFlags.IGNORE_CASE
Pattern.compile("[sξζzkкκcсς][hнlι].{1,3}[dtтτΓг]", 17),
Pattern.compile("(?:(?:[pрρ][hн])|[fd]).{1,3}[kкκcсςxхжχq]", 17), // lots of these end in a 'k' sound, huh
Pattern.compile("[kкκcсςСQq][uμυνvhн]{1,3}[kкκcсςxхжχqmм]", 17),
Pattern.compile("[bъыбвβЪЫБ].?[iτιyуλγУ].?[cсς]", 17),
Pattern.compile("[hн][^aаαΛeезξεЗΣiτιyуλγУ][^aаαΛeезξεЗΣiτιyуλγУ]?[rяΓ]", 17),
Pattern.compile("[tтτΓгcсς][iτιyуλγУ][tтτΓг]+$", 17),
Pattern.compile("(?:(?:[pрρ][hн])|f)[aаαΛhн]{1,}[rяΓ][tтτΓг]", 17),
Pattern.compile("[Ssξζzcсς][hн][iτιyуλγУ].?[sξζzcсς]", 17),
Pattern.compile("[aаαΛ][nи][aаαΛeезξεЗΣiτιyуλγУoоюσοuμυνv]{1,2}[Ssξlιζz]", 17),
Pattern.compile("[aаαΛ]([sξζz]{2})", 17),
Pattern.compile("[kкκcсςСQq][hн]?[uμυνv]([hн]?)[nи]+[tтτΓг]", 17),
Pattern.compile("[nиfvν]..?[jg]", 17), // might as well remove two possible slurs and a body part with one check
Pattern.compile("[pрρ](?:(?:([eезξεЗΣoоюσοuμυνv])\\1)|(?:[eезξεЗΣiτιyуλγУuμυνv]+[sξζz]))", 17), // the grab bag of juvenile words
Pattern.compile("[mм][hнwψшщ]?..?[rяΓ].?d", 17), // should pick up the #1 obscenity from Spanish and French
Pattern.compile("[g][hн]?[aаαАΑΛeеёзξεЕЁЗΕΣ][yуλγУeеёзξεЕЁЗΕΣ]", 17), // could be inappropriate for random text
Pattern.compile("[wψшщuμυνv](?:[hн]?)[aаαΛeеёзξεЗΕΣoоюσοuμυνv](?:[nи]+)[gkкκcсςxхжχq]", 17)
},
genericSanityChecks = new Pattern[]
{
Pattern.compile("[AEIOUaeiou]{3}"),
Pattern.compile("(\\p{L})\\1\\1"),
Pattern.compile("[Ii][iyq]"),
Pattern.compile("[Yy]([aiu])\\1"),
Pattern.compile("[Rr][uy]+[rh]"),
Pattern.compile("[Qq]u[yu]"),
Pattern.compile("[^oaei]uch"),
Pattern.compile("[Hh][tcszi]?h"),
Pattern.compile("[Tt]t[^aeiouy]{2}"),
Pattern.compile("[Yy]h([^aeiouy]|$)"),
Pattern.compile("([xqy])\\1$"),
Pattern.compile("[qi]y$"),
Pattern.compile("[szSZrlRL]+?[^aeiouytdfgkcpbmnslrv][rlsz]"),
Pattern.compile("[UIuiYy][wy]"),
Pattern.compile("^[UIui]e"),
Pattern.compile("^([^aeioyl])\\1", 17)
},
englishSanityChecks = new Pattern[]
{
Pattern.compile("[AEIOUaeiou]{3}"),
Pattern.compile("(\\w)\\1\\1"),
Pattern.compile("(.)\\1(.)\\2"),
Pattern.compile("[Aa][ae]"),
Pattern.compile("[Uu][umlkj]"),
Pattern.compile("[Ii][iyqkhrl]"),
Pattern.compile("[Oo][c]"),
Pattern.compile("[Yy]([aiu])\\1"),
Pattern.compile("[Rr][aeiouy]+[rh]"),
Pattern.compile("[Qq]u[yu]"),
Pattern.compile("[^oaei]uch"),
Pattern.compile("[Hh][tcszi]?h"),
Pattern.compile("[Tt]t[^aeiouy]{2}"),
Pattern.compile("[Yy]h([^aeiouy]|$)"),
Pattern.compile("[szSZrlRL]+?[^aeiouytdfgkcpbmnslr][rlsz]"),
Pattern.compile("[UIuiYy][wy]"),
Pattern.compile("^[UIui][ae]"),
Pattern.compile("q(?:u?)$")
},
japaneseSanityChecks = new Pattern[]
{
Pattern.compile("[AEIOUaeiou]{3}"),
Pattern.compile("(\\w)\\1\\1"),
Pattern.compile("[Tt]s[^u]"),
Pattern.compile("[Ff][^u]"),
Pattern.compile("[Yy][^auo]"),
Pattern.compile("[Tt][ui]"),
Pattern.compile("[SsZzDd]i"),
Pattern.compile("[Hh]u"),
},
arabicSanityChecks = new Pattern[]
{
Pattern.compile("(.)\\1\\1"),
Pattern.compile("-[^aeiou](?:[^aeiou]|$)"),
};
private static final Replacer[]
accentFinders = new Replacer[]
{
Pattern.compile("[àáâäăāãåǎąǻ]").replacer("a"),
Pattern.compile("[èéêëĕēėęě]").replacer("e"),
Pattern.compile("[ìíîïĭīĩįǐı]").replacer("i"),
Pattern.compile("[òóôöŏōõøőǒǿ]").replacer("o"),
Pattern.compile("[ùúûüŭūũůűǔų]").replacer("u"),
Pattern.compile("[æǽ]").replacer("ae"),
Pattern.compile("œ").replacer("oe"),
Pattern.compile("[ÀÁÂÄĂĀÃÅǍĄǺ]").replacer("A"),
Pattern.compile("[ÈÉÊËĔĒĖĘĚ]").replacer("E"),
Pattern.compile("[ÌÍÎÏĬĪĨĮǏ]").replacer("I"),
Pattern.compile("[ÒÓÔÖŎŌÕØŐǑǾ]").replacer("O"),
Pattern.compile("[ÙÚÛÜŬŪŨŮŰǓŲ]").replacer("U"),
Pattern.compile("[ÆǼ]").replacer("Ae"),
Pattern.compile("Œ").replacer("Oe"),
Pattern.compile("Ё").replacer("Е"),
Pattern.compile("Й").replacer("И"),
Pattern.compile("[çćĉċč]").replacer("c"),
Pattern.compile("[þðďđ]").replacer("d"),
Pattern.compile("[ĝğġģ]").replacer("g"),
Pattern.compile("[ĥħ]").replacer("h"),
Pattern.compile("[ĵȷ]").replacer("j"),
Pattern.compile("ķ").replacer("k"),
Pattern.compile("[ĺļľŀłļ]").replacer("l"),
Pattern.compile("[ñńņňŋ]").replacer("n"),
Pattern.compile("[ŕŗřŗŕ]").replacer("r"),
Pattern.compile("[śŝşšș]").replacer("s"),
Pattern.compile("[ţťŧț]").replacer("t"),
Pattern.compile("[ŵẁẃẅ]").replacer("w"),
Pattern.compile("[ýÿŷỳ]").replacer("y"),
Pattern.compile("[źżž]").replacer("z"),
Pattern.compile("[ÇĆĈĊČ]").replacer("C"),
Pattern.compile("[ÞÐĎĐḌ]").replacer("D"),
Pattern.compile("[ĜĞĠĢ]").replacer("G"),
Pattern.compile("[ĤĦḤ]").replacer("H"),
Pattern.compile("Ĵ").replacer("J"),
Pattern.compile("Ķ").replacer("K"),
Pattern.compile("[ĹĻĽĿŁḶḸĻ]").replacer("L"),
Pattern.compile("Ṃ").replacer("M"),
Pattern.compile("[ÑŃŅŇŊṄṆ]").replacer("N"),
Pattern.compile("[ŔŖŘṚṜŖŔ]").replacer("R"),
Pattern.compile("[ŚŜŞŠȘṢ]").replacer("S"),
Pattern.compile("[ŢŤŦȚṬ]").replacer("T"),
Pattern.compile("[ŴẀẂẄ]").replacer("W"),
Pattern.compile("[ÝŸŶỲ]").replacer("Y"),
Pattern.compile("[ŹŻŽ]").replacer("Z"),
Pattern.compile("ё").replacer("е"),
Pattern.compile("й").replacer("и"),
};
static final char[][] accentedVowels = new char[][]{
new char[]{'a', 'à', 'á', 'â', 'ä', 'ā', 'ă', 'ã', 'å', 'ǎ', 'ą', 'ǻ'},
new char[]{'e', 'è', 'é', 'ê', 'ë', 'ē', 'ĕ', 'ė', 'ę', 'ě'},
new char[]{'i', 'ì', 'í', 'î', 'ï', 'ī', 'ĭ', 'ĩ', 'į', 'ǐ', 'ı'},
new char[]{'o', 'ò', 'ó', 'ô', 'ö', 'ō', 'ŏ', 'õ', 'ø', 'ǒ', 'ő', 'ǿ'},
new char[]{'u', 'ù', 'ú', 'û', 'ü', 'ū', 'ŭ', 'ũ', 'ů', 'ű', 'ǔ', 'ų'}
},
accentedConsonants = new char[][]
{
new char[]{
'b'
},
new char[]{
'c', 'ç', 'ć', 'ĉ', 'ċ', 'č',
},
new char[]{
'd', 'þ', 'ð', 'ď', 'đ',
},
new char[]{
'f'
},
new char[]{
'g', 'ĝ', 'ğ', 'ġ', 'ģ',
},
new char[]{
'h', 'ĥ', 'ħ',
},
new char[]{
'j', 'ĵ', 'ȷ',
},
new char[]{
'k', 'ķ',
},
new char[]{
'l', 'ĺ', 'ļ', 'ľ', 'ŀ', 'ł',
},
new char[]{
'm',
},
new char[]{
'n', 'ñ', 'ń', 'ņ', 'ň', 'ŋ',
},
new char[]{
'p',
},
new char[]{
'q',
},
new char[]{
'r', 'ŕ', 'ŗ', 'ř',
},
new char[]{
's', 'ś', 'ŝ', 'ş', 'š', 'ș',
},
new char[]{
't', 'ţ', 'ť', 'ț',
},
new char[]{
'v',
},
new char[]{
'w', 'ŵ', 'ẁ', 'ẃ', 'ẅ',
},
new char[]{
'x',
},
new char[]{
'y', 'ý', 'ÿ', 'ŷ', 'ỳ',
},
new char[]{
'z', 'ź', 'ż', 'ž',
},
};
private static final OrderedMap<String, String> openVowels,
openCons, midCons, closeCons;
static {
registry.put("", null);
openVowels = Maker.makeOM(
"a", "a aa ae ai au ea ia oa ua",
"e", "e ae ea ee ei eo eu ie ue",
"i", "i ai ei ia ie io iu oi ui",
"o", "o eo io oa oi oo ou",
"u", "u au eu iu ou ua ue ui");
openCons = Maker.makeOM(
"b", "b bl br by bw bh",
"bh", "bh",
"c", "c cl cr cz cth sc scl",
"ch", "ch ch chw",
"d", "d dr dz dy dw dh",
"dh", "dh",
"f", "f fl fr fy fw sf",
"g", "g gl gr gw gy gn",
"h", "bh cth ch ch chw dh h hm hy hw kh khl khw ph phl phr sh shl shqu shk shp shm shn shr shw shpl th th thr thl thw",
"j", "j j",
"k", "k kr kl ky kn sk skl shk",
"kh", "kh khl khw",
"l", "bl cl fl gl kl khl l pl phl scl skl spl sl shl shpl tl thl vl zl",
"m", "hm m mr mw my sm smr shm",
"n", "gn kn n nw ny pn sn shn",
"p", "p pl pr py pw pn sp spr spl shp shpl ph phl phr",
"ph", "ph phl phr",
"q", "q",
"qu", "qu squ shqu",
"r", "br cr dr fr gr kr mr pr phr r str spr smr shr tr thr vr wr zvr",
"s", "s sc scl sf sk skl st str sp spr spl sl sm smr sn sw sy squ ts sh shl shqu shk shp shm shn shr shw shpl",
"sh", "sh shl shqu shk shp shm shn shr shw shpl",
"t", "st str t ts tr tl ty tw tl",
"th", "cth th thr thl thw",
"tl", "tl",
"v", "v vr vy zv zvr vl",
"w", "bw chw dw fw gw hw khw mw nw pw sw shw tw thw w wr zw",
"x", "x",
"y", "by dy fy gy hy ky my ny py sy ty vy y zy",
"z", "cz dz z zv zvr zl zy zw");
midCons = Maker.makeOM(
"b", "lb rb bj bl br lbr rbl skbr scbr zb bq bdh dbh bbh lbh rbh bb",
"bh", "bbh dbh lbh rbh",
"c", "lc lsc rc rsc cl cqu cr ct lcr rcl sctr scdr scbr scpr msc mscr nsc nscr ngscr ndscr cc",
"ch", "lch rch rch",
"d", "ld ld rd rd skdr scdr dr dr dr rdr ldr zd zdr ndr ndscr ndskr ndst dq ldh rdh dbh bdh ddh dd",
"dh", "bdh ddh ldh rdh",
"f", "lf rf fl fr fl fr fl fr lfr rfl ft ff",
"g", "lg lg rg rg gl gr gl gr gl gr lgr rgl zg zgr ngr ngl ngscr ngskr gq gg",
"h", "lch lph lth lsh rch rph rsh rth phl phr lphr rphl shl shr lshr rshl msh mshr zth bbh dbh lbh rbh bdh ddh ldh rdh",
"j", "bj lj rj",
"k", "lk lsk rk rsk kl kr lkr rkl sktr skdr skbr skpr tk zk zkr msk mskr nsk nskr ngskr ndskr kq kk",
"kh", "lkh rkh",
"l", "lb lc lch ld lf lg lj lk lm ln lp lph ls lst lt lth lsc lsk lsp lv lz lsh bl lbr rbl cl lcr rcl fl lfr rfl gl lgr rgl kl lkr rkl pl lpr rpl phl lphr rphl shl lshr rshl sl rsl lsl ldr ltr lx ngl nsl msl nsl ll lth tl ltl rtl vl",
"m", "lm rm zm msl msc mscr msh mshr mst msp msk mskr mm",
"n", "ln rn nx zn zn ndr nj ntr ntr ngr ngl nsl nsl nsc nscr ngscr ndscr nsk nskr ngskr ndskr nst ndst nsp nn",
"p", "lp lsp rp rsp pl pr lpr rpl skpr scpr zp msp nsp lph rph phl phr lphr rphl pq pp",
"ph", "lph lph rph rph phl phr lphr rphl",
"q", "bq dq gq kq pq tq",
"qu", "cqu lqu rqu",
"r", "rb rc rch rd rf rg rj rk rm rn rp rph rs rsh rst rt rth rsc rsk rsp rv rz br br br lbr rbl cr cr cr lcr rcl fr fr fr lfr rfl gr gr gr lgr rgl kr kr kr lkr rkl pr pr pr lpr rpl phr phr phr lphr rphl shr shr shr lshr rshl rsl sktr sctr skdr scdr skbr scbr skpr scpr dr dr dr rdr ldr tr tr tr rtr ltr vr rx zr zdr ztr zgr zkr ntr ntr ndr ngr mscr mshr mskr nscr ngscr ndscr nskr ngskr ndskr rr",
"s", "ls lst lsc lsk lsp rs rst rsc rsk rsp sl rsl lsl sktr sctr skdr scdr skbr scbr skpr scpr nsl msl msc mscr mst msp msk mskr nsl nsc nscr ngscr ndscr nsk nskr ngskr ndskr nst ndst nsp lsh rsh sh shl shqu shk shp shm shn shr shw shpl lshr rshl msh mshr ss",
"sh", "lsh rsh sh shl shqu shk shp shm shn shr shw shpl lshr rshl msh mshr",
"t", "ct ft lst lt rst rt sktr sctr tk tr rtr ltr zt ztr ntr ntr mst nst ndst tq ltl rtl tt",
"th", "lth rth zth cth",
"tl", "ltl rtl",
"v", "lv rv vv vl vr",
"w", "bw chw dw fw gw hw khw mw nw pw sw shw tw thw w wr wy zw",
"x", "nx rx lx",
"y", "by dy fy gy hy ky my ny py sy ty vy wy zy",
"z", "lz rz zn zd zt zg zk zm zn zp zb zr zdr ztr zgr zkr zth zz");
closeCons = Maker.makeOM("b", "b lb rb bs bz mb mbs bh bh lbh rbh mbh bb",
"bh", "bh lbh rbh mbh",
"c", "c ck cks lc rc cs cz ct cz cth sc",
"ch", "ch lch rch tch pch kch mch nch",
"d", "d ld rd ds dz dt dsh dth gd nd nds dh dh ldh rdh ndh dd",
"dh", "dh ldh rdh ndh",
"f", "f lf rf fs fz ft fsh ft fth ff",
"g", "g lg rg gs gz gd gsh gth ng ngs gg",
"h", "cth ch lch rch tch pch kch mch nch dsh dth fsh fth gsh gth h hs ksh kth psh pth ph ph ph ph ph ph lph rph phs pht phth",
"j", "j",
"k", "ck cks kch k lk rk ks kz kt ksh kth nk nks sk",
"kh", "kh",
"l", "lb lc lch ld lf lg lk l ls lz lp lph ll",
"m", "mch m ms mb mt mp mbs mps mz sm mm",
"n", "nch n ns nd nt nk nds nks nz ng ngs nn",
"p", "pch mp mps p lp rp ps pz pt psh pth sp sp ph lph rph phs pht phth",
"ph", "ph lph rph phs pht phth",
"q", "q",
"qu", "",
"r", "rb rc rch rd rf rg rk rp rph r rs rz",
"s", "bs cks cs ds fs gs hs ks ls ms mbs mps ns nds nks ngs ps phs rs s st sp st sp sc sk sm ts lsh rsh sh shk shp msh ss",
"sh", "lsh rsh sh shk shp msh",
"t", "ct ft tch dt ft kt mt nt pt pht st st t ts tz tt",
"th", "cth dth fth gth kth pth phth th ths",
"tl", "tl",
"v", "v",
"w", "",
"x", "x",
"y", "",
"z", "bz cz dz fz gz kz lz mz nz pz rz tz z zz");
}
/*
* Removes accented characters from a string; if the "base" characters are non-English anyway then the result won't
* be an ASCII string, but otherwise it probably will be.
* <br>
* Credit to user hashable from http://stackoverflow.com/a/1215117
*
* @param str a string that may contain accented characters
* @return a string with all accented characters replaced with their (possibly ASCII) counterparts
*
public String removeAccents(String str) {
String alteredString = Normalizer.normalize(str, Normalizer.Form.NFD);
alteredString = diacritics.matcher(alteredString).replaceAll("");
alteredString = alteredString.replace('æ', 'a');
alteredString = alteredString.replace('œ', 'o');
alteredString = alteredString.replace('Æ', 'A');
alteredString = alteredString.replace('Œ', 'O');
return alteredString;
}*/
/**
* Removes accented Latin-script characters from a string; if the "base" characters are non-English anyway then the
* result won't be an ASCII string, but otherwise it probably will be.
*
* @param str a string that may contain accented Latin-script characters
* @return a string with all accented characters replaced with their (possibly ASCII) counterparts
*/
public static CharSequence removeAccents(CharSequence str) {
CharSequence alteredString = str;
for (int i = 0; i < accentFinders.length; i++) {
alteredString = accentFinders[i].replace(alteredString);
}
return alteredString;
}
private FakeLanguageGen register(String languageName) {
summary = registry.size() + "@1";
registry.put(languageName,this);
name = languageName;
return copy();
}
private FakeLanguageGen summarize(String brief) {
summary = brief;
return this;
}
private static FakeLanguageGen lovecraft() {
return new FakeLanguageGen(
new String[]{"a", "i", "o", "e", "u", "a", "i", "o", "e", "u", "ia", "ai", "aa", "ei"},
new String[]{},
new String[]{"s", "t", "k", "n", "y", "p", "k", "l", "g", "gl", "th", "sh", "ny", "ft", "hm", "zvr", "cth"},
new String[]{"h", "gl", "gr", "nd", "mr", "vr", "kr"},
new String[]{"l", "p", "s", "t", "n", "k", "g", "x", "rl", "th", "gg", "gh", "ts", "lt", "rk", "kh", "sh", "ng", "shk"},
new String[]{"aghn", "ulhu", "urath", "oigor", "alos", "'yeh", "achtal", "elt", "ikhet", "adzek", "agd"},
new String[]{"'", "-"}, new int[]{1, 2, 3}, new double[]{6, 7, 2},
0.4, 0.31, 0.07, 0.04, null, true);
}
/**
* Ia! Ia! Cthulhu Rl'yeh ftaghn! Useful for generating cultist ramblings or unreadable occult texts. You may want
* to consider mixing this with multiple other languages using {@link #mixAll(Object...)}; using some very different
* languages in low amounts relative to the amount used for this, like {@link #NAHUATL}, {@link #INUKTITUT},
* {@link #SOMALI}, {@link #DEEP_SPEECH}, and {@link #INSECT} can alter the aesthetic of the generated text in ways
* that may help distinguish magic styles.
* <br>
* Zvrugg pialuk, ya'as irlemrugle'eith iposh hmo-es nyeighi, glikreirk shaivro'ei!
*/
public static final FakeLanguageGen LOVECRAFT = lovecraft().register("Lovecraft");
private static FakeLanguageGen english() {
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"au", "ai", "ai", "ou", "ea", "ie", "io", "ei",
},
new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",},
new String[]{
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z",
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y",
"b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n",
"p", "r", "s", "sh", "st", "sl", "t", "tr", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"r", "s", "t", "l", "n",
"str", "spr", "spl", "wr", "kn", "kn", "gn",
},
new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs",
"ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr",
"pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz"
},
new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch",
"ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp",
"p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w",
},
new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy",
"ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition",
"ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition",
"ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly",
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{10, 11, 4, 1},
0.22, 0.1, 0.0, 0.22, englishSanityChecks, true);
}
/**
* Imitation English; may seem closer to Dutch in some generated text, and is not exactly the best imitation.
* Should seem pretty fake to many readers; does not filter out dictionary words but does perform basic vulgarity
* filtering. If you want to avoid generating other words, you can subclass FakeLanguageGen and modify word() .
* <br>
* Mont tiste frot; mousation hauddes?
* Lily wrely stiebes; flarrousseal gapestist.
*/
public static final FakeLanguageGen ENGLISH = english().register("English");
private static FakeLanguageGen greekRomanized(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "i", "i", "au", "ai", "ai", "oi", "oi",
"ia", "io", "u", "u", "eo", "ei", "o", "o", "ou", "oi", "y", "y", "y", "y"},
new String[]{"ui", "ui", "ei", "ei"},
new String[]{"rh", "s", "z", "t", "t", "k", "ch", "n", "th", "kth", "m", "p", "ps", "b", "l", "kr",
"g", "phth", "d", "t", "k", "ch", "n", "ph", "ph", "k",},
new String[]{"lph", "pl", "l", "l", "kr", "nch", "nx", "ps"},
new String[]{"s", "p", "t", "ch", "n", "m", "s", "p", "t", "ch", "n", "m", "b", "g", "st", "rst",
"rt", "sp", "rk", "ph", "x", "z", "nk", "ng", "th", "d", "k", "n", "n",},
new String[]{"os", "os", "os", "is", "is", "us", "um", "eum", "ium", "iam", "us", "um", "es",
"anes", "eros", "or", "or", "ophon", "on", "on", "ikon", "otron", "ik",},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{5, 7, 4, 1}, 0.45, 0.45, 0.0, 0.2, null, true);
}
/**
* Imitation ancient Greek, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers.
* <br>
* Psuilas alor; aipeomarta le liaspa...
*/
public static final FakeLanguageGen GREEK_ROMANIZED = greekRomanized().register("Greek Romanized");
private static FakeLanguageGen greekAuthentic(){
return new FakeLanguageGen(
new String[]{"α", "α", "α", "α", "α", "ο", "ο", "ε", "ε", "ε", "ι", "ι", "ι", "ι", "ι", "αυ", "αι", "αι", "οι", "οι",
"ια", "ιο", "ου", "ου", "εο", "ει", "ω", "ω", "ωυ", "ωι", "υ", "υ", "υ", "υ"},
new String[]{"υι", "υι", "ει", "ει"},
new String[]{"ρ", "σ", "ζ", "τ", "τ", "κ", "χ", "ν", "θ", "κθ", "μ", "π", "ψ", "β", "λ", "κρ",
"γ", "φθ", "δ", "τ", "κ", "χ", "ν", "φ", "φ", "κ",},
new String[]{"λφ", "πλ", "λ", "λ", "κρ", "γχ", "γξ", "ψ"},
new String[]{"σ", "π", "τ", "χ", "ν", "μ", "σ", "π", "τ", "χ", "ν", "μ", "β", "γ", "στ", "ρστ",
"ρτ", "σπ", "ρκ", "φ", "ξ", "ζ", "γκ", "γγ", "θ", "δ", "κ", "ν", "ν",},
new String[]{"ος", "ος", "ος", "ις", "ις", "υς", "υμ", "ευμ", "ιυμ", "ιαμ", "υς", "υμ", "ες",
"ανες", "ερος", "ορ", "ορ", "οφον", "ον", "ον", "ικον", "οτρον", "ικ",},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{5, 7, 4, 1}, 0.45, 0.45, 0.0, 0.2, null, true);
}
/**
* Imitation ancient Greek, using the original Greek alphabet. People may try to translate it and get gibberish.
* Make sure the font you use to render this supports the Greek alphabet! In the GDX display module, most
* fonts support all the Greek you need for this.
* <br>
* Ψυιλασ αλορ; αιπεομαρτα λε λιασπα...
*/
public static final FakeLanguageGen GREEK_AUTHENTIC = greekAuthentic().register("Greek Authentic");
private static FakeLanguageGen french(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"ai", "oi", "oui", "au", "œu", "ou"
},
new String[]{
"ai", "aie", "aou", "eau", "oi", "oui", "oie", "eu", "eu",
"à", "â", "ai", "aî", "aï", "aie", "aou", "aoû", "au", "ay", "e", "é", "ée", "è",
"ê", "eau", "ei", "eî", "eu", "eû", "i", "î", "ï", "o", "ô", "oe", "oê", "oë", "œu",
"oi", "oie", "oï", "ou", "oû", "oy", "u", "û", "ue",
"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "a", "e", "e", "e", "i", "i", "o", "u", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"ai", "ai", "eau", "oi", "oi", "oui", "eu", "au", "au", "ei", "ei", "oe", "oe", "ou", "ou", "ue"
},
new String[]{"tr", "ch", "m", "b", "b", "br", "j", "j", "j", "j", "g", "t", "t", "t", "c", "d", "f", "f", "h", "n", "l", "l",
"s", "s", "s", "r", "r", "r", "v", "v", "p", "pl", "pr", "bl", "br", "dr", "gl", "gr"},
new String[]{"cqu", "gu", "qu", "rqu", "nt", "ng", "ngu", "mb", "ll", "nd", "ndr", "nct", "st",
"xt", "mbr", "pl", "g", "gg", "ggr", "gl", "bl", "j", "gn",
"m", "m", "mm", "v", "v", "f", "f", "f", "ff", "b", "b", "bb", "d", "d", "dd", "s", "s", "s", "ss", "ss", "ss",
"cl", "cr", "ng", "ç", "ç", "rç", "rd", "lg", "rg"},
new String[]{"rt", "ch", "m", "b", "b", "lb", "t", "t", "t", "t", "c", "d", "f", "f", "n", "n", "l", "l",
"s", "s", "s", "r", "r", "p", "rd", "ff", "ss", "ll"
},
new String[]{"e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es", "es",
"e", "e", "e", "e", "e", "é", "é", "er", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es",
"e", "e", "e", "e", "e", "é", "é", "é", "er", "er", "er", "er", "er", "es", "es", "es", "es", "es",
"ent", "em", "en", "en", "aim", "ain", "an", "oin", "ien", "iere", "ors", "anse",
"ombs", "ommes", "ancs", "ends", "œufs", "erfs", "ongs", "aps", "ats", "ives", "ui", "illes",
"aen", "aon", "am", "an", "eun", "ein", "age", "age", "uile", "uin", "um", "un", "un", "un",
"aille", "ouille", "eille", "ille", "eur", "it", "ot", "oi", "oi", "oi", "aire", "om", "on", "on",
"im", "in", "in", "ien", "ien", "ine", "ion", "il", "eil", "oin", "oint", "iguïté", "ience", "incte",
"ang", "ong", "acré", "eau", "ouche", "oux", "oux", "ect", "ecri", "agne", "uer", "aix", "eth", "ut", "ant",
"anc", "anc", "anche", "ioche", "eaux", "ive", "eur", "ancois", "ecois", "ente", "enri",
"arc", "oc", "ouis", "arche", "ique", "ique", "ique", "oque", "arque", "uis", "este", "oir", "oir"
},
new String[]{}, new int[]{1, 2, 3}, new double[]{15, 7, 2}, 0.35, 1.0, 0.0, 0.4, null, true);
}
/**
* Imitation modern French, using the (many) accented vowels that are present in the language. Translating it
* will produce gibberish if it produces anything at all. In the GDX display module, most
* fonts support all the accented characters you need for this.
* <br>
* Bœurter; ubi plaqua se saigui ef brafeur?
*/
public static final FakeLanguageGen FRENCH = french().register("French");
private static FakeLanguageGen russianRomanized(){
return new FakeLanguageGen(
new String[]{"a", "e", "e", "i", "i", "o", "u", "ie", "y", "e", "iu", "ia", "y", "a", "a", "o", "u"},
new String[]{},
new String[]{"b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts",
"b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f", "kh", "ts",
"b", "v", "g", "d", "k", "l", "p", "r", "s", "t", "f",
"zh", "m", "n", "z", "ch", "sh", "shch",
"br", "sk", "tr", "bl", "gl", "kr", "gr"},
new String[]{"bl", "br", "pl", "dzh", "tr", "gl", "gr", "kr"},
new String[]{"b", "v", "g", "d", "zh", "z", "k", "l", "m", "n", "p", "r", "s", "t", "f", "kh", "ts", "ch", "sh",
"v", "f", "sk", "sk", "sk", "s", "b", "d", "d", "n", "r", "r"},
new String[]{"odka", "odna", "usk", "ask", "usky", "ad", "ar", "ovich", "ev", "ov", "of", "agda", "etsky", "ich", "on", "akh", "iev", "ian"},
new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, null, true);
}
/**
* Imitation modern Russian, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers.
* <br>
* Zhydotuf ruts pitsas, gogutiar shyskuchebab - gichapofeglor giunuz ieskaziuzhin.
*/
public static final FakeLanguageGen RUSSIAN_ROMANIZED = russianRomanized().register("Russian Romanized");
private static FakeLanguageGen russianAuthentic(){
return new FakeLanguageGen(
new String[]{"а", "е", "ё", "и", "й", "о", "у", "ъ", "ы", "э", "ю", "я", "ы", "а", "а", "о", "у"},
new String[]{},
new String[]{"б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц",
"б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф", "х", "ц",
"б", "в", "г", "д", "к", "л", "п", "р", "с", "т", "ф",
"ж", "м", "н", "з", "ч", "ш", "щ",
"бр", "ск", "тр", "бл", "гл", "кр", "гр"},
new String[]{"бл", "бр", "пл", "дж", "тр", "гл", "гр", "кр"},
new String[]{"б", "в", "г", "д", "ж", "з", "к", "л", "м", "н", "п", "р", "с", "т", "ф", "х", "ц", "ч", "ш",
"в", "ф", "ск", "ск", "ск", "с", "б", "д", "д", "н", "р", "р"},
new String[]{"одка", "одна", "уск", "аск", "ускы", "ад", "ар", "овйч", "ев", "ов", "оф", "агда", "ёцкы", "йч", "он", "ах", "ъв", "ян"},
new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{4, 5, 6, 5, 3, 1}, 0.1, 0.2, 0.0, 0.12, null, true);
}
/**
* Imitation modern Russian, using the authentic Cyrillic alphabet used in Russia and other countries.
* Make sure the font you use to render this supports the Cyrillic alphabet!
* In the GDX display module, the "smooth" fonts support all the Cyrillic alphabet you need for this.
* <br>
* Жыдотуф руц пйцас, гогутяр шыскучэбаб - гйчапофёглор гюнуз ъсказюжин.
*/
public static final FakeLanguageGen RUSSIAN_AUTHENTIC = russianAuthentic().register("Russian Authentic");
private static FakeLanguageGen japaneseRomanized(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "e", "e", "i", "i", "i", "i", "o", "o", "o", "u", "ou", "u", "ai", "ai"},
new String[]{},
new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g",
"gy", "z", "j", "d", "b", "by", "p", "py",
"k", "t", "n", "s", "k", "t", "d", "s", "sh", "sh", "g", "r", "b",
"k", "t", "n", "s", "k", "t", "b", "s", "sh", "sh", "g", "r", "b",
"k", "t", "n", "s", "k", "t", "z", "s", "sh", "sh", "ch", "ry", "ts"
},
new String[]{"k", "ky", "s", "sh", "t", "ts", "ch", "n", "ny", "h", "f", "hy", "m", "my", "y", "r", "ry", "g",
"gy", "z", "j", "d", "b", "by", "p", "py",
"k", "t", "d", "s", "k", "t", "d", "s", "sh", "sh", "y", "j", "p", "r", "d",
"k", "t", "b", "s", "k", "t", "b", "s", "sh", "sh", "y", "j", "p", "r", "d",
"k", "t", "z", "s", "f", "g", "z", "b", "d", "ts", "sh", "m",
"k", "t", "z", "s", "f", "g", "z", "b", "d", "ts", "sh", "m",
"nn", "nn", "nd", "nz", "mm", "kk", "tt", "ss", "ssh", "tch"},
new String[]{"n"},
new String[]{"ima", "aki", "aka", "ita", "en", "izen", "achi", "uke", "aido", "outsu", "uki", "oku", "aku", "oto", "okyo"},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 3}, 0.3, 0.9, 0.0, 0.07, japaneseSanityChecks, true);
}
/**
* Imitation Japanese, romanized to use the Latin alphabet. Likely to seem pretty fake to many readers.
* <br>
* Narurehyounan nikase keho...
*/
public static final FakeLanguageGen JAPANESE_ROMANIZED = japaneseRomanized().register("Japanese Romanized");
private static FakeLanguageGen swahili(){
return new FakeLanguageGen(
new String[]{"a", "i", "o", "e", "u",
"a", "a", "i", "o", "o", "e", "u",
"a", "a", "i", "o", "o", "u",
"a", "a", "i", "i", "o",
"a", "a", "a", "a", "a",
"a", "i", "o", "e", "u",
"a", "a", "i", "o", "o", "e", "u",
"a", "a", "i", "o", "o", "u",
"a", "a", "i", "i", "o",
"a", "a", "a", "a", "a",
"aa", "aa", "ue", "uo", "ii", "ea"},
new String[]{},
new String[]{
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"nb", "nj", "ns", "nz",
"nb", "nch", "nj", "ns", "ny", "nz",
"nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz",
"nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz",
"nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nv", "nw", "nz",
"mb", "ms", "my", "mz",
"mb", "mch", "ms", "my", "mz",
"mb", "mch", "mk", "mp", "ms", "my", "mz",
"mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz",
"mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mv", "mw", "my", "mz",
"sh", "sh", "sh", "ny", "kw",
"dh", "th", "sh", "ny",
"dh", "th", "sh", "gh", "r", "ny",
"dh", "th", "sh", "gh", "r", "ny",
},
new String[]{
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"b", "h", "j", "l", "s", "y", "m", "n",
"b", "ch", "h", "j", "l", "s", "y", "z", "m", "n",
"b", "ch", "f", "g", "h", "j", "k", "l", "p", "s", "y", "z", "m", "n",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "y", "z", "m", "n", "kw",
"b", "ch", "d", "f", "g", "h", "j", "k", "l", "p", "s", "t", "v", "w", "y", "z", "m", "n", "kw",
"nb", "nj", "ns", "nz",
"nb", "nch", "nj", "ns", "ny", "nz",
"nb", "nch", "nf", "ng", "nj", "nk", "np", "ns", "nz",
"nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nz",
"nb", "nch", "nd", "nf", "ng", "nj", "nk", "np", "ns", "nt", "nw", "nz",
"mb", "ms", "my", "mz",
"mb", "mch", "ms", "my", "mz",
"mb", "mch", "mk", "mp", "ms", "my", "mz",
"mb", "mch", "md", "mk", "mp", "ms", "mt", "my", "mz",
"mb", "mch", "md", "mf", "mg", "mj", "mk", "mp", "ms", "mt", "mw", "my", "mz",
"sh", "sh", "sh", "ny", "kw",
"dh", "th", "sh", "ny",
"dh", "th", "sh", "gh", "r", "ny",
"dh", "th", "sh", "gh", "r", "ny",
"ng", "ng", "ng", "ng", "ng"
},
new String[]{""},
new String[]{"-@"},
new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{3, 8, 6, 9, 2, 2}, 0.2, 1.0, 0.0, 0.12, null, true);
}
/**
* Swahili is one of the more commonly-spoken languages in sub-Saharan Africa, and serves mainly as a shared language
* that is often learned after becoming fluent in one of many other (vaguely-similar) languages of the area. An
* example sentence in Swahili, that this might try to imitate aesthetically, is "Mtoto mdogo amekisoma," meaning
* "The small child reads it" (where it is a book). A notable language feature used here is the redoubling of words,
* which is used in Swahili to emphasize or alter the meaning of the doubled word; here, it always repeats exactly
* and can't make minor changes like a real language might. This generates things like "gata-gata", "hapi-hapi", and
* "mimamzu-mimamzu", always separating with a hyphen here.
* <br>
* As an aside, please try to avoid the ugly stereotypes that fantasy media often assigns to speakers of African-like
* languages when using this or any of the generators. Many fantasy tropes come from older literature written with
* major cultural biases, and real-world cultural elements can be much more interesting to players than yet another
* depiction of a "jungle savage" with stereotypical traits. Consider drawing from existing lists of real-world
* technological discoveries, like
* <a href="https://en.wikipedia.org/wiki/History_of_science_and_technology_in_Africa">this list on Wikipedia</a>,
* for inspiration when world-building; though some groups may not have developed agriculture by early medieval
* times, their neighbors may be working iron and studying astronomy just a short distance away.
* <br>
* Kondueyu; ma mpiyamdabota mise-mise nizakwaja alamsa amja, homa nkajupomba.
*/
public static final FakeLanguageGen SWAHILI = swahili().register("Swahili");
private static FakeLanguageGen somali(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "a", "aa", "aa", "aa",
"e", "e", "ee",
"i", "i", "i", "i", "ii",
"o", "o", "o", "oo",
"u", "u", "u", "uu", "uu",
},
new String[]{},
new String[]{"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "dh", "c", "g", "f", "q", "k", "l", "m",
"n", "w", "h", "y",
"x", "g", "b", "d", "s", "m", "dh", "n", "r",
"g", "b", "s", "dh",
},
new String[]{
"bb", "gg", "dd", "bb", "dd", "rr", "ddh", "cc", "gg", "ff", "ll", "mm", "nn",
"bb", "gg", "dd", "bb", "dd", "gg",
"bb", "gg", "dd", "bb", "dd", "gg",
"cy", "fk", "ft", "nt", "rt", "lt", "qm", "rdh", "rsh", "lq",
"my", "gy", "by", "lkh", "rx", "md", "bd", "dg", "fd", "mf",
"dh", "dh", "dh", "dh",
},
new String[]{
"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h",
"x", "g", "b", "d", "s", "m", "q", "n", "r",
"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n", "h",
"x", "g", "b", "d", "s", "m", "q", "n", "r",
"b", "t", "j", "x", "kh", "d", "r", "s", "sh", "c", "g", "f", "q", "k", "l", "m", "n",
"g", "b", "d", "s", "q", "n", "r",
"b", "t", "x", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n",
"g", "b", "d", "s", "r", "n",
"b", "t", "kh", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n",
"g", "b", "d", "s", "r", "n",
"b", "t", "d", "r", "s", "sh", "g", "f", "q", "k", "l", "m", "n",
"g", "b", "d", "s", "r", "n",
},
new String[]{"aw", "ow", "ay", "ey", "oy", "ay", "ay"},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 4, 5, 4, 1}, 0.25, 0.3, 0.0, 0.08, null, true);
}
/**
* Imitation Somali, using the Latin alphabet. Due to uncommon word structure, unusual allowed combinations of
* letters, and no common word roots with most familiar languages, this may seem like an unidentifiable or "alien"
* language to most readers. However, it's based on the Latin writing system for the Somali language (probably
* closest to the northern dialect), which due to the previously mentioned properties, makes it especially good for
* mixing with other languages to make letter combinations that seem strange to appear. It is unlikely that this
* particular generated language style will be familiar to readers, so it probably won't have existing stereotypes
* associated with the text. One early comment this received was, "it looks like a bunch of letters semi-randomly
* thrown together", which is probably a typical response (the comment was made by someone fluent in German and
* English, and most Western European languages are about as far as you can get from Somali).
* <br>
* Libor cat naqoxekh dhuugad gisiqir?
*/
public static final FakeLanguageGen SOMALI = somali().register("Somali");
private static FakeLanguageGen hindi(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"a", "a", "a", "a", "a", "a", "ā", "ā", "i", "i", "i", "i", "ī", "i", "i", "ī", "ī",
"u", "u", "u", "ū", "u", "ū", "u", "ū", "e", "ai", "ai", "o", "o", "o", "au",
"aĕ", "aĕ", "aĕ", "aĕ", "aĕ", "āĕ", "āĕ", "iĕ", "iĕ", "iĕ", "īĕ", "īĕ",
"uĕ", "uĕ", "ūĕ", "aiĕ", "aiĕ", "oĕ", "oĕ", "oĕ", "auĕ",
//"aĭ", "aĭ", "aĭ", "aĭ", "aĭ", "āĭ", "āĭ", "iĭ", "iĭ", "iĭ", "īĭ", "īĭ",
//"uĭ", "uĭ", "ūĭ", "aiĭ", "aiĭ", "oĭ", "oĭ", "oĭ", "auĭ",
},
new String[]{"á", "í", "ú", "ó", "á", "í", "ú", "ó",
},
new String[]{
"k", "k", "k", "k", "k", "k", "k", "k", "kŗ", "kŕ", "kļ",
"c", "c", "c", "c", "c", "c", "cŗ", "cŕ", "cļ",
"ţ", "t", "t", "t", "t", "t", "t", "t", "t", "t", "tŗ", "tŕ", "tŗ", "tŕ",
"p", "p", "p", "p", "p", "p", "p", "p", "p", "p", "pŗ", "pŕ", "pļ", "pĺ", "pŗ", "pŕ", "p", "p",
"kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "kh", "khŗ", "khŕ", "khļ", "khĺ",
"ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chŗ", "chŕ", "chļ", "chĺ",
"ţh", "th", "th", "th", "th", "th", "th", "th", "th", "th", "thŗ", "thŕ", "thļ", "thĺ",
"ph", "ph", "ph", "ph", "ph", "ph", "ph", "phŗ", "phŕ", "phļ", "phĺ",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "jh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "đh", "dh", "bh",
"ń", "ñ", "ņ", "n", "m", "h", "y", "r", "l", "v", "ś", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "đh", "dh", "bh",
"ń", "ņ", "n", "m", "h", "y", "r", "l", "v", "ş", "s",
"g", "j", "đ", "d", "b", "gh", "đh", "dh", "bh",
"ń", "ņ", "n", "m", "h", "y", "r", "l", "v", "ş", "s",
"g", "đ", "d", "b", "gh", "đh", "dh", "bh", "n", "m", "v", "s",
"g", "đ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v",
"g", "đ", "d", "b", "g", "d", "b", "dh", "bh", "n", "m", "v",
},
new String[]{
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"k", "k", "k", "k", "k", "nk", "rk",
"kŗ", "kŗ", "kŗ", "kŗ", "kŗ", "nkŗ", "rkŗ",
"kŕ", "kŕ", "kŕ", "kŕ", "kŕ", "nkŕ", "rkŕ",
"kļ", "kļ", "kļ", "kļ", "kļ", "nkļ", "rkļ",
"c", "c", "c", "c", "c", "c", "cŗ", "cŕ", "cļ",
"ţ", "t", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"ţ", "t", "t", "t", "t", "nt", "rt",
"tŗ", "tŗ", "tŗ", "tŗ", "tŗ", "ntŗ", "rtŗ",
"tŕ", "tŕ", "tŕ", "tŕ", "tŕ", "ntŕ", "rtŕ",
"tŗ", "tŗ", "tŗ", "tŗ", "tŗ", "ntŗ", "rtŗ",
"tŕ", "tŕ", "tŕ", "tŕ", "tŕ", "ntŕ", "rtŕ",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"pŗ", "pŗ", "pŗ", "pŗ", "pŗ", "npŗ", "rpŗ",
"pŕ", "pŕ", "pŕ", "pŕ", "pŕ", "npŕ", "rpŕ",
"pļ", "pļ", "pļ", "pļ", "pļ", "npļ", "rpļ",
"pĺ", "pĺ", "pĺ", "pĺ", "pĺ", "npĺ", "rpĺ",
"pŗ", "pŗ", "pŗ", "pŗ", "pŗ", "npŗ", "rpŗ",
"pŕ", "pŕ", "pŕ", "pŕ", "pŕ", "npŕ", "rpŕ",
"p", "p", "p", "p", "p", "np", "rp",
"p", "p", "p", "p", "p", "np", "rp",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"kh", "kh", "kh", "kh", "kh", "nkh", "rkh",
"khŗ", "khŗ", "khŗ", "khŗ", "khŗ", "nkhŗ", "rkhŗ",
"khŕ", "khŕ", "khŕ", "khŕ", "khŕ", "nkhŕ", "rkhŕ",
"khļ", "khļ", "khļ", "khļ", "khļ", "nkhļ", "rkhļ",
"khĺ", "khĺ", "khĺ", "khĺ", "khĺ", "nkhĺ", "rkhĺ",
"ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "ch", "chŗ", "chŕ", "chļ", "chĺ",
"ţh", "th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"th", "th", "th", "th", "th", "nth", "rth",
"thŗ", "thŗ", "thŗ", "thŗ", "thŗ", "nthŗ", "rthŗ",
"thŕ", "thŕ", "thŕ", "thŕ", "thŕ", "nthŕ", "rthŕ",
"thļ", "thļ", "thļ", "thļ", "thļ", "nthļ", "rthļ",
"thĺ", "thĺ", "thĺ", "thĺ", "thĺ", "nthĺ", "rthĺ",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"ph", "ph", "ph", "ph", "ph", "nph", "rph",
"phŗ", "phŗ", "phŗ", "phŗ", "phŗ", "nphŗ", "rphŗ",
"phŕ", "phŕ", "phŕ", "phŕ", "phŕ", "nphŕ", "rphŕ",
"phļ", "phļ", "phļ", "phļ", "phļ", "nphļ", "rphļ",
"phĺ", "phĺ", "phĺ", "phĺ", "phĺ", "nphĺ", "rphĺ",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"jh", "đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ñ", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ś", "ś", "ś", "ś", "ś", "nś", "rś",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"j", "j", "j", "j", "j", "nj", "rj",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"ń", "ņ", "n", "m", "m", "m", "m", "m", "nm", "rm",
"h", "y", "y", "y", "y", "y", "ny", "ry",
"r", "l", "v", "v", "v", "v", "v", "nv", "rv",
"ş", "ş", "ş", "ş", "ş", "nş", "rş",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"gh", "gh", "gh", "gh", "gh", "ngh", "rgh",
"đh", "đh", "đh", "đh", "đh", "nđh", "rđh",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"n", "m", "m", "m", "m", "m", "nm", "rm",
"v", "v", "v", "v", "v", "nv", "rv",
"s", "s", "s", "s", "s", "ns", "rs",
"g", "g", "g", "g", "g", "ng", "rg",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"g", "g", "g", "g", "g", "ng", "rg",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"n", "m", "m", "m", "m", "m", "nm", "rm",
"v", "v", "v", "v", "v", "nv", "rv",
"g", "g", "g", "g", "g", "ng", "rg",
"đ", "đ", "đ", "đ", "đ", "nđ", "rđ",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"g", "g", "g", "g", "g", "ng", "rg",
"d", "d", "d", "d", "d", "nd", "rd",
"b", "b", "b", "b", "b", "nb", "rb",
"dh", "dh", "dh", "dh", "dh", "ndh", "rdh",
"bh", "bh", "bh", "bh", "bh", "nbh", "rbh",
"n", "m", "m", "m", "m", "m", "nm", "rm",
"v", "v", "v", "v", "v", "nv", "rv",
},
new String[]{"t", "d", "m", "r", "dh", "b", "t", "d", "m", "r", "dh", "bh", "nt", "nt", "nk", "ş"},
new String[]{"it", "it", "ati", "adva", "aş", "arma", "ardha", "abi", "ab", "aya"},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{1, 2, 3, 3, 1}, 0.15, 0.75, 0.0, 0.12, null, true);
}
/**
* Imitation Hindi, romanized to use the Latin alphabet using accented glyphs similar to the IAST standard.
* Most fonts do not support the glyphs that IAST-standard romanization of Hindi needs, so this uses alternate
* glyphs from at most Latin Extended-A. Relative to the IAST standard, the glyphs {@code "ṛṝḷḹḍṭṅṇṣṃḥ"} become
* {@code "ŗŕļĺđţńņşĕĭ"}, with the nth glyph in the first string being substituted with the nth glyph in the second
* string. You may want to get a variant on this language with {@link #removeAccents()} if you can't display the
* less-commonly-supported glyphs {@code āīūĕĭáíúóŗŕļţĺđńñņśş}. For some time SquidLib had a separate version of
* imitation Hindi that was accurate to the IAST standard, but this version is more usable because font support is
* much better for the glyphs it uses, so the IAST kind was removed (it added quite a bit of code for something that
* was mostly unusable).
* <br>
* Darvāga yar; ghađhinopŕauka āĕrdur, conśaigaijo śabhodhaĕđū jiviđaudu.
*/
public static final FakeLanguageGen HINDI_ROMANIZED = hindi().register("Hindi Romanized");
private static FakeLanguageGen arabic(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "aa", "aa", "aa", "ai", "au",
"a", "i", "u", "a", "i", "u",
"i", "i", "i", "i", "i", "ii", "ii", "ii",
"u", "u", "u", "uu", "uu",
},
new String[]{},
new String[]{"gh", "b", "t", "th", "j", "kh", "khr", "d", "dh", "r", "z", "s", "sh", "shw",
"zh", "khm", "g", "f", "q", "k", "l", "m", "n", "h", "w",
"q", "k", "q", "k", "b", "d", "f", "l", "z", "zh", "h", "h", "kh", "j", "s", "sh", "shw", "r",
"q", "k", "q", "k", "f", "l", "z", "h", "h", "j", "s", "r",
"q", "k", "f", "l", "z", "h", "h", "j", "s", "r",
"al-", "al-", "ibn-",
},
new String[]{
"kk", "kk", "kk", "kk", "kk", "dd", "dd", "dd", "dd",
"nj", "mj", "bj", "mj", "bj", "mj", "bj", "dj", "dtj", "dhj",
"nz", "nzh", "mz", "mzh", "rz", "rzh", "bz", "dz", "tz",
"s-h", "sh-h", "shw-h", "tw", "bn", "fq", "hz", "hl", "khm",
"lb", "lz", "lj", "lf", "ll", "lk", "lq", "lg", "ln"
},
new String[]{
"gh", "b", "t", "th", "j", "kh", "khr", "d", "dh", "r", "z", "s", "sh", "shw", "dt", "jj",
"zh", "khm", "g", "f", "q", "k", "l", "m", "n", "h", "w",
"k", "q", "k", "b", "d", "f", "l", "z", "zh", "h", "h", "kh", "j", "s", "sh", "shw", "r",
"k", "q", "k", "f", "l", "z", "h", "h", "j", "s", "r",
"k", "f", "l", "z", "h", "h", "j", "s", "r",
"b", "t", "th", "j", "kh", "khr", "d", "dh", "r", "z", "s", "sh", "shw", "dt", "jj",
"zh", "g", "f", "q", "k", "l", "m", "n", "h", "w",
"k", "q", "k", "b", "d", "f", "l", "z", "zh", "h", "h", "kh", "j", "s", "sh", "shw", "r",
"k", "q", "k", "f", "l", "z", "h", "h", "j", "s", "r",
"k", "f", "l", "z", "h", "h", "j", "s", "r",
},
new String[]{"aagh", "aagh", "ari", "ari", "aiid", "uuq", "ariid", "adih", "ateh", "adesh", "amiit", "it",
"iit", "akhmen", "akhmed", "ani", "abiib", "iib", "uuni", "iiz", "aqarii", "adiiq",
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{6, 5, 5, 1}, 0.55, 0.65, 0.0, 0.15, arabicSanityChecks, true);
}
/**
* Imitation Arabic, using mostly the Latin alphabet but with some Greek letters for tough transliteration topics.
* It's hard to think of a more different (widely-spoken) language to romanize than Arabic. Written Arabic does not
* ordinarily use vowels (the writing system is called an abjad, in contrast to an alphabet), and it has more than a
* few sounds that are very different from those in English. This version, because of limited support in fonts and
* the need for separate words to be distinguishable with regular expressions, uses somewhat-accurate digraphs or
* trigraphs instead of the many accented glyphs (not necessarily supported by most fonts) in most romanizations of
* Arabic, and this scheme uses no characters from outside ASCII.
* <br>
* Please try to be culturally-sensitive about how you use this generator. Classical Arabic (the variant that
* normally marks vowels explicitly and is used to write the Qur'an) has deep religious significance in Islam, and
* if you machine-generate text that (probably) isn't valid Arabic, but claim that it is real, or that it has
* meaning when it actually doesn't, that would be an improper usage of what this generator is meant to do. In a
* fantasy setting, you can easily confirm that the language is fictional and any overlap is coincidental; an
* example of imitation Arabic in use is the Dungeons and Dragons setting, Al-Qadim, which according to one account
* sounds similar to a word in real Arabic (that does not mean anything like what the designer was aiming for). In a
* historical setting, FakeLanguageGen is probably "too fake" to make a viable imitation for any language, and may
* just sound insulting if portrayed as realistic. You may want to mix ARABIC_ROMANIZED with a very different kind
* of language, like GREEK_ROMANIZED or RUSSIAN_AUTHENTIC, to emphasize that this is not a real-world language.
* <br>
* Hiijakki al-aafusiib rihit, ibn-ullukh aj shwisari!
*/
public static final FakeLanguageGen ARABIC_ROMANIZED = arabic().register("Arabic Romanized");
private static FakeLanguageGen inuktitut(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "aa", "aa", "aa", "aa", "i", "i", "i", "ii", "ii", "u", "u", "u", "uu", "uu", "ai", "ia", "iu", "ua", "ui"},
new String[]{},
new String[]{"p", "t", "k", "q", "s", "l", "h", "v", "j", "g", "r", "m", "n",
"t", "t", "t", "t", "k", "k", "q", "q", "n", "n", "n", "n", "g", "l"},
new String[]{"pp", "tt", "kk", "pk", "tk", "gk", "kp", "kt", "kg", "pq", "tq", "gq", "ss", "ll", "rr", "mm",
"nn", "nng", "ng", "ng",
"ll", "nn", "nn", "nn",},
new String[]{"n", "t", "q", "k", "n", "t", "q", "k", "n", "t", "q", "k", "n", "t", "q", "k", "p", "s", "m", "g", "g", "ng", "ng", "ng"},
new String[]{"itut", "uit", "uq", "iuq", "iaq", "aq", "it", "aat", "aak", "aan", "ait", "ik", "uut", "un", "unnun",
"ung", "ang", "ing", "iin", "iit", "iik", "in",
"uq", "iaq", "aq", "ik", "it", "uit", "ut", "ut", "at", "un", "in"
},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{3, 4, 6, 5, 4}, 0.45, 0.0, 0.0, 0.25, null, true);
}
/**
* Imitation text from an approximation of one of the Inuktitut languages spoken by various people of the Arctic and
* nearby areas. This is likely to be hard to pronounce. Inuktitut is the name accepted in Canada for one language
* family of that area, but other parts of the Arctic circle speak languages with varying levels of difference from
* this style of generated text. The term "Inuit language" may be acceptable, but "Eskimo language" is probably not,
* and when that term is not considered outright offensive it refers to a different language group anyway (more
* properly called Yupik or Yup'ik, and primarily spoken in Siberia instead of Canada and Alaska).
* <br>
* Ugkangungait ninaaq ipkutuilluuq um aitqiinnaitunniak tillingaat.
*/
public static final FakeLanguageGen INUKTITUT = inuktitut().register("Inuktitut");
private static FakeLanguageGen norse(){
return new FakeLanguageGen(
new String[]{"a","a","a","á","á","au","e","e","e","é","é","ei","ey","i","i","í","í","y","y","ý","ý",
"o","o","o","ó","ó","u","u","u","ú","ú","æ","æ","æ","ö","ö",},
new String[]{},
new String[]{"b","bl","br","bj","d","dr","dj","ð","ðl","ðr","f","fl","flj","fr","fn","fj","g","gn","gj","h",
"hj","hl","hr","hv","j","k","kl","kr","kn","kj","l","lj","m","mj","n","nj","p","pl","pr","pj","r",
"rj","s","sj","sl","sn","sp","st","str","skr","skj","sþ","sð","t","tj","v","vl","vr","vj","þ","þl","þr",
"d","f","fl","g","gl","gr","k","h","hr","n","k","l","m","mj","n","r","s","st","t","þ","ð",
"d","f","fl","g","gl","gr","k","h","hr","n","k","l","m","mj","n","r","s","st","t","þ","ð",
"d","f","fl","g","gl","gr","k","h","hr","n","k","l","m","mj","n","r","s","st","t","þ","ð",
"d","f","fl","g","gl","gr","k","h","hr","n","k","l","m","mj","n","r","s","st","t","þ","ð",
"d","f","fl","g","gl","gr","k","h","hr","n","k","l","m","mj","n","r","s","st","t","þ","ð",
"d","d","f","f","fl","g","g","g","gl","gr","k","h","hr","n","k","kl","l","n","r","r","s","st","t","t",
"d","d","f","f","fl","g","g","g","gl","gr","k","h","hr","n","k","kl","l","n","r","r","s","st","t","t",
"d","d","f","f","fl","g","g","g","gl","gr","k","h","hr","n","k","kl","l","n","r","r","s","st","t","t",
"d","d","f","f","fl","g","g","g","gl","gr","k","h","hr","n","k","kl","l","n","r","r","s","st","t","t",
},
new String[]{"bd","bf","bg","bk","bl","bp","br","bt","bv","bm","bn","bð","bj",
"db","df","dg","dk","dl","dp","dr","dt","dv","dm","dn","dð","dþ","dj","ndk","ndb","ndg","ndl","nds","nds",
"ðl","ðr","ðk","ðj","ðg","ðd","ðb","ðp","ðs",
"fb","fd","fg","fk","fl","fp","fr","fs","ft","fv","fm","fn","fð","fj",
"gb","gd","gf","gk","gl","gp","gr","gt","gv","gm","gn","gð","gj",
"h","hj","hl","hr","hv",
"kb","kd","kf","kp","kv","km","kn","kð","kl","kr","nkj","nkr","nkl",
"lbr","ldr","lfr","lg","lgr","lj","lkr","ln","ls","ltr","lv","lð","lðr","lþ",
"mb","md","mk","mg","ml","mp","mr","ms","mt","mv","mð","mþ","mj",
"nb","nl","np","nr","nv","nð","nþ","nj",
"ngl","ngb","ngd","ngk","ngp","ngt","ngv","ngm","ngð","ngþ","ngr",
"mbd","mbg","mbs","mbt","ldg","ldn","ldk","lds","rðn","rðl","gðs","gðr",
"pb","pd","pg","pk","pl","pr","ps","psj","pð","pj",
"rl","rbr","rdr","rg","rgr","rkr","rpr","rs","rts","rtr","rv","rj",
"sb","sbr","sd","sdr","sf","sfj","sg","skr","skl","sm","sn","str","sv","sð","sþ","sj",
"tr","tn","tb","td","tg","tv","tf","tj","tk","tm","tp",},
new String[]{"kk","ll","nn","pp","tt","kk","ll","nn","pp","tt",
"bs","ds","gs","x","rn","gn","gt","gs","ks","kt","nt","nd","nk","nt","ng","ngs","ns",
"ps","pk","pt","pts","lb","ld","lf","lk","lm","lp","lps","lt",
"rn","rb","rd","rk","rp","rt","rm","rð","rþ","sk","sp","st","ts",
"b","d","ð","f","g","gn","h","k","nk","l","m","n","ng","p","r","s","sp","st","sþ","sð","t","v","þ",
"b","d","ð","f","g","gn","h","k","nk","l","m","n","ng","p","r","s","sp","st","sþ","sð","t","v","þ",
"b","d","ð","f","g","gn","h","k","nk","l","m","n","ng","p","r","s","sp","st","sþ","sð","t","v","þ",
"b","b","b","d","d","d","f","f","f","g","g","k","k","nk","l","n","ng","p","p","r","r","r","s","s","st","t","t",
"b","b","b","d","d","d","f","f","f","g","g","k","k","nk","l","n","ng","p","p","r","r","r","s","s","st","t","t",
"b","b","b","d","d","d","f","f","f","g","g","k","k","nk","l","n","ng","p","p","r","r","r","s","s","st","t","t",
},
new String[]{"etta","eþa","uinn","ing","ard","eign","ef","efs","eg","ir","ir","ir","ir","ír","ír","ar","ar",
"ar","ár","or","or","ór","ör","on","on","ón","onn","unn","ung","ut","ett","att","ot"},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 5, 4, 3, 1}, 0.25, 0.5, 0.0, 0.08, genericSanityChecks, true);
}
/**
* Somewhat close to Old Norse, which is itself very close to Icelandic, so this uses Icelandic spelling rules. Not
* to be confused with the language(s) of Norway, where the Norwegian languages are called norsk, and are further
* distinguished into Bokmål and Nynorsk. This should not be likely to seem like any form of Norwegian, since it
* doesn't have the a-with-ring letter 'å' and has the letters eth ('Ðð') and thorn ('Þþ'). If you want to remove
* any letters not present on a US-ASCII keyboard, you can use {@link Modifier#SIMPLIFY_NORSE} on this language or
* some mix of this with other languages; it also changes some of the usage of "j" where it means the English "y"
* sound, making "fjord" into "fyord", which is closer to familiar uses from East Asia like "Tokyo" and "Pyongyang".
* You can also now use {@link #NORSE_SIMPLIFIED} directly, which is probably easiest.
* <br>
* Leyrk tjör stomri kna snó æd ðrépdápá, prygso?
*/
public static final FakeLanguageGen NORSE = norse().register("Norse");
private static FakeLanguageGen nahuatl(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "i", "o", "o", "o", "e", "e", "eo", "oa", "ea"},
new String[]{},
new String[]{"ch", "c", "h", "m", "l", "n", "p", "t", "tl", "tz", "x", "y", "z", "hu", "cu",
"l", "l", "l", "p", "p", "t", "t", "t", "t", "t", "tl", "tl", "tz", "z", "x", "hu"},
new String[]{"zp", "ztl", "zc", "zt", "zl", "ct", "cl", "pl", "mt", "mc", "mch", "cz", "tc", "lc",
"hu", "hu", "hu", "cu"},
new String[]{
"ch", "c", "h", "m", "l", "n", "p", "t", "tl", "tz", "x", "y", "z",
"l", "l", "l", "l", "p", "t", "t", "t", "tl", "tl", "tz", "tz", "z", "x"
},
new String[]{"otl", "eotl", "ili", "itl", "atl", "atli", "oca", "itli", "oatl", "al", "ico", "acual",
"ote", "ope", "oli", "ili", "acan", "ato", "atotl", "ache", "oc", "aloc", "ax", "itziz", "iz"
},
new String[]{}, new int[]{1, 2, 3, 4, 5, 6}, new double[]{3, 4, 5, 4, 3, 1}, 0.3, 0.2, 0.0, 0.3, genericSanityChecks, true)
.addModifiers(new Modifier("c([ie])", "qu$1"),
new Modifier("z([ie])", "c$1"));
}
/**
* Imitation text from an approximation of the language spoken by the Aztec people and also over a million
* contemporary people in parts of Mexico. This is may be hard to pronounce, since it uses "tl" as a normal
* consonant (it can start or end words), but is mostly a fairly recognizable style of language.
* <br>
* Olcoletl latl palitz ach; xatatli tzotloca amtitl, xatloatzoatl tealitozaztitli otamtax?
*/
public static final FakeLanguageGen NAHUATL = nahuatl().register("Nahuatl");
private static FakeLanguageGen mongolian(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "a", "aa", "aa", "e", "i", "i", "i", "i", "i", "i", "i", "i", "ii",
"o", "o", "o", "o", "oo", "u", "u", "u", "u", "u", "u", "u", "u", "uu", "uu", "ai", "ai"},
new String[]{},
new String[]{"g", "m", "n", "g", "m", "n", "g", "m", "n", "n", "n", "ch", "gh", "ch", "gh", "gh", "j", "j", "j", "j",
"s", "s", "s", "t", "ts", "kh", "r", "r", "l", "h", "h", "h", "h", "h", "b", "b", "b", "b", "z", "z", "y", "y"},
new String[]{},
new String[]{"g", "m", "n", "g", "m", "n", "g", "m", "n", "n", "n", "ch", "gh", "ch", "gh", "gh", "gh", "j", "j", "j",
"s", "s", "s", "t", "ts", "kh", "r", "r", "l", "h", "h", "h", "h", "h", "b", "b", "b", "b", "z", "z", "g", "n",
"g", "m", "n", "g", "m", "n", "g", "m", "n", "n", "n", "ch", "gh", "ch", "gh", "gh", "gh", "j", "j", "j", "n",
"s", "s", "s", "t", "ts", "kh", "r", "r", "l", "h", "h", "h", "h", "h", "b", "b", "b", "b", "z", "z", "y", "y",
"ng", "ng", "ng", "ngh", "ngh", "lj", "gch", "sd", "rl", "bl", "sd", "st", "md", "mg", "gd", "gd",
"sv", "rg", "rg", "mr", "tn", "tg", "ds", "dh", "dm", "gts", "rh", "lb", "gr", "gy", "rgh"},
new String[]{"ei", "ei", "ei", "uulj", "iig", "is", "is", "an", "aan", "iis", "alai", "ai", "aj", "ali"
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{5, 9, 3, 1}, 0.3, 0.2, 0.0, 0.07, null, true);
}
/**
* Imitation text from an approximation of one of the languages spoken in the 13th-century Mongol Empire. Can be
* hard to pronounce. This is closest to Middle Mongolian, and is probably not the best way to approximate modern
* Mongolian, which was written for many years in the Cyrillic alphabet (same alphabet as Russian) and has changed a
* lot in other ways.
* <br>
* Ghamgarg zilijuub lirgh arghar zunghichuh naboogh.
*/
public static final FakeLanguageGen MONGOLIAN = mongolian().register("Mongolian");
/**
* A mix of four different languages, using only ASCII characters, that is meant for generating single words for
* creature or place names in fantasy settings.
* <br>
* Adeni, Sainane, Caneros, Sune, Alade, Tidifi, Muni, Gito, Lixoi, Bovi...
*/
public static final FakeLanguageGen FANTASY_NAME = GREEK_ROMANIZED.mix(
RUSSIAN_ROMANIZED.mix(
FRENCH.removeAccents().mix(
JAPANESE_ROMANIZED, 0.5), 0.85), 0.925).register("Fantasy");
/**
* A mix of four different languages with some accented characters added onto an ASCII base, that can be good for
* generating single words for creature or place names in fantasy settings that should have a "fancy" feeling from
* having unnecessary accents added primarily for visual reasons.
* <br>
* Askieno, Blarcīnũn, Mēmida, Zizhounkô, Blęrinaf, Zemĭ, Mónazôr, Renerstă, Uskus, Toufounôr...
*/
public static final FakeLanguageGen FANCY_FANTASY_NAME = FANTASY_NAME.addAccents(0.47, 0.07).register("Fancy Fantasy");
private static FakeLanguageGen goblin(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a",
"e", "e",
"i", "i", "i",
"o", "o", "o", "o",
"u", "u", "u", "u", "u", "u", "u",
},
new String[]{},
new String[]{"b", "g", "d", "m", "h", "n", "r", "v", "sh", "p", "w", "y", "f", "br", "dr", "gr", "pr", "fr",
"br", "dr", "gr", "pr", "fr", "bl", "dw", "gl", "gw", "pl", "fl", "hr",
"b", "g", "d", "m", "h", "n", "r", "b", "g", "d", "m", "h", "n", "r",
"b", "g", "d", "m", "r", "b", "g", "d", "r",
},
new String[]{
"br", "gr", "dr", "pr", "fr", "rb", "rd", "rg", "rp", "rf",
"br", "gr", "dr", "rb", "rd", "rg",
"mb", "mg", "md", "mp", "mf", "bm", "gm", "dm", "pm", "fm",
"mb", "mg", "md", "bm", "gm", "dm",
"bl", "gl", "dw", "pl", "fl", "lb", "ld", "lg", "lp", "lf",
"bl", "gl", "dw", "lb", "ld", "lg",
"nb", "ng", "nd", "np", "nf", "bn", "gn", "dn", "pn", "fn",
"nb", "ng", "nd", "bn", "gn", "dn",
"my", "gy", "by", "py", "mw", "gw", "bw", "pw",
"bg", "gb", "bd", "db", "bf", "fb",
"gd", "dg", "gp", "pg", "gf", "fg",
"dp", "pd", "df", "fd",
"pf", "fp",
"bg", "gb", "bd", "db", "gd", "dg",
"bg", "gb", "bd", "db", "gd", "dg",
"bg", "gb", "bd", "db", "gd", "dg",
"bg", "gb", "bd", "db", "gd", "dg",
"bg", "gb", "bd", "db", "gd", "dg",
},
new String[]{
"b", "g", "d", "m", "n", "r", "sh", "p", "f",
"b", "g", "d", "m", "n", "r", "b", "g", "d", "m", "n", "r", "sh",
"b", "g", "d", "m", "r", "b", "g", "d", "r",
"rb", "rd", "rg", "rp", "rf", "lb", "ld", "lg", "lp", "lf",
},
new String[]{},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{3, 7, 5, 1}, 0.1, 0.15, 0.0, 0.0, genericSanityChecks, true);
}
/**
* Fantasy language that might be suitable for stealthy humanoids, such as goblins, or as a secret language used
* by humans who want to avoid notice. Uses no "hard" sounds like "t" and "k", but also tries to avoid the flowing
* aesthetic of fantasy languages associated with elves. Tends toward clusters of consonants like "bl", "gm", "dg",
* and "rd".
* <br>
* Gwabdip dwupdagorg moglab yurufrub.
*/
public static final FakeLanguageGen GOBLIN = goblin().register("Goblin");
private static FakeLanguageGen elf(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"ai", "ai", "ai", "ea", "ea", "ea", "ia", "ae"
},
new String[]{
"ai", "ai", "ae", "ea", "ia", "ie",
"â", "â", "ai", "âi", "aî", "aï", "î", "î", "ï", "ï", "îe", "iê", "ïe", "iê",
"e", "ë", "ë", "ëa", "ê", "êa", "eâ", "ei", "eî", "o", "ô",
"a", "a", "a", "e", "e", "e", "i", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"a", "a", "e", "e", "i", "o", "a", "a", "a", "e", "e", "e", "i", "i", "o",
"ai", "ai", "ai", "ai", "ai", "ei", "ei", "ei", "ea", "ea", "ea", "ea",
"ie", "ie", "ie", "ie", "ie", "ia", "ia", "ia", "ia"
},
new String[]{"l", "r", "n", "m", "th", "v", "s", "sh", "z", "f", "p", "h", "y", "c",
"l", "r", "n", "m", "th", "v", "f", "y",
"l", "r", "n", "m", "th", "v", "f",
"l", "r", "n", "th", "l", "r", "n", "th",
"l", "r", "n", "l", "r", "n", "l", "r", "n",
"pl", "fy", "ly", "cl", "fr", "pr", "qu",
},
new String[]{"rm", "ln", "lv", "lth", "ml", "mv", "nv", "vr", "rv", "ny", "mn", "nm", "ns", "nth"},
new String[]{
"l", "r", "n", "m", "th", "s",
"l", "r", "n", "th", "l", "r", "n", "th",
"l", "r", "n", "l", "r", "n", "l", "r", "n",
"r", "n", "r", "n", "r", "n", "n", "n", "n", "n"
},
new String[]{},
new String[]{}, new int[]{1, 2, 3, 4, 5}, new double[]{3, 6, 6, 3, 1}, 0.4, 0.3, 0.0, 0.0, genericSanityChecks, true);
}
/**
* Fantasy language that tries to imitate the various languages spoken by elves in J.R.R. Tolkien's works, using
* accented vowels occasionally and aiming for long, flowing, vowel-heavy words. It's called ELF because there isn't
* a consistent usage across fantasy and mythological sources of either "elvish", "elfish", "elven", "elfin", or any
* one adjective for "relating to an elf." In the GDX display module, the "smooth" and "unicode" fonts, among
* others, support all the accented characters you need for this.
* <br>
* Il ilthiê arel enya; meâlelail theasor arôreisa.
*/
public static final FakeLanguageGen ELF = elf().register("Elf");
private static FakeLanguageGen demonic(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a",
"e",
"i", "i",
"o", "o", "o", "o", "o",
"u", "u", "u", "u", "u",
},
new String[]{},
new String[]{
"b", "bh", "d", "dh", "t", "tl", "ts", "k", "ch", "kh", "g", "gh", "f", "x", "s", "sh", "z", "r", "v", "y",
"br", "bhr", "dr", "dhr", "tr", "tsr", "kr", "khr", "gr", "ghr", "fr", "shr", "vr",
"bl", "bhl", "tsl", "kl", "chl", "khl", "gl", "ghl", "fl", "sl", "zl", "vl",
"dz", "chf", "sf", "shf", "zv", "st", "sk",
"t", "t", "t", "ts", "ts", "k", "k", "k", "kh", "kh", "kh", "kh", "khr", "kl", "kl", "kr", "kr",
"z", "z", "z", "v", "v", "v", "zv", "zv", "vr", "vr", "vl", "vl", "dz", "sk", "sk", "sh", "shr",
"x", "x", "x", "gh", "gh", "ghr",
"t", "t", "t", "ts", "ts", "k", "k", "k", "kh", "kh", "kh", "kh", "khr", "kl", "kl", "kr", "kr",
"z", "z", "z", "v", "v", "v", "zv", "zv", "vr", "vr", "vl", "vl", "dz", "sk", "sk", "sh", "shr",
"x", "x", "x", "gh", "gh", "ghr",
"t", "t", "t", "ts", "ts", "k", "k", "k", "kh", "kh", "kh", "kh", "khr", "kl", "kl", "kr", "kr",
"z", "z", "z", "v", "v", "v", "zv", "zv", "vr", "vr", "vl", "vl", "dz", "sk", "sk", "sh", "shr",
"x", "x", "x", "gh", "gh", "ghr",
},
new String[]{},
new String[]{
"b", "bh", "d", "dh", "t", "lt", "k", "ch", "kh", "g", "gh", "f", "x", "s", "sh", "z", "r",
"b", "bh", "d", "dh", "t", "lt", "k", "ch", "kh", "g", "gh", "f", "x", "s", "sh", "z", "r",
"b", "bh", "d", "dh", "t", "lt", "k", "ch", "kh", "g", "gh", "f", "x", "s", "sh", "z", "r",
"b", "bh", "d", "dh", "t", "lt", "k", "ch", "kh", "g", "gh", "f", "x", "s", "sh", "z", "r",
"rb", "rbs", "rbh", "rd", "rds", "rdh", "rt", "rts", "rk", "rks", "rch", "rkh", "rg", "rsh", "rv", "rz",
"lt", "lts", "lk", "lch", "lkh", "lg", "ls", "lz", "lx",
"bs", "ds", "ts", "lts", "ks", "khs", "gs", "fs", "rs", "rx",
"bs", "ds", "ts", "lts", "ks", "khs", "gs", "fs", "rs", "rx",
"rbs", "rds", "rts", "rks", "rkhs", "rgs", "rfs", "rs", "rx",
"lbs", "lds", "lts", "lks", "lkhs", "lgs", "lfs",
"rdz", "rvz", "gz", "rgz", "vd", "kt",
"t", "t", "t", "rt", "lt", "k", "k", "k", "k", "k", "kh", "kh", "kh", "kh", "kh", "rkh", "lk", "rk", "rk",
"z", "z", "z", "z", "v", "rv", "rv", "dz", "ks", "sk", "sh",
"x", "x", "x", "gh", "gh", "gh", "rgh",
"ts", "ts", "ks", "ks", "khs",
"t", "t", "t", "rt", "lt", "k", "k", "k", "k", "k", "kh", "kh", "kh", "kh", "kh", "rkh", "lk", "rk", "rk",
"z", "z", "z", "z", "v", "rv", "rv", "dz", "ks", "sk", "sh",
"x", "x", "x", "gh", "gh", "gh", "rgh",
"ts", "ts", "ks", "ks", "khs",
"t", "t", "t", "rt", "lt", "k", "k", "k", "k", "k", "kh", "kh", "kh", "kh", "kh", "rkh", "lk", "rk", "rk",
"z", "z", "z", "z", "v", "rv", "rv", "dz", "ks", "sk", "sh",
"x", "x", "x", "gh", "gh", "gh", "rgh",
"ts", "ts", "ks", "ks", "khs",
},
new String[]{},
new String[]{"'"}, new int[]{1, 2, 3}, new double[]{6, 7, 3}, 0.05, 0.08, 0.11, 0.0, null, true);
}
/**
* Fantasy language that might be suitable for a language spoken by demons, aggressive warriors, or people who seek
* to emulate or worship similar groups. The tendency here is for DEMONIC to be the language used by creatures that
* are considered evil because of their violence, while INFERNAL would be the language used by creatures that are
* considered evil because of their manipulation and deceit (DEMONIC being "chaotic evil" and INFERNAL being "lawful
* evil"). This uses lots of sounds that don't show up in natural languages very often, mixing harsh or guttural
* sounds like "kh" and "ghr" with rare sounds like "vr", "zv", and "tl". It uses vowel-splitting in a way that is
* similar to LOVECRAFT, sometimes producing sounds like "tsa'urz" or "khu'olk".
* <br>
* Vrirvoks xatughat ogz; olds xu'oz xorgogh!
*/
public static final FakeLanguageGen DEMONIC = demonic().register("Demonic");
private static FakeLanguageGen infernal(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "à", "á", "â", "ä",
"e", "e", "e", "e", "e", "e", "e", "e", "è", "é", "ê", "ë",
"i", "i", "i", "i", "ì", "í", "î", "ï",
"o", "o", "ò", "ó", "ô", "ö",
"u", "u", "ù", "ú", "û", "ü",
},
new String[]{"æ", "ai", "aî", "i", "i", "î", "ï", "ia", "iâ", "ie", "iê", "eu", "eû", "u", "u", "û", "ü"},
new String[]{"b", "br", "d", "dr", "h", "m", "z", "k", "l", "ph", "t", "n", "y", "th", "s", "sh",
"m", "m", "m", "z", "z", "l", "l", "l", "k", "k", "b", "d", "h", "h", "y", "th", "th", "s", "sh",
},
new String[]{
"mm", "mm", "mm", "lb", "dd", "dd", "dd", "ddr", "bb", "bb", "bb", "bbr", "lz", "sm", "zr",
"thsh", "lkh", "shm", "mh", "mh",
},
new String[]{
"b", "d", "h", "m", "n", "z", "k", "l", "ph", "t", "th", "s", "sh", "kh",
"h", "m", "n", "z", "l", "ph", "t", "th", "s",
"h", "h", "h", "m", "m", "n", "n", "n", "n", "n", "l", "l", "l", "l", "l", "t", "t", "t",
"th", "th", "s", "s", "z", "z", "z", "z",
},
new String[]{"ael", "im", "on", "oth", "et", "eus", "iel", "an", "is", "ub", "ez", "ath", "esh", "ekh", "uth", "ut"},
new String[]{"'"}, new int[]{1, 2, 3, 4}, new double[]{3, 5, 9, 4}, 0.75, 0.35, 0.17, 0.07, genericSanityChecks, true);
}
/**
* Fantasy language that might be suitable for a language spoken by fiends, users of witchcraft, or people who seek
* to emulate or worship similar groups. The tendency here is for DEMONIC to be the language used by creatures that
* are considered evil because of their violence, while INFERNAL is the language used by creatures that are
* considered evil because of their manipulation and deceit (DEMONIC being "chaotic evil" and INFERNAL being "lawful
* evil"). The name INFERNAL refers to Dante's Inferno and the various naming conventions used for residents of Hell
* in the more-modern Christian traditions (as well as some of the stylistic conventions of Old Testament figures
* described as false idols, such as Moloch and Mammon). In an effort to make this distinct from the general style
* of names used in ancient Hebrew (since this is specifically meant for the names of villains as opposed to normal
* humans), we add in vowel splits as used in LOVECRAFT and DEMONIC, then add quite a few accented vowels. These
* traits make the language especially well-suited for "deal with the Devil" written bargains, where a single accent
* placed incorrectly could change the meaning of a contract and provide a way for a fiend to gain leverage.
* <br>
* Zézîzûth eke'iez áhìphon; úhiah îbbëphéh haîtemheû esmez...
*/
public static final FakeLanguageGen INFERNAL = infernal().register("Infernal");
private static FakeLanguageGen simplish(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"ai", "ai", "ea", "io", "oi", "ia", "io", "eo"
},
new String[]{"u", "u", "oa"},
new String[]{
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "v", "w", "y", "z",
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y",
"b", "c", "ch", "d", "f", "g", "h", "j", "k", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "c", "ch", "d", "f", "g", "h", "j", "k", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "c", "ch", "d", "f", "g", "h", "j", "k", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "c", "ch", "d", "f", "g", "h", "j", "k", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"r", "s", "t", "l", "n",
},
new String[]{"ch", "j", "w", "y", "v", "w", "y", "w", "y", "ch",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
},
new String[]{"bs", "lt", "mb", "ng", "ng", "nt", "ns", "ps", "mp", "rt", "rg", "sk", "rs", "ts", "lk", "ct",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t", "th", "z",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
"d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
"d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
"d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
"d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "sh", "t",
},
new String[]{},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 18, 6, 1}, 0.26, 0.12, 0.0, 0.0, genericSanityChecks, true);
}
/**
* English-like language that omits complex spelling and doesn't include any of the uncommon word endings of English
* like "ought" or "ation." A good choice when you want something that doesn't use any non-US-keyboard letters,
* looks somewhat similar to English, and tries to be pronounceable without too much effort. This doesn't have any
* doubled or silent letters, nor does it require special rules for pronouncing vowels like "road" vs. "rod", though
* someone could make up any rules they want.
* <br>
* Fledan pranam, simig bag chaimer, drefar, woshash is sasik.
*/
public static final FakeLanguageGen SIMPLISH = simplish().register("Simplish");
private static FakeLanguageGen alien_a(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "a", "ai", "ai", "ao", "ao", "ae", "ae", "e", "e", "e", "e",
"ea", "eo", "i", "i", "i", "i", "i", "i", "ia", "ie", "io", "o", "o", "o", "oa"},
new String[]{},
new String[]{"c", "f", "h", "j", "l", "m", "n", "p", "q", "r", "s", "v", "w", "x", "y", "z",
"c", "h", "j", "l", "m", "n", "q", "r", "s", "v", "w", "x", "y", "z",
"h", "j", "l", "m", "n", "q", "r", "s", "v", "w", "x", "y", "z",
"hc", "hf", "hj", "hl", "hm", "hn", "hq", "hr", "hv", "hw", "hy", "hz",
"cr", "fr", "jr", "mr", "nr", "pr", "qr", "sr", "vr", "xr", "yr", "zr",
"cy", "fy", "jy", "my", "ny", "py", "qy", "ry", "sy", "vy", "xy", "zy",
"cl", "fl", "jl", "ml", "nl", "pl", "ql", "sl", "vl", "xl", "yl", "zl",
},
new String[]{
"cr", "fr", "jr", "mr", "nr", "pr", "qr", "sr", "vr", "xr", "yr", "zr",
"cy", "fy", "jy", "my", "ny", "py", "qy", "ry", "sy", "vy", "xy", "zy",
"cl", "fl", "jl", "ml", "nl", "pl", "ql", "sl", "vl", "xl", "yl", "zl",
"jc", "lc", "mc", "nc", "qc", "rc", "sc", "wc", "yc", "zc",
"cf", "jf", "lf", "nf", "qf", "rf", "sf", "vf", "wf", "yf", "zf",
"cj", "fj", "lj", "mj", "nj", "qj", "rj", "sj", "wj", "yj", "zj",
"cm", "fm", "jm", "lm", "nm", "qm", "rm", "sm", "vm", "wm", "ym", "zm",
"cn", "fn", "jn", "ln", "mn", "qn", "rn", "sn", "vn", "wn", "yn", "zn",
"cp", "fp", "jp", "lp", "mp", "np", "qp", "rp", "sp", "vp", "wp", "yp", "zp",
"cq", "jq", "lq", "mq", "nq", "rq", "sq", "wq", "yq", "zq",
"cs", "fs", "js", "ls", "ms", "ns", "qs", "vs", "ws", "ys", "zs",
"cv", "fv", "jv", "lv", "mv", "nv", "qv", "rv", "sv", "wv", "yv", "zv",
"cw", "fw", "jw", "lw", "mw", "nw", "qw", "rw", "sw", "vw", "yw", "zw",
"cx", "jx", "lx", "mx", "nx", "qx", "rx", "vx", "wx", "yx", "zx",
"cz", "fz", "lz", "mz", "nz", "qz", "rz", "sz", "vz", "wz", "yz",
},
new String[]{
"c", "f", "h", "j", "l", "m", "n", "p", "q", "r", "s", "v", "w", "x", "y", "z",
"c", "h", "j", "l", "m", "n", "q", "r", "s", "v", "w", "x", "y", "z",
"h", "j", "l", "m", "n", "q", "r", "s", "v", "w", "x", "y", "z",
"hc", "hf", "hj", "hl", "hm", "hn", "hq", "hr", "hv", "hw", "hy", "hz",
},
new String[]{},
new String[]{}, new int[]{1, 2, 3}, new double[]{1, 1, 1}, 0.65, 0.6, 0.0, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that could be spoken by some very-non-human culture that would typically be fitting for
* an alien species. This alien language emphasizes unusual consonant groups and prefers the vowels 'a' and 'i',
* sometimes with two different vowels in one syllable, like with 'ea', but never two of the same vowel, like 'ee'.
* Many consonant groups may border on unpronounceable unless a different sound is meant by some letters, such as
* 'c', 'h', 'q', 'x', 'w', and 'y'. In particular, 'x' and 'q' may need to sound like different breathy, guttural,
* or click noises for this to be pronounced by humans effectively.
* <br>
* Jlerno iypeyae; miojqaexli qraisojlea epefsaihj xlae...
*/
public static final FakeLanguageGen ALIEN_A = alien_a().register("Alien A");
private static FakeLanguageGen korean()
{
return new FakeLanguageGen(
new String[]{
"a", "ae", "ya", "yae", "eo", "e", "yeo", "ye", "o", "wa", "wae",
"oe", "yo", "u", "wo", "we", "wi", "yu", "eu", "i", "ui",
"a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "u", "u", "u", "u",
"ae", "ya", "eo", "eo", "eu", "eu", "wa", "wae", "wo", "oe", "oe",
"yo", "yo", "yu", "yu", "eu",
},
new String[]{},
new String[]{
"g", "n", "d", "r", "m", "b", "s", "j", "ch", "k", "t", "p", "h",
"g", "n", "d", "b", "p", "k", "j", "ch", "h",
"g", "n", "d", "b", "p", "k", "j", "h",
"g", "n", "p", "k", "j",
"g", "p", "k",
"g", "p", "k",
},
new String[]{
"g", "kg", "ngn", "kd", "ngn", "ngm", "kb", "ks", "kj", "kch", "k-k", "kt", "kp", "k",
"n", "n-g", "nn", "nd", "nn", "nm", "nb", "ns", "nj", "nch", "nk", "nt", "np", "nh",
"d", "tg", "nn", "td", "nn", "nm", "tb", "ts", "tj", "tch", "tk", "t-t", "tp", "t",
"r", "lg", "nn", "ld", "ll", "lm", "lb", "ls", "lj", "lch", "lk", "lt", "lp", "lh",
"m", "mg", "mn", "md", "mn", "mm", "mb", "ms", "mj", "mch", "mk", "mt", "mp", "mh",
"b", "pg", "mn", "pd", "mn", "mm", "pb", "ps", "pj", "pch", "pk", "pt", "p-p", "p",
"s", "tg", "nn", "td", "nn", "nm", "tb", "ts", "tj", "tch", "tk", "t-t", "tp", "t",
"ng-", "ngg", "ngn", "ngd", "ngn", "ngm", "ngb", "ngs", "ngj", "ngch", "ngk", "ngt", "ngp", "ngh",
"j", "tg", "nn", "td", "nn", "nm", "tb", "ts", "tj", "tch", "tk", "t-t", "tp", "ch",
"t", "t", "t", "j", "j", "j", "g", "g", "g", "g", "n", "n", "n", "n", "n", "ng", "ng", "ng",
"d", "d", "d", "b", "b",
"tt", "nn", "kk", "kk", "ks",
"h", "k", "nn", "t", "nn", "nm", "p", "hs", "ch", "tch", "tk", "tt", "tp", "t",
"kk", "pp", "ss", "tt", "jj", "ks", "nch", "nh", "r",
"r", "r", "r", "r", "r", "r", "r", "r", "r", "r", "r", "r",
"ngg", "ngn", "ngm", "ngj", "ngch", "ngk", "ngp",
"mg", "mch", "mk", "md", "mb", "mp",
"nj", "nch", "nd", "nk", "nb", "nj", "nch", "nd", "nk",
"kg", "kj", "kch"
},
new String[]{
"k", "n", "t", "l", "m", "p", "k", "ng", "h", "n", "n",
"k", "n", "t", "l", "m", "p", "k", "ng", "h", "t",
},
new String[]{"ul", "eul", "eol", "ol", "il", "yeol", "yol", "uk", "euk", "eok", "aek", "ok", "ak",
"on", "ong", "eong", "yang", "yong", "yeong", "ung", "wong", "om", "am", "im", "yuh", "uh", "euh",
"ap", "yaep", "eop", "wep", "yeop"
},
new String[]{"-"},
new int[]{1, 2, 3, 4}, new double[]{14, 9, 3, 1}, 0.14, 0.24, 0.02, 0.09,
null, true);
}
/**
* Imitation text from an approximation of Korean, using the Revised Romanization method that is official in South
* Korea today and is easier to type. The text this makes may be hard to pronounce. Korean is interesting as a
* language to imitate for a number of reasons; many of the sounds in it are rarely found elsewhere, it can cluster
* consonants rather tightly (most languages don't; English does to a similar degree but Japanese hardly has any
* groups of consonants), and there are many more vowel sounds without using tones (here, two or three letters are
* used for a vowel, where the first can be y or w and the rest can be a, e, i, o, or u in some combination). Some
* letter combinations possible here are impossible or very rare in correctly-Romanized actual Korean, such as the
* rare occurrence of a single 'l' before a vowel (it normally only appears in Romanized text before a consonant or
* at the end of a word).
* <br>
* Hyeop euryam, sonyon muk tyeok aengyankeon, koelgwaelmwak.
*/
public static final FakeLanguageGen KOREAN_ROMANIZED = korean().register("Korean Romanized");
private static FakeLanguageGen alien_e(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "aa", "aa",
"e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "ee", "ee", "ee", "ee",
"i", "i", "i", "i", "i", "ii",
"o", "o", "o", "o",
"u", "u", "u"
},
new String[]{},
new String[]{"t", "k", "c", "g", "z", "s", "d", "r", "ts",
"tr", "kr", "cr", "gr", "zr", "st", "sk", "dr",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"t", "k", "c", "g", "r", "ts", "t", "k", "c", "g", "r", "ts",
"t", "k", "c", "g", "r", "ts", "t", "k", "c", "g", "r", "ts",
"t", "k", "c", "g", "r", "ts", "t", "k", "c", "g", "r", "ts",
"t", "k", "ts", "t", "k", "ts", "t", "k", "ts", "t", "k", "ts",
"t", "k", "ts", "t", "k", "ts", "t", "k", "ts", "t", "k", "ts",
"t", "k", "t", "k", "t", "k", "t", "k", "t", "k", "t", "k",
"tr", "kr", "st", "sk", "tq", "kq", "sq"
},
new String[]{
"tt", "kk", "cc", "gg", "zz", "dd", "s", "r", "ts",
"tr", "kr", "cr", "gr", "zr", "st", "sk", "dr",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"tq", "kq", "cq", "gq", "zq", "sq", "dq",
"tk", "kt", "tc", "ct", "gt", "tg", "zt", "tz", "td", "dt", "rt", "rtr", "tst",
"kc", "ck", "gk", "kg", "zk", "kz", "kd", "dk", "rk", "rkr", "tsk", "kts",
"gc", "cg", "zc", "cz", "cd", "dc", "rc", "rcr", "tsc", "cts",
"zg", "gz", "gd", "dg", "rg", "rgr", "tsg", "gts",
"zd", "dz", "rz", "rzr", "tsz", "zts",
"rd", "rdr", "tsd", "dts",
"tt", "tt", "tt", "tt", "tt", "tt",
"tt", "tt", "tt", "tt", "tt", "tt",
"kk", "kk", "kk", "kk", "kk", "kk",
"kk", "kk", "kk", "kk", "kk", "kk",
"kt", "tk", "kt", "tk", "kt", "tk", "kt", "tk",
},
new String[]{
"t", "k", "c", "g", "z", "s", "d", "r", "ts",
"t", "k", "t", "k", "t", "k", "ts",
"t", "k", "c", "g", "z", "s", "d", "r", "ts",
"t", "k", "t", "k", "t", "k", "ts",
"st", "sk", "sc", "sg", "sz", "ds",
"rt", "rk", "rc", "rg", "rz", "rd", "rts"
},
new String[]{},
new String[]{}, new int[]{1, 2, 3}, new double[]{5, 4, 2}, 0.45, 0.0, 0.0, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that could be spoken by some very-non-human culture that would typically be fitting for
* an alien species. This alien language emphasizes hard sounds and prefers the vowels 'e' and 'a', sometimes with
* two of the same vowel, like 'ee', but never with two different vowels in one syllable, like with 'ea'.
* This language is meant to use click sounds, if pronunciation is given, where 'q' modifies a consonant to form a
* click, such as 'tq'. This is like how 'h' modifies letters in English to make 'th' different from 't' or 'h'.
* This may be ideal for a species with a beak (or one that lacks lips for some other reason), since it avoids using
* sounds that require lips (some clicks might be approximated by other species using their lips if this uses some
* alien-specific clicking organ).
* <br>
* Reds zasg izqekkek zagtsarg ukaard ac ots as!
*/
public static final FakeLanguageGen ALIEN_E = alien_e().register("Alien E");
private static FakeLanguageGen alien_i(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "a", "a", "à", "á", "â", "ā", "ä",
"e", "e", "e", "e", "e", "e", "è", "é", "ê", "ē", "ë",
"i", "i", "i", "i", "i", "i", "i", "i", "ì", "í", "î", "ï", "ī",
"i", "i", "i", "i", "i", "i", "i", "i", "ì", "í", "î", "ï", "ī",
"o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "o", "ò", "ó", "ô", "ō", "ö",
"u", "u", "u", "u", "u", "u", "ù", "ú", "û", "ū", "ü",
},
new String[]{},
new String[]{
"r", "l", "ch", "g", "z", "zh", "s", "sh", "th", "m", "n", "p", "b", "j", "v", "h", "r", "l",
"r", "l", "ch", "g", "z", "zh", "s", "sh", "th", "m", "n", "p", "b", "j", "v", "h", "r", "l",
"r", "l", "ch", "g", "z", "zh", "s", "sh", "th", "m", "n", "p", "b", "j", "v", "h", "r", "l",
"r", "r", "r", "r", "r", "l", "l", "l", "l", "l",
"gr", "gl", "zr", "zl", "sl", "shr", "thr", "mr", "nr", "pr", "pl", "br", "bl", "vr", "vl", "hr",
"zv", "sp", "zg"
},
new String[]{
"j", "h",
},
new String[]{
"r", "l", "ch", "g", "z", "zh", "s", "sh", "th", "m", "n", "p", "b", "v", "r", "l",
"th", "zh", "sh", "th", "zh", "sh", "lth", "lzh", "lsh", "rth", "rzh", "rsh",
},
new String[]{},
new String[]{"'"}, new int[]{1, 2, 3, 4}, new double[]{6, 9, 5, 1}, 0.6, 0.4, 0.075, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that could be spoken by some very-non-human culture that would typically be fitting for
* an alien species. This alien language emphasizes "liquid" sounds such as 'l', 'r', and mixes with those and other
* consonants, and prefers the vowels 'i' and 'o', never with two of the same vowel, like 'ee', nor with two
* different vowels in one syllable, like with 'ea'; it uses accent marks heavily and could be a tonal language.
* It sometimes splits vowels with a single apostrophe, and rarely has large consonant clusters.
* <br>
* Asherzhäl zlómór ìsiv ázá nralthóshos, zlôbùsh.
*/
public static final FakeLanguageGen ALIEN_I = alien_i().register("Alien I");
private static FakeLanguageGen alien_o(){
return new FakeLanguageGen(
new String[]{
"a", "e", "i", "o", "o", "o", "o", "u",
"aa", "ea", "ia", "oa", "oa", "oa", "ua", "ae", "ai", "ao", "ao", "ao", "au",
"ee", "ie", "oe", "oe", "oe", "ue", "ei", "eo", "eo", "eo", "eu",
"ii", "oi", "oi", "oi", "ui", "io", "io", "io", "iu",
"oo", "ou", "uo", "oo", "ou", "uo", "oo", "ou", "uo", "uu",
"aa", "ea", "ia", "oa", "oa", "oa", "ua", "ae", "ai", "ao", "ao", "ao", "au",
"ee", "ie", "oe", "oe", "oe", "ue", "ei", "eo", "eo", "eo", "eu",
"ii", "oi", "ui", "io", "io", "io", "iu",
"oo", "ou", "uo", "oo", "ou", "uo", "oo", "ou", "uo", "uu",
"aea", "aia", "aoa", "aoa", "aoa", "aua", "eae", "eie", "eoe", "eoe", "eoe", "eue",
"iai", "iei", "ioi", "ioi", "ioi", "iui", "uau", "ueu", "uiu", "uou",
"oao", "oeo", "oio", "ouo", "oao", "oeo", "oio", "ouo", "oao", "oeo", "oio", "ouo",
"aei", "aeo", "aeo", "aeo", "aeu", "aie", "aio", "aio", "aio", "aiu",
"aoe", "aoi", "aou", "aoe", "aoi", "aou", "aoe", "aoi", "aou", "aue", "aui", "auo", "auo", "auo",
"eai", "eao", "eao", "eao", "eau", "eia", "eio", "eio", "eio", "eiu",
"eoa", "eoi", "eou", "eoa", "eoi", "eou", "eoa", "eoi", "eou", "eua", "eui", "euo", "euo", "euo",
"iae", "iao", "iao", "iao", "iau", "iea", "ieo", "ieo", "ieo", "ieu",
"ioa", "ioe", "iou", "ioa", "ioe", "iou", "ioa", "ioe", "iou", "iua", "iue", "iuo", "iuo", "iuo",
"oae", "oai", "oau", "oea", "oei", "oeu", "oia", "oie", "oiu", "oua", "oue", "oui",
"oae", "oai", "oau", "oea", "oei", "oeu", "oia", "oie", "oiu", "oua", "oue", "oui",
"oae", "oai", "oau", "oea", "oei", "oeu", "oia", "oie", "oiu", "oua", "oue", "oui",
"uae", "uai", "uao", "uao", "uao", "uea", "uei", "ueo", "ueo", "ueo", "uia", "uie",
"uio", "uoa", "uoe", "uoi", "uio", "uoa", "uoe", "uoi", "uio", "uoa", "uoe", "uoi",
},
new String[]{},
new String[]{
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"hm", "hn", "hr", "hw", "hv", "hl", "hy",
"fm", "fn", "fr", "fw", "fv", "fl", "fy",
"mr", "vr", "ry"
},
new String[]{
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"m", "n", "r", "w", "h", "v", "f", "l", "y",
"mm", "nn", "rr", "ww", "hh", "vv", "ff", "ll", "yy",
"mm", "nn", "rr", "ww", "hh", "vv", "ff", "ll", "yy",
"hm", "hn", "hr", "hw", "hv", "hl", "hy",
"fm", "fn", "fr", "fw", "fv", "fl", "fy",
"mr", "vr", "ry"
},
new String[]{
"m", "n", "r", "h", "v", "f", "l",
"m", "n", "r", "h", "v", "f", "l",
"m", "n", "r", "h", "v", "f", "l",
"rm", "rn", "rv", "rf", "rl",
"lm", "ln", "lv", "lf"
},
new String[]{},
new String[]{}, new int[]{1, 2, 3}, new double[]{3, 6, 4}, 0.0, 0.55, 0.0, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that could be spoken by some very-non-human culture that would typically be fitting for
* an alien species. This alien language emphasizes large clusters of vowels, typically with 2 or 3 vowel sounds
* between consonants, though some vowel groups could be interpreted in multiple ways (such as English "maim" and
* "bail", which also have regional differences in pronunciation). As the name would suggest, it strongly prefers
* using the vowel "o", with it present in about half the groups, but doesn't have any preference toward or against
* the other vowels it uses, "a", "e", "i", and "u". The consonants completely avoid hard sounds like "t" and "k",
* medium-hard sounds like "g" and "b", and also sibilants like "s" and "z". This should be fairly hard to
* pronounce, but possible.
* <br>
* Foiuhoeorfeaorm novruol naionouffeu meuif; hmoieloreo naemriou.
*/
public static final FakeLanguageGen ALIEN_O = alien_o().register("Alien O");
// àáâãäåæāăąǻǽaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőœǿoùúûüũūŭůűųuýÿŷỳ
// çðþñýćĉċčďđĝğġģĥħĵķĺļľŀłńņňŋŕŗřśŝşšţťŵŷÿźżžșțẁẃẅ
private static FakeLanguageGen alien_u(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "ä", "i", "o", "o", "o", "ö", "u", "u", "u", "u", "u", "u", "ü", "ü"
},
new String[]{},
new String[]{
"b", "b", "b", "b", "d", "d", "g", "g", "ġ", "h", "h", "h", "h", "ħ",
"l", "l", "l", "l", "ł", "m", "m", "m", "m", "m", "n", "n", "n", "n", "ñ", "ŋ", "p", "p", "p",
"q", "q", "r", "r", "r", "ŕ", "s", "s", "s", "s", "ś", "v", "v", "v", "v",
"w", "w", "w", "w", "ẃ", "y", "y", "y", "y", "ý"
},
new String[]{
"b", "b", "b", "b", "d", "d", "g", "g", "ġ", "h", "h", "h", "h", "ħ",
"l", "l", "l", "l", "ł", "m", "m", "m", "m", "m", "n", "n", "n", "n", "ñ", "ŋ", "p", "p", "p",
"q", "q", "r", "r", "r", "ŕ", "s", "s", "s", "s", "ś", "v", "v", "v", "v",
"w", "w", "w", "w", "ẃ", "y", "y", "y", "y", "ý"
},
new String[]{
"b", "b", "b", "b", "d", "d", "g", "g", "ġ",
"l", "l", "l", "l", "ł", "m", "m", "m", "m", "m", "n", "n", "n", "n", "ñ", "ŋ", "p", "p", "p",
"r", "r", "r", "ŕ", "s", "s", "s", "s", "ś", "v", "v", "v", "v",
},
new String[]{"emb", "embrid", "embraŋ", "eŋ", "eŋul", "eŋov", "eẃul", "eẃuld", "eẃulb",
"eviś", "evim", "ełurn", "ełav", "egiġ", "ergiġ", "elgiġ", "eŕu", "eŕup", "eŕulm", "eŕuv",
"eħul", "eħid", "eħiŋ", "eyü", "eyür", "eyürl", "eyüld", "eyüns", "eqä", "eqäp", "eqäġ",
"esu", "esumb", "esulg", "esurl", "eśo", "eśold", "eśolg", "eśu", "eśur", "eśuŋ",
"eñu", "eñuns", "eñurn", "eño", "eñolb", "eñols"
},
new String[]{"'"}, new int[]{1, 2, 3, 4, 5}, new double[]{3, 4, 7, 5, 2}, 0.4, 0.15, 0.06, 0.5, null, true);
}
/**
* Fantasy/sci-fi language that could be spoken by some very-non-human culture that would typically be fitting for
* an alien species. This alien language is meant to have an abrupt change mid-word for many words, with the suffix
* of roughly half of words using the letter "e", which is absent from the rest of the language; these suffixes can
* also use consonant clusters, which are similarly absent elsewhere. The suffixes would make sense as a historical
* relic or as a linguistic holdout from a historical merger. As the name would suggest, it strongly prefers
* using the vowel "u", with it present in about half the groups, and can use the umlaut accent "ü" on some vowels.
* The consonants completely avoid hard sounds like "t" and "k", and don't cluster; they often have special marks.
* This should be relatively easy to pronounce for an alien language, though the words are rather long.
* <br>
* Üweħid vuŕeħid deẃul leŋul waloyeyür; äyovavü...
*/
public static final FakeLanguageGen ALIEN_U = alien_u().register("Alien U");
private static FakeLanguageGen dragon(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "e", "e", "i", "i", "o", "o", "u",
"a", "a", "a", "e", "e", "i", "i", "o", "o", "u",
"a", "a", "a", "e", "e", "i", "i", "o", "o", "u",
"a", "a", "a", "e", "e", "i", "i", "o", "o", "u",
"a", "a", "a", "a", "a", "a", "e", "i", "o",
"ai", "ai", "aa", "ae", "au", "ea", "ea", "ea",
"ia", "ia", "ie", "io", "io", "oa", "ou"
},
new String[]{
"aa", "aa", "aa", "ai", "ae", "ae", "ae", "au", "au",
"ea", "ea", "eo", "eo",
"ii", "ii", "ia", "ia", "ia", "ia", "ie", "ie", "ie", "io", "io", "io",
"oa", "ou", "ou", "ou", "ou"
},
new String[]{
"ch", "d", "f", "g", "h", "k", "l", "m", "n", "p", "r", "t", "th", "v", "w", "y", "z",
"ch", "d", "f", "g", "h", "k", "l", "m", "n", "p", "r", "t", "th", "v", "w", "y", "z",
"d", "f", "g", "h", "k", "l", "m", "n", "r", "t", "th", "v", "z",
"d", "f", "g", "h", "k", "l", "n", "r", "t", "th", "v", "z",
"d", "f", "g", "h", "l", "k", "l", "n", "r", "t", "th", "v", "z",
"d", "g", "h", "k", "l", "n", "r", "t", "th", "v", "z",
"d", "g", "h", "k", "l", "n", "r", "t", "th", "v", "z",
"d", "g", "k", "l", "r", "t",
"d", "g", "k", "l", "r", "t",
"d", "g", "k", "l", "r", "t",
"k", "k", "t", "t", "v",
"k", "k", "t", "t", "th",
"k", "k", "t", "t", "ch",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "gr", "hr", "kr", "tr", "thr", "dr", "gr", "kr", "tr",
"dr", "gr", "hr", "kr", "tr", "thr", "dr", "gr", "kr", "tr",
},
new String[]{
"rch", "rd", "rg", "rk", "rm", "rn", "rp", "rt", "rth", "rv", "rw", "rz",
"rch", "rd", "rg", "rk", "rm", "rn", "rp", "rt", "rth", "rv", "rw", "rz",
"rdr", "rgr", "rkr", "rtr", "rthr",
"lk", "lt", "lv", "lz",
"ng", "nk", "ng", "nk", "ng", "nk", "ng", "nk", "nt", "nth", "nt", "nth", "nt", "nth", "nd",
"ngr", "nkr", "ntr", "nthr",
"dh", "gh", "lh", "mh", "nh", "rh",
"dch", "dg", "dk", "dth", "dv", "dz",
"kch", "kg", "kd", "kth", "kv", "kz",
"gch", "gd", "gk", "gth", "gv", "gz",
"tch", "tg", "tk", "ty", "tv", "tz",
"zm", "zn", "zk", "zv", "zt", "zg", "zd",
"ch", "d", "f", "g", "h", "k", "l", "m", "n", "p", "r", "t", "th", "v", "w", "y", "z",
"ch", "d", "f", "g", "h", "k", "l", "m", "n", "p", "r", "t", "th", "v", "w", "y", "z",
"d", "f", "g", "h", "k", "l", "m", "n", "r", "t", "th", "v", "z",
"d", "f", "g", "h", "k", "l", "n", "r", "t", "th", "v", "z",
"d", "f", "g", "h", "k", "l", "n", "r", "t", "th", "v",
"d", "g", "k", "l", "n", "r", "t", "th", "v",
"d", "g", "k", "l", "n", "r", "t", "th", "v",
"d", "g", "k", "l", "r", "t",
"d", "g", "k", "l", "r", "t",
"d", "g", "k", "l", "r", "t",
"k", "k", "t", "t", "r",
"k", "k", "t", "t", "r",
"k", "k", "t", "t", "r",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "fr", "gr", "hr", "kr", "tr", "thr",
"dr", "gr", "hr", "kr", "tr", "thr", "dr", "gr", "kr", "tr",
"dr", "gr", "hr", "kr", "tr", "thr", "dr", "gr", "kr", "tr",
},
new String[]{
"z", "z", "z", "t", "t", "t", "n", "r", "k", "th"
},
new String[]{"iamat", "at", "ut", "ok", "iok", "ioz", "ez", "ion", "ioth", "aaz", "iel"},
new String[]{}, new int[]{2, 3, 4, 5}, new double[]{2, 7, 10, 3}, 0.14, 0.04, 0.0, 0.11, genericSanityChecks, true);
}
/**
* Fantasy language that tries to sound like the speech of a powerful and pompous dragon, using long, complex words
* and a mix of hard consonants like "t" and "k", "liquid" consonants like "l" and "r", and sometimes vowel groups
* like "ie" and "aa". It frequently uses consonant clusters involving "r". It uses no accented characters.
* <br>
* Vokegodzaaz kigrofreth ariatarkioth etrokagik deantoznik hragriemitaaz gianehaadaz...
*/
public static final FakeLanguageGen DRAGON = dragon().register("Dragon");
/**
* Fantasy language based closely on {@link #DRAGON}, but with much shorter words normally and closing syllables
* that may sound "rushed" or "crude", though it has the same general frequency of most consonants and vowels.
* This means it still uses lots of "t", "k", and "r", can group two vowels sometimes, and when there's a consonant
* in the middle of a word, it is often accompanied by an "r" on one or both sides. If used with
* {@link NaturalLanguageCipher}, this will look very similar to DRAGON, because the syllable lengths aren't
* determined by this object but by the text being ciphered. Still, the ends of words are often different. It is
* called KOBOLD because, even though the original kobold myth was that of a goblin-like spirit that haunted cobalt
* mines, the modern RPG treatment of kobolds frequently describes them as worshippers of dragons or in some way
* created by dragons, but generally they're a sort of failure to live up to a dragon's high expectations. The feel
* of this language is meant to be something like a dragon's speech, but much less "fancy" and rather curt.
* <br>
* Thritriz, laazak gruz kokak thon lut...
*/
public static final FakeLanguageGen KOBOLD = new FakeLanguageGen(
DRAGON.openingVowels, DRAGON.midVowels, DRAGON.openingConsonants, DRAGON.midConsonants, DRAGON.closingConsonants,
new String[]{"ik", "ak", "ek", "at", "it", "ik", "ak", "ek", "at", "it", "ik", "ak", "ek", "at", "it", "et", "ut", "ark", "irk", "erk"},
DRAGON.vowelSplitters, new int[]{1, 2, 3}, new double[]{5, 11, 1},
0.1, 0.0, 0.0, 0.22, genericSanityChecks, true).register("Kobold");
private static FakeLanguageGen insect(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "a", "a",
"e", "e", "e", "e",
"i", "i", "i", "i", "i", "i", "i",
"o", "o", "o",
"u", "u",
},
new String[]{},
new String[]{"t", "k", "g", "sh", "s", "x", "r", "ts",
"tr", "kr", "gr", "shr", "st", "sk",
"tr", "kr", "st", "sk", "tr", "kr", "st", "sk",
"t", "k", "g", "sh", "s", "x", "r", "ts",
"t", "k", "r", "ts", "ts",
"t", "k", "r", "tr", "kr", "t", "k", "r", "tr", "kr", "t", "k", "r", "tr", "kr",
"t", "k", "t", "k", "t", "k", "t", "k", "t", "k", "t", "k",
},
new String[]{
"rr","rr","rr","rr","rr","rr","rr","rr","rr","rr",
"rt", "rk", "rg", "rsh", "rs", "rx", "rts",
"xt", "xk", "xg", "xr",
"sts", "skr", "str", "sks"
},
new String[]{
"t", "k", "g", "sh", "s", "x", "r", "ts", "t", "k", "g", "sh", "s", "x", "r", "ts",
"rt", "rk", "rg", "rsh", "rs", "rx", "rts",
"t", "t", "t", "t", "t", "t", "k", "k", "k", "k", "k", "k", "x", "x", "rr", "rr", "rr"
},
new String[]{},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{6, 4, 2, 1}, 0.3, 0.1, 0.0, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that would typically be fitting for an insect-like species without a close equivalent to
* human lips. This language emphasizes hard sounds such as 't' and 'k', uses some sibilants such as 's', 'sh', and
* 'x', uses lots of 'r' sounds, includes trill sounds using 'rr' (as in Spanish), and uses primarily 'a' and 'i'
* for vowels, with low complexity on vowels. Differs from {@link #ALIEN_E} by not having harder-to-explain click
* sounds, and adjusting vowels/sibilants a fair bit.
* <br>
* Ritars tsarraxgits, krit trir istsak!
*/
public static final FakeLanguageGen INSECT = insect().register("Insect");
private static FakeLanguageGen maori(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"a", "a", "a", "a", "a", "a", "ā", "ā", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "o", "o", "o", "u", "u",
"ae", "ai", "ai", "ai", "ao", "ao", "ao", "ao", "au",
"ae", "ai", "ai", "ai", "ao", "ao", "ao", "ao", "au",
"āe", "āi", "āi", "āi", "āo", "āo", "āo", "āo", "āu", "oi", "oe", "ou",
"ae", "ai", "ai", "ai", "ao", "ao", "ao", "ao", "au",
"ae", "ai", "ai", "ai", "ao", "ao", "ao", "ao", "au",
"āe", "āi", "āi", "āi", "āo", "āo", "āo", "āo", "āu", "oi", "oe", "ou",
"āa", "āoi", "āoe", "āou",
"āa", "āoi", "āoe", "āou",
"ea", "ei", "ei", "ei", "eo", "eo", "eo", "eu", "eae", "eai", "eao", "eā", "eāe", "eāi", "eāo", "eoi", "eoe", "eou",
"ia", "ia", "ie", "io", "io", "iu", "iae", "iai", "iao", "iau", "iā", "iāe", "iāi", "iāo", "iāu", "ioi", "ioe", "iou",
"oa", "oa", "oa", "oa", "oae", "oai", "oao", "oau", "oā", "oā", "oāe", "oāi", "oāo", "oāu",
"oa", "oa", "oa", "oa", "oae", "oai", "oao", "oau", "oā", "oā", "oāe", "oāi", "oāo", "oāu",
"ua", "ue", "ui", "uo", "uae", "uai", "uao", "uau", "uā", "uāe", "uāi", "uāo", "uāu", "uoi", "uoe", "uou",
"aea", "aea", "aei", "aei", "aei", "aeo", "aeo", "aeo", "aeu",
"aia", "aia", "aia", "aia", "aie", "aio", "aio", "aiu",
"aoa", "aoa",
"aua", "aua", "aue", "aue", "aue", "aui", "aui", "auo",
"āea", "āea", "āei", "āei", "āei", "āeo", "āeo", "āeo", "āeu",
"āia", "āia", "āia", "āia", "āie", "āio", "āio", "āiu",
"āoa", "āoa",
"āua", "āua", "āue", "āue", "āue", "āui", "āui", "āuo",
},
new String[]{},
new String[]{"h", "h", "k", "k", "m", "m", "m", "m", "n", "n", "p", "p",
"r", "r", "r", "r", "r", "t", "t", "t", "t", "w", "w", "ng", "wh", "wh", "wh",
"h", "k", "m", "m", "m", "m", "n", "n", "p", "p",
"r", "r", "r", "r", "r", "t", "t", "t", "t", "w", "w", "wh", "wh", "wh"
},
new String[]{"h", "k", "k", "k", "m", "n", "n", "n", "p", "p", "p", "p", "p",
"r", "r", "r", "t", "t", "t", "w", "ng", "ng", "ng", "ng", "wh", "wh"
},
new String[]{""},
new String[]{},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{5, 5, 4, 2}, 0.2, 1.0, 0.0, 0.0, genericSanityChecks, true);
}
/**
* Imitation text from an approximation of the Maori language, spoken in New Zealand both today and historically,
* and closely related to some other Polynesian languages. This version uses the current standard orthographic
* standard of representing a long "a" with the letter "ā" (adding a macron diacritic).
* <br>
* Māuka whapi enāongupe worute, moa noepo?
*/
public static final FakeLanguageGen MAORI = maori().register("Maori");
private static FakeLanguageGen spanish(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "i", "i", "i", "o", "o", "o", "e", "e", "e", "e", "e", "u", "u"},
new String[]{"a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"a", "a", "a", "a", "a", "a", "i", "i", "i", "i", "o", "o", "o", "o", "o", "e", "e", "e", "e", "e",
"ai", "ai", "eo", "ia", "ia", "ie", "io", "iu", "oi", "ui", "ue", "ua",
"ai", "ai", "eo", "ia", "ia", "ie", "io", "iu", "oi", "ui", "ue", "ua",
"ai", "ai", "eo", "ia", "ia", "ie", "io", "iu", "oi", "ui", "ue", "ua",
"ái", "aí", "éo", "ía", "iá", "íe", "ié", "ío", "íu", "oí", "uí", "ué", "uá",
"á", "é", "í", "ó", "ú", "á", "é", "í", "ó",},
new String[]{"b", "c", "ch", "d", "f", "g", "gu", "h", "j", "l", "m", "n", "p", "qu", "r", "s", "t", "v", "z",
"b", "s", "z", "r", "n", "h", "j", "j", "s", "c", "r",
"b", "s", "z", "r", "n", "h", "j", "s", "c", "r",
"b", "s", "r", "n", "h", "j", "s", "c", "r",
"n", "s", "l", "c", "n", "s", "l", "c",
"br", "gr", "fr"
},
new String[]{"ñ", "rr", "ll", "ñ", "rr", "ll", "mb", "nd", "ng", "nqu", "rqu", "zqu", "zc", "rd", "rb", "rt", "rt", "rc", "sm", "sd"},
new String[]{"r", "n", "s", "s", "r", "n", "s", "s", "r", "n", "s", "s", "r", "n", "s", "s",
"r", "n", "s", "r", "n", "s", "r", "n", "s", "r", "n", "s",
},
new String[]{"on", "ez", "es", "es", "es", "es", "es",
"ador", "edor", "ando", "endo", "indo",
"ar", "as", "amos", "an", "oy", "ay",
"er", "es", "emos", "en", "e",
"ir", "es", "imos", "en", "io",
"o", "a", "o", "a", "o", "a", "o", "a", "os", "as", "os", "as", "os", "as"
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{4, 5, 3, 1}, 0.1, 1.0, 0.0, 0.3, genericSanityChecks, true)
.addModifiers(
new Modifier("([aeouáéóú])i$", "$1y"),
new Modifier("([qQ])ua", "$1ue"), // guapo, agua, guano, all real Spanish, we should allow gua
new Modifier("([qQ])uá", "$1ué"),
new Modifier("([qgQG])u[ouy]", "$1ui"),
new Modifier("([qgQG])u[óú]", "$1uí"));
}
/**
* Imitation text from an approximation of Spanish (not using the variations spoken in Spain, but closer to Latin
* American forms of Spanish). This isn't as close as possible, but it abides by most of the orthographic rules that
* Spanish uses. It uses the acute accent on the vowels á, é, í, ó, and ú, as well as the consonant ñ.
* <br>
* Jamos daí oñuezqui, luarbezquisdas canga ombiurta irri hoño resda!
*/
public static final FakeLanguageGen SPANISH = spanish().register("Spanish");
private static FakeLanguageGen deepSpeech(){
return new FakeLanguageGen(
new String[]{
"a", "a", "o", "o", "o", "o", "u", "u", "u", "u",
"a", "a", "o", "o", "o", "o", "u", "u", "u", "u",
"a", "a", "o", "o", "o", "o", "u", "u", "u", "u",
"a", "a", "o", "o", "o", "o", "u", "u", "u", "u",
"a", "a", "o", "o", "o", "o", "u", "u", "u", "u",
"aa", "aa", "oo", "oo", "oo", "oo", "uu", "uu", "uu", "uu",
"aa", "aa", "oo", "oo", "oo", "oo", "uu", "uu", "uu", "uu",
"ah", "ah", "oh", "oh", "oh", "oh", "uh", "uh", "uh", "uh",
"aah", "ooh", "ooh", "uuh", "uuh",
},
new String[]{},
new String[]{
"m", "ng", "r", "x", "y", "z", "v", "l",
"m", "ng", "r", "x", "y", "z", "v", "l",
"m", "ng", "r", "x", "y", "z", "v", "l",
"m", "ng", "r", "x", "y", "z", "v", "l",
"m", "ng", "r", "x", "y", "z", "v", "l",
"m", "ng", "r", "z", "l",
"m", "ng", "r", "z", "l",
"m", "ng", "r", "z", "l",
"m", "ng", "r", "z", "l",
"mr", "vr", "ry", "zr",
"mw", "vw", "ly", "zw",
"zl", "vl"
},
new String[]{
},
new String[]{
"m", "ng", "r", "x", "z", "v", "l",
"m", "ng", "r", "x", "z", "v", "l",
"m", "ng", "r", "x", "z", "v", "l",
"m", "ng", "r", "x", "z", "v", "l",
"rm", "rng", "rx", "rz", "rv", "rl",
"lm", "lx", "lz", "lv",
},
new String[]{},
new String[]{"'"}, new int[]{1, 2, 3, 4}, new double[]{3, 6, 5, 1}, 0.18, 0.25, 0.07, 0.0, null, true);
}
/**
* Fantasy/sci-fi language that would potentially be fitting for a trade language spoken by various very-different
* groups, such as creatures with tentacled faces who need to communicate with spider-elves and living crystals.
* This language tries to use relatively few sounds so vocally-restricted species can speak it or approximate it,
* but some of its sounds are uncommon. It uses "ng" as Vietnamese does, as a sound that can be approximated with
* "w" but more accurately is like the sound at the end of "gong". It uses a breathy sound in many vowels,
* represented by "h", and this is separate from (and can be combined with) lengthening the vowel by doubling it
* ("a", "ah", "aa", and "aah" are different). The "x" sound can be approximated by any of the "kh" or "q" sounds
* used in various human languages, or with its usage in English for "ks". This does separate some vowels with "'",
* which can be a glottal stop as in Hawaiian or various other languages, or approximated with a brief pause.
* <br>
* Zrolmolurz, voluu, nguu yuh'ongohng!
*/
public static final FakeLanguageGen DEEP_SPEECH = deepSpeech().register("Deep Speech");
/**
* Somewhat close to Old Norse, which is itself very close to Icelandic, but changed to avoid letters not on a
* US-ASCII keyboard. Not to be confused with the language(s) of Norway, where the Norwegian languages are called
* norsk, and are further distinguished into Bokmål and Nynorsk. This just applies {@link Modifier#SIMPLIFY_NORSE}
* to {@link #NORSE}. This replaces eth ('Ðð') and thorn ('Þþ') with 'th' unless preceded by 's' (where 'sð' or 'sþ'
* becomes "st") or followed by 'r' (where 'ðr' or 'þr' becomes 'fr'). It replaces 'Æ' or 'æ' with 'Ae' or 'ae', and
* replaces 'Ö' or 'ö' with 'Ou' or "ou", which can change the length of a String relative to NORSE. It removes all
* other accent marks (since the two-dot umlaut accent has already been changed, this only affects acute accents).
* It also changes some of the usage of "j" where it means the English "y" sound, making "fjord" into "fyord", which
* is closer to familiar uses from East Asia like "Tokyo" and "Pyongyang".
* <br>
* Leyrk tyour stomri kna sno aed frepdapa, prygso?
*/
public static final FakeLanguageGen NORSE_SIMPLIFIED = norse().addModifiers(Modifier.SIMPLIFY_NORSE)
.register("Norse Simplified");
private static FakeLanguageGen hletkip(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "e", "e", "e", "e", "e", "i", "i", "i", "i",
"o", "o", "u", "u", "u", "u",},
new String[]{},
new String[]{
"hf", "hl", "hm", "hn", "hr", "hs", "hv", "hw", "hy", "hz",
"br", "kr", "fr", "mr", "nr", "pr", "khr", "shr", "zhr", "sr", "vr", "thr", "zv", "zr",
"by", "ky", "fy", "my", "ny", "py", "khy", "shy", "zhy", "ry", "sy", "vy", "thy", "zy",
"bl", "kl", "fl", "ml", "nl", "pl", "khl", "shl", "zhl", "sl", "vl", "thl", "lw", "zl",
"bf", "kf", "mf", "nf", "pf", "fsh", "shf", "fr", "sf", "fl", "fr", "fw", "fz",
"bs", "ks", "fs", "ms", "ns", "ps", "skh", "shs", "khs", "shv","shw",
"pkh", "psh", "pth", "pw", "tkh", "tsh", "tth", "tw", "sht", "bkh", "bsh", "bth", "bw",
"dkh", "dth", "dw", "dzh", "khg", "shg", "thg", "gw", "zhg", "khk", "thk", "kw",
},
new String[]{
"hf", "hl", "hm", "hn", "hr", "hs", "hv", "hw", "hy", "hz",
"br", "kr", "fr", "mr", "nr", "pr", "khr", "shr", "zhr", "sr", "vr", "thr", "zv", "zr",
"by", "ky", "fy", "my", "ny", "py", "khy", "shy", "zhy", "ry", "sy", "vy", "thy", "zy",
"bl", "kl", "fl", "ml", "nl", "pl", "khl", "shl", "zhl", "sl", "vl", "thl", "lw", "zl",
"bf", "kf", "mf", "nf", "pf", "fsh", "shf", "fr", "sf", "fl", "fr", "fw", "fz",
"bs", "ks", "fs", "ms", "ns", "ps", "skh", "shs", "khs", "shv","shw",
"pkh", "psh", "pth", "pw", "tkh", "tsh", "tth", "tw", "bkh", "bsh", "bth", "bw",
"dkh", "dsh", "dth", "dw", "khg", "shg", "thg", "gw", "khk", "thk", "kw",
"rb", "rk", "rf", "rm", "rn", "rp", "rkh", "rsh", "rzh", "rh", "rv", "rw", "rz", "rl",
"lb", "lk", "lf", "lm", "ln", "lp", "lkh", "lsh", "lzh", "lh", "lv", "lw", "lz", "lr",
"sb", "sk", "sf", "sm", "sn", "sp", "skh", "gsh", "dzh", "sh", "sv", "sw", "sz", "ts", "st",
"mb", "md", "mk", "mf", "tm", "nm", "mp", "mkh", "msh", "mzh", "mh", "mv", "mw", "mt", "mz",
"nb", "nd", "nk", "nf", "tn", "mn", "np", "nkh", "nsh", "nzh", "nh", "nv", "nw", "nt", "nz",
"zb", "zd", "zk", "zf", "zt", "nz", "zp", "zkh", "zhz", "dz", "hz", "zv", "zw", "tz",
},
new String[]{
},
new String[]{"ip", "ik", "id", "iz", "ir", "ikh", "ish", "is", "ith", "iv", "in", "im", "ib", "if",
"ep", "ek", "ed", "ez", "er", "ekh", "esh", "es", "eth", "ev", "en", "em", "eb", "ef",
"up", "ud", "uz", "ur", "ush", "us", "uth", "uv", "un", "um", "ub", "uf",
},
new String[]{}, new int[]{1, 2, 3}, new double[]{1, 1, 1}, 0.0, 0.4, 0.0, 1.0, null, true);
}
/**
* A fictional language that could ostensibly be spoken by some group of humans, but that isn't closely based on any
* one real-world language. It is meant to have a mix of hard and flowing sounds, roughly like Hebrew or Turkish,
* but with a very different set of consonants and consonant blends. Importantly, consonant sounds are always paired
* here except for the final consonant of a word, which is always one consonant sound if it is used at all. The
* choices of consonant sounds are designed to be unusual, like "hl", "pkh", and "zhg" (which can all start a word).
* <br>
* Nyep khruv kwolbik psesh klulzhanbik psahzahwuth bluryup; hnish zhrim?
*/
public static final FakeLanguageGen HLETKIP = hletkip().register("Hletkip");
private static FakeLanguageGen ancientEgyptian(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "aa", "e", "e", "e", "e", "e", "e", "e", "i", "i", "i",
"u", "u", "u",},
new String[]{},
new String[]{
"b",
"p", "p", "p",
"f", "f", "f", "f", "f",
"m", "m", "m", "m", "m", "m",
"n", "n", "n", "n", "n",
"r", "r", "r", "r", "r", "r",
"h", "h", "h", "h", "h", "h", "h", "h",
"kh", "kh", "kh", "kh", "kh", "kh",
"z",
"s", "s", "s", "s", "s", "s", "s", "s",
"sh", "sh", "sh", "sh",
"k", "k", "k", "k", "k",
"g", "g", "g",
"t", "t", "t", "t", "t", "t",
"th", "th", "th",
"d", "d", "d",
"dj",
"w", "w", "w",
"pt"
},
new String[]{
"b",
"p", "p", "p", "pw", "pkh", "ps", "ps", "pt",
"f", "f", "f", "f", "f", "ft",
"m", "m", "m", "m", "m", "m", "mk", "nm",
"n", "n", "n", "n", "n", "nkh", "nkh", "nk", "nt", "ns",
"r", "r", "r", "r", "r", "r", "rs", "rt",
"h", "h", "h", "h", "h", "h", "h", "h",
"kh", "kh", "kh", "kh", "kh", "kh", "khm", "khm", "khw",
"z",
"s", "s", "s", "s", "s", "s", "s", "s", "st", "sk", "skh",
"sh", "sh", "sh", "sh", "shw",
"k", "k", "k", "k", "k", "kw",
"g", "g", "g",
"t", "t", "t", "t", "t", "t", "ts",
"th", "th", "th",
"d", "d", "d", "ds",
"dj",
"w", "w", "w",
},
new String[]{
"m", "n", "t", "s", "p", "sh", "m", "n", "t", "s", "p", "sh", "m", "n", "t", "s", "p", "sh",
"kh", "f"
},
new String[]{"amon", "amun", "ut", "epsut", "is", "is", "ipsis", "akhti", "eftu", "atsut", "amses"
},
new String[]{"-"}, new int[]{1, 2, 3, 4}, new double[]{4, 7, 3, 2}, 0.5, 0.4, 0.06, 0.09, null, true);
}
/**
* A (necessarily) very rough anglicization of Old Egyptian, a language that has no precisely known pronunciation
* rules and was written with hieroglyphics. This is meant to serve as an analogue for any ancient language with few
* contemporary speakers.
* <br>
* Thenamses upekha efe emesh nabasu ahakhepsut!
*/
// for future reference, consult https://en.wiktionary.org/wiki/Module:egy-pron-Egyptological
public static final FakeLanguageGen ANCIENT_EGYPTIAN = ancientEgyptian().register("Ancient Egyptian");
private static FakeLanguageGen crow(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a","a", "a", "a","a", "a", "a", "á", "á", "aa", "aa", "áá", "áa",
"e", "e", "e", "e", "e", "e", "ee", "ée", "é", "éé",
"i", "i", "i", "i", "i", "i", "i", "i", "i", "i", "ii", "íí", "íi", "í",
"o", "o", "o", "o", "o", "o", "o", "oo", "óó", "óo", "ó",
"u", "u","u", "u","u", "u","u", "u", "u", "u", "uu", "úú", "úu", "ú",
"ia", "ua", "ia", "ua", "ia", "ua", "ia", "ua", "ía", "úa"
},
new String[]{
},
new String[]{
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s"},
new String[]{
"bb", "pp", "ss", "kk", "ll", "mm", "nn", "dd", "tt",
"kk", "kk", "mm", "kk", "kk", "mm", "dd", "ss",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s",
"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s"
},
new String[]{"b", "p", "s", "x", "k", "l", "m", "n", "d", "t", "h", "w", "ch", "sh",
"k", "k", "m", "k", "k", "m", "d", "s"
},
new String[]{
},
new String[]{"-"}, new int[]{1, 2, 3, 4, 5}, new double[]{5, 7, 6, 4, 2}, 0.4, 1.0, 0.12, 0.0, null, true);
}
/**
* A rough imitation of the Crow language of the American Midwest, using some tone marks. Some of the orthography
* rules aren't clear across Internet information about the language, so this really is a "fake" language it will be
* generating, not the real thing at all. This considers 'x' to be the rough back-of-throat noise that isn't in
* English other than in loanwords, like the Scottish "loch," and in names like the German "Bach." Doubled (to use
* the linguistic term, geminated) consonants are pronounced for a longer time, and doubled vowels with the same
* accent mark or no accent mark are also lengthened. An un-accented vowel has a normal tone, an accented vowel has
* a high tone, and an accented vowel followed by an un-accented vowel has a falling tone. This last feature is the
* least common among languages here, and is a good way of distinguishing imitation Crow from other languages.
* <br>
* Pashu-umíkiki; chinébúlu ak kóokutú shu-eníí-a ipíimúu heekokáakoku?
*/
public static final FakeLanguageGen CROW = crow().register("Crow");
private static FakeLanguageGen imp(){
return new FakeLanguageGen(
new String[]{"a", "a", "a", "a", "a", "á", "á", "á", "aa", "aa", "aa", "aaa", "aaa", "aaa", "áá", "áá", "ááá", "ááá",
"e", "e", "e", "e", "e", "e",
"i", "i", "i", "i", "i", "i", "i", "i", "i", "i", "í", "í", "í", "í",
"ii", "ii", "ii", "iii", "iii", "iii", "íí", "íí", "ííí", "ííí",
"u", "u", "u", "u", "u", "u", "u", "u", "ú", "ú", "ú", "uu", "uu", "uu", "úú", "úú", "úúú", "úúú",
"ia", "ia", "ia", "ui", "ui"
},
new String[]{
},
new String[]{
"s", "k", "d", "t", "h", "f", "g", "r", "r", "r", "r", "gh", "ch",
"sk", "st", "skr", "str", "kr", "dr", "tr", "fr", "gr"
},
new String[]{
"s", "k", "d", "t", "h", "f", "g", "r", "r", "r", "r", "gh", "ch",
"sk", "st", "skr", "str", "kr", "dr", "tr", "fr", "gr"
},
new String[]{
"s", "k", "d", "t", "g", "gh", "ch"
},
new String[]{
},
new String[]{"-"}, new int[]{1, 2, 3}, new double[]{7, 11, 4}, 0.2, 0.5, 0.4, 0.0, null, true);
}
/**
* A fantasy language meant for obnoxious screeching annoying enemies more-so than for intelligent friends or foes.
* Uses accented vowels to mean "louder or higher-pitched" and up to three repeats of any vowel to lengthen it.
* <br>
* Siii-aghak fítríííg dú-úgh ru-úúk, grííírá!
*/
public static final FakeLanguageGen IMP = imp().register("Imp");
private static FakeLanguageGen malay(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "a", "ai", "ai", "au",
"e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e", "e",
"i", "i", "i", "i", "i", "i", "i", "i", "ia", "ia",
"o", "o", "o", "o", "o", "o", "ou",
"u", "u", "u", "u", "u", "u", "u", "u", "u", "ua", "ua",},
new String[]{},
new String[]{
"b", "b", "b", "b",
"ch",
"d", "d", "d", "d",
"f",
"g", "g",
"h", "h",
"j", "j", "j", "j",
"k", "k", "k", "k", "k", "k",
"kh",
"l", "l", "l", "l", "l", "l", "l",
"m", "m", "m", "m",
"n", "n", "n",
"p", "p", "p", "p", "p",
"r", "r",
"s", "s", "s", "s", "s",
"sh", "sh",
"t", "t", "t", "t",
"w",
"y",
"z",
},
new String[]{
"b", "b", "b", "b",
"ch",
"d", "d", "d", "d",
"f",
"g", "g",
"h", "h", "h", "h", "h",
"j", "j", "j",
"k", "k", "k", "k", "k", "k", "k", "k", "k",
"kn",
"kh",
"l", "l", "l", "l", "l", "l", "l",
"m", "m", "m", "m", "m", "m",
"n", "n", "n", "n", "n", "n", "n", "n", "n", "n",
"nt", "nt", "nj",
"ng", "ng", "ng", "ng",
"ngk","ngg",
"ny", "ny",
"p", "p", "p", "p", "p",
"r", "r", "r", "r", "r", "r", "r", "r",
"rb", "rd", "rg", "rk", "rs", "rt", "rn", "rn",
"s", "s", "s", "s", "s", "s",
"sh", "sh",
"t", "t", "t", "t", "t", "t",
"w",
"y",
"z",
},
new String[]{
"k", "k", "k", "k", "k", "k", "t", "t", "t", "n", "n", "n", "n", "n", "n", "n", "n",
"ng", "ng", "ng", "m", "m", "m", "s", "s", "l", "l", "l", "l", "l", "h", "h"
},
new String[]{"uk", "uk", "ok", "an", "at", "ul", "ang", "ih", "it", "is", "ung", "un", "ah"
},
new String[]{}, new int[]{1, 2, 3}, new double[]{5, 3, 2}, 0.2, 0.25, 0.0, 0.2, genericSanityChecks, true);
}
/**
* An approximation of the Malay language or any of its close relatives, such as Indonesian. This differs from Malay
* as it is normally written by using "ch" for what Malay writes as "c" (it is pronounced like the start of "chow"),
* and "sh" for what Malay writes as "sy" (pronounced like the start of "shoe").
* <br>
* Kashanyah satebok bisal bekain akinuk an as, penah lukul...
*/
public static final FakeLanguageGen MALAY = malay().register("Malay");
private static FakeLanguageGen celestial(){
return new FakeLanguageGen(
new String[]{
"a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o",
"a", "a", "a", "a", "a", "a", "a", "e", "e", "e", "i", "i", "i", "i", "i", "o", "o", "o",
"ă", "ă", "ĕ", "ĭ", "ŏ"
},
new String[]{},
new String[]{
"l", "r", "n", "m", "v", "b", "d", "s", "th", "sh", "z", "h", "y", "w", "j",
"l", "r", "n", "m", "v", "b", "d", "s", "th", "sh", "z", "h", "y", "w", "j",
"l", "r", "n", "m", "v", "b", "d", "s", "th", "sh", "z", "h", "y", "w", "j",
"n", "m", "v", "s", "z", "h", "y", "w", "j",
"n", "m", "v", "s", "z", "h", "y", "w", "j",
"n", "m", "s", "h", "y", "j",
"n", "m", "s", "h", "y", "j",
"n", "m", "s", "h", "y", "j",
"h", "h", "h", "h", "h", "h", "h", "h",
"m", "m", "m", "m", "m", "m",
"ry", "ly", "by", "dy", "ny", "my", "vy", "by", "dy", "sy", "zy",
"bl", "br", "dr", "shl", "shr", "hr"
},
new String[]{
"j", "j", "j",
"mh", "mb", "md", "mr", "ms", "mz", "mv",
"nh", "nb", "nd", "nr", "ns", "nz", "nv",
"zh", "zb", "zd", "zr", "zv",
"bd", "db", "bm", "bn", "dm", "dn",
"ry", "ly", "by", "dy", "ny", "my", "vy", "by", "dy", "sy", "zy", "wy", "jy",
"bl", "br", "dr", "shl", "shr", "hr"
},
new String[]{
"l", "r", "n", "m", "v", "b", "d", "s", "th", "sh", "z",
"l", "r", "n", "m", "v", "b", "d", "s", "th", "sh",
"l", "r", "n", "m", "v", "b", "d", "th",
"l", "r", "n", "m", "b", "d", "th",
"r", "n", "m", "r", "n", "m", "r", "n", "m", "r", "n", "m", "r", "n", "m", "r", "n", "m",
},
new String[]{
"am", "an", "ar", "av", "em", "el", "ez", "eth", "ev", "es", "im", "id", "in", "oth", "om",
"ar", "el", "es", "im", "oth",
"ăyom", "ĕzra", "ĭdniv", "ŏlor", "evyăd", "iyĕr", "abĭl", "onrŏv"
},
new String[]{"'"}, new int[]{1, 2, 3}, new double[]{5, 6, 2}, 0.45, 0.1, 0.04, 0.14, genericSanityChecks, true);
}
/**
* Fantasy language that is meant to sound like it could be spoken by divine or (magical) otherworldly beings.
* Sometimes uses the breve mark (as in {@code ăĕĭŏ}) over vowels and rarely splits consonants with {@code '}.
* Uses very few harsh sounds, and may be easy to confuse with {@link #ELF} (this tends to use much shorter words).
* This happens to sound a little like Hebrew, but since this doesn't have some consonants that are commonly used in
* Hebrew, and because this uses accented vowels that aren't in Hebrew, they should be different enough that this
* language can seem "not of this world."
* <br>
* Emŏl ebin hanzi'ab, isharar omrihrel nevyăd.
*/
public static final FakeLanguageGen CELESTIAL = celestial().register("Celestial");
private static FakeLanguageGen chinese(){
return new FakeLanguageGen(
new String[]{
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū", "yū", "á", "é", "í", "ó", "ú", "á", "í", "ó", "ú", "yú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ", "yǔ", "à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù", "yù",
"a", "e", "i", "o", "u", "a", "i", "o", "u", "yu", "a", "e", "i", "o", "u", "a", "i", "o", "u", "yu",
},
new String[]{
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"ā", "ē", "ī", "ō", "ū", "ā", "ī", "ō", "ū",
"á", "é", "í", "ó", "ú", "á", "í", "ó", "ú",
"ǎ", "ě", "ǐ", "ǒ", "ǔ", "ǎ", "ǐ", "ǒ", "ǔ",
"à", "è", "ì", "ò", "ù", "à", "ì", "ò", "ù",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"a", "e", "i", "o", "u", "a", "i", "o", "u",
"āí", "āó", "āú", "ēá", "īá", "īú", "ōá", "ūá", "ūé",
"āǐ", "āǒ", "āǔ", "ēǎ", "īǎ", "īǔ", "ōǎ", "ūǎ", "ūě",
"āì", "āò", "āù", "ēà", "īà", "īù", "ōà", "ūà", "ūè",
"āi", "āo", "āu", "ēa", "īa", "īu", "ōa", "ūa", "ūe",
"áī", "áō", "áū", "éā", "íā", "íū", "óā", "úā", "úē",
"áǐ", "áǒ", "áǔ", "éǎ", "íǎ", "íǔ", "óǎ", "ǔǎ", "ǔě",
"áì", "áò", "áù", "éà", "íà", "íù", "óà", "ùà", "ùè",
"ái", "áo", "áu", "éa", "ía", "íu", "óa", "ua", "ue",
"ǎī", "ǎō", "ǎū", "ěā", "ǐā", "ǐū", "ǒā", "ǔā", "ǔē",
"ǎí", "ǎó", "ǎú", "ěá", "ǐá", "ǐú", "ǒá", "ǔá", "ǔé",
"ǎì", "ǎò", "ǎù", "ěà", "ǐà", "ǐù", "ǒà", "ǔà", "ǔè",
"ǎi", "ǎo", "ǎu", "ěa", "ǐa", "ǐu", "ǒa", "ǔa", "ǔe",
"àī", "àō", "àū", "èā", "ìā", "ìū", "òā", "ùā", "ùē",
"àí", "àó", "àú", "èá", "ìá", "ìú", "òá", "ùá", "ùé",
"àǐ", "àǒ", "àǔ", "èǎ", "ìǎ", "ìǔ", "òǎ", "ùǎ", "ùě",
"ài", "ào", "àu", "èa", "ìa", "ìu", "òa", "ùa", "ùe",
"aī", "aō", "aū", "eā", "iā", "iū", "oā", "uā", "uē",
"aí", "aó", "aú", "eá", "iá", "iú", "oá", "uá", "ué",
"aǐ", "aǒ", "aǔ", "eǎ", "iǎ", "iǔ", "oǎ", "uǎ", "uě",
"aì", "aò", "aù", "eà", "ià", "iù", "oà", "uà", "uè",
"yū", "yú", "yū", "yú", "yū", "yú",
"yǔ", "yù", "yǔ", "yù", "yǔ", "yù",
"yu", "yu", "yu", "yu", "yu", "yu",
},
new String[]{
"b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x",
"zh", "ch", "sh", "r", "z", "ts", "s",
"b", "p", "m", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"b", "p", "m", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"d", "t", "g", "k", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"d", "t", "g", "k", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
},
new String[]{
"nb", "np", "nf", "nd", "nt", "nl", "ng", "nk", "nj", "nq", "nx", "nzh", "nch", "nsh", "nz", "nts", "ns",
"nb", "np", "nf", "nd", "nt", "nl", "ng", "nk", "nj", "nq", "nx", "nzh", "nch", "nsh", "nz", "nts", "ns",
"b", "p", "m", "f", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "zh", "ch", "sh", "r", "z", "ts", "s",
"b", "p", "m", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"b", "p", "m", "d", "t", "n", "l", "g", "k", "h", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"d", "t", "g", "k", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
"d", "t", "g", "k", "j", "q", "x", "zh", "ch", "sh", "z", "ts", "s",
},
new String[]{
"n", "n", "n", "n", "n", "n", "n",
"ng", "ng", "ng", "ng", "ng", "ng",
"r", "r", "r",
},
new String[]{},
new String[]{}, new int[]{1, 2, 3}, new double[]{14, 3, 1}, 0.175, 0.55, 0.0, 0.0, genericSanityChecks, true);
}
/**
* An approximation of Hanyu Pinyin, a Romanization technique used for Mandarin Chinese that has been in common use
* since the 1980s. This makes some slight changes so the vulgarity filters this uses can understand how some
* letters sound; Pinyin's letter c becomes ts, and this replaces the u with umlaut, ü, in all cases with yu.
* <br>
* Tuàn tiāzhǎn dér, ǔngínbǔng xōr shàū kán nu tsīn.
*/
public static final FakeLanguageGen CHINESE_ROMANIZED = chinese().register("Chinese Romanized");
private static FakeLanguageGen cherokee(){
return new FakeLanguageGen(
new String[]{
"a", "e", "i", "o", "u", "ü", "a", "e", "i", "o", "u", "ü", "a", "e", "i", "o", "u", "ü",
"a", "e", "i", "o", "u", "ü", "a", "e", "i", "o", "u", "ü", "a", "e", "i", "o", "u", "ü",
"ai", "au", "oa", "oi", "ai", "au", "oa", "oi",
"a", "a", "a", "a", "a", "a", "a", "a", "a",
"ah", "ah", "ah", "ah", "ah", "ah", "ah",
},
new String[]{
},
new String[]{
"g", "k", "h", "l", "n", "qu", "s", "d", "t", "dl", "ts", "w", "y",
"g", "k", "h", "l", "n", "qu", "s", "d", "t", "dl", "ts", "w", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "n", "qu", "s", "d", "t",
"g", "h", "n", "qu", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
},
new String[]{
"g", "k", "h", "l", "n", "qu", "s", "d", "t", "dl", "ts", "w", "y",
"g", "k", "h", "l", "n", "qu", "s", "d", "t", "dl", "ts", "w", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "l", "n", "qu", "s", "d", "t", "ts", "y",
"g", "h", "n", "qu", "s", "d", "t",
"g", "h", "n", "qu", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
"h", "n", "s", "d", "t", "h", "n", "s", "d", "t",
"sn", "sn", "st", "st", "squ", "squ",
"th", "kh", "sh", "th", "kh", "sh", "th", "kh", "sh",
"th", "sh", "th", "sh", "th", "sh", "th", "sh",
},
new String[]{
"s"
},
new String[]{
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{4, 7, 6, 2}, 0.3, 0.96, 0.0, 0.0, null, true);
}
/**
* A rough imitation of the Cherokee language, using an attempt at romanizing the syllabary the language is often
* written with, using only the parts of the language that are usually written down. Some of the orthography
* rules aren't clear across Internet information about the language, so this really is a "fake" language it will be
* generating, not the real thing at all. The vowel 'ü' is used in place of the 'v' that the normal transliteration
* uses, to help with profanity-checking what this generates; it is pronounced like in the French word "un".
* <br>
* Dah utugü tsahnahsütoi gohü usütahdi asi tsau dah tashi.
*/
public static final FakeLanguageGen CHEROKEE_ROMANIZED = cherokee().register("Cherokee Romanized");
private static FakeLanguageGen vietnamese() {
return new FakeLanguageGen(new String[]{
"a", "à", "á", "â", "ä", "ā", "ă",
"e", "è", "é", "ê", "ë", "ē", "ĕ",
"i", "ì", "í", "î", "ï", "ī", "ĭ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"u", "ù", "ú", "û", "ü", "ū", "ŭ",
},
new String[]{
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"e", "è", "é", "ê", "ë", "ē", "ĕ",
"i", "ì", "í", "î", "ï", "ī", "ĭ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"u", "ù", "ú", "û", "ü", "ū", "ŭ",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"e", "è", "é", "ê", "ë", "ē", "ĕ",
"i", "ì", "í", "î", "ï", "ī", "ĭ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"u", "ù", "ú", "û", "ü", "ū", "ŭ",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"a", "à", "á", "â", "ä", "ā", "ă",
"e", "è", "é", "ê", "ë", "ē", "ĕ",
"i", "ì", "í", "î", "ï", "ī", "ĭ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"o", "ò", "ó", "ô", "ö", "ō", "ŏ",
"u", "ù", "ú", "û", "ü", "ū", "ŭ",
"ua", "uà", "uá", "uâ", "uä", "uā", "uă",
"ie", "iè", "ié", "iê", "ië", "iē", "iĕ",
"ie", "iè", "ié", "iê", "ië", "iē", "iĕ",
"ie", "ìe", "íe", "îe", "ïe", "īe", "ĭe",
"iu", "ìu", "íu", "îu", "ïu", "īu", "ĭu",
"oi", "òi", "ói", "ôi", "öi", "ōi", "ŏi",
"uo", "ùo", "úo", "ûo", "üo", "ūo", "ŭo",
"uo", "ùo", "úo", "ûo", "üo", "ūo", "ŭo",
"y", "y", "y", "y", "y", "y", "y",
"ye", "yè", "yé", "yê", "yë", "yē", "yĕ",
},
new String[]{
"b", "c", "ch", "d", "ð", "g", "h", "k", "kh", "l", "m", "n", "ng", "nh", "p", "ph", "qu", "r",
"s", "t", "th", "tr", "v", "x",
"b", "c", "d", "ð", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "ð", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "l", "n", "ng", "p", "ph", "th", "tr",
"b", "c", "d", "l", "n", "ng", "p", "ph", "th", "tr",
"b", "c", "d", "l", "n", "ng", "p",
"b", "c", "d", "l", "n", "ng", "p",
"b", "c", "d", "l", "n", "ng", "p",
}, new String[]{
"b", "c", "ch", "d", "ð", "g", "h", "k", "kh", "l", "m", "n", "ng", "nh", "p", "ph", "qu", "r",
"s", "t", "th", "tr", "v", "x",
"b", "c", "d", "ð", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "ð", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "h", "l", "m", "n", "ng", "p", "ph", "t", "th", "tr", "v",
"b", "c", "d", "l", "n", "ng", "p", "ph", "t", "th", "tr",
"b", "c", "d", "l", "n", "ng", "p", "ph", "t", "th", "tr",
"b", "c", "d", "l", "n", "ng", "p", "t",
"b", "c", "d", "l", "n", "ng", "p", "t",
"b", "c", "d", "l", "n", "ng", "p",
},
new String[]{
"b", "c", "ch", "d", "ð", "g", "h", "k", "kh", "m", "m", "n", "ng", "nh", "p", "ch", "r",
"s", "t", "x",
"b", "c", "d", "ð", "h", "m", "m", "n", "ng", "p", "n", "t", "nh", "ng", "c",
"b", "c", "d", "ð", "h", "m", "m", "n", "ng", "p", "n", "t", "nh", "ng", "c",
"b", "c", "d", "h", "m", "m", "n", "ng", "p", "n", "t", "nh", "ng", "c",
"b", "c", "d", "m", "n", "ng", "p", "n", "t", "nh", "ng",
"b", "c", "d", "m", "n", "ng", "p", "n", "t", "nh", "ng",
"b", "c", "d", "m", "n", "ng", "p", "t",
"b", "c", "d", "m", "n", "ng", "p", "t",
"b", "c", "d", "m", "n", "ng", "p",
}, new String[]{}, new String[]{}, new int[]{1, 2, 3}, new double[]{37.0, 3.0, 1.0},
0.04, 0.4, 0.0, 0.0, genericSanityChecks, true);
}
/**
* A very rough imitation of the Vietnamese language, without using the accurate characters Vietnamese really uses
* but that are rare in fonts. Since so many letters in correct Vietnamese aren't available in most fonts, this
* can't represent most of the accented vowels in the language, but it tries, with 6 accents for each of a, e, i, o,
* and u, though none for y. It also uses 'ð' from Icelandic in place of the correct d with bar. This could also
* maybe be used as an approximation of (badly) Romanized Thai, since Thai normally uses its own script but also has
* many tones (which would be indicated by the accents here).
* <br>
* Bach trich, nŏ ngiukh nga cä tran ngonh...
*/
public static final FakeLanguageGen VIETNAMESE = vietnamese().register("Vietnamese");
private static FakeLanguageGen latin(){
return new FakeLanguageGen(
new String[]{
"a", "e", "i", "o", "u",
"a", "e", "i", "o", "u",
"a", "e", "i", "o", "u",
"ae", "ei", "eu", "ui",
"a", "a", "a", "a", "i", "i", "i", "o", "u", "u",
"a", "a", "a", "a", "i", "i", "o", "u", "u",
"a", "a", "a", "a", "i", "i", "o", "u",
},
new String[]{
},
new String[]{
"b", "d", "f", "m", "n", "c", "g", "gn", "h", "y", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "y", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"c", "c", "c", "d", "m", "m", "m", "s", "s", "t"
},
new String[]{
"b", "d", "f", "m", "n", "c", "g", "gn", "h", "y", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "y", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "rh", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "g", "h", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "f", "m", "n", "c", "l", "p", "qu", "r", "s", "t", "v",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"b", "d", "m", "n", "c", "l", "p", "r", "s", "t",
"c", "c", "c", "d", "m", "m", "m", "s", "s", "t",
"x", "x", "x", "x", "x", "x", "xc", "xc", "sc", "sc",
"ct", "ct", "ct", "ct", "ct", "ct",
"nd", "nd", "nd", "nd", "nd", "nd",
"nn", "nn", "rr", "ll", "ll", "nt", "nt", "nt", "nt", "nt"
},
new String[]{
""
},
new String[]{
"us", "um", "is", "it", "ii", "am", "ius",
"us", "um", "is", "it", "ii", "am", "ius",
"us", "um", "is", "it", "ii", "am", "ius",
"us", "um", "is", "it", "ii", "am", "ius",
"id", "in", "ad", "em", "os", "at",
"id", "in", "ad", "em", "os", "at",
"uit", "ant", "unt", "eo",
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{7, 8, 6, 1}, 0.2, 1.0, 0.0, 0.7, genericSanityChecks, true);
}
/**
* An imitation of Classical Latin, using some modern conventions so it can be suitable for scientific names or
* other common English uses of Latin words. This tries to avoid the Latin letters that were mostly used for Greek
* loanwords. You may want to capitalize these letters if they represent written ancient text, since Latin from the
* Classical period didn't use lower-case letters.
* <br>
* Eisunt re ennius gin, vi.
*/
public static final FakeLanguageGen LATIN = latin().register("Latin");
/**
* An array that stores all the hand-made FakeLanguageGen constants; it does not store randomly-generated languages
* nor does it store modifications or mixes of languages. The order these are stored in is related to the numeric
* codes for languages in the {@link #serializeToString()} output, but neither is dependent on the other if this
* array is changed for some reason (which is not recommended, but not out of the question). If this is modified,
* then it is probably a bad idea to assign null to any elements in registered; special care is taken to avoid null
* elements in its original state, so some code may rely on the items being usable and non-null.
*/
public static final FakeLanguageGen[] registered;
public static final String[] registeredNames;
static {
// the first item in registry is null so it can be a placeholder for random languages; we want to skip it.
registered = new FakeLanguageGen[registry.size()-1];
registeredNames = new String[registered.length];
for (int i = 0; i < registered.length; i++) {
registeredNames[i] = registry.keyAt(i+1);
registered[i] = registry.getAt(i+1);
}
}
/**
* If a FakeLanguageGen is known and is in {@link #registered}, this allows you to look up that FakeLanguageGen by
* name (using a name from {@link #registeredNames}).
* @param name a String name such as "English", "Korean Romanized", or "Russian Authentic"
* @return a FakeLanguageGen corresponding to the given name, or null if none was found
*/
public static FakeLanguageGen get(String name)
{
return registry.get(name);
}
/**
* If a FakeLanguageGen is known and is in {@link #registered}, this allows you to look up that FakeLanguageGen by
* index, from 0 to {@code FakeLanguageGen.registered.length - 1}.
* @param index an int from 0 to {@code FakeLanguageGen.registered.length - 1}
* @return a FakeLanguageGen corresponding to the given index, or null if none was found
*/
public static FakeLanguageGen getAt(int index)
{
return registry.getAt(index);
}
/**
* If a FakeLanguageGen is known and is in {@link #registered}, this allows you to look up that FakeLanguageGen's
* name by index, from 0 to {@code FakeLanguageGen.registeredNames.length - 1}.
* @param index an int from 0 to {@code FakeLanguageGen.registeredNames.length - 1}
* @return a FakeLanguageGen corresponding to the given index, or null if none was found
*/
public static String nameAt(int index)
{
return registry.keyAt(index);
}
/**
* FakeLanguageGen constants that are meant to sound like specific real-world languages, and that all use the Latin
* script (like English) with maybe some accents.
*/
public static final FakeLanguageGen[] romanizedHumanLanguages = {
ENGLISH, KOREAN_ROMANIZED, SPANISH, SWAHILI, NORSE_SIMPLIFIED, ARABIC_ROMANIZED, HINDI_ROMANIZED, FRENCH,
MAORI, GREEK_ROMANIZED, INUKTITUT, RUSSIAN_ROMANIZED, NAHUATL, JAPANESE_ROMANIZED, MONGOLIAN, SOMALI, CROW,
ANCIENT_EGYPTIAN, MALAY, CHINESE_ROMANIZED, CHEROKEE_ROMANIZED, VIETNAMESE, LATIN
};
/**
* Zero-arg constructor for a FakeLanguageGen; produces a FakeLanguageGen equivalent to FakeLanguageGen.ENGLISH .
*/
public FakeLanguageGen() {
this(
new String[]{
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "a", "o", "o", "o", "e", "e", "e", "e", "e", "i", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"a", "a", "a", "o", "o", "e", "e", "e", "i", "i", "i", "u",
"au", "ai", "ai", "ou", "ea", "ie", "io", "ei",
},
new String[]{"u", "u", "oa", "oo", "oo", "oo", "ee", "ee", "ee", "ee",},
new String[]{
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gl", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "qu", "r", "s", "sh", "sk", "st", "sp", "sl", "sm", "sn", "t", "tr", "th", "thr", "v", "w", "y", "z",
"b", "bl", "br", "c", "cl", "cr", "ch", "d", "dr", "f", "fl", "fr", "g", "gr", "h", "j", "k", "l", "m", "n",
"p", "pl", "pr", "r", "s", "sh", "st", "sp", "sl", "t", "tr", "th", "w", "y",
"b", "br", "c", "ch", "d", "dr", "f", "g", "h", "j", "l", "m", "n",
"p", "r", "s", "sh", "st", "sl", "t", "tr", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"b", "d", "f", "g", "h", "l", "m", "n",
"p", "r", "s", "sh", "t", "th",
"r", "s", "t", "l", "n",
"str", "spr", "spl", "wr", "kn", "kn", "gn",
},
new String[]{"x", "cst", "bs", "ff", "lg", "g", "gs",
"ll", "ltr", "mb", "mn", "mm", "ng", "ng", "ngl", "nt", "ns", "nn", "ps", "mbl", "mpr",
"pp", "ppl", "ppr", "rr", "rr", "rr", "rl", "rtn", "ngr", "ss", "sc", "rst", "tt", "tt", "ts", "ltr", "zz"
},
new String[]{"b", "rb", "bb", "c", "rc", "ld", "d", "ds", "dd", "f", "ff", "lf", "rf", "rg", "gs", "ch", "lch", "rch", "tch",
"ck", "ck", "lk", "rk", "l", "ll", "lm", "m", "rm", "mp", "n", "nk", "nch", "nd", "ng", "ng", "nt", "ns", "lp", "rp",
"p", "r", "rn", "rts", "s", "s", "s", "s", "ss", "ss", "st", "ls", "t", "t", "ts", "w", "wn", "x", "ly", "lly", "z",
"b", "c", "d", "f", "g", "k", "l", "m", "n", "p", "r", "s", "t", "w",
},
new String[]{"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ate", "ite", "ism", "ist", "er", "er", "er", "ed", "ed", "ed", "es", "es", "ied", "y", "y", "y", "y",
"ay", "ay", "ey", "oy", "ay", "ay", "ey", "oy",
"ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition",
"ough", "aught", "ant", "ont", "oe", "ance", "ell", "eal", "oa", "urt", "ut", "iom", "ion", "ion", "ision", "ation", "ation", "ition",
"ily", "ily", "ily", "adly", "owly", "oorly", "ardly", "iedly",
},
new String[]{}, new int[]{1, 2, 3, 4}, new double[]{10, 11, 4, 1}, 0.22, 0.1, 0.0, 0.22, englishSanityChecks, true);
}
/**
* This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this
* class, such as LOVECRAFT and GREEK_ROMANIZED in the source code.
*
* @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start
* of a word or in the middle; elements may be repeated to make them more common
* @param midVowels String array where each element is a vowel or group of vowels that may appear in the
* middle of the word; all openingVowels are automatically copied into this internally.
* Elements may be repeated to make them more common
* @param openingConsonants String array where each element is a consonant or consonant cluster that can appear
* at the start of a word; elements may be repeated to make them more common
* @param midConsonants String array where each element is a consonant or consonant cluster than can appear
* between vowels; all closingConsonants are automatically copied into this internally.
* Elements may be repeated to make them more common
* @param closingConsonants String array where each element is a consonant or consonant cluster than can appear
* at the end of a word; elements may be repeated to make them more common
* @param closingSyllables String array where each element is a syllable starting with a vowel and ending in
* whatever the word should end in; elements may be repeated to make them more common
* @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this,
* then "a-a" may be possible; elements may be repeated to make them more common
* @param syllableLengths int array where each element is a possible number of syllables a word can use; closely
* tied to syllableFrequencies
* @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and
* represents how often each syllable count should appear relative to other counts; there
* is no need to restrict the numbers to add up to any other number
* @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels;
* higher numbers yield more words starting with vowels
* @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher
* numbers yield more words ending in vowels
* @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how
* often a vowel will be split into two vowels separated by one of those splitters
* @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of
* closingSyllables is used instead of ending normally
*/
public FakeLanguageGen(String[] openingVowels, String[] midVowels, String[] openingConsonants,
String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters,
int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency,
double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency) {
this(openingVowels, midVowels, openingConsonants, midConsonants, closingConsonants, closingSyllables,
vowelSplitters, syllableLengths, syllableFrequencies, vowelStartFrequency, vowelEndFrequency,
vowelSplitFrequency, syllableEndFrequency, englishSanityChecks, true);
}
/**
* This is a very complicated constructor! Maybe look at the calls to this to initialize static members of this
* class, such as LOVECRAFT and GREEK_ROMANIZED in the source code.
*
* @param openingVowels String array where each element is a vowel or group of vowels that may appear at the start
* of a word or in the middle; elements may be repeated to make them more common
* @param midVowels String array where each element is a vowel or group of vowels that may appear in the
* middle of the word; all openingVowels are automatically copied into this internally.
* Elements may be repeated to make them more common
* @param openingConsonants String array where each element is a consonant or consonant cluster that can appear
* at the start of a word; elements may be repeated to make them more common
* @param midConsonants String array where each element is a consonant or consonant cluster than can appear
* between vowels; all closingConsonants are automatically copied into this internally.
* Elements may be repeated to make them more common
* @param closingConsonants String array where each element is a consonant or consonant cluster than can appear
* at the end of a word; elements may be repeated to make them more common
* @param closingSyllables String array where each element is a syllable starting with a vowel and ending in
* whatever the word should end in; elements may be repeated to make them more common
* @param vowelSplitters String array where each element is a mark that goes between vowels, so if "-" is in this,
* then "a-a" may be possible; elements may be repeated to make them more common
* @param syllableLengths int array where each element is a possible number of syllables a word can use; closely
* tied to syllableFrequencies
* @param syllableFrequencies double array where each element corresponds to an element in syllableLengths and
* represents how often each syllable count should appear relative to other counts; there
* is no need to restrict the numbers to add up to any other number
* @param vowelStartFrequency a double between 0.0 and 1.0 that determines how often words start with vowels;
* higher numbers yield more words starting with vowels
* @param vowelEndFrequency a double between 0.0 and 1.0 that determines how often words end with vowels; higher
* numbers yield more words ending in vowels
* @param vowelSplitFrequency a double between 0.0 and 1.0 that, if vowelSplitters is not empty, determines how
* often a vowel will be split into two vowels separated by one of those splitters
* @param syllableEndFrequency a double between 0.0 and 1.0 that determines how often an element of
* closingSyllables is used instead of ending normally
* @param sane true to perform sanity checks for pronounce-able sounds to most English speakers, replacing many
* words that are impossible to say; slows down generation slightly, irrelevant for non-Latin alphabets
* @param clean true to perform vulgarity/obscenity checks on the word, replacing it if it is too close to a
* common English vulgarity, obscenity, or slur/epithet; slows down generation slightly
*/
public FakeLanguageGen(String[] openingVowels, String[] midVowels, String[] openingConsonants,
String[] midConsonants, String[] closingConsonants, String[] closingSyllables, String[] vowelSplitters,
int[] syllableLengths, double[] syllableFrequencies, double vowelStartFrequency,
double vowelEndFrequency, double vowelSplitFrequency, double syllableEndFrequency,
Pattern[] sane, boolean clean) {
this.openingVowels = openingVowels;
this.midVowels = new String[openingVowels.length + midVowels.length];
System.arraycopy(midVowels, 0, this.midVowels, 0, midVowels.length);
System.arraycopy(openingVowels, 0, this.midVowels, midVowels.length, openingVowels.length);
this.openingConsonants = openingConsonants;
this.midConsonants = new String[midConsonants.length + closingConsonants.length];
System.arraycopy(midConsonants, 0, this.midConsonants, 0, midConsonants.length);
System.arraycopy(closingConsonants, 0, this.midConsonants, midConsonants.length, closingConsonants.length);
this.closingConsonants = closingConsonants;
this.vowelSplitters = vowelSplitters;
this.closingSyllables = closingSyllables;
this.syllableFrequencies = new double[syllableLengths[syllableLengths.length - 1]];
double total = 0.0, bias = 0.0;
for (int i = 0; i < syllableLengths.length; i++) {
total += (this.syllableFrequencies[syllableLengths[i]-1] = syllableFrequencies[i]);
bias += syllableLengths[i] * syllableFrequencies[i];
}
totalSyllableFrequency = total;
syllableBias = bias / total;
if (vowelStartFrequency > 1.0)
this.vowelStartFrequency = 1.0 / vowelStartFrequency;
else
this.vowelStartFrequency = vowelStartFrequency;
if (vowelEndFrequency > 1.0)
this.vowelEndFrequency = 1.0 / vowelEndFrequency;
else
this.vowelEndFrequency = vowelEndFrequency;
if (vowelSplitters.length == 0)
this.vowelSplitFrequency = 0.0;
else if (vowelSplitFrequency > 1.0)
this.vowelSplitFrequency = 1.0 / vowelSplitFrequency;
else
this.vowelSplitFrequency = vowelSplitFrequency;
if (closingSyllables.length == 0)
this.syllableEndFrequency = 0.0;
else if (syllableEndFrequency > 1.0)
this.syllableEndFrequency = 1.0 / syllableEndFrequency;
else
this.syllableEndFrequency = syllableEndFrequency;
this.clean = clean;
sanityChecks = sane;
modifiers = new ArrayList<>(4);
}
private FakeLanguageGen(String[] openingVowels, String[] midVowels, String[] openingConsonants,
String[] midConsonants, String[] closingConsonants, String[] closingSyllables,
String[] vowelSplitters, double[] syllableFrequencies,
double vowelStartFrequency, double vowelEndFrequency, double vowelSplitFrequency,
double syllableEndFrequency, Pattern[] sanityChecks, boolean clean,
List<Modifier> modifiers) {
this.openingVowels = copyStrings(openingVowels);
this.midVowels = copyStrings(midVowels);
this.openingConsonants = copyStrings(openingConsonants);
this.midConsonants = copyStrings(midConsonants);
this.closingConsonants = copyStrings(closingConsonants);
this.closingSyllables = copyStrings(closingSyllables);
this.vowelSplitters = copyStrings(vowelSplitters);
this.syllableFrequencies = Arrays.copyOf(syllableFrequencies, syllableFrequencies.length);
this.vowelStartFrequency = vowelStartFrequency;
this.vowelEndFrequency = vowelEndFrequency;
this.vowelSplitFrequency = vowelSplitFrequency;
this.syllableEndFrequency = syllableEndFrequency;
double total = 0.0, bias = 0.0;
for (int i = 0; i < syllableFrequencies.length; i++) {
total += syllableFrequencies[i];
bias += (i + 1.0) * syllableFrequencies[i];
}
totalSyllableFrequency = total;
syllableBias = bias / total;
if (sanityChecks == null)
this.sanityChecks = null;
else {
this.sanityChecks = new Pattern[sanityChecks.length];
System.arraycopy(sanityChecks, 0, this.sanityChecks, 0, sanityChecks.length);
}
this.clean = clean;
this.modifiers = new ArrayList<>(modifiers);
}
private static String[] processParts(OrderedMap<String, String> parts, Set<String> missingSounds,
Set<String> forbidden, IRNG rng, double repeatSingleChance,
int preferredLimit) {
int l, sz = parts.size();
List<String> working = new ArrayList<>(sz * 24);
String pair;
for (int e = 0; e < parts.size(); e++) {
Map.Entry<String, String> sn = parts.entryAt(e);
if (missingSounds.contains(sn.getKey()))
continue;
for (String t : sn.getValue().split(" ")) {
if (forbidden.contains(t))
continue;
l = t.length();
int num;
char c;
switch (l) {
case 0:
break;
case 1:
working.add(t);
working.add(t);
working.add(t);
c = t.charAt(0);
num = 0;
boolean repeat = true;
switch (c) {
case 'w':
num += 2;
case 'y':
case 'h':
num += 4;
case 'q':
case 'x':
num += 4;
repeat = false;
break;
case 'i':
case 'u':
repeat = false;
num = 13;
break;
case 'z':
case 'v':
num = 4;
break;
case 'j':
num = 7;
break;
default:
if (e >= preferredLimit)
num = 6;
else
num = 13;
}
for (int i = 0; i < num * 3; i++) {
if (rng.nextDouble() < 0.75) {
working.add(t);
}
}
if (repeat && rng.nextDouble() < repeatSingleChance) {
pair = t + t;
if (missingSounds.contains(pair))
continue;
working.add(pair);
working.add(pair);
working.add(pair);
if (rng.nextDouble() < 0.7) {
working.add(pair);
working.add(pair);
}
if (rng.nextDouble() < 0.7) {
working.add(pair);
}
}
break;
case 2:
if (rng.nextDouble() < 0.65) {
c = t.charAt(1);
switch (c) {
case 'z':
num = 1;
break;
case 'w':
num = 3;
break;
case 'n':
num = 4;
break;
default:
if (e >= preferredLimit)
num = 2;
else
num = 7;
}
working.add(t);
for (int i = 0; i < num; i++) {
if (rng.nextDouble() < 0.25) {
working.add(t);
}
}
}
break;
case 3:
if (rng.nextDouble() < 0.5) {
c = t.charAt(0);
switch (c) {
case 'z':
num = 1;
break;
case 'w':
num = 3;
break;
case 'n':
num = 4;
break;
default:
if (e >= preferredLimit)
num = 2;
else
num = 6;
}
working.add(t);
for (int i = 0; i < num; i++) {
if (rng.nextDouble() < 0.2) {
working.add(t);
}
}
}
break;
default:
if (rng.nextDouble() < 0.3 && (t.charAt(l - 1) != 'z' || rng.nextDouble() < 0.1)) {
working.add(t);
}
break;
}
}
}
return working.toArray(new String[0]);
}
public static FakeLanguageGen randomLanguage(IRNG rng) {
return randomLanguage(rng.nextLong());
}
public static FakeLanguageGen randomLanguage(long seed) {
GWTRNG rng = new GWTRNG(seed);
int[] lengths = new int[rng.between(3, 5)];
System.arraycopy(new int[]{1, 2, 3, 4}, 0, lengths, 0, lengths.length);
double[] chances = new double[lengths.length];
System.arraycopy(new double[]{
5 + rng.nextDouble(4), 13 + rng.nextDouble(9), 3 + rng.nextDouble(3), 1 + rng.nextDouble(2)
}, 0, chances, 0, chances.length);
double vowelHeavy = rng.between(0.2, 0.5), removalRate = rng.between(0.15, 0.65);
int sz = openCons.size();
int[] reordering = rng.randomOrdering(sz), vOrd = rng.randomOrdering(openVowels.size());
OrderedMap<String, String>
parts0 = new OrderedMap<>(openVowels),
parts1 = new OrderedMap<>(openCons),
parts2 = new OrderedMap<>(midCons),
parts3 = new OrderedMap<>(closeCons);
OrderedSet<String> forbidden = new OrderedSet<>(1024, 0.25f), missingSounds = new OrderedSet<>(64, 0.875f);
parts1.reorder(reordering);
parts2.reorder(reordering);
parts3.reorder(reordering);
parts0.reorder(vOrd);
int n;
int mn = Math.min(rng.nextInt(3), rng.nextInt(3)), sz0, p0s;
for (n = 0; n < mn; n++) {
missingSounds.add(parts0.keyAt(0));
Collections.addAll(forbidden, parts0.getAt(0).split(" "));
parts0.removeFirst();
}
p0s = parts0.size();
sz0 = Math.max(rng.between(1, p0s + 1), rng.between(1, p0s + 1));
char[] nextAccents = new char[sz0], unaccented = new char[sz0];
int vowelAccent = rng.between(1, 7);
for (int i = 0; i < sz0; i++) {
nextAccents[i] = accentedVowels[vOrd[i + mn]][vowelAccent];
unaccented[i] = accentedVowels[vOrd[i + mn]][0];
}
if (rng.nextDouble() < 0.8) {
for (int i = 0; i < sz0; i++) {
char ac = nextAccents[i], ua = unaccented[i];
String v = "", uas = String.valueOf(ua);
Pattern pat = Pattern.compile("\\b([aeiou]*)(" + ua + ")([aeiou]*)\\b");
Replacer rep = pat.replacer("$1$2$3 $1" + ac + "$3"), repLess = pat.replacer("$1" + ac + "$3");
for (int j = 0; j < p0s; j++) {
String k = parts0.keyAt(j);
if (uas.equals(k)) // uas is never null, always length 1
v = parts0.getAt(j);
else {
String current = parts0.getAt(j);
String[] splits = current.split(" ");
for (int s = 0; s < splits.length; s++) {
if (forbidden.contains(uas) && splits[s].contains(uas))
forbidden.add(splits[s].replace(ua, ac));
}
parts0.put(k, rep.replace(current));
}
}
parts0.put(String.valueOf(ac), repLess.replace(v));
}
}
n = 0;
if (rng.nextDouble() < 0.75) {
missingSounds.add("z");
Collections.addAll(forbidden, parts1.get("z").split(" "));
Collections.addAll(forbidden, parts2.get("z").split(" "));
Collections.addAll(forbidden, parts3.get("z").split(" "));
n++;
}
if (rng.nextDouble() < 0.82) {
missingSounds.add("x");
Collections.addAll(forbidden, parts1.get("x").split(" "));
Collections.addAll(forbidden, parts2.get("x").split(" "));
Collections.addAll(forbidden, parts3.get("x").split(" "));
n++;
}
if (rng.nextDouble() < 0.92) {
missingSounds.add("qu");
Collections.addAll(forbidden, parts1.get("qu").split(" "));
Collections.addAll(forbidden, parts2.get("qu").split(" "));
Collections.addAll(forbidden, parts3.get("qu").split(" "));
n++;
}
if (rng.nextDouble() < 0.96) {
missingSounds.add("q");
Collections.addAll(forbidden, parts1.get("q").split(" "));
Collections.addAll(forbidden, parts2.get("q").split(" "));
Collections.addAll(forbidden, parts3.get("q").split(" "));
n++;
}
if (rng.nextDouble() < 0.97) {
missingSounds.add("tl");
Collections.addAll(forbidden, parts1.get("tl").split(" "));
Collections.addAll(forbidden, parts2.get("tl").split(" "));
Collections.addAll(forbidden, parts3.get("tl").split(" "));
n++;
}
if (rng.nextDouble() < 0.86) {
missingSounds.add("ph");
Collections.addAll(forbidden, parts1.get("ph").split(" "));
Collections.addAll(forbidden, parts2.get("ph").split(" "));
Collections.addAll(forbidden, parts3.get("ph").split(" "));
n++;
}
if (rng.nextDouble() < 0.94) {
missingSounds.add("kh");
Collections.addAll(forbidden, parts1.get("kh").split(" "));
Collections.addAll(forbidden, parts2.get("kh").split(" "));
Collections.addAll(forbidden, parts3.get("kh").split(" "));
n++;
}
if (rng.nextDouble() < 0.96) {
missingSounds.add("bh");
missingSounds.add("dh");
Collections.addAll(forbidden, parts1.get("bh").split(" "));
Collections.addAll(forbidden, parts2.get("bh").split(" "));
Collections.addAll(forbidden, parts3.get("bh").split(" "));
Collections.addAll(forbidden, parts1.get("dh").split(" "));
Collections.addAll(forbidden, parts2.get("dh").split(" "));
Collections.addAll(forbidden, parts3.get("dh").split(" "));
n++;
n++;
}
for (; n < sz * removalRate; n++) {
missingSounds.add(parts1.keyAt(n));
missingSounds.add(parts2.keyAt(n));
missingSounds.add(parts3.keyAt(n));
Collections.addAll(forbidden, parts1.getAt(n).split(" "));
Collections.addAll(forbidden, parts2.getAt(n).split(" "));
Collections.addAll(forbidden, parts3.getAt(n).split(" "));
}
return new FakeLanguageGen(
processParts(parts0, missingSounds, forbidden, rng, 0.0, p0s),
new String[]{},
processParts(openCons, missingSounds, forbidden, rng, 0.0, 4096),
processParts(midCons, missingSounds, forbidden, rng, (rng.nextDouble() * 3 - 0.75) * 0.4444, 4096),
processParts(closeCons, missingSounds, forbidden, rng, (rng.nextDouble() * 3 - 0.75) * 0.2857, 4096),
new String[]{},
new String[]{}, lengths, chances, vowelHeavy, vowelHeavy * 1.8, 0.0, 0.0, genericSanityChecks, true).summarize("0#" + seed + "@1");
}
protected static boolean checkAll(CharSequence testing, Pattern[] checks) {
CharSequence fixed = removeAccents(testing);
for (int i = 0; i < checks.length; i++) {
if (checks[i].matcher(fixed).find())
return false;
}
return true;
}
/**
* Checks a CharSequence, such as a String, against an overzealous vulgarity filter, returning true if the text
* could contain vulgar elements or words that could seem vulgar or juvenile. The idea here is that false positives
* are OK as long as there are very few false negatives (missed vulgar words). Does not check punctuation or numbers
* that could look like letters.
* @param testing the text, as a CharSequence such as a String, to check
* @return true if the text could contain a vulgar or juvenile element; false if it probably doesn't
*/
public static boolean checkVulgarity(CharSequence testing)
{
CharSequence fixed = removeAccents(testing);
for (int i = 0; i < vulgarChecks.length; i++) {
if (vulgarChecks[i].matcher(fixed).find())
{
// System.out.println(vulgarChecks[i]);
return true;
}
}
return false;
}
/**
* Generate a word from this FakeLanguageGen, using and changing the current seed.
*
* @param capitalize true if the word should start with a capital letter, false otherwise
* @return a word in the fake language as a String
*/
public String word(boolean capitalize) {
return word(srng, capitalize);
}
/**
* Generate a word from this FakeLanguageGen using the specified long seed to use for a shared StatefulRNG.
* If seed is the same, a FakeLanguageGen should produce the same word every time with this method.
*
* @param seed the seed, as a long, to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @return a word in the fake language as a String
*/
public String word(long seed, boolean capitalize) {
srng.setState(seed);
return word(srng, capitalize);
}
/**
* Generate a word from this FakeLanguageGen using the specified RNG.
*
* @param rng the RNG to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @return a word in the fake language as a String
*/
public String word(IRNG rng, boolean capitalize) {
while (true) {
sb.setLength(0);
ender.setLength(0);
double syllableChance = rng.nextDouble(totalSyllableFrequency);
int syllables = 1, i = 0;
for (int s = 0; s < syllableFrequencies.length; s++) {
if(syllableChance < syllableFrequencies[s])
{
syllables = s + 1;
break;
} else
{
syllableChance -= syllableFrequencies[s];
}
}
if (rng.nextDouble() < vowelStartFrequency) {
sb.append(rng.getRandomElement(openingVowels));
if (syllables == 1)
sb.append(rng.getRandomElement(closingConsonants));
else
sb.append(rng.getRandomElement(midConsonants));
i++;
} else {
sb.append(rng.getRandomElement(openingConsonants));
}
String close = "";
boolean redouble = false;
if (i < syllables) {
if (rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (syllables & 1) == 0) {
redouble = true;
syllables >>= 1;
//sb.append(close.replaceAll("@\\d", sb.toString()));
}
if (!close.contains("@"))
ender.append(close);
else if (rng.nextDouble() < vowelEndFrequency) {
ender.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
}
} else {
ender.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
if (rng.nextDouble() >= vowelEndFrequency) {
ender.append(rng.getRandomElement(closingConsonants));
if (rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (syllables & 1) == 0) {
redouble = true;
syllables >>= 1;
//sb.append(close.replaceAll("@\\d", sb.toString()));
}
if (!close.contains("@"))
ender.append(close);
}
}
}
i += vowelClusters.matcher(ender).findAll().count();
}
for (; i < syllables; i++) {
sb.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
sb.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
sb.append(rng.getRandomElement(midConsonants));
}
sb.append(ender);
if (redouble && i <= syllables + 1) {
sb.append(close.replaceAll("@", sb.toString()));
}
if (sanityChecks != null && !checkAll(sb, sanityChecks))
{
continue;
}
for (int m = 0; m < modifiers.size(); m++) {
modifiers.get(m).modify(rng, sb);
}
if (capitalize)
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
if (clean && !checkAll(sb, vulgarChecks))
{
continue;
}
return sb.toString();
}
}
/**
* Generate a word from this FakeLanguageGen with an approximate number of syllables using the specified long seed
* to use for a shared StatefulRNG.
* If seed and the other parameters are the same, a FakeLanguageGen should produce the same word every time with
* this method.
*
* @param seed the seed, as a long, to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @param approxSyllables the approximate number of syllables to produce in the word; there may be more syllables
* @return a word in the fake language as a String
*/
public String word(long seed, boolean capitalize, int approxSyllables) {
srng.setState(seed);
return word(srng, capitalize, approxSyllables);
}
/**
* Generate a word from this FakeLanguageGen using the specified RNG with an approximate number of syllables.
*
* @param rng the RNG to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @param approxSyllables the approximate number of syllables to produce in the word; there may be more syllables
* @return a word in the fake language as a String
*/
public String word(IRNG rng, boolean capitalize, int approxSyllables) {
return word(rng, capitalize, approxSyllables, null);
}
/**
* Generate a word from this FakeLanguageGen with an approximate number of syllables using the specified long seed
* to use for a shared StatefulRNG. This takes an array of {@link Pattern} objects (from RegExodus, not
* java.util.regex) that should match invalid outputs, such as words that shouldn't be generated in some context due
* to vulgarity or cultural matters. If seed and the other parameters are the same, a FakeLanguageGen should produce
* the same word every time with this method.
*
* @param seed the seed, as a long, to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @param approxSyllables the approximate number of syllables to produce in the word; there may be more syllables
* @param additionalChecks an array of RegExodus Pattern objects that match invalid words (these may be additional vulgarity checks, for example)
* @return a word in the fake language as a String
*/
public String word(long seed, boolean capitalize, int approxSyllables, Pattern[] additionalChecks) {
srng.setState(seed);
return word(srng, capitalize, approxSyllables, additionalChecks);
}
/**
* Generate a word from this FakeLanguageGen using the specified RNG with an approximate number of syllables.
* This takes an array of {@link Pattern} objects (from RegExodus, not java.util.regex) that should match invalid
* outputs, such as words that shouldn't be generated in some context due to vulgarity or cultural matters.
*
* @param rng the RNG to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @param approxSyllables the approximate number of syllables to produce in the word; there may be more syllables
* @param additionalChecks an array of RegExodus Pattern objects that match invalid words (these may be additional vulgarity checks, for example)
* @return a word in the fake language as a String
*/
public String word(IRNG rng, boolean capitalize, int approxSyllables, Pattern[] additionalChecks) {
if (approxSyllables <= 0) {
sb.setLength(0);
sb.append(rng.getRandomElement(openingVowels));
for (int m = 0; m < modifiers.size(); m++) {
modifiers.get(m).modify(rng, sb);
}
if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
}
while (true) {
sb.setLength(0);
ender.setLength(0);
int i = 0;
if (rng.nextDouble() < vowelStartFrequency) {
sb.append(rng.getRandomElement(openingVowels));
if (approxSyllables == 1 && closingConsonants.length > 0)
sb.append(rng.getRandomElement(closingConsonants));
else if (midConsonants.length > 0)
sb.append(rng.getRandomElement(midConsonants));
i++;
} else if (openingConsonants.length > 0) {
sb.append(rng.getRandomElement(openingConsonants));
}
String close = "";
boolean redouble = false;
if (i < approxSyllables) {
if (closingSyllables.length > 0 && rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (approxSyllables & 1) == 0) {
redouble = true;
approxSyllables = approxSyllables >> 1;
//sb.append(close.replaceAll("@\\d", sb.toString()));
}
if (!close.contains("@"))
ender.append(close);
else if (redouble && rng.nextDouble() < vowelEndFrequency) {
ender.append(rng.getRandomElement(midVowels));
if (vowelSplitters.length > 0 && rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
}
} else {
ender.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
if (rng.nextDouble() >= vowelEndFrequency) {
ender.append(rng.getRandomElement(closingConsonants));
if (rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (approxSyllables & 1) == 0) {
redouble = true;
approxSyllables = approxSyllables >> 1;
//sb.append(close.replaceAll("@\\d", sb.toString()));
}
if (!close.contains("@"))
ender.append(close);
}
}
}
i += vowelClusters.matcher(ender).findAll().count();
}
for (; i < approxSyllables; i++) {
sb.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
sb.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
sb.append(rng.getRandomElement(midConsonants));
}
sb.append(ender);
if (redouble && i <= approxSyllables + 1) {
sb.append(close.replaceAll("@", sb.toString()));
}
if (sanityChecks != null && !checkAll(sb, sanityChecks))
continue;
for (int m = 0; m < modifiers.size(); m++) {
modifiers.get(m).modify(rng, sb);
}
if (clean && !checkAll(sb, vulgarChecks))
continue;
if (additionalChecks != null && !checkAll(sb, additionalChecks))
continue;
if (capitalize)
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
}
}
/**
* Generate a word from this FakeLanguageGen using the specified StatefulRNG with an approximate number of
* syllables, potentially setting the state of rng mid-way through the word to another seed from {@code reseeds}
* more than once if the word is long enough. This overload is less likely to be used very often.
*
* @param rng the StatefulRNG to use for the randomized string building
* @param capitalize true if the word should start with a capital letter, false otherwise
* @param approxSyllables the approximate number of syllables to produce in the word; there may be more syllables
* @param reseeds an array or varargs of additional long seeds to seed {@code rng} with mid-generation
* @return a word in the fake language as a String
*/
public String word(IStatefulRNG rng, boolean capitalize, int approxSyllables, long... reseeds) {
if (approxSyllables <= 0) {
sb.setLength(0);
sb.append(rng.getRandomElement(openingVowels));
for (int m = 0; m < modifiers.size(); m++) {
modifiers.get(m).modify(rng, sb);
}
if (capitalize) sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
return sb.toString();
}
int numSeeds, fraction = 1;
if (reseeds != null)
numSeeds = Math.min(reseeds.length, approxSyllables - 1);
else numSeeds = 0;
while (true) {
sb.setLength(0);
ender.setLength(0);
int i = 0;
if (rng.nextDouble() < vowelStartFrequency) {
sb.append(rng.getRandomElement(openingVowels));
if (approxSyllables == 1)
sb.append(rng.getRandomElement(closingConsonants));
else
sb.append(rng.getRandomElement(midConsonants));
i++;
} else {
sb.append(rng.getRandomElement(openingConsonants));
}
String close = "";
boolean redouble = false;
if (i < approxSyllables) {
if (numSeeds > 0 && i > 0 && i == approxSyllables * fraction / (1 + numSeeds))
rng.setState(reseeds[fraction++ - 1]);
if (rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (approxSyllables & 1) == 0) {
redouble = true;
approxSyllables = approxSyllables >> 1;
}
if (!close.contains("@"))
ender.append(close);
else if (rng.nextDouble() < vowelEndFrequency) {
ender.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
}
} else {
ender.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
ender.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
if (rng.nextDouble() >= vowelEndFrequency) {
ender.append(rng.getRandomElement(closingConsonants));
if (rng.nextDouble() < syllableEndFrequency) {
close = rng.getRandomElement(closingSyllables);
if (close.contains("@") && (approxSyllables & 1) == 0) {
redouble = true;
approxSyllables = approxSyllables >> 1;
//sb.append(close.replaceAll("@\\d", sb.toString()));
}
if (!close.contains("@"))
ender.append(close);
}
}
}
i += vowelClusters.matcher(ender).findAll().count();
}
for (; i < approxSyllables; i++) {
if (numSeeds > 0 && i > 0 && i == approxSyllables * fraction / (1 + numSeeds))
rng.setState(reseeds[fraction++ - 1]);
sb.append(rng.getRandomElement(midVowels));
if (rng.nextDouble() < vowelSplitFrequency) {
sb.append(rng.getRandomElement(vowelSplitters))
.append(rng.getRandomElement(midVowels));
}
sb.append(rng.getRandomElement(midConsonants));
}
sb.append(ender);
if (redouble && i <= approxSyllables + 1) {
sb.append(close.replaceAll("@", sb.toString()));
}
if (sanityChecks != null && !checkAll(sb, sanityChecks))
continue;
for (int m = 0; m < modifiers.size(); m++) {
modifiers.get(m).modify(rng, sb);
}
if (capitalize)
sb.setCharAt(0, Character.toUpperCase(sb.charAt(0)));
if (clean && !checkAll(sb, vulgarChecks))
continue;
return sb.toString();
}
}
private static final String[] mid = {",", ",", ",", ";"}, end = {".", ".", ".", "!", "?", "..."};
/**
* Generate a sentence from this FakeLanguageGen, using and changing the current seed, with the length in words
* between minWords and maxWords, both inclusive. This can use commas and semicolons between words, and can end a
* sentence with ".", "!", "?", or "...".
*
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @return a sentence in the fake language as a String
*/
public String sentence(int minWords, int maxWords) {
return sentence(srng, minWords, maxWords, mid, end, 0.2);
}
/**
* Generate a sentence from this FakeLanguageGen, using the given seed as a long, with the length in words between
* minWords and maxWords, both inclusive. This can use commas and semicolons between words, and can end a
* sentence with ".", "!", "?", or "...".
*
* @param seed the seed, as a long, for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @return a sentence in the fake language as a String
*/
public String sentence(long seed, int minWords, int maxWords) {
srng.setState(seed);
return sentence(srng, minWords, maxWords);
}
/**
* Generate a sentence from this FakeLanguageGen, using the given RNG, with the length in words between minWords and
* maxWords, both inclusive. This can use commas and semicolons between words, and can end a
* sentence with ".", "!", "?", or "...".
*
* @param rng the RNG to use for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @return a sentence in the fake language as a String
*/
public String sentence(IRNG rng, int minWords, int maxWords) {
return sentence(rng, minWords, maxWords, mid,
end, 0.2);
}
/**
* Generate a sentence from this FakeLanguageGen, using and changing the current seed. The sentence's length in
* words will be between minWords and maxWords, both inclusive. It will put one of the punctuation Strings from
* {@code midPunctuation} between two words (before the space) at a frequency of {@code midPunctuationFrequency}
* (between 0 and 1), and will end the sentence with one String chosen from {@code endPunctuation}.
*
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @return a sentence in the fake language as a String
*/
public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency) {
return sentence(srng, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency);
}
/**
* Generate a sentence from this FakeLanguageGen, using the given seed as a long. The sentence's length in
* words will be between minWords and maxWords, both inclusive. It will put one of the punctuation Strings from
* {@code midPunctuation} between two words (before the space) at a frequency of {@code midPunctuationFrequency}
* (between 0 and 1), and will end the sentence with one String chosen from {@code endPunctuation}.
*
* @param seed the seed, as a long, for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @return a sentence in the fake language as a String
*/
public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency) {
srng.setState(seed);
return sentence(srng, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency);
}
/**
* Generate a sentence from this FakeLanguageGen using the specific RNG. The sentence's length in
* words will be between minWords and maxWords, both inclusive. It will put one of the punctuation Strings from
* {@code midPunctuation} between two words (before the space) at a frequency of {@code midPunctuationFrequency}
* (between 0 and 1), and will end the sentence with one String chosen from {@code endPunctuation}.
*
* @param rng the RNG to use for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @return a sentence in the fake language as a String
*/
public String sentence(IRNG rng, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency) {
if (minWords < 1)
minWords = 1;
if (minWords > maxWords)
maxWords = minWords;
if (midPunctuationFrequency > 1.0) {
midPunctuationFrequency = 1.0 / midPunctuationFrequency;
}
ssb.setLength(0);
ssb.ensureCapacity(12 * maxWords);
ssb.append(word(rng, true));
for (int i = 1; i < minWords; i++) {
if (rng.nextDouble() < midPunctuationFrequency) {
ssb.append(rng.getRandomElement(midPunctuation));
}
ssb.append(' ').append(word(rng, false));
}
for (int i = minWords; i < maxWords && rng.nextInt(2 * maxWords) > i; i++) {
if (rng.nextDouble() < midPunctuationFrequency) {
ssb.append(rng.getRandomElement(midPunctuation));
}
ssb.append(' ').append(word(rng, false));
}
if (endPunctuation != null && endPunctuation.length > 0)
ssb.append(rng.getRandomElement(endPunctuation));
return ssb.toString();
}
/**
* Generate a sentence from this FakeLanguageGen that fits in the given length limit. The sentence's length in
* words will be between minWords and maxWords, both inclusive, unless it would exceed maxChars, in which case it is
* truncated. It will put one of the punctuation Strings from {@code midPunctuation} between two words (before the
* space) at a frequency of {@code midPunctuationFrequency} (between 0 and 1), and will end the sentence with one
* String chosen from {@code endPunctuation}.
*
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords}
* @return a sentence in the fake language as a String
*/
public String sentence(int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency, int maxChars) {
return sentence(srng, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency, maxChars);
}
/**
* Generate a sentence from this FakeLanguageGen that fits in the given length limit, using the given seed as a
* long. The sentence's length in words will be between minWords and maxWords, both inclusive, unless it would
* exceed maxChars, in which case it is truncated. It will put one of the punctuation Strings from
* {@code midPunctuation} between two words (before the space) at a frequency of {@code midPunctuationFrequency}
* (between 0 and 1), and will end the sentence with one String chosen from {@code endPunctuation}.
*
* @param seed the seed, as a long, for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords}
* @return a sentence in the fake language as a String
*/
public String sentence(long seed, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency, int maxChars) {
srng.setState(seed);
return sentence(srng, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency, maxChars);
}
/**
* Generate a sentence from this FakeLanguageGen using the given RNG that fits in the given length limit. The
* sentence's length in words will be between minWords and maxWords, both inclusive, unless it would exceed
* maxChars, in which case it is truncated. It will put one of the punctuation Strings from {@code midPunctuation}
* between two words (before the space) at a frequency of {@code midPunctuationFrequency} (between 0 and 1), and
* will end the sentence with one String chosen from {@code endPunctuation}.
*
* @param rng the RNG to use for the randomized string building
* @param minWords an int for the minimum number of words in a sentence; should be at least 1
* @param maxWords an int for the maximum number of words in a sentence; should be at least equal to minWords
* @param midPunctuation a String array where each element is a comma, semicolon, or the like that goes before a
* space in the middle of a sentence
* @param endPunctuation a String array where each element is a period, question mark, or the like that goes at
* the very end of a sentence
* @param midPunctuationFrequency a double between 0.0 and 1.0 that determines how often Strings from
* midPunctuation should be inserted before spaces
* @param maxChars the longest string length this can produce; should be at least {@code 6 * minWords}
* @return a sentence in the fake language as a String
*/
public String sentence(IRNG rng, int minWords, int maxWords, String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency, int maxChars) {
if(maxChars < 0)
return sentence(rng, minWords, maxWords, midPunctuation, endPunctuation, midPunctuationFrequency);
if (minWords < 1)
minWords = 1;
if (minWords > maxWords)
maxWords = minWords;
if (midPunctuationFrequency > 1.0) {
midPunctuationFrequency = 1.0 / midPunctuationFrequency;
}
if (maxChars < 4)
return "!";
if (maxChars <= 5 * minWords) {
minWords = 1;
maxWords = 1;
}
int frustration = 0;
ssb.setLength(0);
ssb.ensureCapacity(maxChars);
String next = word(rng, true);
while (next.length() >= maxChars - 1 && frustration < 50) {
next = word(rng, true);
frustration++;
}
if (frustration >= 50) return "!";
ssb.append(next);
for (int i = 1; i < minWords && ssb.length() < maxChars - 7; i++) {
if (rng.nextDouble() < midPunctuationFrequency && ssb.length() < maxChars - 3) {
ssb.append(rng.getRandomElement(midPunctuation));
}
next = word(rng, false);
while (ssb.length() + next.length() >= maxChars - 2 && frustration < 50) {
next = word(rng, false);
frustration++;
}
if (frustration >= 50) break;
ssb.append(' ').append(next);
}
for (int i = minWords; i < maxWords && ssb.length() < maxChars - 7 && rng.nextInt(2 * maxWords) > i && frustration < 50; i++) {
if (rng.nextDouble() < midPunctuationFrequency && ssb.length() < maxChars - 3) {
ssb.append(rng.getRandomElement(midPunctuation));
}
next = word(rng, false);
while (ssb.length() + next.length() >= maxChars - 2 && frustration < 50) {
next = word(rng, false);
frustration++;
}
if (frustration >= 50) break;
ssb.append(' ');
ssb.append(next);
}
if (endPunctuation != null && endPunctuation.length > 0) {
next = rng.getRandomElement(endPunctuation);
if (ssb.length() + next.length() >= maxChars)
ssb.append('.');
else
ssb.append(next);
}
if (ssb.length() > maxChars)
return "!";
return ssb.toString();
}
protected String[] merge1000(IRNG rng, String[] me, String[] other, double otherInfluence) {
if (other.length <= 0 && me.length <= 0)
return new String[]{};
String[] ret = new String[1000];
int otherCount = (int) (1000 * otherInfluence);
int idx = 0;
if (other.length > 0) {
String[] tmp = new String[other.length];
rng.shuffle(other, tmp);
for (idx = 0; idx < otherCount; idx++) {
ret[idx] = tmp[idx % tmp.length];
}
}
if (me.length > 0) {
String[] tmp = new String[me.length];
rng.shuffle(me, tmp);
for (; idx < 1000; idx++) {
ret[idx] = tmp[idx % tmp.length];
}
} else {
for (; idx < 1000; idx++) {
ret[idx] = other[idx % other.length];
}
}
return ret;
}
protected static String[] accentVowels(IRNG rng, String[] me, double influence) {
String[] ret = new String[1000];
int otherCount = (int) (1000 * influence);
int idx;
Matcher matcher;
if (me.length > 0) {
String[] tmp = new String[me.length];
rng.shuffle(me, tmp);
for (idx = 0; idx < otherCount; idx++) {
ret[idx] = tmp[idx % tmp.length]
.replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)])
.replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)])
.replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)])
.replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)])
.replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]);
matcher = repeats.matcher(ret[idx]);
if (matcher.find()) {
ret[idx] = matcher.replaceAll(rng.getRandomElement(me));
}
}
for (; idx < 1000; idx++) {
ret[idx] = tmp[idx % tmp.length];
}
} else
return new String[]{};
return ret;
}
protected static String[] accentConsonants(IRNG rng, String[] me, double influence) {
String[] ret = new String[1000];
int otherCount = (int) (1000 * influence);
int idx;
Matcher matcher;
if (me.length > 0) {
String[] tmp = new String[me.length];
rng.shuffle(me, tmp);
for (idx = 0; idx < otherCount; idx++) {
ret[idx] = tmp[idx % tmp.length]
//0
.replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)])
.replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)])
.replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)])
.replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)])
.replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)])
.replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)])
.replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)])
.replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)])
//9
.replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)])
//11
//12
.replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)])
.replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)])
.replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)])
//16
.replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)])
//18
.replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)])
.replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]);
matcher = repeats.matcher(ret[idx]);
if (matcher.find()) {
ret[idx] = matcher.replaceAll(rng.getRandomElement(me));
}
}
for (; idx < 1000; idx++) {
ret[idx] = tmp[idx % tmp.length];
}
} else
return new String[]{};
return ret;
}
protected static String[] accentBoth(IRNG rng, String[] me, double vowelInfluence, double consonantInfluence) {
String[] ret = new String[1000];
int idx;
Matcher matcher;
if (me.length > 0) {
String[] tmp = new String[me.length];
rng.shuffle(me, tmp);
for (idx = 0; idx < 1000; idx++) {
boolean subVowel = rng.nextDouble() < vowelInfluence, subCon = rng.nextDouble() < consonantInfluence;
if (subVowel && subCon) {
ret[idx] = tmp[idx % tmp.length]
.replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)])
.replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)])
.replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)])
.replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)])
.replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)])
//0
.replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)])
.replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)])
.replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)])
.replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)])
.replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)])
.replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)])
.replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)])
.replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)])
//9
.replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)])
//11
//12
.replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)])
.replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)])
.replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)])
//16
.replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)])
//18
.replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)])
.replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]);
matcher = repeats.matcher(ret[idx]);
if (matcher.find()) {
ret[idx] = matcher.replaceAll(rng.getRandomElement(me));
}
} else if (subVowel) {
ret[idx] = tmp[idx % tmp.length]
.replace('a', accentedVowels[0][rng.nextInt(accentedVowels[0].length)])
.replace('e', accentedVowels[1][rng.nextInt(accentedVowels[1].length)])
.replace('i', accentedVowels[2][rng.nextInt(accentedVowels[2].length)])
.replace('o', accentedVowels[3][rng.nextInt(accentedVowels[3].length)])
.replace('u', accentedVowels[4][rng.nextInt(accentedVowels[4].length)]);
matcher = repeats.matcher(ret[idx]);
if (matcher.find()) {
ret[idx] = matcher.replaceAll(rng.getRandomElement(me));
}
} else if (subCon) {
ret[idx] = tmp[idx % tmp.length]
//0
.replace('c', accentedConsonants[1][rng.nextInt(accentedConsonants[1].length)])
.replace('d', accentedConsonants[2][rng.nextInt(accentedConsonants[2].length)])
.replace('f', accentedConsonants[3][rng.nextInt(accentedConsonants[3].length)])
.replace('g', accentedConsonants[4][rng.nextInt(accentedConsonants[4].length)])
.replace('h', accentedConsonants[5][rng.nextInt(accentedConsonants[5].length)])
.replace('j', accentedConsonants[6][rng.nextInt(accentedConsonants[6].length)])
.replace('k', accentedConsonants[7][rng.nextInt(accentedConsonants[7].length)])
.replace('l', accentedConsonants[8][rng.nextInt(accentedConsonants[8].length)])
//9
.replace('n', accentedConsonants[10][rng.nextInt(accentedConsonants[10].length)])
//11
//12
.replace('r', accentedConsonants[13][rng.nextInt(accentedConsonants[13].length)])
.replace('s', accentedConsonants[14][rng.nextInt(accentedConsonants[14].length)])
.replace('t', accentedConsonants[15][rng.nextInt(accentedConsonants[15].length)])
//16
.replace('w', accentedConsonants[17][rng.nextInt(accentedConsonants[17].length)])
//18
.replace('y', accentedConsonants[19][rng.nextInt(accentedConsonants[19].length)])
.replace('z', accentedConsonants[20][rng.nextInt(accentedConsonants[20].length)]);
matcher = repeats.matcher(ret[idx]);
if (matcher.find()) {
ret[idx] = matcher.replaceAll(rng.getRandomElement(me));
}
} else ret[idx] = tmp[idx % tmp.length];
}
} else
return new String[]{};
return ret;
}
/**
* Makes a new FakeLanguageGen that mixes this object with {@code other}, mingling the consonants and vowels they
* use as well as any word suffixes or other traits, and favoring the qualities in {@code other} by
* {@code otherInfluence}, which will value both languages evenly if it is 0.5 .
* <br>
* You should generally prefer {@link #mix(double, FakeLanguageGen, double, Object...)} or
* {@link #mixAll(Object...)} if you ever mix 3 or more languages. Chaining this mix() method can be very
* counter-intuitive because the weights are relative, while in the other mix() and mixAll() they are absolute.
* @param other another FakeLanguageGen to mix along with this one into a new language
* @param otherInfluence how much other should affect the pair, with 0.5 being equal and 1.0 being only other used
* @return a new FakeLanguageGen with traits from both languages
*/
public FakeLanguageGen mix(FakeLanguageGen other, double otherInfluence) {
otherInfluence = Math.max(0.0, Math.min(otherInfluence, 1.0));
double myInfluence = 1.0 - otherInfluence;
GWTRNG rng = new GWTRNG(hashCode(), other.hashCode() ^ NumberTools.doubleToMixedIntBits(otherInfluence));
String[] ov = merge1000(rng, openingVowels, other.openingVowels, otherInfluence),
mv = merge1000(rng, midVowels, other.midVowels, otherInfluence),
oc = merge1000(rng, openingConsonants, other.openingConsonants, otherInfluence *
Math.max(0.0, Math.min(1.0, 1.0 - other.vowelStartFrequency + vowelStartFrequency))),
mc = merge1000(rng, midConsonants, other.midConsonants, otherInfluence),
cc = merge1000(rng, closingConsonants, other.closingConsonants, otherInfluence *
Math.max(0.0, Math.min(1.0, 1.0 - other.vowelEndFrequency + vowelEndFrequency))),
cs = merge1000(rng, closingSyllables, other.closingSyllables, otherInfluence *
Math.max(0.0, Math.min(1.0, other.syllableEndFrequency - syllableEndFrequency))),
splitters = merge1000(rng, vowelSplitters, other.vowelSplitters, otherInfluence);
double[] fr = new double[Math.max(syllableFrequencies.length, other.syllableFrequencies.length)];
System.arraycopy(syllableFrequencies, 0, fr, 0, syllableFrequencies.length);
for (int i = 0; i < other.syllableFrequencies.length; i++) {
fr[i] += other.syllableFrequencies[i];
}
ArrayList<Modifier> mods = new ArrayList<>(modifiers.size() + other.modifiers.size());
mods.addAll(modifiers);
mods.addAll(other.modifiers);
return new FakeLanguageGen(ov, mv, oc, mc, cc, cs, splitters, fr,
vowelStartFrequency * myInfluence + other.vowelStartFrequency * otherInfluence,
vowelEndFrequency * myInfluence + other.vowelEndFrequency * otherInfluence,
vowelSplitFrequency * myInfluence + other.vowelSplitFrequency * otherInfluence,
syllableEndFrequency * myInfluence + other.syllableEndFrequency * otherInfluence,
(sanityChecks == null) ? other.sanityChecks : sanityChecks, true, mods)
.setName(otherInfluence > 0.5 ? other.name + "/" + name : name + "/" + other.name);
}
private static double readDouble(Object o) {
if (o instanceof Double) return (Double) o;
else if (o instanceof Float) return (Float) o;
else if (o instanceof Long) return ((Long) o).doubleValue();
else if (o instanceof Integer) return (Integer) o;
else if (o instanceof Short) return (Short) o;
else if (o instanceof Byte) return (Byte) o;
else if (o instanceof Character) return (Character) o;
return 0.0;
}
/**
* Produces a FakeLanguageGen by mixing this FakeLanguageGen with one or more other FakeLanguageGen objects. Takes
* a weight for this, another FakeLanguageGen, a weight for that FakeLanguageGen, then a possibly-empty group of
* FakeLanguageGen parameters and the weights for those parameters. If other1 is null or if pairs has been given a
* value of null instead of the normal (possibly empty) array of Objects, then this simply returns a copy of this
* FakeLanguageGen. Otherwise, it will at least mix this language with other1 using the given weights for each.
* If pairs is not empty, it has special requirements for what types it allows and in what order, but does no type
* checking. Specifically, pairs requires the first Object to be a FakeLanguageGen, the next to be a number of some
* kind that will be the weight for the previous FakeLanguageGen(this method can handle non-Double weights, and
* converts them to Double if needed), and every two parameters after that to follow the same order and pattern
* (FakeLanguageGen, then number, then FakeLanguageGen, then number...). Weights are absolute, and don't depend on
* earlier weights, which is the case when chaining the {@link #mix(FakeLanguageGen, double)} method. This makes
* reasoning about the ideal weights for multiple mixed languages easier; to mix 3 languages equally you can use
* 3 equal weights with this, whereas with mix chaining you would need to mix the first two with 0.5 and the third
* with 0.33 .
* <br>
* It's up to you whether you want to use {@link #mixAll(Object...)} or this method; they call the same code and
* produce the same result, including the summary for serialization support. You probably shouldn't use
* {@link #mix(FakeLanguageGen, double)} with two arguments in new code, since it's easy to make mistakes when
* mixing three or more languages (calling that twice or more).
*
* @param myWeight the weight to assign this FakeLanguageGen in the mix
* @param other1 another FakeLanguageGen to mix in; if null, this method will abort and return {@link #copy()}
* @param weight1 the weight to assign other1 in the mix
* @param pairs may be empty, not null; otherwise must alternate between FakeLanguageGen and number (weight) elements
* @return a FakeLanguageGen produced by mixing this with any FakeLanguageGen arguments by the given weights
*/
public FakeLanguageGen mix(double myWeight, FakeLanguageGen other1, double weight1, Object... pairs) {
if (other1 == null || pairs == null)
return copy();
OrderedSet<Modifier> mods = new OrderedSet<>(modifiers);
FakeLanguageGen mixer = removeModifiers();
FakeLanguageGen[] languages = new FakeLanguageGen[2 + (pairs.length >>> 1)];
double[] weights = new double[languages.length];
String[] summaries = new String[languages.length];
boolean summarize = true;
double total = 0.0, current, weight;
languages[0] = mixer;
total += weights[0] = myWeight;
if ((summaries[0] = mixer.summary) == null) summarize = false;
mods.addAll(other1.modifiers);
languages[1] = other1.removeModifiers();
total += weights[1] = weight1;
if (summarize && (summaries[1] = languages[1].summary) == null) summarize = false;
for (int i = 1, p = 2; i < pairs.length; i += 2, p++) {
if (pairs[i] == null || pairs[i - 1] == null)
continue;
languages[p] = ((FakeLanguageGen) pairs[i - 1]).removeModifiers();
total += weights[p] = readDouble(pairs[i]);
if (summarize && (summaries[p] = languages[p].summary) == null) summarize = false;
}
if (total == 0)
return copy();
current = myWeight / total;
for (int i = 1; i < languages.length; i++) {
if ((weight = weights[i]) > 0)
mixer = mixer.mix(languages[i], weight / total / (current += weight / total));
}
if (summarize) {
sb.setLength(0);
String c;
int idx;
for (int i = 0; i < summaries.length; i++) {
c = summaries[i];
idx = c.indexOf('@');
if (idx >= 0) {
sb.append(c, 0, idx + 1).append(weights[i]);
if (i < summaries.length - 1)
sb.append('~');
}
}
return mixer.summarize(sb.toString()).addModifiers(mods);
} else
return mixer.addModifiers(mods);
}
/**
* Produces a FakeLanguageGen from a group of FakeLanguageGen parameters and the weights for those parameters.
* Requires the first Object in pairs to be a FakeLanguageGen, the next to be a number of some kind that will be the
* weight for the previous FakeLanguageGen(this method can handle non-Double weights, and converts them to Double
* if needed), and every two parameters after that to follow the same order and pattern (FakeLanguageGen, then
* number, then FakeLanguageGen, then number...). There should be at least 4 elements in pairs, half of them
* languages and half of them weights, for this to do any mixing, but it can produce a result with as little as one
* FakeLanguageGen (returning a copy of the first FakeLanguageGen). Weights are absolute, and don't depend on
* earlier weights, which is the case when chaining the {@link #mix(FakeLanguageGen, double)} method. This makes
* reasoning about the ideal weights for multiple mixed languages easier; to mix 3 languages equally you can use
* 3 equal weights with this, whereas with mix chaining you would need to mix the first two with 0.5 and the third
* with 0.33 .
* <br>
* This is probably the most intuitive way to mix languages here, though there's also
* {@link #mix(double, FakeLanguageGen, double, Object...)}, which is very similar but doesn't take its parameters
* in quite the same way (it isn't static, and treats the FakeLanguageGen object like the first item in pairs here).
* Used internally in the deserialization code.
*
* @param pairs should have at least one item, and must alternate between FakeLanguageGen and number (weight) elements
* @return a FakeLanguageGen produced by mixing any FakeLanguageGen arguments by the given weights
*/
public static FakeLanguageGen mixAll(Object... pairs) {
int len;
if (pairs == null || (len = pairs.length) <= 0)
return ENGLISH.copy();
if (len < 4)
return ((FakeLanguageGen) pairs[0]).copy();
Object[] pairs2 = new Object[len - 4];
if (len > 4)
System.arraycopy(pairs, 4, pairs2, 0, len - 4);
return ((FakeLanguageGen) pairs[0]).mix(readDouble(pairs[1]), (FakeLanguageGen) pairs[2], readDouble(pairs[3]), pairs2);
}
/**
* Produces a new FakeLanguageGen like this one but with extra vowels and/or consonants possible, adding from a wide
* selection of accented vowels (if vowelInfluence is above 0.0) and/or consonants (if consonantInfluence is above
* 0.0). This may produce a gibberish-looking language with no rhyme or reason to the accents, and generally
* consonantInfluence should be very low if it is above 0 at all.
* @param vowelInfluence between 0.0 and 1.0; if 0.0 will not affect vowels at all
* @param consonantInfluence between 0.0 and 1.0; if 0.0 will not affect consonants at all
* @return a new FakeLanguageGen with modifications to add accented vowels and/or consonants
*/
public FakeLanguageGen addAccents(double vowelInfluence, double consonantInfluence) {
vowelInfluence = Math.max(0.0, Math.min(vowelInfluence, 1.0));
consonantInfluence = Math.max(0.0, Math.min(consonantInfluence, 1.0));
GWTRNG rng = new GWTRNG(hashCode(),
NumberTools.doubleToMixedIntBits(vowelInfluence)
^ NumberTools.doubleToMixedIntBits(consonantInfluence));
String[] ov = accentVowels(rng, openingVowels, vowelInfluence),
mv = accentVowels(rng, midVowels, vowelInfluence),
oc = accentConsonants(rng, openingConsonants, consonantInfluence),
mc = accentConsonants(rng, midConsonants, consonantInfluence),
cc = accentConsonants(rng, closingConsonants, consonantInfluence),
cs = accentBoth(rng, closingSyllables, vowelInfluence, consonantInfluence);
return new FakeLanguageGen(ov, mv, oc, mc, cc, cs, vowelSplitters, syllableFrequencies,
vowelStartFrequency,
vowelEndFrequency,
vowelSplitFrequency,
syllableEndFrequency, sanityChecks, clean, modifiers).setName(name + "-Bònüs");
}
private static String[] copyStrings(String[] start) {
String[] next = new String[start.length];
System.arraycopy(start, 0, next, 0, start.length);
return next;
}
/**
* Useful for cases with limited fonts, this produces a new FakeLanguageGen like this one but with all accented
* characters removed (including almost all non-ASCII Latin-alphabet characters, but only some Greek and Cyrillic
* characters). This will replace letters like "A with a ring" with just "A". Some of the letters chosen as
* replacements aren't exact matches.
* @return a new FakeLanguageGen like this one but without accented letters
*/
public FakeLanguageGen removeAccents() {
String[] ov = copyStrings(openingVowels),
mv = copyStrings(midVowels),
oc = copyStrings(openingConsonants),
mc = copyStrings(midConsonants),
cc = copyStrings(closingConsonants),
cs = copyStrings(closingSyllables);
for (int i = 0; i < ov.length; i++) {
ov[i] = removeAccents(openingVowels[i]).toString();
}
for (int i = 0; i < mv.length; i++) {
mv[i] = removeAccents(midVowels[i]).toString();
}
for (int i = 0; i < oc.length; i++) {
oc[i] = removeAccents(openingConsonants[i]).toString();
}
for (int i = 0; i < mc.length; i++) {
mc[i] = removeAccents(midConsonants[i]).toString();
}
for (int i = 0; i < cc.length; i++) {
cc[i] = removeAccents(closingConsonants[i]).toString();
}
for (int i = 0; i < cs.length; i++) {
cs[i] = removeAccents(closingSyllables[i]).toString();
}
return new FakeLanguageGen(ov, mv, oc, mc, cc, cs, vowelSplitters, syllableFrequencies,
vowelStartFrequency,
vowelEndFrequency,
vowelSplitFrequency,
syllableEndFrequency, sanityChecks, clean, modifiers);
}
/**
* Returns the name of this FakeLanguageGen, such as "English" or "Deep Speech", if one was registered for this.
* In the case of hybrid languages produced by {@link #mix(FakeLanguageGen, double)} or related methods, this should
* produce a String like "English/French" (or "English/French/Maori" if more are mixed together). If no name was
* registered, this will return "Nameless Language".
* @return the human-readable name of this language, or "Nameless Language" if none is known
*/
public String getName() {
return name;
}
private FakeLanguageGen setName(final String languageName)
{
name = languageName;
return this;
}
/**
* Adds the specified Modifier objects from a Collection to a copy of this FakeLanguageGen and returns it.
* You can obtain a Modifier with the static constants in the FakeLanguageGen.Modifier nested class, the
* FakeLanguageGen.modifier() method, or Modifier's constructor.
*
* @param mods an array or vararg of Modifier objects
* @return a copy of this with the Modifiers added
*/
public FakeLanguageGen addModifiers(Collection<Modifier> mods) {
FakeLanguageGen next = copy();
next.modifiers.addAll(mods);
if(next.summary != null){
sb.setLength(0);
sb.append(next.summary);
for (int i = 0; i < mods.size(); i++) {
sb.append('℗').append(next.modifiers.get(i).serializeToString());
}
next.summarize(sb.toString());
}
return next;
}
/**
* Adds the specified Modifier objects to a copy of this FakeLanguageGen and returns it.
* You can obtain a Modifier with the static constants in the FakeLanguageGen.Modifier nested class, the
* FakeLanguageGen.modifier() method, or Modifier's constructor.
*
* @param mods an array or vararg of Modifier objects
* @return a copy of this with the Modifiers added
*/
public FakeLanguageGen addModifiers(Modifier... mods) {
FakeLanguageGen next = copy();
Collections.addAll(next.modifiers, mods);
if(next.summary != null){
sb.setLength(0);
sb.append(next.summary);
for (int i = 0; i < mods.length; i++) {
sb.append('℗').append(next.modifiers.get(i).serializeToString());
}
next.summarize(sb.toString());
}
return next;
}
/**
* Creates a copy of this FakeLanguageGen with no modifiers.
*
* @return a copy of this FakeLanguageGen with modifiers removed.
*/
public FakeLanguageGen removeModifiers() {
FakeLanguageGen next = copy();
next.modifiers.clear();
if(next.summary != null){
next.summarize(StringKit.safeSubstring(next.summary, 0, next.summary.indexOf('℗')));
}
return next;
}
/**
* Convenience method that just calls {@link Modifier#Modifier(String, String)}.
* @param pattern a String that will be interpreted as a regex pattern using {@link Pattern}
* @param replacement a String that will be interpreted as a replacement string for pattern; can include "$1" and the like if pattern has groups
* @return a Modifier that can be applied to a FakeLanguagGen
*/
public static Modifier modifier(String pattern, String replacement) {
return new Modifier(pattern, replacement);
}
/**
* Convenience method that just calls {@link Modifier#Modifier(String, String, double)}.
* @param pattern a String that will be interpreted as a regex pattern using {@link Pattern}
* @param replacement a String that will be interpreted as a replacement string for pattern; can include "$1" and the like if pattern has groups
* @param chance the chance, as a double between 0 and 1, that the Modifier will take effect
* @return a Modifier that can be applied to a FakeLanguagGen
*/
public static Modifier modifier(String pattern, String replacement, double chance) {
return new Modifier(pattern, replacement, chance);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
FakeLanguageGen that = (FakeLanguageGen) o;
if (clean != that.clean) return false;
if (Double.compare(that.totalSyllableFrequency, totalSyllableFrequency) != 0) return false;
if (Double.compare(that.vowelStartFrequency, vowelStartFrequency) != 0) return false;
if (Double.compare(that.vowelEndFrequency, vowelEndFrequency) != 0) return false;
if (Double.compare(that.vowelSplitFrequency, vowelSplitFrequency) != 0) return false;
if (Double.compare(that.syllableEndFrequency, syllableEndFrequency) != 0) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(openingVowels, that.openingVowels)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(midVowels, that.midVowels)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(openingConsonants, that.openingConsonants)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(midConsonants, that.midConsonants)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(closingConsonants, that.closingConsonants)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(vowelSplitters, that.vowelSplitters)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(closingSyllables, that.closingSyllables)) return false;
if (!Arrays.equals(syllableFrequencies, that.syllableFrequencies)) return false;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
if (!Arrays.equals(sanityChecks, that.sanityChecks)) return false;
return modifiers != null ? modifiers.equals(that.modifiers) : that.modifiers == null;
}
@Override
public int hashCode() {
int result = 31 * 31 * 31 * 31 +
31 * 31 * 31 * CrossHash.hash(openingVowels) +
31 * 31 * CrossHash.hash(midVowels) +
31 * CrossHash.hash(openingConsonants) +
CrossHash.hash(midConsonants) | 0;
result = 31 * 31 * 31 * 31 * result +
31 * 31 * 31 * CrossHash.hash(closingConsonants) +
31 * 31 * CrossHash.hash(vowelSplitters) +
31 * CrossHash.hash(closingSyllables) ^
(clean ? 1 : 0);
result = 31 * 31 * 31 * 31 * result +
31 * 31 * 31 * CrossHash.hash(syllableFrequencies) +
31 * 31 * NumberTools.doubleToMixedIntBits(totalSyllableFrequency) +
31 * NumberTools.doubleToMixedIntBits(vowelStartFrequency) +
NumberTools.doubleToMixedIntBits(vowelEndFrequency) | 0;
result = 31 * 31 * 31 * 31 * result +
31 * 31 * 31 * (sanityChecks != null ? sanityChecks.length + 1 : 0) +
31 * 31 * NumberTools.doubleToMixedIntBits(syllableEndFrequency) +
31 * NumberTools.doubleToMixedIntBits(vowelSplitFrequency) | 0;
if(modifiers != null) {
for (int i = 0; i < modifiers.size(); i++) {
result = result + 7 * (i + 1) * modifiers.get(i).hashCode() | 0;
}
}
return result;
}
public long hash64() {
long result = CrossHash.hash64(openingVowels);
result = 31L * result + CrossHash.hash64(midVowels);
result = 31L * result + CrossHash.hash64(openingConsonants);
result = 31L * result + CrossHash.hash64(midConsonants);
result = 31L * result + CrossHash.hash64(closingConsonants);
result = 31L * result + CrossHash.hash64(vowelSplitters);
result = 31L * result + CrossHash.hash64(closingSyllables);
result = 31L * result + CrossHash.hash64(syllableFrequencies);
result = 31L * result + (clean ? 1L : 0L);
result = 31L * result + NumberTools.doubleToLongBits(totalSyllableFrequency);
result = 31L * result + NumberTools.doubleToLongBits(vowelStartFrequency);
result = 31L * result + NumberTools.doubleToLongBits(vowelEndFrequency);
result = 31L * result + NumberTools.doubleToLongBits(vowelSplitFrequency);
result = 31L * result + NumberTools.doubleToLongBits(syllableEndFrequency);
result = 31L * result + (sanityChecks != null ? sanityChecks.length + 1L : 0L);
result *= 31L;
if(modifiers != null) {
for (int i = 0; i < modifiers.size(); i++) {
result += 7L * (i + 1L) * CrossHash.hash64(modifiers.get(i).alterations);
}
}
return result;
}
@Override
public String toString() {
return "FakeLanguageGen{" +
"openingVowels=" + Arrays.toString(openingVowels) +
", midVowels=" + Arrays.toString(midVowels) +
", openingConsonants=" + Arrays.toString(openingConsonants) +
", midConsonants=" + Arrays.toString(midConsonants) +
", closingConsonants=" + Arrays.toString(closingConsonants) +
", vowelSplitters=" + Arrays.toString(vowelSplitters) +
", closingSyllables=" + Arrays.toString(closingSyllables) +
", clean=" + clean +
", syllableFrequencies=" + Arrays.toString(syllableFrequencies) +
", totalSyllableFrequency=" + totalSyllableFrequency +
", vowelStartFrequency=" + vowelStartFrequency +
", vowelEndFrequency=" + vowelEndFrequency +
", vowelSplitFrequency=" + vowelSplitFrequency +
", syllableEndFrequency=" + syllableEndFrequency +
", sanityChecks=" + Arrays.toString(sanityChecks) +
", modifiers=" + modifiers +
'}';
}
public FakeLanguageGen copy() {
return new FakeLanguageGen(openingVowels, midVowels, openingConsonants, midConsonants,
closingConsonants, closingSyllables, vowelSplitters, syllableFrequencies, vowelStartFrequency,
vowelEndFrequency, vowelSplitFrequency, syllableEndFrequency, sanityChecks, clean, modifiers)
.summarize(summary).setName(name);
}
public String serializeToString() {
return (summary == null) ? "" : summary;
}
public static FakeLanguageGen deserializeFromString(String data) {
if (data == null || data.equals(""))
return ENGLISH.copy();
int poundIndex = data.indexOf('#'), snailIndex = data.indexOf('@'), tempBreak = data.indexOf('℗'),
breakIndex = (tempBreak < 0) ? data.length() : tempBreak,
tildeIndex = Math.min(data.indexOf('~'), breakIndex), prevTildeIndex = -1;
if (tildeIndex < 0)
tildeIndex = breakIndex;
if (snailIndex < 0)
return ENGLISH.copy();
ArrayList<Object> pairs = new ArrayList<>(4);
while (snailIndex >= 0) {
if (poundIndex >= 0 && poundIndex < snailIndex) // random case
{
pairs.add(randomLanguage(Long.parseLong(data.substring(poundIndex + 1, snailIndex))));
pairs.add(StringKit.intFromDec(data, snailIndex + 1, tildeIndex));
poundIndex = -1;
} else {
pairs.add(registry.getAt(Integer.parseInt(data.substring(prevTildeIndex + 1, snailIndex))));
pairs.add(StringKit.intFromDec(data, snailIndex + 1, tildeIndex));
}
snailIndex = data.indexOf('@', snailIndex + 1);
if (snailIndex > breakIndex)
break;
prevTildeIndex = tildeIndex;
tildeIndex = Math.min(data.indexOf('~', tildeIndex + 1), breakIndex);
if (tildeIndex < 0)
tildeIndex = data.length();
}
ArrayList<Modifier> mods = new ArrayList<>(8);
if (breakIndex == tempBreak) {
tildeIndex = breakIndex - 1;
while ((prevTildeIndex = data.indexOf('℗', tildeIndex + 1)) >= 0) {
tildeIndex = data.indexOf('℗', prevTildeIndex + 1);
if (tildeIndex < 0) tildeIndex = data.length();
mods.add(Modifier.deserializeFromString(data.substring(prevTildeIndex, tildeIndex)));
}
}
FakeLanguageGen flg = mixAll(pairs.toArray());
flg.modifiers.addAll(mods);
return flg;
}
public static class Modifier implements Serializable {
private static final long serialVersionUID = 1734863678490422371L;
private static final StringBuilder modSB = new StringBuilder(32);
public final Alteration[] alterations;
public Modifier() {
alterations = new Alteration[0];
}
public Modifier(String pattern, String replacement) {
alterations = new Alteration[]{new Alteration(pattern, replacement)};
}
public Modifier(String pattern, String replacement, double chance) {
alterations = new Alteration[]{new Alteration(pattern, replacement, chance)};
}
public Modifier(Alteration... alts) {
alterations = (alts == null) ? new Alteration[0] : alts;
}
public StringBuilder modify(IRNG rng, StringBuilder sb) {
Matcher m;
Replacer.StringBuilderBuffer tb;
boolean found;
Alteration alt;
for (int a = 0; a < alterations.length; a++) {
alt = alterations[a];
modSB.setLength(0);
tb = Replacer.wrap(modSB);
m = alt.replacer.getPattern().matcher(sb);
found = false;
while (true) {
if (alt.chance >= 1 || rng.nextDouble() < alt.chance) {
if (!Replacer.replaceStep(m, alt.replacer.getSubstitution(), tb))
break;
found = true;
} else {
if (!m.find())
break;
found = true;
m.getGroup(MatchResult.PREFIX, tb);
m.getGroup(MatchResult.MATCH, tb);
m.setTarget(m, MatchResult.SUFFIX);
}
}
if (found) {
m.getGroup(MatchResult.TARGET, tb);
sb.setLength(0);
sb.append(modSB);
}
}
return sb;
}
/**
* For a character who always pronounces 's', 'ss', and 'sh' as 'th'.
*/
public static final Modifier LISP = new Modifier("[tţťț]?[sśŝşšș]+h?", "th");
/**
* For a character who always lengthens 's' and 'z' sounds not starting a word.
*/
public static final Modifier HISS = new Modifier("(.)([sśŝşšșzźżž])+", "$1$2$2$2");
/**
* For a character who has a 20% chance to repeat a starting consonant or vowel.
*/
public static final Modifier STUTTER = new Modifier(
new Alteration("^([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυωаеёийъыэюяоу]+)", "$1-$1", 0.2),
new Alteration("^([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųαοειυωаеёийъыэюяоу]+)", "$1-$1", 0.2));
/**
* For a language that has a 40% chance to repeat a single Latin vowel (a, e, o, or a variant on one of them
* like å or ö, but not merged letters like æ and œ).
*/
public static final Modifier DOUBLE_VOWELS = new Modifier(
"([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳ]|^)"
+ "([aàáâãäåāăąǻeèéêëēĕėęěòóôõöøōŏőǿ])"
+ "([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳ]|$)", "$1$2$2$3", 0.4);
/**
* For a language that has a 50% chance to repeat a single consonant.
*/
public static final Modifier DOUBLE_CONSONANTS = new Modifier("([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυωаеёийъыэюяоу])" +
"([^aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυωаеёийъыэюяоуqwhjx])" +
"([aàáâãäåæāăąǻǽeèéêëēĕėęěiìíîïĩīĭįıoòóôõöøōŏőœǿuùúûüũūŭůűųyýÿŷỳαοειυωаеёийъыэюяоу]|$)", "$1$2$2$3", 0.5);
/**
* For a language that never repeats the same letter twice in a row.
*/
public static final Modifier NO_DOUBLES = new Modifier("(.)\\1", "$1");
/**
* Removes accented letters and the two non-English consonants from text generated with {@link #NORSE}.
* Replaces á, é, í, ý, ó, æ, ú, and ö with a, e, i, y, o, ae, and ou. In some instances, replaces j
* with y. Replaces ð and þ with th and th, except for when preceded by s (then it replaces sð or sþ
* with st or st) or when the start of a word is fð or fþ, where it replaces with fr or fr.
*/
public static final Modifier SIMPLIFY_NORSE = replacementTable(
"á", "a",
"é", "e",
"í", "i",
"ý", "y",
"ó", "o",
"ú", "u",
"æ", "ae",
"ö", "ou",
"([^aeiou])jy", "$1yai",
"([^aeiou])j(?:[aeiouy]+)", "$1yo",
"s([ðþ])", "st",
"\\bf[ðþ]", "fr",
"[ðþ]", "th");
/**
* Simple changes to merge "ae" into "æ", "oe" into "œ", and any of "aé", "áe", or "áé" into "ǽ".
*/
public static final Modifier LIGATURES = replacementTable("ae", "æ", "oe", "œ", "áe", "ǽ", "aé", "ǽ", "áé", "ǽ");
/**
* Simple changes to merge "æ" into "ae", "œ" into "oe", and "ǽ" into "áe".
*/
public static final Modifier SPLIT_LIGATURES = replacementTable("æ", "ae", "œ", "oe", "ǽ", "áe");
/**
* Some changes that can be applied when sanity checks (which force re-generating a new word) aren't appropriate
* for fixing a word that isn't pronounceable.
*/
public static final Modifier GENERAL_CLEANUP = replacementTable(
"[æǽœìíîïĩīĭįıiùúûüũūŭůűųuýÿŷỳy]([æǽœýÿŷỳy])", "$1",
"q([ùúûüũūŭůűųu])$", "q$1e",
"([ìíîïĩīĭįıi])[ìíîïĩīĭįıi]", "$1",
"([æǽœìíîïĩīĭįıiùúûüũūŭůűųuýÿŷỳy])[wŵẁẃẅ]$", "$1",
"([ùúûüũūŭůűųu])([òóôõöøōŏőǿo])", "$2$1",
"[àáâãäåāăąǻaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőǿoùúûüũūŭůűųuýÿŷỳy]([æǽœ])", "$1",
"([æǽœ])[àáâãäåāăąǻaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőǿoùúûüũūŭůűųuýÿŷỳy]", "$1",
"([wŵẁẃẅ])[wŵẁẃẅ]", "$1",
"qq", "q");
//àáâãäåāăąǻæǽaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőœǿoùúûüũūŭůűųuýÿŷỳy
//bcçćĉċčdþðďđfgĝğġģhĥħjĵȷkķlĺļľŀłmnñńņňŋpqrŕŗřsśŝşšștţťțvwŵẁẃẅxyýÿŷỳzźżž
/**
* Creates a Modifier that will replace the nth char in initial with the nth char in change. Expects initial and
* change to be the same length, but will use the lesser length if they are not equal-length. Because of the
* state of the text at the time modifiers are run, only lower-case letters need to be searched for.
*
* @param initial a String containing lower-case letters or other symbols to be swapped out of a text
* @param change a String containing characters that will replace occurrences of characters in initial
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier charReplacementTable(String initial, String change) {
Alteration[] alts = new Alteration[Math.min(initial.length(), change.length())];
for (int i = 0; i < alts.length; i++) {
//literal string syntax; avoids sensitive escaping issues and also doesn't need a character class,
// which is slightly slower and has some odd escaping cases.
alts[i] = new Alteration("\\Q" + initial.charAt(i), change.substring(i, i + 1));
}
return new Modifier(alts);
}
/**
* Creates a Modifier that will replace the nth String key in map with the nth value. Because of the
* state of the text at the time modifiers are run, only lower-case letters need to be searched for.
* This overload of replacementTable allows full regex pattern strings as keys and replacement syntax,
* such as searching for "([aeiou])\\1+" to find repeated occurrences of the same vowel, and "$1" in
* this example to replace the repeated section with only the first vowel.
* The ordering of map matters if a later key contains an earlier key (the earlier one will be replaced
* first, possibly making the later key not match), or if an earlier replacement causes a later one to
* become valid.
*
* @param map containing String keys to replace and String values to use instead; replacements happen in order
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier replacementTable(OrderedMap<String, String> map) {
if (map == null)
return new Modifier();
Alteration[] alts = new Alteration[map.size()];
for (int i = 0; i < alts.length; i++) {
alts[i] = new Alteration(map.keyAt(i), map.getAt(i));
}
return new Modifier(alts);
}
/**
* Creates a Modifier that will replace the (n*2)th String in pairs with the (n*2+1)th value in pairs. Because
* of the state of the text at the time modifiers are run, only lower-case letters need to be searched for.
* This overload of replacementTable allows full regex syntax for search and replacement Strings,
* such as searching for "([aeiou])\\1+" to find repeated occurrences of the same vowel, and "$1" in
* this example to replace the repeated section with only the first vowel.
* The ordering of pairs matters if a later search contains an earlier search (the earlier one will be replaced
* first, possibly making the later search not match), or if an earlier replacement causes a later one to
* become valid.
*
* @param pairs array or vararg of alternating Strings to search for and Strings to replace with; replacements happen in order
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier replacementTable(String... pairs) {
int len;
if (pairs == null || (len = pairs.length) <= 1)
return new Modifier();
Alteration[] alts = new Alteration[len >> 1];
for (int i = 0; i < alts.length; i++) {
alts[i] = new Alteration(pairs[i<< 1], pairs[i<<1|1]);
}
return new Modifier(alts);
}
/**
* Adds the potential for the String {@code insertion} to be used as a vowel in addition to the vowels that the
* language already uses; insertion will replace an existing vowel (at any point in a word that had a vowel
* generated) with a probability of {@code chance}, so chance should be low (0.1 at most) unless you want the
* newly-inserted vowel to be likely to be present in every word of some sentences.
* @param insertion the String to use as an additional vowel
* @param chance the chance for a vowel cluster to be replaced with insertion; normally 0.1 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertVowel(String insertion, double chance)
{
return new Modifier(anyVowelCluster, insertion, chance);
}
/**
* Adds the potential for the String {@code insertion} to be used as a consonant in addition to the consonants
* that the language already uses; insertion will replace an existing consonant (at any point in a word that had
* a consonant generated) with a probability of {@code chance}, so chance should be low (0.1 at most) unless you
* want the newly-inserted consonant to be likely to be present in every word of some sentences.
* @param insertion the String to use as an additional consonant
* @param chance the chance for a consonant cluster to be replaced with insertion; normally 0.1 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertConsonant(String insertion, double chance)
{
return new Modifier(anyConsonantCluster, insertion, chance);
}
/**
* Adds the potential for the String {@code insertion} to be used as a vowel in addition to the vowels that the
* language already uses; insertion will replace an existing vowel at the start of a word with a probability of
* {@code chance}, so chance should be low (0.2 at most) unless you want the newly-inserted vowel to be likely
* to start every word of some sentences. Not all languages can start words with vowels, or do that very rarely,
* so this might not do anything.
* @param insertion the String to use as an additional opening vowel
* @param chance the chance for a vowel cluster at the start of a word to be replaced with insertion; normally 0.2 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertOpeningVowel(String insertion, double chance)
{
return new Modifier("\\b[àáâãäåæāăąǻǽaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőœǿoùúûüũūŭůűųuýÿŷỳyαοειυωаеёийоуъыэюя]+", insertion, chance);
}
/**
* Adds the potential for the String {@code insertion} to be used as a consonant in addition to the consonants
* that the language already uses; insertion will replace an existing consonant at the start of a word with a
* probability of {@code chance}, so chance should be low (0.2 at most) unless you want the newly-inserted
* consonant to be likely to start every word of some sentences. Not all languages can start words with
* consonants, or do that very rarely, so this might not do anything.
* @param insertion the String to use as an additional opening consonant
* @param chance the chance for a consonant cluster at the start of a word to be replaced with insertion; normally 0.2 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertOpeningConsonant(String insertion, double chance)
{
return new Modifier("\\b[bcçćĉċčdþðďđfgĝğġģhĥħjĵȷkķlĺļľŀłmnñńņňŋpqrŕŗřsśŝşšștţťțvwŵẁẃẅxyýÿŷỳzźżžρσζτκχνθμπψβλγφξςбвгдклпрстфхцжмнзчшщ]+", insertion, chance);
}
/**
* Adds the potential for the String {@code insertion} to be used as a vowel in addition to the vowels that the
* language already uses; insertion will replace an existing vowel at the end of a word with a probability of
* {@code chance}, so chance should be low (0.2 at most) unless you want the newly-inserted vowel to be likely
* to end every word of some sentences. Not all languages can end words with vowels, or do that very
* rarely, so this might not do anything.
* @param insertion the String to use as an additional closing vowel
* @param chance the chance for a vowel cluster at the end of a word to be replaced with insertion; normally 0.2 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertClosingVowel(String insertion, double chance)
{
return new Modifier("[àáâãäåæāăąǻǽaèéêëēĕėęěeìíîïĩīĭįıiòóôõöøōŏőœǿoùúûüũūŭůűųuýÿŷỳyαοειυωаеёийоуъыэюя]+\\b", insertion, chance);
}
/**
* Adds the potential for the String {@code insertion} to be used as a consonant in addition to the consonants
* that the language already uses; insertion will replace an existing consonant at the end of a word with a
* probability of {@code chance}, so chance should be low (0.2 at most) unless you want the newly-inserted
* consonant to be likely to end every word of some sentences. Not all languages can end words with consonants,
* or do that very rarely, so this might not do anything.
* @param insertion the String to use as an additional closing consonant
* @param chance the chance for a consonant cluster at the end of a word to be replaced with insertion; normally 0.2 or less
* @return a Modifier that can be added to a FakeLanguageGen with its addModifiers() method
*/
public static Modifier insertClosingConsonant(String insertion, double chance)
{
return new Modifier("[bcçćĉċčdþðďđfgĝğġģhĥħjĵȷkķlĺļľŀłmnñńņňŋpqrŕŗřsśŝşšștţťțvwŵẁẃẅxyýÿŷỳzźżžρσζτκχνθμπψβλγφξςбвгдклпрстфхцжмнзчшщ]+\\b", insertion, chance);
}
/**
* Replaces any characters this can produce that aren't in ASCII or Latin-1 with Latin-script stand-ins; this
* will often use accented characters, but will only use those present in Latin-1 (which many fonts support).
* <br>
* The rationale for this Modifier is to allow users of FakeLanguageGen who don't display with the wide-ranging
* fonts in the display module to still be able to display something reasonable for generated text.
*/
public static final Modifier REDUCE_ACCENTS = replacementTable("ā", "â", "ă", "ä", "ą", "ã", "ǻ", "å", "ǽ", "áe",
"ē", "ê", "ĕ", "ë", "ė", "ë", "ę", "è", "ě", "é", "ĩ", "í", "ī", "î", "į", "ì", "ĭ", "ï", "ı", "iy", "ō", "ô",
"ŏ", "ö", "ő", "ó", "œ", "oe", "ǿ", "ø", "ũ", "ú", "ŭ", "ü", "ů", "ùo", "ű", "ú", "ų", "ù", "ŷ", "ý", "ỳ", "ÿ",
// done with latin vowels...
"ć", "ç", "ĉ", "ç", "ċ", "ç", "č", "ç", "ď", "dh", "đ", "dh", "ĝ", "gh", "ğ", "gh", "ġ", "gh", "ģ", "gh",
"ĥ", "hh", "ħ", "hh", "ĵ", "jh", "ȷ", "jj", "ķ", "kc", "ĺ", "lh", "ļ", "ll", "ľ", "ly", "ŀł", "yl", "ł", "wl",
"ń", "nn", "ņ", "wn", "ň", "nh", "ŋ", "ng", "ŕ", "rh", "ŗ", "wr", "ř", "rr", "ś", "ss", "ŝ", "hs",
"ş", "sy", "š", "ws", "ș", "sw", "ţ", "wt", "ť", "tt", "ț", "ty", "ŵ", "ww", "ẁ", "hw", "ẃ", "wh", "ẅ", "uw",
"ź", "hz", "ż", "zy", "ž", "zz",
// greek
"α", "a", "ο", "o", "ε", "e", "ι", "i", "υ", "y", "ω", "au",
"κρ", "kr", "γγ", "ng", "γκ", "nk", "γξ", "nx", "γχ", "nch", "ρστ", "rst", "ρτ", "rt",
"ρ", "rh", "σ", "s", "ζ", "z", "τ", "t", "κ", "k", "χ", "ch", "ν", "n", "ξ", "x",
"θ", "th", "μ", "m", "π", "p", "ψ", "ps", "β", "b", "λ", "l", "γ", "g", "δ", "d", "φ", "ph", "ς", "s",
// cyrillic
"а", "a", "е", "e", "ё", "ë", "и", "i", "й", "î", "о", "o", "у", "u", "ъ", "ie", "ы", "y", "э", "e", "ю", "iu", "я", "ia",
"б", "b", "в", "v", "г", "g", "д", "d", "к", "k", "л", "l", "п", "p", "р", "r", "с", "s", "т", "t",
"ф", "f", "х", "kh", "ц", "ts", "ч", "ch", "ж", "zh", "м", "m", "н", "n", "з", "z", "ш", "sh", "щ", "shch");
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Modifier modifier = (Modifier) o;
// Probably incorrect - comparing Object[] arrays with Arrays.equals
return Arrays.equals(alterations, modifier.alterations);
}
@Override
public int hashCode() {
return CrossHash.hash(alterations);
}
@Override
public String toString() {
return "Modifier{" +
"alterations=" + Arrays.toString(alterations) +
'}';
}
public String serializeToString() {
if (alterations.length == 0) return "\6";
modSB.setLength(0);
modSB.append('\6');
for (int i = 0; i < alterations.length; i++)
modSB.append(alterations[i].serializeToString()).append('\6');
return modSB.toString();
}
public static Modifier deserializeFromString(String data) {
int currIdx = data.indexOf(6), altIdx = currIdx, matches = 0;
while (currIdx >= 0) {
if ((currIdx = data.indexOf(6, currIdx + 1)) < 0)
break;
matches++;
}
Alteration[] alts = new Alteration[matches];
for (int i = 0; i < matches; i++) {
alts[i] = Alteration.deserializeFromString(data.substring(altIdx + 1, altIdx = data.indexOf(6, altIdx + 1)));
}
return new Modifier(alts);
}
}
public static class Alteration implements Serializable {
private static final long serialVersionUID = -2138854697837563188L;
public Replacer replacer;
public String replacement;
public double chance;
public Alteration() {
this("[tţťț]?[sśŝşšș]+h?", "th");
}
public Alteration(String pattern, String replacement) {
this.replacement = replacement;
replacer = Pattern.compile(pattern).replacer(replacement);
chance = 1.0;
}
public Alteration(String pattern, String replacement, double chance) {
this.replacement = replacement;
replacer = Pattern.compile(pattern).replacer(replacement);
this.chance = chance;
}
public Alteration(Pattern pattern, String replacement, double chance) {
this.replacement = replacement;
replacer = pattern.replacer(replacement);
this.chance = chance;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Alteration that = (Alteration) o;
if (Double.compare(that.chance, chance) != 0) return false;
return replacer.equals(that.replacer);
}
@Override
public int hashCode() {
long result;
result = CrossHash.hash64(replacer.getPattern().serializeToString());
result = 31L * result + NumberTools.doubleToLongBits(chance);
result ^= result >>> 32;
return (int) (0xFFFFFFFFL & result);
}
@Override
public String toString() {
return "Alteration{" +
"replacer=" + replacer +
", chance=" + chance +
'}';
}
public String serializeToString() {
return replacer.getPattern().serializeToString() + '\2' + replacement + '\4' + chance;
}
public static Alteration deserializeFromString(String data) {
int split2 = data.indexOf('\2'), split4 = data.indexOf('\4');
return new Alteration(Pattern.deserializeFromString(data.substring(0, split2)),
data.substring(split2 + 1, split4),
Double.parseDouble(data.substring(split4 + 1)));
}
}
/**
* A simple way to bundle a FakeLanguageGen with the arguments that would be passed to it when calling
* {@link FakeLanguageGen#sentence(IRNG, int, int, String[], String[], double, int)} or one of its overloads.
* You can call {@link #sentence()} on this to produce another String sentence with the parameters it was given
* at construction. The parameters to
* {@link #SentenceForm(FakeLanguageGen, IStatefulRNG, int, int, String[], String[], double, int)} are stored in fields of
* the same name, and all fields in this class are public and modifiable.
*/
public static class SentenceForm implements Serializable
{
private static final long serialVersionUID = 1246527948419533147L;
public IStatefulRNG rng;
public int minWords, maxWords, maxChars;
public String[] midPunctuation, endPunctuation;
public double midPunctuationFrequency;
public FakeLanguageGen language;
/**
* Builds a SentenceForm with all default fields, using {@link FakeLanguageGen#FANTASY_NAME} for a language,
* using between 1 and 9 words in a sentence, and otherwise defaulting to how
* {@link #SentenceForm(FakeLanguageGen, int, int)} behaves.
*/
public SentenceForm()
{
this(FakeLanguageGen.FANTASY_NAME, FakeLanguageGen.srng, 1, 9,
mid,
end, 0.18, -1);
}
/**
* Builds a SentenceForm with only a few fields specified. The {@link #rng} will be made based on
* FakeLanguageGen's static {@link FakeLanguageGen#srng} field, maxChars will be -1 so the sentence length
* will be limited only by maxWords and the length of words produced, and the between-word and end-of-sentence
* punctuation will be set to reasonable defaults. This places either a comma or a semicolon after a word in the
* middle of a sentence about 18% of the time ({@code midPunctuationFrequency} is 0.18), and can end a sentence
* in a period, exclamation mark, question mark, or ellipsis (the "..." punctuation).
* @param language A FakeLanguageGen to use to generate words
* @param minWords minimum words per sentence
* @param maxWords maximum words per sentence
*/
public SentenceForm(FakeLanguageGen language, int minWords, int maxWords)
{
this(language, FakeLanguageGen.srng, minWords, maxWords, mid,
end, 0.18, -1);
}
/**
* Builds a SentenceForm with all fields specified except for {@link #rng}, which will be made based on
* FakeLanguageGen's static {@link FakeLanguageGen#srng} field, and maxChars, which means the sentence length
* will be limited only by maxWords and the length of words produced.
* @param language A FakeLanguageGen to use to generate words
* @param minWords minimum words per sentence
* @param maxWords maximum words per sentence
* @param midPunctuation an array of Strings that can be used immediately after words in the middle of sentences, like "," or ";"
* @param endPunctuation an array of Strings that can end a sentence, like ".", "?", or "..."
* @param midPunctuationFrequency the probability that two words will be separated by a String from midPunctuation, between 0.0 and 1.0
*/
public SentenceForm(FakeLanguageGen language, int minWords, int maxWords, String[] midPunctuation,
String[] endPunctuation, double midPunctuationFrequency)
{
this(language, FakeLanguageGen.srng, minWords, maxWords, midPunctuation, endPunctuation,
midPunctuationFrequency, -1);
}
/**
* Builds a SentenceForm with all fields specified except for {@link #rng}, which will be made based on
* FakeLanguageGen's static {@link FakeLanguageGen#srng} field.
* @param language A FakeLanguageGen to use to generate words
* @param minWords minimum words per sentence
* @param maxWords maximum words per sentence
* @param midPunctuation an array of Strings that can be used immediately after words in the middle of sentences, like "," or ";"
* @param endPunctuation an array of Strings that can end a sentence, like ".", "?", or "..."
* @param midPunctuationFrequency the probability that two words will be separated by a String from midPunctuation, between 0.0 and 1.0
* @param maxChars the maximum number of chars to use in a sentence, or -1 for no hard limit
*/
public SentenceForm(FakeLanguageGen language, int minWords, int maxWords, String[] midPunctuation,
String[] endPunctuation, double midPunctuationFrequency, int maxChars)
{
this(language, FakeLanguageGen.srng, minWords, maxWords, midPunctuation, endPunctuation,
midPunctuationFrequency, maxChars);
}
/**
* Builds a SentenceForm with all fields specified; each value is referenced directly except for {@code rng},
* which will not change or be directly referenced (a new GWTRNG will be used with the same state value).
* @param language A FakeLanguageGen to use to generate words
* @param rng a StatefulRNG that will not be directly referenced; the state will be copied into a new StatefulRNG
* @param minWords minimum words per sentence
* @param maxWords maximum words per sentence
* @param midPunctuation an array of Strings that can be used immediately after words in the middle of sentences, like "," or ";"
* @param endPunctuation an array of Strings that can end a sentence, like ".", "?", or "..."
* @param midPunctuationFrequency the probability that two words will be separated by a String from midPunctuation, between 0.0 and 1.0
* @param maxChars the maximum number of chars to use in a sentence, or -1 for no hard limit
*/
public SentenceForm(FakeLanguageGen language, IStatefulRNG rng, int minWords, int maxWords,
String[] midPunctuation, String[] endPunctuation,
double midPunctuationFrequency, int maxChars)
{
this.language = language;
this.rng = new GWTRNG(rng.getState());
this.minWords = minWords;
this.maxWords = maxWords;
this.midPunctuation = midPunctuation;
this.endPunctuation = endPunctuation;
this.midPunctuationFrequency = midPunctuationFrequency;
this.maxChars = maxChars;
}
public String sentence()
{
return language.sentence(rng, minWords, maxWords, midPunctuation, endPunctuation,
midPunctuationFrequency, maxChars);
}
public String serializeToString() {
return language.serializeToString() + '℘' +
rng.getState() + '℘' +
minWords + '℘' +
maxWords + '℘' +
StringKit.join("ℙ", midPunctuation) + '℘' +
StringKit.join("ℙ", endPunctuation) + '℘' +
NumberTools.doubleToLongBits(midPunctuationFrequency) + '℘' +
maxChars;
}
public static SentenceForm deserializeFromString(String ser)
{
int gap = ser.indexOf('℘');
FakeLanguageGen lang = FakeLanguageGen.deserializeFromString(ser.substring(0, gap));
GWTRNG rng = new GWTRNG(
StringKit.longFromDec(ser,gap + 1, gap = ser.indexOf('℘', gap + 1)));
int minWords = StringKit.intFromDec(ser,gap + 1, gap = ser.indexOf('℘', gap + 1));
int maxWords = StringKit.intFromDec(ser,gap + 1, gap = ser.indexOf('℘', gap + 1));
String[] midPunctuation =
StringKit.split(ser.substring(gap + 1, gap = ser.indexOf('℘', gap + 1)), "ℙ");
String[] endPunctuation =
StringKit.split(ser.substring(gap + 1, gap = ser.indexOf('℘', gap + 1)), "ℙ");
double midFreq = NumberTools.longBitsToDouble(StringKit.longFromDec(ser,gap + 1, gap = ser.indexOf('℘', gap + 1)));
int maxChars = StringKit.intFromDec(ser,gap + 1, ser.length());
return new SentenceForm(lang, rng, minWords, maxWords, midPunctuation, endPunctuation, midFreq, maxChars);
}
}
}
| yellowstonegames/SquidLib | squidlib-util/src/main/java/squidpony/FakeLanguageGen.java |
1,808 | package com.huawei.i18n.tmr.datetime.data;
import java.util.HashMap;
public class LocaleParamGetEl {
public HashMap<String, String> date = new HashMap<String, String>() {
/* class com.huawei.i18n.tmr.datetime.data.LocaleParamGetEl.AnonymousClass1 */
{
put("param_am", "π\\.μ\\.|πμ");
put("param_pm", "μ\\.μ\\.|μμ");
put("param_MMM", "Ιαν|Φεβ|Μαρ|Απρ|Μαΐ|Ιουν|Ιουλ|Αυγ|Σεπ|Οκτ|Νοε|Δεκ");
put("param_MMMM", "Ιανουαρίου|Φεβρουαρίου|Μαρτίου|Απριλίου|Μαΐου|Ιουνίου|Ιουλίου|Αυγούστου|Σεπτεμβρίου|Οκτωβρίου|Νοεμβρίου|Δεκεμβρίου");
put("param_E", "Κυρ|Δευ|Τρί|Τετ|Πέμ|Παρ|Σάβ");
put("param_E2", "Κυρ|Δευ|Τρί|Τετ|Πέμ|Παρ|Σάβ");
put("param_EEEE", "Κυριακή|Δευτέρα|Τρίτη|Τετάρτη|Πέμπτη|Παρασκευή|Σάββατο");
put("param_days", "σήμερα|αύριο|μεθαύριο");
put("param_thisweek", "αυτήν\\s+την\\s+Κυριακή|αυτήν\\s+τη\\s+Δευτέρα|αυτήν\\s+την\\s+Τρίτη|αυτήν\\s+την\\s+Τετάρτη|αυτήν\\s+την\\s+Πέμπτη|αυτήν\\s+την\\s+Παρασκευή|αυτό\\s+το\\s+Σάββατο");
put("param_nextweek", "επόμενη\\s+Κυριακή|επόμενη\\s+Δευτέρα|επόμενη\\s+Τρίτη|επόμενη\\s+Τετάρτη|επόμενη\\s+Πέμπτη|επόμενη\\s+Παρασκευή|επόμενο\\s+Σάββατο");
}
};
}
| dstmath/HWFramework | MATE-20_EMUI_11.0.0/src/main/java/com/huawei/i18n/tmr/datetime/data/LocaleParamGetEl.java |
1,812 | package gui;
import api.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class Slave {
private static JLabel myLabel = new JLabel("Βαθμολογία καταλύματος:");
private static JLabel myLabel2 = new JLabel("Δώσε την αξιολόγηση σου:");
private static final Font font = new Font("Courier", Font.BOLD,12);
private static SpinnerModel model = new SpinnerNumberModel(1,1,5,0.1);
private static JSpinner mySpinner = new JSpinner(model);
private static JTextField tex= new JTextField();
private static JButton myButton = new JButton("Υποβολή");
private static JPanel myPanel = new JPanel();
protected static JInternalFrame internalFrame;
private static Accommodation currentAccommodation;
private JButton buttonForInternal = new JButton("Εισαγωγή αξιολόγησης");
private static JTextArea area;
public Slave(JFrame frame, Accommodation acc, User connectedUser) {
currentAccommodation = acc;
myPanel.setLayout(new GridLayout(4,1));
internalFrame = new JInternalFrame();
internalFrame.setClosable(true);
internalFrame.setLayout(new BorderLayout());
internalFrame.setTitle(acc.getName());
area = new JTextArea(acc.toString());
area.setEditable(false);
area.setFont(font);
internalFrame.add(area,BorderLayout.CENTER);
createContentOfFrame();
if (connectedUser instanceof Customer) {
internalFrame.add(buttonForInternal,BorderLayout.PAGE_END);
buttonForInternal.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e)
{
createContent(acc,connectedUser,"",0,0);
//((Customer) connectedUser).getMyReviews().get(selected)
}
});
}
internalFrame.pack();
frame.add(internalFrame);
internalFrame.setLocation(781,21);//Στο 780 σταματαεί το JTabbedPane αρα 1 pixel πιο δεξία. Το κάθε Tab έχει 19 pixels ύψος, επιλέγω 21 για να είναι στο ίδιο ύψος τελικα.
internalFrame.setVisible(true);
internalFrame.setResizable(false);
}
public static void createContent(Accommodation acc, User connectedUser, String message, int service, int selectedRow)
{
JPanel temp = new JPanel();
mySpinner = new JSpinner(model);
temp.setLayout(new GridLayout(2,2));
temp.add(myLabel);
temp.add(mySpinner);
temp.add(myLabel2);
mySpinner.setSize(50,50);
if(service == 1)
{
Double value =((Customer) connectedUser).getMyReviews().get(selectedRow).getRating();//Παίρνω την τιμή για το mySpinner
mySpinner.setValue(value);
}
String input = JOptionPane.showInputDialog(null,temp,message);
if (input == null) {
return;
}
try {
if (input.length() < 3 || input.length() > 1024) {
throw new Exception("Review content must be between 3 and 1024 characters.");
}
if (service == 0) { // Αν το service==0 τοτέ εισάγουμε καινουργια αξιολόγηση, αλλιώ επεξεργαζόμαστε κάποια.
((Customer) connectedUser).reviewAdd((Double)mySpinner.getValue(), input, acc, (Customer)connectedUser);
App.addRowToTable(acc.getName(),acc.getType(),acc.getCity(),acc.getRoad(),acc.getPostalCode(),mySpinner.getValue()+"");
} else
{
((Customer) connectedUser).setReviewContent(selectedRow, input);
((Customer) connectedUser).setRating(selectedRow, (Double)mySpinner.getValue());
}
for (int i = 0; i < App.getAccItems().size(); i++) {
if (App.getAccItems().get(i).getAccommodationInfo().equals(acc)) {
App.getAccItems().get(i).setReviewLabel(acc.getAverage() + "");
}
}
updateTextArea();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage(),"", JOptionPane.ERROR_MESSAGE);
}
}
protected static void updateTextArea() {
area.setText(currentAccommodation.toString());
internalFrame.pack();
}
private void createContentOfFrame() {
myPanel.setLayout(new GridLayout(2,2));
myPanel.add(myLabel);
myPanel.add(mySpinner);
myPanel.add(myLabel2);
mySpinner.setSize(50,50);
area.setFont(font);
}
}
| StylianosBairamis/oop-myreviews-project | src/gui/Slave.java |
1,813 | package gr.aueb.cf.ch4;
/**
* Ένας μικρός βάτραχος θέλει να περάσει ένα ποτάμι.
* Ο frog βρίσκεται στη θέση X και θέλει να φτάσει στη
* θέση Y (ή σε θέση > Υ). Ο frog jumps a fixed distance, D.
*
* Βρίσκει τον ελάχιστο αριθμό jumps που ο small from πρέπει'
* να κάνει ώστε να φτάσει (ή να ξεπεράσει) τον στόχο.
*
* Για παράδειγμα, αν έχουμε:
* X = 10
* Y = 85
* D = 30,
*
* τότε ο small frog θα χρειαστεί 3 jumps, γιατί:
* Starts at 10, και μετά to 1o jump πάει στη θέση 10 + 30 = 40
* Στο 2ο jump, πάει 40 + 30 = 70
* Και στο 3ο jump, πάει 70 + 30 = 100
*/
public class FrogApp {
public static void main(String[] args) {
int jumps = 0;
int x = 10;
int y = 85;
int jmp = 30;
jumps = (int) Math.ceil((y - x) / (double) jmp);
System.out.println("Jumps: " + jumps);
}
}
| a8anassis/codingfactory23a | src/gr/aueb/cf/ch4/FrogApp.java |
1,814 | package gr.aueb.cf.solutions.ch7;
/**
* Encrypts strings (English Uppercase Alphabet)
* based on Julius Caesar algorithm, shifting
* the initial string k positions to the right.
* Julius Caesar shifted three position to the right,
* while Augustus Caesar shifted one RHS position.
*/
public class CryptoV1 {
public static void main(String[] args) {
String s = "JULIUS CAESAR";
final int KEY = 45;
String encrypted = encrypt(s, KEY);
System.out.printf("%s --> %s\n", s, encrypted);
String decrypted = decrypt(encrypted, KEY);
System.out.printf("%s --> %s\n", encrypted, decrypted);
}
/**
* Encrypts a string with symmetric-like cryptography.
* Shifts initial chars key-positions to the right.
*
* @param s the initial string
* @param key the secret key
* @return the encrypted string
*/
public static String encrypt(String s, int key) {
StringBuilder encrypted = new StringBuilder();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch)) encrypted.append(cipher(ch, key));
else encrypted.append(ch);
}
return encrypted.toString();
}
/**
* Decrypts a string with symmetric-like cryptography.
* Shifts encrypted chars key-positions to the left.
*
* @param s the encrypted string
* @param key the secret key
* @return the decrypted string
*/
public static String decrypt(String s, int key) {
StringBuilder decrypted = new StringBuilder();
char ch;
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isAlphabetic(ch)) decrypted.append(decipher(ch, key));
else decrypted.append(ch);
}
return decrypted.toString();
}
/**
* Encrypts an eng uppercase char based on
* a secret key.
*
* @param ch the initial char
* @param key the secret key
* @return the encrypted char
*/
public static char cipher(char ch, int key) {
int m, c;
// message (char) position in 0-25
// (English alphabet /Uppercase)
m = ch - 65;
// cipher position in 0-25
c = (m + key) % 26;
return (char) (c + 65);
}
/**
* Decrypts an eng uppercase char based on
* a secret key.
*
* @param ch the encrypted char
* @param key the secret key
* @return the decrypted char
*/
public static char decipher(char ch, int key) {
int m, c;
// message (char) position in 0-25
// (English alphabet /Uppercase)
c = ch - 65;
// decipher position in 0 - 25
// Αν το key είναι > 26 το c-key+26 είναι αρνητικό
// Μπορούμε να πάρουμε
m = (c - key + 26 * (Math.abs(c-key) + 1)) % 26;
return (char) (m + 65);
}
}
| a8anassis/codingfactory5-java | src/gr/aueb/cf/solutions/ch7/CryptoV1.java |
1,818 | package gr.uom.randomnumber;
import static android.app.PendingIntent.getActivity;
import static gr.uom.randomnumber.R.id.headerfirst;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView number;
private TextView header;
private Button abutton;
private Button zbutton;
private Button tbutton;
private Button nbutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Ένωση με την γραφική διεπαφή
number = findViewById(R.id.number);
header = findViewById(R.id.headerfirst);
abutton = findViewById(R.id.abutton);
zbutton = findViewById(R.id.zbutton);
tbutton = findViewById(R.id.toastBtn);
nbutton = findViewById(R.id.nextbtn);
// Τίτλος για ομορφιά
header.setText("Καλώς ήλθες\n στην σούπερ εφρμογή για\n Random νουμέρια");
// Ενέργεια του κουμπιού που θα προσθέτει 1 στο νούμερο
abutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer num = Integer.parseInt(number.getText().toString());
num++;
// number.setText(String.valueOf(num)); // Άλλος τρόπος για να εμφανίζει
number.setText(num.toString());
}
});
// Ενέργεια του κουμπιού που θα μηδενίζει το νούμερο
zbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Integer num = Integer.parseInt(number.getText().toString());
num = 0;
// number.setText(String.valueOf(num));
number.setText(num.toString());
}
});
// Ενέργεια του κουμπιού που θα εμφανίζει ένα Toast
tbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Μπρό! Το νούμερο είναι το " + number.getText().toString()
, Toast.LENGTH_LONG).show();
}
});
// Ένα listener για το κουμπί για μετακίνηση στην επόμενη οθόνη
nbutton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendSecondActivity(view);
}
});
}
// Μέθοδος που θα μετακινεί στην επόμενη οθόνη τα δεδομένα με Intent
public void sendSecondActivity(View view){
Integer arithmos = Integer.parseInt(number.getText().toString());
// Φτιάχνουμε το Intent και τα στέλνουμε στο δεύτερο activity.
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("ARITHMOS", arithmos.toString());
startActivity(intent);
}
} | iosifidis/UoM-Applied-Informatics | s6/Mobile Application Developement/Small-Exam-Problems/RandomNumber/MainActivity.java |
1,829 |
package graphix;
import edu.uci.ics.jung.algorithms.layout.StaticLayout;
import edu.uci.ics.jung.graph.ObservableGraph;
import edu.uci.ics.jung.graph.event.GraphEvent;
import edu.uci.ics.jung.graph.event.GraphEventListener;
import edu.uci.ics.jung.io.GraphMLWriter;
import edu.uci.ics.jung.visualization.VisualizationViewer;
import edu.uci.ics.jung.visualization.control.ModalGraphMouse;
import edu.uci.ics.jung.visualization.decorators.ToStringLabeller;
import edu.uci.ics.jung.visualization.renderers.Renderer;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Paint;
import java.awt.Point;
import java.awt.geom.Point2D;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import org.apache.commons.collections15.Factory;
import org.apache.commons.collections15.Transformer;
import popup.MyPopupMenus;
import popup.MyPopupPlugin;
import algorithms.BreadthFirstSearch;
import algorithms.DepthFirstSearch;
import graph.Edge;
import graph.EdgeForm;
import algorithms.HeuristicSearch;
import graph.MazeGraph;
import graph.Node;
import graph.NodeForm;
import graph.Operator;
import algorithms.SearchAlgorithmDialog;
import edu.uci.ics.jung.graph.util.Pair;
import graph.SearchGraph;
import graph.MyEditingModalGraphMouse;
/**
* ΕΑΠ - ΠΛΗ31 - 4η ΕΡΓΑΣΙΑ 2015-2016
* @author Tsakiridis Sotiris
*/
public class MainFrame extends javax.swing.JFrame {
// Ο γράφος αναζήτησης μαζί με το layout και το visualization server
private SearchGraph searchGraph;
private StaticLayout<Node, Edge> graphLayout;
private VisualizationViewer<Node, Edge> graphPanel;
MyEditingModalGraphMouse graphMouse;
// Observable graph για την καταγραφή συμβάντων
private ObservableGraph observableGraph;
// getters
public SearchGraph getSearchGraph() { return this.searchGraph; }
/**
* Creates new form MainFrameTest
*/
public MainFrame() {
initComponents();
// start maximazed and set icon
setExtendedState(java.awt.Frame.MAXIMIZED_BOTH);
ClassLoader cl = getClass().getClassLoader();
ImageIcon icon = new ImageIcon(cl.getResource("img/graphix.png"));
setIconImage(icon.getImage());
// Δημιουργούμε ένα νέο κενό γράφο αναζήτησης
// με έναν default τελεστή δράσης
// Δημιουργούμε ένα νέο γράφο αναζήτησης και ανοίγουμε τη
// φόρμα καταχώρησης τελεστών δράσης
SearchGraph sg = new SearchGraph();
sg.getOperators().put("GO", new Operator("GO", "Προεπιλεγμένος τελεστής δράσης", 1));
this.searchGraph = sg;
this.observableGraph = new ObservableGraph(searchGraph);
// Διαμορφώνουμε το panel
createGraphPanel();
cardPanel.removeAll();
cardPanel.repaint();
cardPanel.revalidate();
cardPanel.add(graphPanel, BorderLayout.CENTER);
cardPanel.repaint();
cardPanel.revalidate();
// Κατάσταση = EDITING (σχεδίαση)
editStateMenu.setSelected(true);
editStateButton.setSelected(true);
graphMouse.setMode(ModalGraphMouse.Mode.EDITING);
}
/**
* 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() {
stateGroupMenu = new javax.swing.ButtonGroup();
stateGroupButtons = new javax.swing.ButtonGroup();
viewEdgeLabelGroup = new javax.swing.ButtonGroup();
viewNodeLabelGroup = new javax.swing.ButtonGroup();
jPanel1 = new javax.swing.JPanel();
jToolBar2 = new javax.swing.JToolBar();
newFreeButton = new javax.swing.JButton();
newMazeButton = new javax.swing.JButton();
openButton = new javax.swing.JButton();
saveButton = new javax.swing.JButton();
jSeparator2 = new javax.swing.JToolBar.Separator();
pickStateButton = new javax.swing.JToggleButton();
editStateButton = new javax.swing.JToggleButton();
zoomStateButton = new javax.swing.JToggleButton();
cardPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
fileMenu = new javax.swing.JMenu();
newFreeMenu = new javax.swing.JMenuItem();
newMazeMenu = new javax.swing.JMenuItem();
openMenu = new javax.swing.JMenuItem();
saveMenu = new javax.swing.JMenuItem();
jSeparator1 = new javax.swing.JPopupMenu.Separator();
exitMenu = new javax.swing.JMenuItem();
viewMenu = new javax.swing.JMenu();
jMenu2 = new javax.swing.JMenu();
viewNodeLabel = new javax.swing.JCheckBoxMenuItem();
viewNodeHeuritic = new javax.swing.JCheckBoxMenuItem();
viewNodeLabelAndHeuritic = new javax.swing.JCheckBoxMenuItem();
viewNodeNone = new javax.swing.JCheckBoxMenuItem();
jMenu1 = new javax.swing.JMenu();
viewEdgeOperator = new javax.swing.JCheckBoxMenuItem();
viewEdgeWeight = new javax.swing.JCheckBoxMenuItem();
viewEdgeNone = new javax.swing.JCheckBoxMenuItem();
stateMenu = new javax.swing.JMenu();
pickStateMenu = new javax.swing.JCheckBoxMenuItem();
editStateMenu = new javax.swing.JCheckBoxMenuItem();
zoomStateMenu = new javax.swing.JCheckBoxMenuItem();
paramMenu = new javax.swing.JMenu();
operatorsMenus = new javax.swing.JMenuItem();
algorithmMenu = new javax.swing.JMenu();
dfsMenu = new javax.swing.JMenuItem();
bfsMenu = new javax.swing.JMenuItem();
greedyMenu = new javax.swing.JMenuItem();
astarMenu = new javax.swing.JMenuItem();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Graphix");
jToolBar2.setFloatable(false);
jToolBar2.setRollover(true);
newFreeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/new24.png"))); // NOI18N
newFreeButton.setToolTipText("Νέος κενός χώρος αναζήτησης");
newFreeButton.setFocusable(false);
newFreeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
newFreeButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
newFreeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newFreeButtonActionPerformed(evt);
}
});
jToolBar2.add(newFreeButton);
newMazeButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/newmaze24.png"))); // NOI18N
newMazeButton.setToolTipText("Νέος χώρος αναζήτησης από λαβύρινθο");
newMazeButton.setFocusable(false);
newMazeButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
newMazeButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
newMazeButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newMazeButtonActionPerformed(evt);
}
});
jToolBar2.add(newMazeButton);
openButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/open.png"))); // NOI18N
openButton.setToolTipText("Άνοιγμα");
openButton.setFocusable(false);
openButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
openButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
openButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openButtonActionPerformed(evt);
}
});
jToolBar2.add(openButton);
saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
saveButton.setToolTipText("Αποθήκευση");
saveButton.setFocusable(false);
saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
saveButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveButtonActionPerformed(evt);
}
});
jToolBar2.add(saveButton);
jToolBar2.add(jSeparator2);
stateGroupButtons.add(pickStateButton);
pickStateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/pick24.png"))); // NOI18N
pickStateButton.setToolTipText("Επιλογή");
pickStateButton.setFocusable(false);
pickStateButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
pickStateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
pickStateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pickStateButtonActionPerformed(evt);
}
});
jToolBar2.add(pickStateButton);
stateGroupButtons.add(editStateButton);
editStateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/edit24.png"))); // NOI18N
editStateButton.setSelected(true);
editStateButton.setToolTipText("Εισαγωγή κόμβων/ακμών");
editStateButton.setFocusable(false);
editStateButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
editStateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
editStateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editStateButtonActionPerformed(evt);
}
});
jToolBar2.add(editStateButton);
stateGroupButtons.add(zoomStateButton);
zoomStateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/move24.png"))); // NOI18N
zoomStateButton.setToolTipText("Zoom");
zoomStateButton.setFocusable(false);
zoomStateButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
zoomStateButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
zoomStateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomStateButtonActionPerformed(evt);
}
});
jToolBar2.add(zoomStateButton);
cardPanel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.LOWERED));
cardPanel.setLayout(new java.awt.CardLayout());
jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
jLabel1.setText("© ΕΑΠ 2016 - ΠΛΗ31 - ΤΣΑΚΙΡΙΔΗΣ ΣΩΤΗΡΗΣ ([email protected])");
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(cardPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 678, Short.MAX_VALUE)
.addContainerGap())
.addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cardPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 345, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE))
);
fileMenu.setText("Αρχείο");
newFreeMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/new24.png"))); // NOI18N
newFreeMenu.setText("Δημιουργία κενού χώρου αναζήτησης");
newFreeMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newFreeMenuActionPerformed(evt);
}
});
fileMenu.add(newFreeMenu);
newMazeMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/newmaze24.png"))); // NOI18N
newMazeMenu.setText("Δημιουργία από λαβύρινθο");
newMazeMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
newMazeMenuActionPerformed(evt);
}
});
fileMenu.add(newMazeMenu);
openMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/open.png"))); // NOI18N
openMenu.setText("Άνοιγμα χώρου αναζήτησης");
openMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
openMenuActionPerformed(evt);
}
});
fileMenu.add(openMenu);
saveMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/save.png"))); // NOI18N
saveMenu.setText("Αποθήκευση χώρου αναζήτησης");
saveMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
saveMenuActionPerformed(evt);
}
});
fileMenu.add(saveMenu);
fileMenu.add(jSeparator1);
exitMenu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/exit.png"))); // NOI18N
exitMenu.setText("Έξοδος");
exitMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
exitMenuActionPerformed(evt);
}
});
fileMenu.add(exitMenu);
jMenuBar1.add(fileMenu);
viewMenu.setText("Προβολή");
jMenu2.setText("Ετικέτες κόμβων");
viewNodeLabelGroup.add(viewNodeLabel);
viewNodeLabel.setSelected(true);
viewNodeLabel.setText("Ονομασία κόμβου");
viewNodeLabel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewNodeLabelActionPerformed(evt);
}
});
jMenu2.add(viewNodeLabel);
viewNodeLabelGroup.add(viewNodeHeuritic);
viewNodeHeuritic.setText("Τιμή ευρετικού");
viewNodeHeuritic.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewNodeHeuriticActionPerformed(evt);
}
});
jMenu2.add(viewNodeHeuritic);
viewNodeLabelGroup.add(viewNodeLabelAndHeuritic);
viewNodeLabelAndHeuritic.setText("Όνομα και τιμή ευρετικού");
viewNodeLabelAndHeuritic.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewNodeLabelAndHeuriticActionPerformed(evt);
}
});
jMenu2.add(viewNodeLabelAndHeuritic);
viewNodeLabelGroup.add(viewNodeNone);
viewNodeNone.setText("Καμμία");
viewNodeNone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewNodeNoneActionPerformed(evt);
}
});
jMenu2.add(viewNodeNone);
viewMenu.add(jMenu2);
jMenu1.setText("Ετικέτες ακμών");
viewEdgeLabelGroup.add(viewEdgeOperator);
viewEdgeOperator.setText("Τελεστής δράσης");
viewEdgeOperator.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewEdgeOperatorActionPerformed(evt);
}
});
jMenu1.add(viewEdgeOperator);
viewEdgeLabelGroup.add(viewEdgeWeight);
viewEdgeWeight.setText("Βάρος ακμής");
viewEdgeWeight.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewEdgeWeightActionPerformed(evt);
}
});
jMenu1.add(viewEdgeWeight);
viewEdgeLabelGroup.add(viewEdgeNone);
viewEdgeNone.setSelected(true);
viewEdgeNone.setText("Καμμία");
viewEdgeNone.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
viewEdgeNoneActionPerformed(evt);
}
});
jMenu1.add(viewEdgeNone);
viewMenu.add(jMenu1);
jMenuBar1.add(viewMenu);
stateMenu.setText("Κατάσταση");
stateGroupMenu.add(pickStateMenu);
pickStateMenu.setText("Επιλογή");
pickStateMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
pickStateMenuActionPerformed(evt);
}
});
stateMenu.add(pickStateMenu);
stateGroupMenu.add(editStateMenu);
editStateMenu.setSelected(true);
editStateMenu.setText("Σχεδίαση");
editStateMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
editStateMenuActionPerformed(evt);
}
});
stateMenu.add(editStateMenu);
stateGroupMenu.add(zoomStateMenu);
zoomStateMenu.setText("Μετακίνηση/Ζουμ");
zoomStateMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
zoomStateMenuActionPerformed(evt);
}
});
stateMenu.add(zoomStateMenu);
jMenuBar1.add(stateMenu);
paramMenu.setText("Παράμετροι");
operatorsMenus.setText("Τελεστές δράσης...");
operatorsMenus.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
operatorsMenusActionPerformed(evt);
}
});
paramMenu.add(operatorsMenus);
jMenuBar1.add(paramMenu);
algorithmMenu.setText("Αλγόριθμοι");
dfsMenu.setText("Αναζήτηση κατά βάθος (DFS)");
dfsMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dfsMenuActionPerformed(evt);
}
});
algorithmMenu.add(dfsMenu);
bfsMenu.setText("Αναζήτηση κατά πλάτος (BFS)");
bfsMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
bfsMenuActionPerformed(evt);
}
});
algorithmMenu.add(bfsMenu);
greedyMenu.setText("Άπληστη αναζήτηση");
greedyMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
greedyMenuActionPerformed(evt);
}
});
algorithmMenu.add(greedyMenu);
astarMenu.setText("Αναζήτηση Α*");
astarMenu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
astarMenuActionPerformed(evt);
}
});
algorithmMenu.add(astarMenu);
jMenuBar1.add(algorithmMenu);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void newFreeMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newFreeMenuActionPerformed
// Δημιουργούμε ένα νέο γράφο αναζήτησης και ανοίγουμε
SearchGraph sg = new SearchGraph();
sg.getOperators().put("GO", new Operator("GO", "Προεπιλεγμένος τελεστής δράσης", 1));
// Εκχωρούμε το γράφο
this.searchGraph = sg;
this.observableGraph = new ObservableGraph(searchGraph);
// Διαμορφώνουμε το panel
createGraphPanel();
cardPanel.removeAll();
cardPanel.repaint();
cardPanel.revalidate();
cardPanel.add(graphPanel, BorderLayout.CENTER);
cardPanel.repaint();
cardPanel.revalidate();
// Κατάσταση = EDITING (σχεδίαση)
editStateMenu.setSelected(true);
editStateButton.setSelected(true);
graphMouse.setMode(ModalGraphMouse.Mode.EDITING);
}//GEN-LAST:event_newFreeMenuActionPerformed
private void newMazeMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newMazeMenuActionPerformed
// Άνοιγμα του maze
MazePanelDialog maze = new MazePanelDialog(this, true);
maze.setLocationRelativeTo(this);
maze.setVisible(true);
// Αν πατήσαμε άκυρο επιτρέφουμε
if (!maze.isOk()) return;
// Παίρνουμε το grid και δημιουργούμε ένα MazeGraph
searchGraph = new MazeGraph(maze.getGrid(), maze.hasDiagonals());
observableGraph = new ObservableGraph(searchGraph);
// Δίνουμε την τιμή της ευρετικής συνάρτησης
// Αν είναι χωρίς διαγώνιες κινήσεις -> απόσταση Manhattan
// Αν είναι με διαγώνιες κινήσεις -> Ευκλείδια
// Ως ευρετικό χρησιμοποιούμε την απόσταση manhattan
ArrayList<Node> targetNodes = searchGraph.getTargetNodes();
if (targetNodes.size() != 1) return;
Node target = searchGraph.getTargetNodes().get(0);
for (Node n : searchGraph.getVertices()) {
if (maze.hasDiagonals()) {
n.setH(Util.eucledian(n, target));
n.setF(n.getH());
}
else {
n.setH(Util.manhattan(n, target));
n.setF(n.getH());
}
}
// Διαμορφώνουμε το panel
createGraphPanel();
cardPanel.removeAll();
cardPanel.repaint();
cardPanel.revalidate();
cardPanel.add(graphPanel, BorderLayout.CENTER);
cardPanel.repaint();
cardPanel.revalidate();
}//GEN-LAST:event_newMazeMenuActionPerformed
private void saveMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMenuActionPerformed
// Ανοίγουμε το παράθυρο επιλογής αρχείου
// Φιλτράρουμε τα αρχεία .xml
final JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Επιλογή αρχείου αποθήκευσης XML");
FileNameExtensionFilter filter;
filter = new FileNameExtensionFilter("Αρχεία XML", "xml");
fc.setFileFilter(filter);
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File selectedFile = fc.getSelectedFile();
// Αν δεν έχει κατάληξη .xml την προσθέτουμε
if ( !selectedFile.getAbsolutePath().endsWith(".xml") )
selectedFile = new File(selectedFile.getAbsolutePath() + ".xml");
// Αν υπάρχει ήδη το αρχείο, μήνυμα ότι θα αντικατασταθεί
if (selectedFile.exists()) {
int result = JOptionPane.showConfirmDialog(null,
"Το όνομα αρχείου υπάρχει ήδη.\nΘέλετε να αντικατασταθεί?",
"Το αρχείο υπάρχει ήδη", JOptionPane.YES_NO_OPTION);
if (result != JOptionPane.YES_OPTION) return;
}
// Save the contents of Xml to selectedFile
try {
GraphMLWriter<Node, Edge> ml = new GraphMLWriter();
FileWriter fw = new FileWriter(selectedFile);
searchGraph.updateNodePositions(graphLayout);
// Αποθηκεύουμε τα δεδομένα
searchGraph.saveToGraphML(ml);
ml.save(searchGraph, fw);
fw.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}//GEN-LAST:event_saveMenuActionPerformed
private void openMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openMenuActionPerformed
SearchGraph sg = SearchGraph.load();
if (sg == null) return;
this.searchGraph = sg;
this.observableGraph = new ObservableGraph(searchGraph);
// Διαμορφώνουμε το panel
// Ανακτούμε τις αποθηκευμένες θέσεις των nodes
createGraphPanel();
for (Node n : searchGraph.getVertices())
graphLayout.setLocation(n, new Point2D.Double(n.getX(), n.getY()));
cardPanel.removeAll();
cardPanel.repaint();
cardPanel.revalidate();
cardPanel.add(graphPanel, BorderLayout.CENTER);
cardPanel.repaint();
cardPanel.revalidate();
}//GEN-LAST:event_openMenuActionPerformed
private void exitMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitMenuActionPerformed
// Μήνυμα επιβεβαίωσης και έξοδος
int dialogResult = JOptionPane.showConfirmDialog (null,
"Θέλετε να κλείσετε την εφαρμογή?","Έξοδος",JOptionPane.YES_NO_OPTION);
if(dialogResult == JOptionPane.YES_OPTION){
System.exit( 0 );
}
}//GEN-LAST:event_exitMenuActionPerformed
private void greedyMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_greedyMenuActionPerformed
// Αν δεν υπάρχει γράφος, μήνυμα και επιστροφή
if (this.searchGraph == null) {
JOptionPane.showMessageDialog(null,
"Πρέπει να δημιουργήσετε πρώτα έναν χώρο αναζήτησης.",
"Σφάλμα", JOptionPane.ERROR_MESSAGE);
return;
}
// Δημιουργία και άνοιγμα του modal dialog
// Ενημερώνουμε τις συντεταγμένες των κόμβων
searchGraph.resetSolutionPath();
searchGraph.updateNodePositions(graphLayout);
HeuristicSearch greedy = new HeuristicSearch(searchGraph, HeuristicSearch.GREEDY);
String title = "Άπληστος αλγόριθμος αναζήτησης (Greedy)";
SearchAlgorithmDialog dlg = new SearchAlgorithmDialog(this, true, title, greedy);
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}//GEN-LAST:event_greedyMenuActionPerformed
private void dfsMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dfsMenuActionPerformed
// Αν δεν υπάρχει γράφος, μήνυμα και επιστροφή
if (this.searchGraph == null) {
JOptionPane.showMessageDialog(null,
"Πρέπει να δημιουργήσετε πρώτα έναν χώρο αναζήτησης.",
"Σφάλμα", JOptionPane.ERROR_MESSAGE);
return;
}
// Καθαρίζουμε την λίστα της επιτυχούς διαδρομής
// (μπορεί να υπάρχει από προηγούμενη αναζήτηση)
// και δημιουργούμε ένα στιγμιότυπο του αλγορίθμου
// Ενημερώνουμε τις συντεταγμένες των κόμβων
searchGraph.resetSolutionPath();
searchGraph.updateNodePositions(graphLayout);
DepthFirstSearch dfs = new DepthFirstSearch(searchGraph);
// Δημιουργία και άνοιγμα του modal dialog
String title = "Αλγόριθμος αναζήτησης κατά βάθος (DFS)";
SearchAlgorithmDialog dlg = new SearchAlgorithmDialog(this, true, title, dfs);
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}//GEN-LAST:event_dfsMenuActionPerformed
private void bfsMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bfsMenuActionPerformed
// Αν δεν υπάρχει γράφος, μήνυμα και επιστροφή
if (this.searchGraph == null) {
JOptionPane.showMessageDialog(null,
"Πρέπει να δημιουργήσετε πρώτα έναν χώρο αναζήτησης.",
"Σφάλμα", JOptionPane.ERROR_MESSAGE);
return;
}
// Καθαρίζουμε την λίστα της επιτυχούς διαδρομής
// (μπορεί να υπάρχει από προηγούμενη αναζήτηση)
// και δημιουργούμε ένα στιγμιότυπο του αλγορίθμου
// Ενημερώνουμε τις συνταταγμένες των κόμβων
searchGraph.resetSolutionPath();
searchGraph.updateNodePositions(graphLayout);
BreadthFirstSearch bfs = new BreadthFirstSearch(searchGraph);
// Δημιουργία και άνοιγμα του modal dialog
String title = "Αλγόριθμος αναζήτησης κατά πλάτος (BFS)";
SearchAlgorithmDialog dlg = new SearchAlgorithmDialog(this, true, title, bfs);
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}//GEN-LAST:event_bfsMenuActionPerformed
private void astarMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_astarMenuActionPerformed
// Αν δεν υπάρχει γράφος, μήνυμα και επιστροφή
if (this.searchGraph == null) {
JOptionPane.showMessageDialog(null,
"Πρέπει να δημιουργήσετε πρώτα έναν χώρο αναζήτησης.",
"Σφάλμα", JOptionPane.ERROR_MESSAGE);
return;
}
// Δημιουργία και άνοιγμα του modal dialog
// Ενημερώνουμε τις συντεταγμένες των κόμβων
searchGraph.resetSolutionPath();
searchGraph.updateNodePositions(graphLayout);
HeuristicSearch astar = new HeuristicSearch(searchGraph, HeuristicSearch.ASTAR);
String title = "Αλγόριθμος αναζήτησης Α*";
SearchAlgorithmDialog dlg = new SearchAlgorithmDialog(this, true, title, astar);
dlg.setLocationRelativeTo(this);
dlg.setVisible(true);
}//GEN-LAST:event_astarMenuActionPerformed
private void operatorsMenusActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_operatorsMenusActionPerformed
// Αν δεν υπάρχει γράφος, μήνυμα και επιστροφή
if (this.searchGraph == null) {
JOptionPane.showMessageDialog(null,
"Πρέπει να δημιουργήσετε πρώτα έναν χώρο αναζήτησης.",
"Σφάλμα", JOptionPane.ERROR_MESSAGE);
return;
}
// Άνοιγμα της φόρμας επεξεργασίας τελεστών δράσης
// για το συγκεκριμένο γράφο αναζήτησης
OperatorListForm opForm = new OperatorListForm(this, true, searchGraph);
opForm.setLocationRelativeTo(this);
opForm.setVisible(true);
// Αν πατήσαμε "ακύρωση" επιστρέφουμε
if (!opForm.isOk()) return;
// Ανανεώνουμε την προβολή
this.graphPanel.repaint();
this.graphPanel.revalidate();
}//GEN-LAST:event_operatorsMenusActionPerformed
private void viewEdgeOperatorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewEdgeOperatorActionPerformed
if (this.graphPanel == null) return;
if (viewEdgeOperator.isSelected()) {
graphPanel.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
Edge e = (Edge)o;
return e.getOperator().getLabel();
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewEdgeOperatorActionPerformed
private void newFreeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newFreeButtonActionPerformed
newFreeMenuActionPerformed(evt);
}//GEN-LAST:event_newFreeButtonActionPerformed
private void newMazeButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newMazeButtonActionPerformed
newMazeMenuActionPerformed(evt);
}//GEN-LAST:event_newMazeButtonActionPerformed
private void openButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openButtonActionPerformed
openMenuActionPerformed(evt);
}//GEN-LAST:event_openButtonActionPerformed
private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
saveMenuActionPerformed(evt);
}//GEN-LAST:event_saveButtonActionPerformed
private void editStateMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editStateMenuActionPerformed
editStateButton.setSelected(editStateMenu.isSelected());
if (editStateMenu.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.EDITING);
}
}//GEN-LAST:event_editStateMenuActionPerformed
private void zoomStateMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomStateMenuActionPerformed
zoomStateButton.setSelected(zoomStateMenu.isSelected());
if (zoomStateMenu.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
}
}//GEN-LAST:event_zoomStateMenuActionPerformed
private void zoomStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_zoomStateButtonActionPerformed
zoomStateMenu.setSelected(zoomStateButton.isSelected());
if (zoomStateButton.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
}
}//GEN-LAST:event_zoomStateButtonActionPerformed
private void editStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_editStateButtonActionPerformed
editStateMenu.setSelected(editStateButton.isSelected());
if (editStateButton.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.EDITING);
}
}//GEN-LAST:event_editStateButtonActionPerformed
private void pickStateMenuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pickStateMenuActionPerformed
pickStateButton.setSelected(pickStateMenu.isSelected());
if (pickStateMenu.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
}
}//GEN-LAST:event_pickStateMenuActionPerformed
private void pickStateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_pickStateButtonActionPerformed
pickStateMenu.setSelected(pickStateButton.isSelected());
if (pickStateButton.isSelected()) {
graphMouse.setMode(ModalGraphMouse.Mode.PICKING);
}
}//GEN-LAST:event_pickStateButtonActionPerformed
private void viewEdgeNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewEdgeNoneActionPerformed
if (this.graphPanel == null) return;
if (viewEdgeNone.isSelected()) {
graphPanel.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
return "";
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewEdgeNoneActionPerformed
private void viewEdgeWeightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewEdgeWeightActionPerformed
if (this.graphPanel == null) return;
if (viewEdgeWeight.isSelected()) {
graphPanel.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
Edge e = (Edge)o;
return Double.toString(e.getWeight());
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewEdgeWeightActionPerformed
private void viewNodeLabelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewNodeLabelActionPerformed
if (this.graphPanel == null) return;
if (viewNodeLabel.isSelected()) {
graphPanel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
Node n = (Node)o;
return n.getLabel();
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewNodeLabelActionPerformed
private void viewNodeHeuriticActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewNodeHeuriticActionPerformed
if (this.graphPanel == null) return;
if (viewNodeHeuritic.isSelected()) {
graphPanel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
Node n = (Node)o;
return Double.toString(n.getH());
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewNodeHeuriticActionPerformed
private void viewNodeNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewNodeNoneActionPerformed
if (this.graphPanel == null) return;
if (viewNodeNone.isSelected()) {
graphPanel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
return "";
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewNodeNoneActionPerformed
private void viewNodeLabelAndHeuriticActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viewNodeLabelAndHeuriticActionPerformed
if (this.graphPanel == null) return;
if (viewNodeLabelAndHeuritic.isSelected()) {
graphPanel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller() {
@Override
public String transform(Object o) {
Node n = (Node)o;
return n.getLabel() + "(" + Double.toString(n.getH()) + ")";
}
});
}
graphPanel.repaint();
graphPanel.revalidate();
}//GEN-LAST:event_viewNodeLabelAndHeuriticActionPerformed
// Δημιουργούμε το graphPanel
private void createGraphPanel() {
// Αν δεν έχει αρχικοποιηθει το searchGraph επιστρέφουμε
if (searchGraph == null) return;
graphLayout = new StaticLayout<Node, Edge>(observableGraph);
graphPanel = new VisualizationViewer(graphLayout);
graphMouse = new MyEditingModalGraphMouse(graphPanel.getRenderContext(), new VertexFactory(), new EdgeFactory());
graphPanel.setLayout(new BorderLayout());
// Τα νέα popup menus για τους κόμβους και τις ακμές
MyPopupPlugin myPlugin = new MyPopupPlugin();
myPlugin.setNodePopup(MyPopupMenus.nodePopup(this));
myPlugin.setEdgePopup(MyPopupMenus.edgePopup(this));
graphMouse.remove(graphMouse.getPopupEditingPlugin());
graphMouse.add(myPlugin);
// set the mouse to panel
graphPanel.setGraphMouse(graphMouse);
// Θέτουμε τις συντεταγμένες των κόμβων
for (Node n : searchGraph.getVertices()) {
graphLayout.setLocation(n, new Point2D.Double(n.getX(), n.getY()));
}
// set node colors
Transformer<Node, Paint> nodePaint = new Transformer<Node, Paint>() {
@Override
public Paint transform(Node n) {
// Αν είναι ο κόμβος έναρξη τον βάφουμε κόκκινο
// Αν είναι κόμβος-στόχος, τον βάφουμε μπλε
// Οι υπόλοιπο κόμβοι είναι άσπροι
if (n.isStartNode()) return Color.RED;
if (n.isTargetNode()) return Color.GREEN;
// default
return Color.WHITE;
}
};
// Ετικέτε κόμβων και ακμών
graphPanel.getRenderContext().setVertexFillPaintTransformer(nodePaint);
graphPanel.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
graphPanel.getRenderer().getVertexLabelRenderer().setPosition(Renderer.VertexLabel.Position.NW);
graphPanel.getRenderContext().getEdgeLabelRenderer().setRotateEdgeLabels(true); // όχι παράλληλες ετικέτες
viewNodeLabel.setSelected(true);
viewEdgeNone.setSelected(true);
// Συμβάν εισαγωγης νέου κόμβου και ακμής
observableGraph.addGraphEventListener(new GraphEventListener<Node, Edge>(){
@Override
public void handleGraphEvent(GraphEvent<Node, Edge> evt) {
// Νέος κόμβος
if (evt.getType() == GraphEvent.Type.VERTEX_ADDED) {
GraphEvent.Vertex ve = (GraphEvent.Vertex)evt;
Node node = (Node)ve.getVertex();
if (node.isDeleted()) {
MainFrame.this.observableGraph.removeVertex(node);
}
// Αν ο νέος κόμβος είναι κόμβος έναρξης
// ενημερώνουμε την λίστα των κόμβων
// (μήπως υπάρχει ήδη κάποιος άλλος οπότε τον αλλάζουμε)
if (node.isStartNode()) {
for (Node n : searchGraph.getVertices())
if (n != node && n.isStartNode()) n.setStartNode(false);
}
}
// Νέα ακμή
if (evt.getType() == GraphEvent.Type.EDGE_ADDED) {
GraphEvent.Edge ee = (GraphEvent.Edge)evt;
Edge edge = (Edge)ee.getEdge();
// Αν έχει τεθεί το flag διαγραφής, διέγραψέ την
if (edge.isDeleted()) {
MainFrame.this.observableGraph.removeEdge(edge);
return;
}
// Αν είναι ανακύκλωση, διέγραψέ την
Pair<Node> pair = MainFrame.this.observableGraph.getEndpoints(edge);
if (pair.getFirst() == pair.getSecond())
MainFrame.this.observableGraph.removeEdge(edge);
}
}
});
// Αρχική κατάσταση λειτουργίας
zoomStateMenu.setSelected(true);
zoomStateButton.setSelected(true);
graphMouse.setMode(ModalGraphMouse.Mode.TRANSFORMING);
}
class VertexFactory implements Factory<Node> {
@Override
public Node create() {
Node n = new Node("");
NodeForm nf = new NodeForm(null, true, n);
Point p = graphPanel.getMousePosition();
n.setX(p.getX());
n.setY(p.getY());
nf = new NodeForm(MainFrame.this, true, n);
nf.setLocation(p);
nf.setVisible(true);
// Αν πατήσαμε "Άκυρο" θέτουμε το flag διαγραφής
// έτσι ώστε να διαγραφεί κατά το συμβάναν newVerterx
if (!nf.isOk()) n.setDeleted(true);
return n;
}
}
class EdgeFactory implements Factory<Edge> {
int i=0;
@Override
public Edge create() {
Edge e = new Edge();
Point p = graphPanel.getMousePosition();
EdgeForm ef = new EdgeForm(MainFrame.this, true, e, searchGraph.getOperators());
ef.setLocation(p);
ef.setVisible(true);
// Αν πατήσαμε "Άκυρο" θέτουμε το flag διαγραφής
// έτσι ώστε να διαγραφεί κατά το συμβάναν newVerterx
if (!ef.isOk()) e.setDeleted(true);
return e;
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JMenu algorithmMenu;
private javax.swing.JMenuItem astarMenu;
private javax.swing.JMenuItem bfsMenu;
private javax.swing.JPanel cardPanel;
private javax.swing.JMenuItem dfsMenu;
private javax.swing.JToggleButton editStateButton;
private javax.swing.JCheckBoxMenuItem editStateMenu;
private javax.swing.JMenuItem exitMenu;
private javax.swing.JMenu fileMenu;
private javax.swing.JMenuItem greedyMenu;
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPopupMenu.Separator jSeparator1;
private javax.swing.JToolBar.Separator jSeparator2;
private javax.swing.JToolBar jToolBar2;
private javax.swing.JButton newFreeButton;
private javax.swing.JMenuItem newFreeMenu;
private javax.swing.JButton newMazeButton;
private javax.swing.JMenuItem newMazeMenu;
private javax.swing.JButton openButton;
private javax.swing.JMenuItem openMenu;
private javax.swing.JMenuItem operatorsMenus;
private javax.swing.JMenu paramMenu;
private javax.swing.JToggleButton pickStateButton;
private javax.swing.JCheckBoxMenuItem pickStateMenu;
private javax.swing.JButton saveButton;
private javax.swing.JMenuItem saveMenu;
private javax.swing.ButtonGroup stateGroupButtons;
private javax.swing.ButtonGroup stateGroupMenu;
private javax.swing.JMenu stateMenu;
private javax.swing.ButtonGroup viewEdgeLabelGroup;
private javax.swing.JCheckBoxMenuItem viewEdgeNone;
private javax.swing.JCheckBoxMenuItem viewEdgeOperator;
private javax.swing.JCheckBoxMenuItem viewEdgeWeight;
private javax.swing.JMenu viewMenu;
private javax.swing.JCheckBoxMenuItem viewNodeHeuritic;
private javax.swing.JCheckBoxMenuItem viewNodeLabel;
private javax.swing.JCheckBoxMenuItem viewNodeLabelAndHeuritic;
private javax.swing.ButtonGroup viewNodeLabelGroup;
private javax.swing.JCheckBoxMenuItem viewNodeNone;
private javax.swing.JToggleButton zoomStateButton;
private javax.swing.JCheckBoxMenuItem zoomStateMenu;
// End of variables declaration//GEN-END:variables
}
| artibet/graphix | src/graphix/MainFrame.java |
1,830 | package com.jacobrobertson.rootsweb;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.IOUtils;
public class WikipediaParser {
public static void main(String[] args) throws Exception {
List<Item> roots = downloadRoots();
// printWordsUsedTwice(roots);
printCompleteRootsReplacement(roots);
}
public static List<Item> downloadRoots() throws Exception {
String page = download();
return parse(page);
}
public static List<Item> parse(String page) {
// Root Meaning in English Origin language Etymology (root origin) English examples
Pattern tablePattern = Pattern.compile("\\| (.*?) \\|\\| (.*?) \\|\\| .*?\\|\\| (.*?) \\|\\| (.*)");
Matcher matcher = tablePattern.matcher(page);
List<Item> roots = new ArrayList<Item>();
while (matcher.find()) {
String words = matcher.group(4);
String def = matcher.group(2);
String etymology = matcher.group(3);
Set<String> eroots = parseEtymologyToRoots(etymology);
def = cleanDefinition(def);
Item root = new Item(null, def);
parseName(matcher.group(1), root);
root.getAlternatives().addAll(eroots);
roots.add(root);
String[] split = words.split(",");
for (String word: split) {
word = word.trim();
if (word.startsWith("[")) {
word = word.substring(2, word.length() - 2);
}
int bar = word.indexOf("|");
if (bar > 0) {
word = word.substring(bar + 1);
}
word = word.replaceAll("'''", "");
root.getRoots().add(word);
}
}
return roots;
}
/*
* ''[[wikt:cado#Latin|cadere]]'', ''casus''
* [[wikt:καλός#Ancient Greek|καλός]] (''kalós'') "beautiful"; [[wikt:κάλλος#Ancient Greek|κάλλος]] (''kállos'') "beauty", κάλλιστος (''kállistos'')
* from Latin ''[[wikt:calx#Latin|calx]]'' (genitive ''calcis'') "lime", from Greek [[wikt:χάλιξ#Ancient Greek|χάλιξ]] (''khalix'') "pebble", "limestone"
* ''acutus'', past participle of ''acuere'' "to sharpen", from ''[[wikt:acus#Latin|acus]]'' "needle"
* ''[[wikt:acer#Latin|acer, acris]]'', ''[[wikt:acerbus|acerbus]]'', ''[[wikt:aceo|acere]]''
* ''[[wikt:leo#Latin|leo'']], ''leonis''
*/
private static Set<String> parseEtymologyToRoots(String text) {
Pattern w = Pattern.compile("\\[\\[wikt:(.*?)(#.*?)?\\|(.*?)\\]\\]");
Pattern p = Pattern.compile("''(.*?)''");
Matcher m = p.matcher(text);
Set<String> roots = new HashSet<String>();
StringBuilder buf = new StringBuilder();
while (m.find()) {
String root = m.group(1);
root = root.trim();
if (root.indexOf('(') < 0) {
Matcher wm = w.matcher(root);
if (wm.matches()) {
if (buf.length() > 0) {
buf.append(",");
}
buf.append(wm.group(1));
buf.append(",");
buf.append(wm.group(3));
} else {
if (buf.length() > 0) {
buf.append(",");
}
buf.append(root);
}
}
}
String[] split = buf.toString().split(",");
for (String one: split) {
one = getCleanRootName(one);
roots.add(one);
}
return roots;
}
private static String getCleanRootName(String name) {
name = name.trim();
if (name.startsWith("-")) {
name = name.substring(1);
}
if (name.endsWith("-")) {
name = name.substring(0, name.length() - 1);
}
return name;
}
/*
* One of
* simple
* words [[with]] brackets
* words [[with|some]] more [[brackets like|this]]
*/
private static Pattern definitionPattern = Pattern.compile("\\[\\[(.*?)\\]\\]");
private static List<Item> merge(List<Item> wikiRoots, Collection<Item> driveRoots) {
// we start with the drive roots, because we've manually fixed a lot there - don't want to undo that
List<Item> merged = new ArrayList<Item>(driveRoots);
for (Item wikiRoot: wikiRoots) {
boolean found = false;
for (Item driveRoot: driveRoots) {
if (isDuplicate(wikiRoot, driveRoot, true)) {
found = true;
break;
}
}
if (!found) {
System.out.println("New root? " + wikiRoot.getSimpleName() + "(" + wikiRoot.getDefinition() + ")");
merged.add(wikiRoot);
}
}
return merged;
}
private static boolean isDuplicate(Item wikiRoot, Item driveRoot, boolean compareNames) {
if (compareNames && !wikiRoot.getSimpleName().equals(driveRoot.getSimpleName())) {
return false;
}
String driveDef = JsonDataMaker.getComparableDef(driveRoot.getDefinition());
String wikiDef = JsonDataMaker.getComparableDef(wikiRoot.getDefinition());
if (driveDef.equals(wikiDef)) {
return true;
}
if (wikiDef.contains(driveDef)) {
System.out.println(">>>>>> consider manual merge of " + wikiRoot.getSimpleName() + " wikiDef(" + wikiDef + "), driveDef(" + driveDef + ")");
return true;
}
if (driveDef.contains(wikiDef)) {
return true;
}
if (driveRoot.getParent() != null) {
return isDuplicate(wikiRoot, driveRoot.getParent(), false);
}
return false;
}
/**
* Due to the way there are duplicates, we will just print a brand-new list
*/
public static void printCompleteRootsReplacement(List<Item> wikiRoots) throws Exception {
List<Item> alternates = generateAlternates(wikiRoots);
wikiRoots.addAll(alternates);
Map<String, Item> existing = JsonDataMaker.downloadRootItems();
List<Item>roots = merge(wikiRoots, existing.values());
assignNumbersToAllRoots(roots);
List<String> lines = new ArrayList<String>();
for (Item root: roots) {
String name = root.getName();
if (root.getParent() == null) {
lines.add(name + "\t" + root.getDefinition());
} else {
lines.add(name + "\t>" + root.getParent().getName());
}
}
Collections.sort(lines);
for (String line: lines) {
System.out.println(line);
}
}
private static List<Item> generateAlternates(List<Item> roots) {
List<Item> alts = new ArrayList<Item>();
for (Item root: roots) {
List<Item> some = generateAlternates(root);
alts.addAll(some);
}
return alts;
}
private static List<Item> generateAlternates(Item root) {
List<Item> alts = new ArrayList<Item>();
List<String> strings = root.getAlternatives();
for (String alt: strings) {
// System.out.println(root.getName() + ", " + alt);
Item i = new Item(alt, root.getDefinition());
i.setParent(root);
alts.add(i);
}
return alts;
}
/**
* TODO assign numbers to alternate roots (in fact the code here doesn't do anything - apparently all changes are to alternates)
* - will need to get the right definition, and assign numbers based on the sorting of those
* TODO to make this truly effective, will need to load in existing roots as well, because we might have some preexisting numbers
* @param roots
*/
private static void assignNumbersToAllRoots(List<Item> roots) {
Collections.sort(roots, new ItemNameComparator());
Map<String, Item> map = new HashMap<String, Item>();
Map<String, Integer> counts = new HashMap<String, Integer>();
for (Item root: roots) {
Integer count = counts.get(root.getSimpleName());
if (count == null) {
count = 0;
}
count++;
if (count > 1) {
// fix the first count if it wasn't already fixed
Item first = map.get(root.getSimpleName());
if (first != null) {
String newName = root.getSimpleName() + "(1)";
first.setName(newName);
}
// update this guys's number
String newName = root.getSimpleName() + "(" + count + ")";
root.setName(newName);
} else {
// put in map so we can look back and fix later if needed
map.put(root.getSimpleName(), root);
}
counts.put(root.getSimpleName(), count);
}
// now that the base roots are assigned, assign to all the alternates
}
public static class ItemNameComparator implements Comparator<Item> {
@Override
public int compare(Item i1, Item i2) {
String s1 = i1.getSimpleName();
String s2 = i2.getSimpleName();
int comp = s1.compareTo(s2);
if (comp != 0) {
return comp;
}
Integer n1 = i1.getNumber();
Integer n2 = i2.getNumber();
if (n1 != n2) {
if (n1 == 0) {
return 1;
} else if (n2 == 0) {
return -1;
} else {
return n1.compareTo(n2);
}
}
return i1.getDefinition().compareTo(i2.getDefinition());
}
}
public static String cleanDefinition(String def) {
StringBuilder buf = new StringBuilder();
Matcher m = definitionPattern.matcher(def);
int last = 0;
while (m.find()) {
String sub = def.substring(last, m.start()).trim();
buf.append(sub);
buf.append(" ");
last = m.end() + 1;
String part = m.group(1);
int pos = part.indexOf("|");
if (pos > 0) {
part = part.substring(pos + 1);
}
buf.append(part);
}
if (last < def.length()) {
String sub = def.substring(last);
buf.append(sub);
}
return buf.toString().trim();
}
/**
* Worst case scenarios are possible:
* '''ab-''', '''a-''', '''abs-''', '''au-''' <ref>{{Cite web | url=http://www.perseus.tufts.edu/hopper/text?doc=Perseus%3Atext%3A1999.04.0059%3Aentry%3Dab | title=Charlton T. Lewis, Charles Short, A Latin Dictionary, *badchars* | accessdate=2015-03-31}}</ref>
*
* need to handle this too
* '''{{nowrap|-cid-}}'''
*/
private static void parseName(String text, Item item) {
// if (text.contains("nowrap")) {
// text = text.trim();
// }
// remove all citations and links (the order here matters)
// text = text.replaceAll("'''\\{\\{nowrap\\|", "");
// text = text.replaceAll("\\}\\}'''", "");
text = text.replaceAll("\\{\\{nowrap\\|(.*?)\\}\\}", "$1");
text = text.replaceAll("\\{\\{.*?\\}\\}", "");
text = text.replaceAll("\\[\\[(.*?)\\]\\]", "$1");
text = text.replaceAll("\\(.*?\\)", "");
text = text.replaceAll("(<|<).*?>", "");
// remove all boldings
text = text.replaceAll("'''", "");
// split
String[] split = text.split(",");
// remove all dashes and spaces
String first = null;
for (String name: split) {
name = getCleanRootName(name);
if (first == null) {
first = name;
} else {
item.getAlternatives().add(name);
}
}
item.setName(first);
}
public static void printWordsUsedTwice(List<Item> roots) throws Exception {
Map<String, Item> existing = JsonDataMaker.downloadWordItems();
Map<String, Item> driveRoots = JsonDataMaker.downloadRootItems();
Set<String> found = new HashSet<String>();
List<String> strings = new ArrayList<String>();
for (Item root: roots) {
if (root.getName() == null) {
continue;
}
Set<String> set = root.getRoots();
// System.out.println(">>>> Start >>>> " + set);
for (Item checkRoot: roots) {
// these "roots" are actually the words
Set<String> checkSet = checkRoot.getRoots();
if (set == checkSet) {
continue;
}
Set<String> test = new HashSet<String>(checkSet);
test.retainAll(set);
if (!test.isEmpty()) {
String testString = test.iterator().next();
if (
!found.contains(testString)
&& !existing.containsKey(testString)
&& checkRoot.getName() != null
&& root.getName() != null
) {
found.add(testString);
// try to determine the actual root numbers
root = getDriveRoot(root, driveRoots);
checkRoot = getDriveRoot(checkRoot, driveRoots);
strings.add(testString + "\t" + root.getName() + ", " + checkRoot.getName());
}
}
}
}
Collections.sort(strings);
for (String s: strings) {
System.out.println(s);
}
}
public static List<Item> getSimpleMatches(Item wikiRoot, Map<String, Item> driveRoots) {
return getSimpleMatches(wikiRoot.getName(), driveRoots);
}
public static List<Item> getSimpleMatches(String wikiName, Map<String, Item> driveRoots) {
List<Item> matches = new ArrayList<Item>();
for (Item driveRoot: driveRoots.values()) {
String driveName = driveRoot.getSimpleName();
if (driveName.equals(wikiName)) {
matches.add(driveRoot);
}
}
return matches;
}
private static Item getDriveRoot(Item wikiRoot, Map<String, Item> driveRoots) {
String wikiDef = JsonDataMaker.getComparableDef(wikiRoot.getDefinition());
List<Item> matches = getSimpleMatches(wikiRoot, driveRoots);
if (!matches.isEmpty()) {
for (Item match: matches) {
String matchDef = JsonDataMaker.getComparableDef(match.getDefinition());
if (wikiDef.equals(matchDef)) {
return match;
}
}
for (Item match: matches) {
String matchDef = JsonDataMaker.getComparableDef(match.getDefinition());
if (wikiDef.contains(matchDef) || matchDef.contains(wikiDef)) {
return match;
}
}
System.out.println(">>>>> could not figure out match for : " + wikiRoot.getName());
}
return wikiRoot;
}
public static String download() throws Exception {
String path = "https://en.wikipedia.org/w/index.php?title=List_of_Greek_and_Latin_roots_in_English&action=edit";
URL u = new URL(path);
InputStream in = u.openStream();
String page = IOUtils.toString(in);
// System.out.println(page);
return page;
}
}
| jacobrobertson/roots-web | src/main/java/com/jacobrobertson/rootsweb/WikipediaParser.java |
1,831 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.EuresiErgasias;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ProvoliAtomonPouZitounController implements Initializable {
@FXML
public TableView<tableManager> table;
@FXML
public TableColumn<tableManager, String> eponimo, onoma, patronimo, imGennisis, eidikotita, tilefono, dieuthinsi, dimos, ekpaideusi, oikKatastasi, diploma, empeiria;
@FXML
public TableColumn<tableManager, Integer> id;
@FXML
public Button backButton;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.LockEdit le = new sopho.LockEdit();
private ObservableList<tableManager> data;
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing table
data = getInitialTableData();
table.setItems(data);
id.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
eponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
onoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
patronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
imGennisis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("imGennisis"));
eidikotita.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eidikotita"));
tilefono.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tilefono"));
dieuthinsi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dieuthinsi"));
dimos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dimos"));
ekpaideusi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("ekpaideusi"));
oikKatastasi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("oikKatastasi"));
diploma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("diploma"));
empeiria.setCellValueFactory(new PropertyValueFactory<tableManager, String>("empeiria"));
table.getColumns().setAll(id, eponimo, onoma, patronimo, imGennisis, eidikotita, tilefono, dieuthinsi, dimos, ekpaideusi, oikKatastasi, diploma, empeiria);
//end of initialization of table
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/EuresiErgasias/EuresiErgasiasMain.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Edit(ActionEvent e) throws IOException, SQLException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε ένα άτομο από τον πίνακα.", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "zitounergasia")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "zitounergasia")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/EuresiErgasias/EpeksergasiaAtomouPouZita.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή το επιλεγμένο άτομο. Βεβαιωθείτε ότι η καρτέλα του επιλεγμένου ατόμου δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void Delete(ActionEvent e){
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε ένα άτομο από τον πίνακα για να διαγράψετε!", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε το άτομο με στοιχεία Επώνυμο: " + tbl.getEponimo() + " και Όνομα: " + tbl.getOnoma() + " από τη λίστα με τα άτομα που ζητούν εργασία; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία του ατόμου αυτού στη συνέχεια...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM zitounergasia WHERE id = ?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί το άτομο από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
table.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliAtomonPouZitounController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class tableManager {
private SimpleIntegerProperty id;
private SimpleStringProperty eponimo;
private SimpleStringProperty onoma;
private SimpleStringProperty patronimo;
private SimpleStringProperty imGennisis;
private SimpleStringProperty eidikotita;
private SimpleStringProperty tilefono;
private SimpleStringProperty dieuthinsi;
private SimpleStringProperty dimos;
private SimpleStringProperty ekpaideusi;
private SimpleStringProperty oikKatastasi;
private SimpleStringProperty diploma;
private SimpleStringProperty empeiria;
public tableManager(){}
public tableManager(int id, String eponimo, String onoma, String patronimo, String imGennisis, String eidikotita, String tilefono, String dieuthinsi, String dimos, String ekpaideusi, String oikKatastasi, String diploma, String empeiria){
this.id = new SimpleIntegerProperty(id);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.imGennisis = new SimpleStringProperty(imGennisis);
this.eidikotita = new SimpleStringProperty(eidikotita);
this.tilefono = new SimpleStringProperty(tilefono);
this.dieuthinsi = new SimpleStringProperty(dieuthinsi);
this.dimos = new SimpleStringProperty(dimos);
this.ekpaideusi = new SimpleStringProperty(ekpaideusi);
this.oikKatastasi = new SimpleStringProperty(oikKatastasi);
this.diploma = new SimpleStringProperty(diploma);
this.empeiria = new SimpleStringProperty(empeiria);
}
public Integer getId(){
return id.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getImGennisis(){
return imGennisis.get();
}
public String getEidikotita(){
return eidikotita.get();
}
public String getDieuthinsi(){
return dieuthinsi.get();
}
public String getDimos(){
return dimos.get();
}
public String getTilefono(){
return tilefono.get();
}
public String getEkpaideusi(){
return ekpaideusi.get();
}
public String getOikKatastasi(){
return oikKatastasi.get();
}
public String getDiploma(){
return diploma.get();
}
public String getEmpeiria(){
return empeiria.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
try {
String sql = "SELECT * FROM zitounergasia";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn=db.ConnectDB();
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
sopho.ResultKeeper.rs=rs;
rs.last();
if(rs.getRow()>0){
rs.beforeFirst();
while(rs.next()){
String ekpaideusi = "";
//we have to convert the 0 and 1 value from the db to strings
if(rs.getInt("ye")==1){
ekpaideusi += "ΥΕ, ";
}
if(rs.getInt("de")==1){
ekpaideusi += "ΔΕ, ";
}
if(rs.getInt("te")==1){
ekpaideusi += "ΤΕ, ";
}
if(rs.getInt("pe")==1){
ekpaideusi += "ΠΕ, ";
}
if(ekpaideusi.length()>1){
ekpaideusi = ekpaideusi.substring(0, ekpaideusi.length()-2);//to remove the space and the comma
}
String oikKatastasi = "";
//we have to convert oikKatastasi to String
if(rs.getInt("oikKatastasi")==0){
oikKatastasi = "Άγαμος";
}else if(rs.getInt("oikKatastasi")==1){
oikKatastasi = "Έγγαμος";
}else if(rs.getInt("oikKatastasi")==2){
oikKatastasi = "Διαζευγμένος";
}else if(rs.getInt("oikKatastasi")==3){
oikKatastasi = "Χήρος";
}
// we can add data to the initial table using the following command
list.add(new tableManager(rs.getInt("id"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), rs.getDate("imGennisis").toString(), rs.getString("eidikotita"), rs.getString("tilefono"), rs.getString("dieuthinsi"), rs.getString("dimos"), ekpaideusi, oikKatastasi, rs.getString("diploma"), rs.getString("empeiria")));
}
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliAtomonPouZitounController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/EuresiErgasias/ProvoliAtomonPouZitounController.java |
1,834 | package com.fivasim.antikythera;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.opengl.GLSurfaceView.Renderer;
import android.os.Build;
import static com.fivasim.antikythera.Initial2.*;
public class OpenGLRenderer2 implements Renderer {
private Gear gears[] = new Gear[num_gears];
private Gear axles[] = new Gear[num_axles];
private Pointer pointers[] = new Pointer[num_pointers];
private Gear pointerbase = new Gear( new float[]{0f, 1.5f, 1f, 50f, 0f, 0f} );
private Plate plates[] = new Plate[2];
private static int framecount = 0;
public static float curX = 0f;
public static float curY = 0f;
public static float curX1 = 0f;
public static float curY1 = 0f;
public static float curDist = 0f;
public static int touchmode = 0;
public static float angle = 0f;
public static float fullrotate_x = 0f;
public static float fullrotate_y = 0f;
public static float fullrotate_z = 0f;
public static float position_x = 0f;
public static float position_y = 0f;
public static float zoomfac = 0f;
public static long timestamp = System.currentTimeMillis();
private Bitmap bitmap;
public OpenGLRenderer2() {
int i;
// Initialize our gears.
for (i=0;i<num_gears;i++) {
gears[i] = new Gear(geardata[i]);
}
for (i=0;i<num_axles;i++) {
axles[i] = new Gear(axledata[i]);
}
for (i=0;i<num_pointers;i++) {
pointers[i] = new Pointer( pointer_len[i], pointer_pos[i]);
}
plates[0] = new Plate(60.0f, 40.0f, 25.0f);
plates[1] = new Plate(60.0f, 40.0f,-41.0f);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceCreated(javax.microedition
* .khronos.opengles.GL10, javax.microedition.khronos.egl.EGLConfig)
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Set the background color to black ( rgba ).
gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// Enable Smooth Shading, default not really needed.
gl.glShadeModel(GL10.GL_SMOOTH);
// Depth buffer setup.
gl.glClearDepthf(1.0f);
// Enables depth testing.
gl.glEnable(GL10.GL_DEPTH_TEST);
// The type of depth testing to do.
gl.glDepthFunc(GL10.GL_LEQUAL);
// Really nice perspective calculations.
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
//gl.glEnable(GL10.GL_DITHER);
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onDrawFrame(javax.microedition.
* khronos.opengles.GL10)
*/
public void onDrawFrame(GL10 gl) {
if( Build.VERSION.SDK_INT >= 7 ){
framecount++;
if (framecount == 10) {
antikythera2.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp);
timestamp = System.currentTimeMillis();
framecount = 0;
} else if (antikythera2.fps == 0f) {
if (timestamp == 0) {
timestamp = System.currentTimeMillis();
} else {
framecount = 0;
antikythera2.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) );
timestamp = System.currentTimeMillis();
}
}
} else {
framecount++;
if (framecount == 10) {
antikythera2_nomulti.fps = (float)(framecount*1000)/(float)(System.currentTimeMillis()-timestamp);
timestamp = System.currentTimeMillis();
framecount = 0;
} else if (antikythera2.fps == 0f) {
if (timestamp == 0) {
timestamp = System.currentTimeMillis();
} else {
framecount = 0;
antikythera2_nomulti.fps = (float)(1000f/(float)(System.currentTimeMillis()-timestamp) );
timestamp = System.currentTimeMillis();
}
}
}
//timestamp = System.currentTimeMillis();
double rmik=4.0;
double rmeg, cosx;
//double kentro_k1 = 0.0; //x=0, y=0
double kentro_k2 = gearpos[21][0] - gearpos[20][0]; //x=;, y=0
double kentro_k[] = {0.0, 0.0}; //κεντρο πυρρου k
gl.glDisable(GL10.GL_LIGHTING);
// Clears the screen and depth buffer.
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// Replace the current matrix with the identity matrix
gl.glLoadIdentity();
// Translates 4 units into the screen.
if (position_x > 100f) { position_x = 100f;}
if (position_x <-100f) { position_x =-100f;}
if (position_y > 100f) { position_y = 100f;}
if (position_y <-100f) { position_y =-100f;}
gl.glTranslatef(position_x, position_y, -120f + zoomfac);
gl.glRotatef( fullrotate_x, 1f, 0f, 0f);
gl.glRotatef( fullrotate_y, 0f, 1f, 0f);
gl.glRotatef( fullrotate_z, 0f, 0f, 1f);
// Draw our gears
int i;
for (i=0;i<num_gears;i++) {
gl.glPushMatrix();
gl.glTranslatef(gearpos[i][0],gearpos[i][1], gearpos[i][2]); //Κέντρο γραναζιού
if(i==num_gears-1) { //Αν το γρανάζι είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα)
gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f);
}
if((i==21)||(i==2)||(i==12)||(i==7))//Το γρανάζι του Ιππάρχου
{
kentro_k[0]= rmik * Math.cos((angle ) * M_PI / 180.0);
kentro_k[1]= rmik * Math.sin((angle ) * M_PI / 180.0);
//Απόσταση πύρρου με κέντρο k2
rmeg = Math.sqrt(Math.pow((kentro_k[0]-kentro_k2),2) + Math.pow(kentro_k[1],2));
//Ταχύτητα k2 = ταχύτητα πύρρου / απόσταση
cosx = (rmeg*rmeg + rmik*rmik - kentro_k2*kentro_k2) / (2 * rmik * rmeg);
if((i==21)||(i==2)){
gearpos[i][3] = (float)( (gearpos[20][3] * rmik * cosx) / (rmeg) );
if(i==21) {
pointer_pos[1][3]= gearpos[i][3]; }
} else {
gearpos[i][3]= (float)( -(gearpos[20][3] * rmik * cosx) / (rmeg) );
}
}
if (!Preferences.rotate_backwards) {
startangle[i] -= Preferences.rotation_speed * gearpos[i][3];
} else {
startangle[i] += Preferences.rotation_speed * gearpos[i][3];
}
gl.glRotatef( startangle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού
gears[i].draw(gl, (int)gearpos[i][4]);
gl.glPopMatrix();
}
//axles
for (i=0;i<num_axles;i++) {
gl.glPushMatrix();
if(axle_differential[i]!=0) { //Αν ανήκει στα διαφορικά γρανάζια του μηχανισμού Περιστροφή διαφορικού
if(i==num_axles-1) {//Αν είναι το χερούλι της μανιβέλας
gl.glTranslatef( axlepos[i-1][0], axlepos[i-1][1], axlepos[i-1][2]); //Κέντρο κύκλου περιστροφής
if (!Preferences.rotate_backwards) {
axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i];
} else {
axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i];
}
gl.glRotatef( axle_differential_angle[i], 1.0f, 0.0f, 0.0f);
} else { //Οποιόσδήποτε άλλος άξονας γραναζιού (ΙΠΠΑΡΧΟΣ Κ1)
gl.glTranslatef( gearpos[20][0], gearpos[20][1], 0.0f); //Κέντρο κύκλου περιστροφής
if (!Preferences.rotate_backwards) {
axle_differential_angle[i] -= Preferences.rotation_speed * axle_differential[i];
} else {
axle_differential_angle[i] += Preferences.rotation_speed * axle_differential[i];
}
gl.glRotatef( axle_differential_angle[i], 0.0f, 0.0f, 1.0f);
}
}
if(i==9) {
gl.glTranslatef( 4f,0f, axlepos[i][2]); } //Κέντρο άξονα
else {
gl.glTranslatef(axlepos[i][0],axlepos[i][1], axlepos[i][2]);} //Κέντρο γραναζιού
if(i>=num_axles-3) { //Αν είναι η μανιβέλα να πάρει σωστή θέση (κάθετο στα υπόλοιπα)
gl.glRotatef( 90f, 0.0f, 1.0f, 0.0f);
}
if (!Preferences.rotate_backwards) {
axle_angle[i] -= Preferences.rotation_speed * axlepos[i][3];
} else {
axle_angle[i] += Preferences.rotation_speed * axlepos[i][3];
}
gl.glRotatef( axle_angle[i], 0f, 0f, 1f); //Περιστροφή γραναζιού
axles[i].draw(gl, (int)axlepos[i][4]);
gl.glPopMatrix();
}
//pointers
for (i=0;i<num_pointers;i++) {
gl.glPushMatrix();
gl.glTranslatef( pointer_pos[i][0], pointer_pos[i][1], pointer_pos[i][2]); //Κέντρο δείκτη
//Περιστροφή δείκτη γύρω απ' τον άξονά του. Ο συντελεστής του angle είναι η ταχύτητα περιστροφής
if (!Preferences.rotate_backwards) {
pointer_angle[i] -= Preferences.rotation_speed * pointer_pos[i][3];
} else {
pointer_angle[i] += Preferences.rotation_speed * pointer_pos[i][3];
}
gl.glRotatef(pointer_angle[i] , 0.0f, 0.0f, 1.0f);
pointers[i].draw(gl, (int)pointer_pos[i][4]);
pointerbase.draw(gl, (int)pointer_pos[i][4]);
gl.glPopMatrix();
}
//plates
if (Preferences.plate_visibility) {
for (i=0;i<2;i++) {
plates[i].draw(gl);
}
}
if (!Preferences.rotate_backwards) {
angle -= Preferences.rotation_speed;
} else {
angle += Preferences.rotation_speed;
}
}
/*
* (non-Javadoc)
*
* @see
* android.opengl.GLSurfaceView.Renderer#onSurfaceChanged(javax.microedition
* .khronos.opengles.GL10, int, int)
*/
public void onSurfaceChanged(GL10 gl, int width, int height) {
if (Preferences.plate_visibility) {
if( Build.VERSION.SDK_INT >= 7 ){
bitmap = antikythera2.bitmap;
} else {
bitmap = antikythera2_nomulti.bitmap;
}
gl.glEnable(GL10.GL_TEXTURE_2D);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
// Sets the current view port to the new size.
gl.glViewport(0, 0, width, height);
// Select the projection matrix
gl.glMatrixMode(GL10.GL_PROJECTION);
// Reset the projection matrix
gl.glLoadIdentity();
// Calculate the aspect ratio of the window
GLU.gluPerspective(gl, 75.0f, (float) width / (float) height, 0.1f, 750.0f);
// Select the modelview matrix
gl.glMatrixMode(GL10.GL_MODELVIEW);
// Reset the modelview matrix
gl.glLoadIdentity();
}
}
| fivasim/Antikythera-Simulation | Antikythera/src/com/fivasim/antikythera/OpenGLRenderer2.java |
1,836 | /*
* @(#)Parallelepiped.java 1.0 12.09.2012
*
* Copyright (c) 2012 Dmitry Tsechoev.
* Moscow, Russia.
* All rights reserved.
*
* This software is the confidential and proprietary information of
* Dmitry Tsechoev. ("Confidential Information"). You shall not
* disclose such Confidential Information and shall use it only in
* accordance with the terms of the license agreement you entered into
* with Dmitry.
*
* Би-сми-Лляхи-р-рахмани-р-рахим...
*/
package org.itmuslim.science.mathematics.geometry.stereometry.shape;
/**
* Параллелепи́пед (от греч. παράλλος — параллельный и греч. επιπεδον — плоскость) — призма, основанием которой
* служит параллелограмм, или (равносильно) многогранник, у которого шесть граней и каждая из них параллелограмм.
*
* @author Dmitry Tsechoev (OPCTXO)
* @version 1.0 12.09.2012
*/
public class Parallelepiped implements Shape {
protected double a;
protected double b;
protected double c;
private double h;
public double getA() {
return a;
}
public void setA(double a) {
this.a = a;
}
public double getB() {
return b;
}
public void setB(double b) {
this.b = b;
}
public double getC() {
return c;
}
public void setC(double c) {
this.c = c;
}
public double getHeight() {
return h;
}
public void setHeight(double h) {
this.h = h;
}
protected Parallelepiped() {
}
protected Parallelepiped(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
private Parallelepiped(double a, double b, double c, double h) {
this.a = a;
this.b = b;
this.c = c;
this.h = h;
}
public static Parallelepiped create() {
return new Parallelepiped();
}
public static Parallelepiped create(double a, double b, double c) {
return new Parallelepiped(a, b, c);
}
public static Parallelepiped create(double a, double b, double c, double h) {
return new Parallelepiped(a, b, c, h);
}
public double lateralSurfaceSquare() {
return (2*a + 2 * b) * h;
}
private double footprint(double h) {
return 0.0; //TODO
}
public double totalSurfaceSquare() {
return lateralSurfaceSquare() + 2; //TODO
}
public double volume() {
return h; //TODO
}
}
| Kanunnikoff/mathematics | src/org/itmuslim/science/mathematics/geometry/stereometry/shape/Parallelepiped.java |
1,837 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.MathimataStiriksis;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ListaKathigitonController implements Initializable {
@FXML
public Button backButton;
@FXML
public TableView<tableManager> table;
@FXML
public TableColumn<tableManager, String> eponimo, onoma, patronimo, dieuthinsi, tilefono, mathimata;
@FXML
public TableColumn<tableManager, Integer> id;
private ObservableList<tableManager> data;
sopho.StageLoader sl = new sopho.StageLoader();
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing table
data = getInitialTableData();
table.setItems(data);
id.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
eponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
onoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
patronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
tilefono.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tilefono"));
dieuthinsi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dieuthinsi"));
mathimata.setCellValueFactory(new PropertyValueFactory<tableManager, String>("mathimata"));
table.getColumns().setAll(id, eponimo, onoma, patronimo, tilefono, dieuthinsi, mathimata);
//end of initialization of table
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/MathimataStiriksis/MathimataMain.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Select(ActionEvent e) throws IOException, SQLException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν καθηγητή από τον πίνακα.", "error");
cm.showAndWait();
}else{
sopho.LockEdit le = new sopho.LockEdit();
tableManager tbl = table.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "kathigites")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "kathigites")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/MathimataStiriksis/EpeksergasiaKathigiti.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο καθηγητή. Βεβαιωθείτε ότι η καρτέλα του καθηγητή δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void Delete(ActionEvent e){
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε εναν καθηγητή από τον πίνακα για να διαγράψετε!", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε τον καθηγητή: "+tbl.getEponimo()+" "+tbl.getOnoma()+" από τη λίστα των καθηγητών; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία του καθηγητή αυτού στη συνέχεια...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM kathigites WHERE id = ?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί ο καθηγητής από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
table.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(ListaKathigitonController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class tableManager {
private SimpleIntegerProperty id;
private SimpleStringProperty eponimo;
private SimpleStringProperty onoma;
private SimpleStringProperty patronimo;
private SimpleStringProperty dieuthinsi;
private SimpleStringProperty tilefono;
private SimpleStringProperty mathimata;
public tableManager(){}
public tableManager(Integer id, String eponimo, String onoma, String patronimo, String dieuthinsi, String tilefono, String mathimata){
this.id = new SimpleIntegerProperty(id);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.dieuthinsi = new SimpleStringProperty(dieuthinsi);
this.tilefono = new SimpleStringProperty(tilefono);
this.mathimata = new SimpleStringProperty(mathimata);
}
public Integer getId(){
return id.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getDieuthinsi(){
return dieuthinsi.get();
}
public String getTilefono(){
return tilefono.get();
}
public String getMathimata(){
return mathimata.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
try {
String sql = "SELECT * FROM kathigites";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn=db.ConnectDB();
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
sopho.ResultKeeper.rs=rs;
rs.last();
if(rs.getRow()>0){
rs.beforeFirst();
while(rs.next()){
// we can add data to the initial table using the following command
list.add(new tableManager(rs.getInt("id"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), rs.getString("dieuthinsi"), rs.getString("tilefono") +", "+ rs.getString("tilefono2"), rs.getString("mathimata")));
}
}
} catch (SQLException ex) {
Logger.getLogger(ListaKathigitonController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/MathimataStiriksis/ListaKathigitonController.java |
1,838 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.Ofeloumenoi;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ListaOfeloumenonController implements Initializable {
@FXML
public Button backButton;
@FXML
private TableView <tableManager> resultTable;
@FXML
private TableColumn <tableManager, Integer> colID;
@FXML
private TableColumn <tableManager, String> colRegisterDate, colBarcode, colEponimo, colPatronimo, colOnoma, colGennisi, colDimos, colAnergos, colEpaggelma, colEisodima, colEksartiseis, colEthnikotita, colMetanastis, colRoma, colOikKatastasi, colTekna, colMellousaMama, colMonogoneiki, colPoliteknos, colAsfForeas, colXronios, colPathisi, colAmea, colMonaxiko, colEmfiliVia, colSpoudastis, colAnenergos;
private ObservableList <tableManager> data;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.LockEdit le = new sopho.LockEdit();
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing result table
data = getInitialTableData();
//filling table with data
resultTable.setItems(data);
colID.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
colBarcode.setCellValueFactory(new PropertyValueFactory<tableManager, String>("barcode"));
colRegisterDate.setCellValueFactory(new PropertyValueFactory<tableManager, String>("registerDate"));
colEponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
colOnoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
colPatronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
colGennisi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("imGennisis"));
colDimos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dimos"));
colAnergos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("anergos"));
colEpaggelma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("epaggelma"));
colEisodima.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eisodima"));
colEksartiseis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eksartiseis"));
colEthnikotita.setCellValueFactory(new PropertyValueFactory<tableManager, String>("ethnikotita"));
colMetanastis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("metanastis"));
colRoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("roma"));
colOikKatastasi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("oikKatastasi"));
colTekna.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tekna"));
colMellousaMama.setCellValueFactory(new PropertyValueFactory<tableManager, String>("mellousaMama"));
colMonogoneiki.setCellValueFactory(new PropertyValueFactory<tableManager, String>("monogoneiki"));
colPoliteknos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("politeknos"));
colAsfForeas.setCellValueFactory(new PropertyValueFactory<tableManager, String>("asfForeas"));
colAmea.setCellValueFactory(new PropertyValueFactory<tableManager, String>("amea"));
colXronios.setCellValueFactory(new PropertyValueFactory<tableManager, String>("xronios"));
colPathisi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("pathisi"));
colMonaxiko.setCellValueFactory(new PropertyValueFactory<tableManager, String>("monaxiko"));
colEmfiliVia.setCellValueFactory(new PropertyValueFactory<tableManager, String>("emfiliVia"));
colSpoudastis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("spoudastis"));
colAnenergos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("anenergos"));
//setting the data to the table
resultTable.getColumns().setAll(colID, colRegisterDate, colBarcode, colEponimo, colOnoma, colPatronimo, colGennisi, colDimos, colAnergos, colEpaggelma, colEisodima, colEksartiseis, colEthnikotita, colMetanastis, colRoma, colOikKatastasi, colTekna, colMellousaMama, colMonogoneiki, colPoliteknos, colAsfForeas, colAmea, colXronios, colPathisi, colMonaxiko, colEmfiliVia, colSpoudastis, colAnenergos);
}
@FXML
public void GoBack(ActionEvent event) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/Ofeloumenoi/OfeloumenoiMain.fxml", stage, true, false); //resizable true, utility false
}
@FXML
public void Edit(ActionEvent event) throws IOException, SQLException{
int index = resultTable.getSelectionModel().getSelectedIndex();
if(index==-1){
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν ωφελούμενο από τον πίνακα προκειμένου να επεξεργαστείτε τα στοιχεία του", "error");
cm.showAndWait();
}else{
tableManager tbl = resultTable.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "ofeloumenoi")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "ofeloumenoi")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ωφελούμενου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=index;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/Ofeloumenoi/EditOfeloumenoi.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο ωφελούμενο. Βεβαιωθείτε ότι η καρτέλα του ωφελούμενου δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void Delete(ActionEvent event) throws IOException{
int sel = resultTable.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν ωφελούμενο από τον πίνακα για να διαγράψετε!", "error");
cm.showAndWait();
}else{
tableManager tbl = resultTable.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε τον ωφελούμενο με επώνυμο: "+tbl.getEponimo()+" και όνομα: "+tbl.getOnoma()+"; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία του μετά τη διαγραφή...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM ofeloumenoi WHERE id=?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί ο επιλεγμένος ωφελούμενος από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
resultTable.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(sopho.Ofeloumenoi.ListaOfeloumenonController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public static class tableManager { //this is a helper class to display the data from the resultSet to the table properly.
private IntegerProperty id;
private StringProperty barcode;
private StringProperty registerDate;
private StringProperty eponimo;
private StringProperty onoma;
private StringProperty patronimo;
private StringProperty imGennisis;
private StringProperty dimos;
private StringProperty anergos;
private StringProperty epaggelma;
private StringProperty eisodima;
private StringProperty eksartiseis;
private StringProperty ethnikotita;
private StringProperty metanastis;
private StringProperty roma;
private StringProperty oikKatastasi;
private StringProperty tekna;
private StringProperty mellousaMama;
private StringProperty monogoneiki;
private StringProperty politeknos;
private StringProperty asfForeas;
private StringProperty amea;
private StringProperty xronios;
private StringProperty pathisi;
private StringProperty monaxiko;
private StringProperty emfiliVia;
private StringProperty spoudastis;
private StringProperty anenergos;
public tableManager(){}
private tableManager(Integer id, String registerDate, String barcode, String eponimo, String onoma, String patronimo, String imGennisis, String dimos, String anergos, String epaggelma, String eisodima, String eksartiseis, String ethnikotita, String metanastis, String roma, String oikKatastasi, String tekna, String mellousaMama, String monogoneiki, String politeknos, String asfForeas, String amea, String xronios, String pathisi, String monaxiko, String emfiliVia, String spoudastis, String anenergos){
this.id = new SimpleIntegerProperty(id);
this.barcode = new SimpleStringProperty(barcode);
this.registerDate = new SimpleStringProperty(registerDate);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.imGennisis = new SimpleStringProperty(imGennisis);
this.dimos = new SimpleStringProperty(dimos);
this.anergos = new SimpleStringProperty(anergos);
this.epaggelma = new SimpleStringProperty(epaggelma);
this.eisodima = new SimpleStringProperty(eisodima);
this.eksartiseis = new SimpleStringProperty(eksartiseis);
this.ethnikotita = new SimpleStringProperty(ethnikotita);
this.metanastis = new SimpleStringProperty(metanastis);
this.roma = new SimpleStringProperty(roma);
this.oikKatastasi = new SimpleStringProperty(oikKatastasi);
this.tekna = new SimpleStringProperty(tekna);
this.mellousaMama = new SimpleStringProperty(mellousaMama);
this.monogoneiki = new SimpleStringProperty(monogoneiki);
this.politeknos = new SimpleStringProperty(politeknos);
this.asfForeas = new SimpleStringProperty(asfForeas);
this.amea = new SimpleStringProperty(amea);
this.xronios = new SimpleStringProperty(xronios);
this.pathisi = new SimpleStringProperty(pathisi);
this.monaxiko = new SimpleStringProperty(monaxiko);
this.emfiliVia = new SimpleStringProperty(emfiliVia);
this.spoudastis = new SimpleStringProperty(spoudastis);
this.anenergos = new SimpleStringProperty(anenergos);
}
//the following get and set methods are required. Else the table cells will appear blank
public Integer getId(){
return id.get();
}
public String getBarcode(){
return barcode.get();
}
public String getRegisterDate(){
return registerDate.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getImGennisis(){
return imGennisis.get();
}
public String getDimos(){
return dimos.get();
}
public String getAnergos(){
return anergos.get();
}
public String getEpaggelma(){
return epaggelma.get();
}
public String getEisodima(){
return eisodima.get();
}
public String getEksartiseis(){
return eksartiseis.get();
}
public String getEthnikotita(){
return ethnikotita.get();
}
public String getMetanastis(){
return metanastis.get();
}
public String getRoma(){
return roma.get();
}
public String getOikKatastasi(){
return oikKatastasi.get();
}
public String getTekna(){
return tekna.get();
}
public String getMellousaMama(){
return mellousaMama.get();
}
public String getMonogoneiki(){
return monogoneiki.get();
}
public String getPoliteknos(){
return politeknos.get();
}
public String getAsfForeas(){
return asfForeas.get();
}
public String getAmea(){
return amea.get();
}
public String getXronios(){
return xronios.get();
}
public String getPathisi(){
return pathisi.get();
}
public String getMonaxiko(){
return monaxiko.get();
}
public String getEmfiliVia(){
return emfiliVia.get();
}
public String getSpoudastis(){
return spoudastis.get();
}
public String getAnenergos(){
return anenergos.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
sopho.DBClass db = new sopho.DBClass();
Connection conn = db.ConnectDB();
String sql = "SELECT * FROM ofeloumenoi";
PreparedStatement pst;
try {
pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
rs.last();
if(rs.getRow()>0){
sopho.ResultKeeper.rs = rs;
//we have to add the values from database to the table
rs.beforeFirst();
while(rs.next()){
String oikKatastasi = "";
int oikKatIndex = rs.getInt("oikKatastasi");
if(oikKatIndex>=0){//otherwise no selection was made
switch(oikKatIndex){
case 0: oikKatastasi="Άγαμος";
break;
case 1: oikKatastasi="Έγγαμος";
break;
case 2: oikKatastasi="Διαζευγμένος";
break;
case 3: oikKatastasi="Χήρος";
break;
default: break;
}
}
String asfForeas = "";
int asfForeasIndex = rs.getInt("asfForeas");
if(asfForeasIndex>=0){//otherwise no selection was made
switch(asfForeasIndex){
case 0: asfForeas="Ανασφάλιστος";
break;
case 1: asfForeas="ΙΚΑ";
break;
case 2: asfForeas="ΟΓΑ";
break;
case 3: asfForeas="ΟΑΕΕ";
break;
case 4: asfForeas="ΕΤΑΑ";
break;
case 5: asfForeas="ΕΟΠΥΥ";
break;
case 6: asfForeas="ΤΠΔΥ";
break;
case 7: asfForeas="ΤΑΠΙΤ";
break;
case 8: asfForeas="ΕΤΑΠ – ΜΜΕ";
break;
case 9: asfForeas="Άλλο";
break;
default: break;
}
}
String birthdate="";
if(rs.getDate("imGennisis")!=null){
birthdate = rs.getDate("imGennisis").toString();
}
list.add(new tableManager(rs.getInt("id"), rs.getDate("registerDate").toString(), rs.getString("barcode"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), birthdate, rs.getString("dimos"), ConvertToYesNo(rs.getInt("anergos")), rs.getString("epaggelma"), rs.getString("eisodima"), rs.getString("eksartiseis"), rs.getString("ethnikotita"), ConvertToYesNo(rs.getInt("metanastis")), ConvertToYesNo(rs.getInt("roma")), oikKatastasi, rs.getInt("arithmosTeknon")+"", ConvertToYesNo(rs.getInt("mellousaMama")), ConvertToYesNo(rs.getInt("monogoneiki")), ConvertToYesNo(rs.getInt("politeknos")), asfForeas, ConvertToYesNo(rs.getInt("amea")), ConvertToYesNo(rs.getInt("xronios")), rs.getString("pathisi"), ConvertToYesNo(rs.getInt("monaxikos")), ConvertToYesNo(rs.getInt("emfiliVia")), ConvertToYesNo(rs.getInt("spoudastis")), ConvertToYesNo(rs.getInt("anenergos"))));
}
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Ενημέρωση", "Δεν έχετε προσθέσει ωφελούμενους ακόμη. Θέλετε να προσθέσετε έναν ωφελούμενο τώρα;", "question");
cm.showAndWait();
Stage stage = (Stage) backButton.getScene().getWindow();
if(cm.saidYes){
sl.StageLoad("/sopho/Ofeloumenoi/AddOfeloumenoi.fxml", stage, true, false); //stage to open, stage to close, resizable, utility
}else{
sl.StageLoad("/sopho/Ofeloumenoi/OfeloumenoiMain.fxml", stage, false, true); //stage to open, stage to close, resizable, utility
}
}
} catch (SQLException | IOException ex) {
Logger.getLogger(ListaOfeloumenonController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
public String ConvertToYesNo(int flag){
String s;
if(flag==1){
s="ΝΑΙ";
}else{
s="ΟΧΙ";
}
return s;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/Ofeloumenoi/ListaOfeloumenonController.java |
1,839 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.EuresiErgasias;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ProvoliDiathesimonTheseonController implements Initializable {
@FXML
public Button backButton;
@FXML
public TableView<tableManager> table;
@FXML
public TableColumn<tableManager, String> thesi, eponimia, eponimo, onoma, patronimo, tilefono, dieuthinsi;
@FXML
public TableColumn<tableManager, Integer> id;
private ObservableList<tableManager> data;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.LockEdit le = new sopho.LockEdit();
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing table
data = getInitialTableData();
table.setItems(data);
id.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
thesi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("thesi"));
eponimia.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimia"));
eponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
onoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
patronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
tilefono.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tilefono"));
dieuthinsi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dieuthinsi"));
table.getColumns().setAll(id, thesi, eponimia, eponimo, onoma, patronimo, tilefono, dieuthinsi);
//end of initialization of table
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/EuresiErgasias/EuresiErgasiasMain.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Select(ActionEvent e) throws IOException, SQLException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε μια θέση από τον πίνακα προκειμένου να την κατοχυρώσετε σε κάποιον", "error");
cm.showAndWait();
}else{
sopho.DBClass db = new sopho.DBClass();
//we have to check if there are persons that ask for jobs otherwise the available job will have no person to be occupied by.
String sql = "SELECT * FROM zitounergasia";
Connection conn = db.ConnectDB();
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
rs.last();
Stage stage = (Stage) backButton.getScene().getWindow();
if(rs.getRow()>0){
//we have results
sopho.ResultKeeper.selectedIndex=sel;
sl.StageLoad("/sopho/EuresiErgasias/KatoxirosiThesis.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να καταχωρήσετε άτομο που ζητά εργασία προτού επιχειρήσετε να κατοχυρώσετε τη θέση εργασίας σε κάποιον. Αυτή τη στιγμή δεν υπάρχουν άτομα στα οποία μπορείτε να κατοχυρώσετε τη θέση εργασίας.", "error");
cm.showAndWait();
sl.StageLoad("/sopho/EuresiErgasias/KataxorisiAtomouPouZita.fxml", stage, true, false); //resizable true, utility false
}
}
}
@FXML
public void Edit(ActionEvent e) throws IOException, SQLException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε μια θέση από τον πίνακα.", "error");
cm.showAndWait();
}else{
sopho.ResultKeeper.selectedIndex=sel;
tableManager tbl = table.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "theseisergasias")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "theseisergasias")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/EuresiErgasias/EpeksergasiaThesisErgasias.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή την επιλεγμένη θέση εργασίας. Βεβαιωθείτε ότι η καρτέλα της θέσης εργασίας δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void EditErgodotis(ActionEvent e) throws IOException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν εργοδότη από τον πίνακα.", "error");
cm.showAndWait();
}else{
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/EuresiErgasias/EpeksergasiaStoixeionErgodoti.fxml", stage, true, false); //resizable true, utility false
}
}
@FXML
public void Delete(ActionEvent e){
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε μια θέση από τον πίνακα για να διαγράψετε!", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε τη θέση: "+tbl.getThesi()+" από τις διαθέσιμες θέσεις; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία της θέσης αυτής στη συνέχεια...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM theseisergasias WHERE id = ?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί η θέση εργασίας από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
table.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliDiathesimonTheseonController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class tableManager {
private SimpleIntegerProperty id;
private SimpleStringProperty eponimia;
private SimpleStringProperty eponimo;
private SimpleStringProperty onoma;
private SimpleStringProperty patronimo;
private SimpleStringProperty dieuthinsi;
private SimpleStringProperty tilefono;
private SimpleStringProperty thesi;
public tableManager(){}
public tableManager(Integer id, String eponimia, String eponimo, String onoma, String patronimo, String dieuthinsi, String tilefono, String thesi){
this.id = new SimpleIntegerProperty(id);
this.eponimia = new SimpleStringProperty(eponimia);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.dieuthinsi = new SimpleStringProperty(dieuthinsi);
this.tilefono = new SimpleStringProperty(tilefono);
this.thesi = new SimpleStringProperty(thesi);
}
public Integer getId(){
return id.get();
}
public String getEponimia(){
return eponimia.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getDieuthinsi(){
return dieuthinsi.get();
}
public String getTilefono(){
return tilefono.get();
}
public String getThesi(){
return thesi.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
try {
String sql = "SELECT * FROM theseisergasias";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn=db.ConnectDB();
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
sopho.ResultKeeper.rs=rs;
rs.last();
if(rs.getRow()>0){
rs.beforeFirst();
while(rs.next()){
// we can add data to the initial table using the following command
list.add(new tableManager(rs.getInt("id"), rs.getString("eponimia"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), rs.getString("dieuthinsi"), rs.getString("tilefono"), rs.getString("thesi")));
}
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliDiathesimonTheseonController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/EuresiErgasias/ProvoliDiathesimonTheseonController.java |
1,840 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.Ofeloumenoi;
import java.io.IOException;
import java.net.URL;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.Period;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class SearchOfeloumenoiResultsController implements Initializable {
@FXML
public Label info;
@FXML
private TableView <tableManager> resultTable;
@FXML
private TableColumn <tableManager, Integer> colId;
@FXML
private TableColumn <tableManager, String> colRegisterDate, colEponimo, colPatronimo, colOnoma, colIlikia, colDimos, colAnergos, colEpaggelma, colEisodima, colEksartiseis, colEthnikotita, colMetanastis, colRoma, colOikKatastasi, colTekna, colMellousaMama, colMonogoneiki, colPoliteknos, colAsfForeas, colXronios, colPathisi, colAmea, colMonaxiko, colEmfiliVia, colSpoudastis, colAnenergos;
private ObservableList <tableManager> data;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.LockEdit le = new sopho.LockEdit();
public ResultSet rs = sopho.ResultKeeper.rs;
@Override
public void initialize(URL url, ResourceBundle rb) {
//setting a text about the results found
int resultsNumber=0;
try {
rs.last();
resultsNumber = rs.getRow();
rs.beforeFirst();
} catch (SQLException ex) {
Logger.getLogger(SearchOfeloumenoiResultsController.class.getName()).log(Level.SEVERE, null, ex);
}
info.setText("Βρέθηκαν " + resultsNumber + " αποτελέσματα με βάση τα κριτήρια που έχετε θέσει στην αναζήτηση.");
//initialzing result table
data = getInitialTableData();
//filling table with data
resultTable.setItems(data);
colId.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
colRegisterDate.setCellValueFactory(new PropertyValueFactory<tableManager, String>("registerDate"));
colEponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
colOnoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
colPatronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
colIlikia.setCellValueFactory(new PropertyValueFactory<tableManager, String>("ilikia"));
colDimos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dimos"));
colAnergos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("anergos"));
colEpaggelma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("epaggelma"));
colEisodima.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eisodima"));
colEksartiseis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eksartiseis"));
colEthnikotita.setCellValueFactory(new PropertyValueFactory<tableManager, String>("ethnikotita"));
colMetanastis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("metanastis"));
colRoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("roma"));
colOikKatastasi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("oikKatastasi"));
colTekna.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tekna"));
colMellousaMama.setCellValueFactory(new PropertyValueFactory<tableManager, String>("mellousaMama"));
colMonogoneiki.setCellValueFactory(new PropertyValueFactory<tableManager, String>("monogoneiki"));
colPoliteknos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("politeknos"));
colAsfForeas.setCellValueFactory(new PropertyValueFactory<tableManager, String>("asfForeas"));
colAmea.setCellValueFactory(new PropertyValueFactory<tableManager, String>("amea"));
colXronios.setCellValueFactory(new PropertyValueFactory<tableManager, String>("xronios"));
colPathisi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("pathisi"));
colMonaxiko.setCellValueFactory(new PropertyValueFactory<tableManager, String>("monaxiko"));
colEmfiliVia.setCellValueFactory(new PropertyValueFactory<tableManager, String>("emfiliVia"));
colSpoudastis.setCellValueFactory(new PropertyValueFactory<tableManager, String>("spoudastis"));
colAnenergos.setCellValueFactory(new PropertyValueFactory<tableManager, String>("anenergos"));
//setting the data to the table
resultTable.getColumns().setAll(colId, colRegisterDate, colEponimo, colOnoma, colPatronimo, colIlikia, colDimos, colAnergos, colEpaggelma, colEisodima, colEksartiseis, colEthnikotita, colMetanastis, colRoma, colOikKatastasi, colTekna, colMellousaMama, colMonogoneiki, colPoliteknos, colAsfForeas, colAmea, colXronios, colPathisi, colMonaxiko, colEmfiliVia, colSpoudastis, colAnenergos);
}
@FXML
public void GoBack(ActionEvent event) throws IOException{
Stage stage = (Stage) info.getScene().getWindow();
sl.StageLoad("/sopho/Ofeloumenoi/SearchOfeloumenoi.fxml", stage, true, false); //resizable true, utility false
}
@FXML
public void NewSearch(ActionEvent event) throws IOException{
Stage stage = (Stage) info.getScene().getWindow();
sl.StageLoad("/sopho/Ofeloumenoi/SearchOfeloumenoi.fxml", stage, true, false); //resizable true, utility false
}
@FXML
public void Select(ActionEvent event) throws IOException, SQLException{
int index = resultTable.getSelectionModel().getSelectedIndex();
if(index==-1){
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν ωφελούμενο από τον πίνακα προκειμένου να επεξεργαστείτε τα στοιχεία του", "error");
cm.showAndWait();
}else{
tableManager tbl = resultTable.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "ofeloumenoi")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "ofeloumenoi")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ωφελούμενου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=index;
Stage stage = (Stage) info.getScene().getWindow();
sl.StageLoad("/sopho/Ofeloumenoi/EditOfeloumenoi.fxml", stage, true, false); //resizable true, utility false.
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο ωφελούμενο. Βεβαιωθείτε ότι η καρτέλα του ωφελούμενου δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
public static class tableManager { //this is a helper class to display the data from the resultSet to the table properly.
private IntegerProperty id;
private StringProperty registerDate;
private StringProperty eponimo;
private StringProperty onoma;
private StringProperty patronimo;
private StringProperty ilikia;
private StringProperty dimos;
private StringProperty anergos;
private StringProperty epaggelma;
private StringProperty eisodima;
private StringProperty eksartiseis;
private StringProperty ethnikotita;
private StringProperty metanastis;
private StringProperty roma;
private StringProperty oikKatastasi;
private StringProperty tekna;
private StringProperty mellousaMama;
private StringProperty monogoneiki;
private StringProperty politeknos;
private StringProperty asfForeas;
private StringProperty amea;
private StringProperty xronios;
private StringProperty pathisi;
private StringProperty monaxiko;
private StringProperty emfiliVia;
private StringProperty spoudastis;
private StringProperty anenergos;
public tableManager(){}
private tableManager( Integer id, String registerDate, String eponimo, String onoma, String patronimo, String ilikia, String dimos, String anergos, String epaggelma, String eisodima, String eksartiseis, String ethnikotita, String metanastis, String roma, String oikKatastasi, String tekna, String mellousaMama, String monogoneiki, String politeknos, String asfForeas, String amea, String xronios, String pathisi, String monaxiko, String emfiliVia, String spoudastis, String anenergos){
this.id = new SimpleIntegerProperty(id);
this.registerDate = new SimpleStringProperty(registerDate);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.ilikia = new SimpleStringProperty(ilikia);
this.dimos = new SimpleStringProperty(dimos);
this.anergos = new SimpleStringProperty(anergos);
this.epaggelma = new SimpleStringProperty(epaggelma);
this.eisodima = new SimpleStringProperty(eisodima);
this.eksartiseis = new SimpleStringProperty(eksartiseis);
this.ethnikotita = new SimpleStringProperty(ethnikotita);
this.metanastis = new SimpleStringProperty(metanastis);
this.roma = new SimpleStringProperty(roma);
this.oikKatastasi = new SimpleStringProperty(oikKatastasi);
this.tekna = new SimpleStringProperty(tekna);
this.mellousaMama = new SimpleStringProperty(mellousaMama);
this.monogoneiki = new SimpleStringProperty(monogoneiki);
this.politeknos = new SimpleStringProperty(politeknos);
this.asfForeas = new SimpleStringProperty(asfForeas);
this.amea = new SimpleStringProperty(amea);
this.xronios = new SimpleStringProperty(xronios);
this.pathisi = new SimpleStringProperty(pathisi);
this.monaxiko = new SimpleStringProperty(monaxiko);
this.emfiliVia = new SimpleStringProperty(emfiliVia);
this.spoudastis = new SimpleStringProperty(spoudastis);
this.anenergos = new SimpleStringProperty(anenergos);
}
//the following get and set methods are required. Else the table cells will appear blank
public Integer getId(){
return id.get();
}
public String getRegisterDate(){
return registerDate.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getIlikia(){
return ilikia.get();
}
public String getDimos(){
return dimos.get();
}
public String getAnergos(){
return anergos.get();
}
public String getEpaggelma(){
return epaggelma.get();
}
public String getEisodima(){
return eisodima.get();
}
public String getEksartiseis(){
return eksartiseis.get();
}
public String getEthnikotita(){
return ethnikotita.get();
}
public String getMetanastis(){
return metanastis.get();
}
public String getRoma(){
return roma.get();
}
public String getOikKatastasi(){
return oikKatastasi.get();
}
public String getTekna(){
return tekna.get();
}
public String getMellousaMama(){
return mellousaMama.get();
}
public String getMonogoneiki(){
return monogoneiki.get();
}
public String getPoliteknos(){
return politeknos.get();
}
public String getAsfForeas(){
return asfForeas.get();
}
public String getAmea(){
return amea.get();
}
public String getXronios(){
return xronios.get();
}
public String getPathisi(){
return pathisi.get();
}
public String getMonaxiko(){
return monaxiko.get();
}
public String getEmfiliVia(){
return emfiliVia.get();
}
public String getSpoudastis(){
return spoudastis.get();
}
public String getAnenergos(){
return anenergos.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
//we have to add the values from database to the table
try{
rs.beforeFirst();
while(rs.next()){
Date imGennisis = rs.getDate("imGennisis");
LocalDate today = LocalDate.now();
LocalDate birthday = imGennisis.toLocalDate();
Period p = Period.between(birthday, today);
String age = p.getYears() + ""; //this trick is because int cannot be dereferenced.
String oikKatastasi = "";
int oikKatIndex = rs.getInt("oikKatastasi");
if(oikKatIndex>=0){//otherwise no selection was made
switch(oikKatIndex){
case 0: oikKatastasi="Άγαμος";
break;
case 1: oikKatastasi="Έγγαμος";
break;
case 2: oikKatastasi="Διαζευγμένος";
break;
case 3: oikKatastasi="Χήρος";
break;
default: break;
}
}
String asfForeas = "";
int asfForeasIndex = rs.getInt("asfForeas");
if(asfForeasIndex>=0){//otherwise no selection was made
switch(asfForeasIndex){
case 0: asfForeas="Ανασφάλιστος";
break;
case 1: asfForeas="ΙΚΑ";
break;
case 2: asfForeas="ΟΓΑ";
break;
case 3: asfForeas="ΟΑΕΕ";
break;
case 4: asfForeas="ΕΤΑΑ";
break;
case 5: asfForeas="ΕΟΠΥΥ";
break;
case 6: asfForeas="ΤΠΔΥ";
break;
case 7: asfForeas="ΤΑΠΙΤ";
break;
case 8: asfForeas="ΕΤΑΠ – ΜΜΕ";
break;
case 9: asfForeas="Άλλο";
break;
default: break;
}
}
list.add(new tableManager(rs.getInt("id"), rs.getDate("registerDate").toString(), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), age, rs.getString("dimos"), ConvertToYesNo(rs.getInt("anergos")), rs.getString("epaggelma"), rs.getString("eisodima"), rs.getString("eksartiseis"), rs.getString("ethnikotita"), ConvertToYesNo(rs.getInt("metanastis")), ConvertToYesNo(rs.getInt("roma")), oikKatastasi, rs.getInt("arithmosTeknon")+"", ConvertToYesNo(rs.getInt("mellousaMama")), ConvertToYesNo(rs.getInt("monogoneiki")), ConvertToYesNo(rs.getInt("politeknos")), asfForeas, ConvertToYesNo(rs.getInt("amea")), ConvertToYesNo(rs.getInt("xronios")), rs.getString("pathisi"), ConvertToYesNo(rs.getInt("monaxikos")), ConvertToYesNo(rs.getInt("emfiliVia")), ConvertToYesNo(rs.getInt("spoudastis")), ConvertToYesNo(rs.getInt("anenergos"))));
}
} catch (SQLException ex) {
Logger.getLogger(MultipleSearchResultsController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
public String ConvertToYesNo(int flag){
String s;
if(flag==1){
s="ΝΑΙ";
}else{
s="ΟΧΙ";
}
return s;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/Ofeloumenoi/SearchOfeloumenoiResultsController.java |
1,841 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.Filoksenoumenoi;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ProvoliTrexontonFiloksenoumenonController implements Initializable {
@FXML
public Button backButton;
@FXML
public TableView<tableManager> table;
@FXML
public TableColumn<tableManager, String> eponimo, onoma, patronimo, date, aitia, loipa;
@FXML
public TableColumn<tableManager, Integer> id;
sopho.StageLoader sl = new sopho.StageLoader();
private ObservableList<tableManager> data;
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing table
data = getInitialTableData();
table.setItems(data);
table.setEditable(true);
id.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
eponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
onoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
patronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
date.setCellValueFactory(new PropertyValueFactory<tableManager, String>("date"));
date.setSortType(TableColumn.SortType.DESCENDING);
aitia.setCellValueFactory(new PropertyValueFactory<tableManager, String>("aitia"));
loipa.setCellValueFactory(new PropertyValueFactory<tableManager, String>("loipa"));
table.getColumns().setAll(id, eponimo, onoma, patronimo, date, aitia, loipa);
table.getSortOrder().add(date);//sorting by date in descending order
//end of initialization of table
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/Filoksenoumenoi/FiloksenoumenoiMain.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Apoxorisi(ActionEvent e) throws IOException{
sopho.ResultKeeper.rs = rs;
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν φιλοξενούμενο από τον πίνακα.", "error");
cm.showAndWait();
}else{
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/Filoksenoumenoi/DilosiApoxorisis.fxml", stage, false, true); //resizable false, utility true
}
}
@FXML
public void Edit(ActionEvent e) throws IOException, SQLException{
sopho.ResultKeeper.rs = rs;
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν φιλοξενούμενο από τον πίνακα.", "error");
cm.showAndWait();
}else{
sopho.LockEdit le = new sopho.LockEdit();
tableManager tbl = table.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "filoksenoumenoi")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "filoksenoumenoi")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/Filoksenoumenoi/EpeksergasiaFiloksenoumenou.fxml", stage, false, true); //resizable false, utility true
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο φιλοξενούμενο. Βεβαιωθείτε ότι η καρτέλα του φιλοξενούμενου δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void Delete(ActionEvent e) throws IOException{
sopho.ResultKeeper.rs = rs;
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε έναν φιλοξενούμενο από τον πίνακα.", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε τον φιλοξενούμενο με επώνυμο: "+tbl.getEponimo()+" και όνομα: "+ tbl.getOnoma() +" από τη λίστα με τους τρέχοντες φιλοξενούμενους; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία του φιλοξενούμενου αυτού στη συνέχεια...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM filoksenoumenoi WHERE id = ?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί ο φιλοξενούμενος από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
table.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliTrexontonFiloksenoumenonController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class tableManager { //this is a helper class to display the data from the resultSet to the table properly.
private SimpleIntegerProperty id;
private SimpleStringProperty eponimo;
private SimpleStringProperty onoma;
private SimpleStringProperty patronimo;
private SimpleStringProperty date;
private SimpleStringProperty aitia;
private SimpleStringProperty loipa;
public tableManager(){}
public tableManager(Integer id, String eponimo, String onoma, String patronimo, String date, String aitia, String loipa){
this.id = new SimpleIntegerProperty(id);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.date = new SimpleStringProperty(date);
this.aitia = new SimpleStringProperty(aitia);
this.loipa = new SimpleStringProperty(loipa);
}
public Integer getId(){
return id.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getDate(){
return date.get();
}
public String getAitia(){
return aitia.get();
}
public String getLoipa(){
return loipa.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData() {
List<tableManager> list = new ArrayList<>();
try {
String sql = "SELECT * FROM filoksenoumenoi WHERE apoxorisi=0";
conn = db.ConnectDB();
pst=conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
// we can add data to the initial table using the following command
list.add(new tableManager(rs.getInt("id"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), rs.getDate("date").toString(), rs.getString("aitia"), rs.getString("loipa")));
}
} catch (SQLException ex) {
Logger.getLogger(ProvoliTrexontonFiloksenoumenonController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/Filoksenoumenoi/ProvoliTrexontonFiloksenoumenonController.java |
1,844 | package com.example.billy.cainstructionquiz;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.math.RoundingMode;
import java.security.SecureRandom;
import java.text.DecimalFormat;
public class QuizActivity extends AppCompatActivity {
private static final String TAG = "button";
private static final String ADDBTN = "addButton";
private static final String SUBBTN = "subButton";
private static final String MULTBTN = "multButton";
private static final String DIVBTN = "divButton";
private static final String QUESTION = "Πόσο κάνει ";
private static final String ADDACTION = " σύν ";
private static final String SUBACTION = " μείον ";
private static final String MULTACTION = " επί ";
private static final String DIVACTION = " διά ";
private static final String QUESTIONMARK = ";";
private static final String WINMESSAGE = "Μπράβο!";
private static final String LOSEMESSAGE = "Προσπάθησε ξανά, αυτή την φόρα θα τα καταφέρεις!";
private static final String ERRORMESSAGE = "Προσπάθησε ξανά, έδωσες λάθος αριθμό!";
private static final String EASY = "Εύκολο";
private static final String MEDIUM = "Μέτριο";
private static final String HARD = "Δύσκολο";
private SecureRandom random = new SecureRandom();
private int number1;
private int number2;
private int rightAnswers;
private int rightAddAnswers;
private int rightSubAnswers;
private int rightMultAnswers;
private int rightDivAnswers;
private int wrongAnswers;
private int wrongAddAnswers;
private int wrongSubAnswers;
private int wrongMultAnswers;
private int wrongDivAnswers;
private String action="";
private TextView questionTxtView;
private EditText answerEditText;
private Animation shakeAnimation;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
private String difficulty;
private String background_color;
@Override
protected void onResume() {
super.onResume();
String background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.RED);
RelativeLayout rl = (RelativeLayout) findViewById(R.id.activity_quiz);
switch(background_color){
case MainActivity.GREEN: rl.setBackgroundResource(R.drawable.blackboard_background_green); break;
case MainActivity.RED: rl.setBackgroundResource(R.drawable.blackboard_background_red); break;
case MainActivity.BLUE: rl.setBackgroundResource(R.drawable.blackboard_background_blue); break;
case MainActivity.PINK: rl.setBackgroundResource(R.drawable.blackboard_background_pink); break;
case MainActivity.PURPLE: rl.setBackgroundResource(R.drawable.blackboard_background_purple); break;
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
background_color = sharedPref.getString(MainActivity.COLOR, MainActivity.GREEN);
switch(background_color){
case MainActivity.GREEN: setTheme(R.style.AppTheme_Green); break;
case MainActivity.RED: setTheme(R.style.AppTheme_Red); break;
case MainActivity.BLUE: setTheme(R.style.AppTheme_Blue); break;
case MainActivity.PINK: setTheme(R.style.AppTheme_Pink); break;
case MainActivity.PURPLE: setTheme(R.style.AppTheme_Purple); break;
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
//Αρχικοποίηση του animation του κουμπιού
shakeAnimation = AnimationUtils.loadAnimation(getApplicationContext(),R.anim.shake_effect);
questionTxtView = (TextView) findViewById(R.id.questionTxtView);
answerEditText = (EditText) findViewById(R.id.answerEditText);
//KeyListener για να τρέχει την συνάρτηση υπολογισμού και με το πλήκτρο enter.
answerEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
checkProcess();
return true;
}
return false;
}
});
//Αρχικοποίηση του Default SharedPreference Manager και Editor
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
editor = sharedPref.edit();
//Εισαγωγή των μεταβλητών από τα SharedPreferrence για τα στατιστικά του παιχνιδιού
int defaultValue = getResources().getInteger(R.integer.answers_default);
rightAnswers = sharedPref.getInt(getString(R.string.right_answers), defaultValue);
rightAddAnswers = sharedPref.getInt(getString(R.string.right_add_answers), defaultValue);
rightSubAnswers = sharedPref.getInt(getString(R.string.right_sub_answers), defaultValue);
rightMultAnswers = sharedPref.getInt(getString(R.string.right_mult_answers), defaultValue);
rightDivAnswers = sharedPref.getInt(getString(R.string.right_div_answers), defaultValue);
wrongAnswers = sharedPref.getInt(getString(R.string.wrong_answers), defaultValue);
wrongAddAnswers = sharedPref.getInt(getString(R.string.wrong_add_answers), defaultValue);
wrongSubAnswers = sharedPref.getInt(getString(R.string.wrong_sub_answers), defaultValue);
wrongMultAnswers = sharedPref.getInt(getString(R.string.wrong_mult_answers), defaultValue);
wrongDivAnswers = sharedPref.getInt(getString(R.string.wrong_div_answers), defaultValue);
//Εισαγωγή της μεταβλητής από τα SharedPreferrence για την δυσκολία του παιχνιδιού
//Σε περίπτωση προβλήματος με την μεταβλητή του SharedPreferrence για την δυσκολία να βάζει αυτόματα εύκολο
difficulty = sharedPref.getString(MainActivity.DIFFICULTY, EASY);
//Αρχικοποίηση των αριθμών για την πράξη βάση της δυσκολίας
setRandoms();
//Εύρεση πράξης από τα στοιχεία που προήρθαν από το προηγούμενο Activity
String buttonString="";
Intent i = getIntent();
Bundle b = i.getExtras();
if(b!=null) {
buttonString = (String) b.get(TAG);
}
switch(buttonString){
case ADDBTN: action=ADDACTION; break;
case SUBBTN: action=SUBACTION; break;
case MULTBTN: action=MULTACTION; break;
case DIVBTN: action=DIVACTION; break;
}
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void setRandoms(){
switch(difficulty){
case EASY:
number1 = random.nextInt(10 - 1) + 1;
number2 = random.nextInt(10 - 1) + 1;
break;
case MEDIUM:
number1 = random.nextInt(100 - 1) + 1;
number2 = random.nextInt(100 - 1) + 1;
break;
case HARD:
number1 = random.nextInt(1000 - 1) + 1;
number2 = random.nextInt(1000 - 1) + 1;
break;
}
}
// Η συνάρτηση dialog παίρνει μια μεταβλητή integer οπού όταν είναι 0 σημαίνει ότι είναι νικητήριο dialog και όταν είναι 1 είναι ηττημένο dialog
// ενώ όταν είναι -1 (ή οποιοσδήποτε άλλος ακέραιος) σημαίνει οτι υπήρξε κάποιο πρόβλημα με τον αριθμό.
private void dialog(int win_or_lose){
final Dialog dialog = new Dialog(QuizActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.custom_dialog);
TextView text = (TextView) dialog.findViewById(R.id.textView);
ImageView image = (ImageView) dialog.findViewById(R.id.image);
if(win_or_lose==0){
text.setText(WINMESSAGE);
rightAnswers++;
editor.putInt(getString(R.string.right_answers), rightAnswers);
image.setImageResource(R.drawable.star);
final MediaPlayer mediaPlayer = MediaPlayer.create(QuizActivity.this, R.raw.tada);
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
mp.release();
}
});
}else if (win_or_lose==1){
image.setImageResource(R.drawable.sad_face);
text.setText(LOSEMESSAGE);
wrongAnswers++;
editor.putInt(getString(R.string.wrong_answers), wrongAnswers);
}else{
image.setImageResource(R.drawable.error_icon);
text.setText(ERRORMESSAGE);
}
editor.commit();
dialog.show();
Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
}, 5000);
}
private void resetValues(){
setRandoms();
answerEditText.setText("");
questionTxtView.setText(QUESTION+String.valueOf(number1)+action+String.valueOf(number2)+QUESTIONMARK);
}
private void checkProcess(){
DecimalFormat df = new DecimalFormat("#.#");
df.setRoundingMode(RoundingMode.HALF_UP);
int counter = 0;
for( int i=0; i<answerEditText.getText().toString().length(); i++ ) {
if( answerEditText.getText().toString().charAt(i) == '.' || answerEditText.getText().toString().charAt(i) == ',') {
counter++;
}
}
if(counter==0 || counter==1) {
String answer_string = df.format(Double.parseDouble(answerEditText.getText().toString())).replace(',','.');
double answer = Double.parseDouble(answer_string);
switch (action) {
case ADDACTION:
if (answer == (number1 + number2)) {
dialog(0);
resetValues();
rightAddAnswers++;
editor.putInt(getString(R.string.right_add_answers), rightAddAnswers);
} else {
dialog(1);
wrongAddAnswers++;
editor.putInt(getString(R.string.wrong_add_answers), wrongAddAnswers);
}
break;
case SUBACTION:
if (answer == (number1 - number2)) {
dialog(0);
resetValues();
rightSubAnswers++;
editor.putInt(getString(R.string.right_sub_answers), rightSubAnswers);
} else {
dialog(1);
wrongSubAnswers++;
editor.putInt(getString(R.string.wrong_sub_answers), wrongSubAnswers);
}
break;
case MULTACTION:
if (answer == (number1 * number2)) {
dialog(0);
resetValues();
rightMultAnswers++;
editor.putInt(getString(R.string.right_mult_answers), rightMultAnswers);
} else {
dialog(1);
wrongMultAnswers++;
editor.putInt(getString(R.string.wrong_mult_answers), wrongMultAnswers);
}
break;
case DIVACTION:
if (answer == Double.parseDouble(df.format((double) number1 / number2).replace(',','.'))) {
dialog(0);
resetValues();
rightDivAnswers++;
editor.putInt(getString(R.string.right_div_answers), rightDivAnswers);
} else {
dialog(1);
wrongDivAnswers++;
editor.putInt(getString(R.string.wrong_div_answers), wrongDivAnswers);
}
break;
}
editor.commit();
}else {
dialog(-1);
}
}
public void checkButtonPressed(View v){
v.startAnimation(shakeAnimation);
checkProcess();
}
}
| Billeclipse/C.A.InstructionQuiz-Project | CAInstructionQuiz/app/src/main/java/com/example/billy/cainstructionquiz/QuizActivity.java |
1,845 | /* LanguageTool, a natural language style checker
* Copyright (C) 2005 Daniel Naber (http://www.danielnaber.de)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package org.languagetool.rules.el;
import org.junit.Before;
import org.junit.Test;
import org.languagetool.JLanguageTool;
import org.languagetool.TestTools;
import org.languagetool.language.Greek;
import org.languagetool.rules.RuleMatch;
import java.io.IOException;
import static org.junit.Assert.assertEquals;
/**
* ReplaceHomonymsRule TestCase.
*
* @author Nikos-Antonopoulos
*
*/
public class ReplaceHomonymsRuleTest {
private ReplaceHomonymsRule rule;
private JLanguageTool langTool;
@Before
public void setUp() throws IOException {
rule = new ReplaceHomonymsRule(TestTools.getMessages("el"), new Greek());
langTool = new JLanguageTool(new Greek());
}
// correct sentences
@Test
public void testRule() throws IOException {
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Στην Ελλάδα επικρατεί εύκρατο κλίμα.")).length);
assertEquals(0, rule.match(langTool.getAnalyzedSentence("Καλή τύχη σου εύχομαι.")).length);
}
// test for a wrong usage of a word inside a sentence
@Test
public void testRuleInsideOfSentence() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence("Του ευχήθηκα καλή τείχη για το διαγώνισμα."));
assertEquals(1, matches.length);
assertEquals("καλή τύχη", matches[0].getSuggestedReplacements().get(0));
}
// test for a wrong usage of a word in the beggining of a sentence.
@Test
public void testRuleBegginingOfSentence() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
"Τεχνητό κόμμα είναι μια ακραία μορφή αναισθησίας."));
assertEquals(1, matches.length);
assertEquals("Τεχνητό κώμα", matches[0].getSuggestedReplacements().get(0));
}
// test for a wrong usage of a word in the beggining of a sentence while capitalizing letter if needed.
@Test
public void testRuleWithCapitalization() throws IOException {
RuleMatch[] matches = rule.match(langTool.getAnalyzedSentence(
"γάλος πρόεδρος."));
assertEquals(1, matches.length);
assertEquals("Γάλλος πρόεδρος", matches[0].getSuggestedReplacements().get(0));
}
}
| languagetool-org/languagetool | languagetool-language-modules/el/src/test/java/org/languagetool/rules/el/ReplaceHomonymsRuleTest.java |
1,846 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.Ofeloumenoi;
import java.io.IOException;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class MultipleSearchResultsController implements Initializable {
@FXML
public Button backButton;
@FXML
private TableView <tableManager> resultTable;
@FXML
private TableColumn <tableManager, Integer> colId;
@FXML
private TableColumn <tableManager, String> colBarcode;
@FXML
private TableColumn <tableManager, String> colOnoma;
@FXML
private TableColumn <tableManager, String> colEponimo;
@FXML
private TableColumn <tableManager, String> colTilefono;
@FXML
private TableColumn <tableManager, String> colAfm;
@FXML
private TableColumn <tableManager, String> colTautotita;
private ObservableList <tableManager> data;
ResultSet rs = sopho.ResultKeeper.rs;
sopho.LockEdit le = new sopho.LockEdit();
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing result table
data = getInitialTableData();
//filling table with data
resultTable.setItems(data);
colId.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
colBarcode.setCellValueFactory(new PropertyValueFactory<tableManager, String>("barcode"));
colOnoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
colEponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
colTilefono.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tilefono"));
colAfm.setCellValueFactory(new PropertyValueFactory<tableManager, String>("afm"));
colTautotita.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tautotita"));
//setting the data to the table
resultTable.getColumns().setAll(colId, colBarcode, colOnoma, colEponimo, colTilefono, colAfm, colTautotita);
}
sopho.StageLoader sl = new sopho.StageLoader();
@FXML
public void GoBack (ActionEvent event) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad(sopho.StageLoader.lastStage, stage, true, false); //resizable true, utility false
}
@FXML
public void Select (ActionEvent event) throws IOException{
try {
int sel = resultTable.getSelectionModel().getSelectedIndex();
if (sel==-1){
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Πρέπει να επιλέξετε τουλάχιστον έναν ωφελούμενο από τη λίστα με τα αποτελέσματα!", "error");
cm.showAndWait();
}else{
//loading selected row data to variables.
sopho.ResultKeeper.selectedIndex = sel;
Stage stage = (Stage) backButton.getScene().getWindow();
//now we have to make some distinctions because we use the same stage for two different purposes.
if (sopho.StageLoader.lastStage.equals("/sopho/Ofeloumenoi/OfeloumenoiMain.fxml")) {
tableManager tbl = resultTable.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "ofeloumenoi")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "ofeloumenoi")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
sl.StageLoad("/sopho/Ofeloumenoi/EditOfeloumenoi.fxml", stage, true, false); //resizable true, utility false.
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο ωφελούμενο. Βεβαιωθείτε ότι η καρτέλα του ωφελούμενου δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}else if(sopho.StageLoader.lastStage.equals("/sopho/Eidi/EidiMain.fxml")){
sopho.ResultKeeper.selectedIndex=sel;
sl.StageLoad("/sopho/Eidi/EidiDothikan.fxml", stage, true, false); //resizable true, utility false.
}
}
}catch(Exception e){
System.out.println("table selection error " + e);
}
}
public static class tableManager { //this is a helper class to display the data from the resultSet to the table properly.
private IntegerProperty id;
private StringProperty barcode;
private StringProperty onoma;
private StringProperty eponimo;
private StringProperty tilefono;
private StringProperty afm;
private StringProperty tautotita;
public tableManager(){}
private tableManager(Integer id, String barcode, String onoma, String eponimo, String tilefono, String afm, String tautotita ){
this.id = new SimpleIntegerProperty(id);
this.barcode = new SimpleStringProperty(barcode);
this.onoma = new SimpleStringProperty(onoma);
this.eponimo = new SimpleStringProperty(eponimo);
this.tilefono = new SimpleStringProperty(tilefono);
this.afm = new SimpleStringProperty(afm);
this.tautotita = new SimpleStringProperty(tautotita);
}
//the following get and set methods are required. Else the table cells will appear blank
public Integer getId(){
return id.get();
}
public String getBarcode(){
return barcode.get();
}
public String getOnoma(){
return onoma.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getTilefono(){
return tilefono.get();
}
public String getAfm(){
return afm.get();
}
public String getTautotita(){
return tautotita.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
//we have to add the values from database to the table
try{
rs.beforeFirst();
while(rs.next()){
list.add(new tableManager( rs.getInt("id"), rs.getString("barcode"), rs.getString("onoma"), rs.getString("eponimo"), rs.getString("tilefono"), rs.getString("afm"), rs.getString("tautotita")));
}
} catch (SQLException ex) {
Logger.getLogger(MultipleSearchResultsController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/Ofeloumenoi/MultipleSearchResultsController.java |
1,847 | /*
* /* ---------------------------------------------LICENSE-----------------------------------------------------
* *
* *YOU ARE NOT ALLOWED TO MODIFY THE LICENSE OR DELETE THE LICENSE FROM THE FILES
* *
* *This is an open source project hosted at github: https://github.com/ellak-monades-aristeias/Sopho
* *
* *This application is distributed with the following license:
* *code with license EUPL v1.1 and content with license CC-BY-SA 4.0.
* *
* *The development of the application is funded by EL/LAK (http://www.ellak.gr)
* *
* *
*/
package sopho.MathimataStiriksis;
import java.io.IOException;
import java.net.URL;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Stage;
public class ListaMathitonController implements Initializable {
@FXML
public Button backButton;
@FXML
public TableView<tableManager> table;
@FXML
public TableColumn<tableManager, String> eponimo, onoma, patronimo, dieuthinsi, tilefono, mathimata;
@FXML
public TableColumn<tableManager, Integer> id;
private ObservableList<tableManager> data;
sopho.StageLoader sl = new sopho.StageLoader();
sopho.LockEdit le = new sopho.LockEdit();
@Override
public void initialize(URL url, ResourceBundle rb) {
//initialzing table
data = getInitialTableData();
table.setItems(data);
id.setCellValueFactory(new PropertyValueFactory<tableManager, Integer>("id"));
eponimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("eponimo"));
onoma.setCellValueFactory(new PropertyValueFactory<tableManager, String>("onoma"));
patronimo.setCellValueFactory(new PropertyValueFactory<tableManager, String>("patronimo"));
tilefono.setCellValueFactory(new PropertyValueFactory<tableManager, String>("tilefono"));
dieuthinsi.setCellValueFactory(new PropertyValueFactory<tableManager, String>("dieuthinsi"));
mathimata.setCellValueFactory(new PropertyValueFactory<tableManager, String>("mathimata"));
table.getColumns().setAll(id, eponimo, onoma, patronimo, tilefono, dieuthinsi, mathimata);
//end of initialization of table
}
@FXML
public void GoBack(ActionEvent e) throws IOException{
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/MathimataStiriksis/MathimataMain.fxml", stage, false, true); //resizable false, utility true
}
@FXML
public void Select(ActionEvent e) throws IOException, SQLException{
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε ένα μαθητή από τον πίνακα.", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
int id = tbl.getId();
if(!le.CheckLock(id, "mathites")){//check if editing is locked because another user is currently editing the data.
if (!le.LockEditing(true, id, "mathites")){//check if lock editing is successful else display message about it
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Πρόβλημα", "Τα στοιχεία του ατόμου που επιλέξατε δεν μπόρεσαν να κλειδωθούν για επεξεργασία. Αυτό σημαίνει ότι μπορεί να επεξεργαστεί και άλλος χρήστης παράλληλα τα ίδια στοιχεία και να διατηρηθούν οι αλλαγές που θα αποθηκεύσει ο άλλος χρήστης. Μπορείτε να επεξεργαστείτε τα στοιχεία ή να βγείτε και να μπείτε και πάλι στα στοιχεία για να κλειδώσουν.", "error");
cm.showAndWait();
}
sopho.ResultKeeper.selectedIndex=sel;
Stage stage = (Stage) backButton.getScene().getWindow();
sl.StageLoad("/sopho/MathimataStiriksis/EpeksergasiaMathiti.fxml", stage, true, false); //resizable true, utility false
}else{
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Κάποιος άλλος χρήστης επεξεργάζεται αυτή τη στιγμή τον επιλεγμένο μαθητή. Βεβαιωθείτε ότι η καρτέλα του μαθητή δεν είναι ανοιχτή σε κάποιον άλλον υπολογιστή και προσπαθήστε και πάλι.", "error");
cm.showAndWait();
}
}
}
@FXML
public void Delete(ActionEvent e){
int sel = table.getSelectionModel().getSelectedIndex();
if(sel==-1){
//the user did not select a line
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Προσοχή!", "Θα πρέπει να επιλέξετε ενα μαθητή από τον πίνακα για να διαγράψετε!", "error");
cm.showAndWait();
}else{
tableManager tbl = table.getSelectionModel().getSelectedItem();
sopho.Messages.CustomMessageController cm = new sopho.Messages.CustomMessageController(null, "Είστε σίγουροι;", "Θέλετε σίγουρα να διαγράψετε το μαθητή: "+tbl.getEponimo()+" "+tbl.getOnoma()+" από τη λίστα των μαθητών; Δεν θα μπορείτε να ανακτήσετε τα στοιχεία του μαθητή αυτού στη συνέχεια...", "question");
cm.showAndWait();
if(cm.saidYes){
int idNumber = tbl.getId();
String sql="DELETE FROM mathites WHERE id = ?";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn = db.ConnectDB();
try {
pst = conn.prepareStatement(sql);
pst.setInt(1,idNumber);
int flag = pst.executeUpdate();
if(flag<=0){
sopho.Messages.CustomMessageController cm2 = new sopho.Messages.CustomMessageController(null, "Πρόβλημα!", "Δεν μπόρεσε να διαγραφεί ο μαθητής από τη βάση δεδομένων", "error");
cm2.showAndWait();
}else{
//get the new rs and set the table again
//this prevents the bug of deleting a line from the table and passing the oldrs to the ResultKeeper. If the oldrs was passed and the new selectedIndex was passed to ResultKeeper the selected row of rs would not correspond to the table row because the rs would have also the deleted row of the table.
data = getInitialTableData();
table.setItems(data);
}
} catch (SQLException ex) {
Logger.getLogger(ListaMathitonController.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
public class tableManager {
private SimpleIntegerProperty id;
private SimpleStringProperty eponimo;
private SimpleStringProperty onoma;
private SimpleStringProperty patronimo;
private SimpleStringProperty dieuthinsi;
private SimpleStringProperty tilefono;
private SimpleStringProperty mathimata;
public tableManager(){}
public tableManager(Integer id, String eponimo, String onoma, String patronimo, String dieuthinsi, String tilefono, String mathimata){
this.id = new SimpleIntegerProperty(id);
this.eponimo = new SimpleStringProperty(eponimo);
this.onoma = new SimpleStringProperty(onoma);
this.patronimo = new SimpleStringProperty(patronimo);
this.dieuthinsi = new SimpleStringProperty(dieuthinsi);
this.tilefono = new SimpleStringProperty(tilefono);
this.mathimata = new SimpleStringProperty(mathimata);
}
public Integer getId(){
return id.get();
}
public String getEponimo(){
return eponimo.get();
}
public String getOnoma(){
return onoma.get();
}
public String getPatronimo(){
return patronimo.get();
}
public String getDieuthinsi(){
return dieuthinsi.get();
}
public String getTilefono(){
return tilefono.get();
}
public String getMathimata(){
return mathimata.get();
}
}
//this is required to get the initial data from the table and push them to an observableList.
private ObservableList<tableManager> getInitialTableData(){
List<tableManager> list = new ArrayList<>();
try {
String sql = "SELECT * FROM mathites";
sopho.DBClass db = new sopho.DBClass();
Connection conn=null;
PreparedStatement pst = null;
ResultSet rs = null;
conn=db.ConnectDB();
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
sopho.ResultKeeper.rs=rs;
rs.last();
if(rs.getRow()>0){
rs.beforeFirst();
while(rs.next()){
// we can add data to the initial table using the following command
list.add(new tableManager(rs.getInt("id"), rs.getString("eponimo"), rs.getString("onoma"), rs.getString("patronimo"), rs.getString("dieuthinsi"), rs.getString("tilefono"), rs.getString("mathimata")));
}
}
} catch (SQLException ex) {
Logger.getLogger(ListaMathitonController.class.getName()).log(Level.SEVERE, null, ex);
}
ObservableList<tableManager> mydata = FXCollections.observableList(list);
return mydata;
}
}
| ellak-monades-aristeias/Sopho | src/sopho/MathimataStiriksis/ListaMathitonController.java |
1,856 | package gr.rambou.myicarus;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
public class LoginActivity extends Activity {
private SessionManager session;
private Animation moveRight;
private Animation moveLeft;
private ImageView im;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
im = (ImageView) findViewById(R.id.sun);
ImageView waves = (ImageView) findViewById(R.id.waves);
ImageView icarus = (ImageView) findViewById(R.id.icarus);
// load the animation
moveRight = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.moveright);
moveLeft = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.moveleft);
waves.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.waves));
icarus.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.icarus));
ProgressBar spinner = (ProgressBar)findViewById(R.id.progressBar);
// Session Manager
session = new SessionManager(getApplicationContext());
String username = session.getUserDetails().get(SessionManager.KEY_NAME);
String password = session.getUserDetails().get(SessionManager.KEY_PASSWORD);
if(username!=null) {
if (!username.toString().isEmpty()) {
new Login().execute(username.toString(), password.toString());
}
}
((TextView) findViewById(R.id.Username)).setText(username);
}
public void Login_Clicked(View view) {
hideKeyboard();
im.startAnimation(moveRight);
//Take components from xml
TextView username = (TextView) findViewById(R.id.Username);
TextView password = (TextView) findViewById(R.id.Password);
new Login().execute(username.getText().toString(),password.getText().toString());
}
private void hideKeyboard() {
// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
private void loading(boolean load){
TextView username = (TextView) findViewById(R.id.Username);
TextView password = (TextView) findViewById(R.id.Password);
Button login = (Button) findViewById(R.id.Login);
ProgressBar spinner = (ProgressBar)findViewById(R.id.progressBar);
if(load){
spinner.setVisibility(View.VISIBLE);
username.setVisibility(View.INVISIBLE);
password.setVisibility(View.INVISIBLE);
login.setVisibility(View.INVISIBLE);
}else{
spinner.setVisibility(View.INVISIBLE);
username.setVisibility(View.VISIBLE);
password.setVisibility(View.VISIBLE);
login.setVisibility(View.VISIBLE);
}
}
// Title AsyncTask
private class Login extends AsyncTask<String, Void, Boolean> {
Icarus myicarus;
String username, password;
@Override
protected void onPreExecute() {
loading(true);
}
@Override
protected Boolean doInBackground(String... params) {
System.setProperty("jsse.enableSNIExtension", "false");
username = params[0];
password = params[1];
myicarus = new Icarus(username, password);
return myicarus.login();
}
@Override
protected void onPostExecute(Boolean result) {
if(!result){
TextView error = (TextView) findViewById(R.id.ErrorMsg);
error.setText(getString(R.string.Error_Login));
error.setVisibility(View.VISIBLE);
loading(false);
im.startAnimation(moveLeft);
}else{
session.createLoginSession(username, password);
Intent i = new Intent(LoginActivity.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putSerializable("icarus", myicarus);
i.putExtras(bundle);
// Closing all the Activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i); //Στην onCreate της MainActivity κάνω retrieve το object Icarus - φτιάξε τα υπόλοιπα, δες τι έκανε και ο Χάρης
LoginActivity.this.finish();
}
}
}
}
| AegeanHawks/MobileIcarus | app/src/main/java/gr/rambou/myicarus/LoginActivity.java |
1,858 | package csd.uoc.gr.view;
import csd.uoc.gr.model.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;
import java.time.DayOfWeek;
/**
* @author Konstantinos Ntavarinos
* <p>The GraphicUI class is responsible for every frame/button the user sees on the screen,
* also is responsible for updating the panel after an event.</p>
*/
public class GraphicUI extends JFrame{
private JButton player1RollDice;
private JButton player1MyDealCards;
private JButton player1GetLoan;
private JButton player1EndTurn;
private JButton player2RollDice;
private JButton player2MyDealCards;
private JButton player2GetLoan;
private JButton player2EndTurn;
private JButton getDealCard;
private JButton getMailCard;
private JLabel[] days;
private JLabel player1DiceImage;
private JLabel player2DiceImage;
private JLabel jackpotPrize;
private JLabel[] imagesPosition;
private JLabel player1Name;
private JLabel player1Money;
private JLabel player1Loan;
private JLabel player1Bills;
private JLabel player2Name;
private JLabel player2Money;
private JLabel player2Loan;
private JLabel player2Bills;
private JLabel bluePawn;
private JLabel yellowPawn;
private JPanel player1Card;
private JPanel player2Card;
private int currentCard = 0;
private JTextArea infobox;
private final ClassLoader cldr;
private JLayeredPaneExtension mainPanel;
/**
* <b>constructor</b>: Creates a new window, initializes Buttons/Panels/Labels/Images.<br />
* <b>Post conditions</b>: A new window is created with button, panels, labels and images.
*/
public GraphicUI() {
cldr = this.getClass().getClassLoader();
this.setResizable(false);
this.setTitle("PayDay");
this.setPreferredSize(new Dimension(1333, 1000));
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
public void initButtons(){
getDealCard = new JButton();
URL dealCardURL = cldr.getResource("csd/uoc/gr/resources/gameImages/dealCard.png");
assert dealCardURL != null;
Image dealCardImage = new ImageIcon(dealCardURL).getImage();
getDealCard.setIcon(new ImageIcon(dealCardImage));
getDealCard.setBounds(1095, 505,185,95);
getMailCard = new JButton();
URL mailCardURL = cldr.getResource("csd/uoc/gr/resources/gameImages/mailCard.png");
assert mailCardURL != null;
Image mailCardImage = new ImageIcon(mailCardURL).getImage();
getMailCard.setIcon(new ImageIcon(mailCardImage));
getMailCard.setBounds(885, 505, 185, 95);
player1RollDice = new JButton("Roll Dice");
player1RollDice.setBounds(5,210, 180, 30);
player1RollDice.setFont(new Font("Plain",Font.PLAIN,16));
player1MyDealCards = new JButton("My Deal Cards");
player1MyDealCards.setBounds(5,245,180,30);
player1MyDealCards.setFont(new Font("Plain", Font.PLAIN, 16));
player1GetLoan = new JButton("Get Loan");
player1GetLoan.setBounds(5,280,180,30);
player1GetLoan.setFont(new Font("Plain", Font.PLAIN, 16));
player1EndTurn = new JButton("End Turn");
player1EndTurn.setBounds(190,280,180,30);
player1EndTurn.setFont(new Font("Plain", Font.PLAIN, 16));
player1RollDice.setName("RollDice1");
player1MyDealCards.setName("MyDealCards1");
player1GetLoan.setName("GetLoan1");
player1EndTurn.setName("EndTurn1");
player1Card.add(player1Name);
player1Card.add(player1Money);
player1Card.add(player1Loan);
player1Card.add(player1Bills);
player1Card.add(player1RollDice);
player1Card.add(player1MyDealCards);
player1Card.add(player1GetLoan);
player1Card.add(player1EndTurn);
player2RollDice = new JButton("Roll Dice");
player2RollDice.setBounds(5,210, 180, 30);
player2RollDice.setFont(new Font("Plain",Font.PLAIN,16));
player2MyDealCards = new JButton("My Deal Cards");
player2MyDealCards.setBounds(5,245,180,30);
player2MyDealCards.setFont(new Font("Plain", Font.PLAIN, 16));
player2GetLoan = new JButton("Get Loan");
player2GetLoan.setBounds(5,280,180,30);
player2GetLoan.setFont(new Font("Plain", Font.PLAIN, 16));
player2EndTurn = new JButton("End Turn");
player2EndTurn.setBounds(190,280,180,30);
player2EndTurn.setFont(new Font("Plain", Font.PLAIN, 16));
player2RollDice.setName("RollDice2");
player2MyDealCards.setName("MyDealCards2");
player2GetLoan.setName("GetLoan2");
player2EndTurn.setName("EndTurn2");
player2Card.add(player2Name);
player2Card.add(player2Money);
player2Card.add(player2Loan);
player2Card.add(player2Bills);
player2Card.add(player2RollDice);
player2Card.add(player2MyDealCards);
player2Card.add(player2GetLoan);
player2Card.add(player2EndTurn);
getDealCard.setName("DealCard");
getMailCard.setName("MailCard");
mainPanel.add(getDealCard);
mainPanel.add(getMailCard);
mainPanel.repaint();
}
/**
* <b>transformer</b>: Initialises the board tiles.<br/>
* <b>Pre condition</b>: boardImages not null.<br/>
* <b>Post condition</b>: Initialises the board tiles with the boardImages.
* @param boardImages Array of Tiles which contains images and more.
*/
public void initBoardTiles(ArrayList<Tile> boardImages){
URL imageURL = cldr.getResource("csd/uoc/gr/resources/gameImages/bg_greenFix.png");
assert imageURL != null;
Image background = new ImageIcon(imageURL).getImage();
mainPanel = new JLayeredPaneExtension(background);
this.setLocation(300,0 );
URL logoURL = cldr.getResource("csd/uoc/gr/resources/gameImages/logo.png");
assert logoURL != null;
Image logoImage = new ImageIcon(logoURL).getImage();
JLabel payDayLogo = new JLabel();
payDayLogo.setIcon(new ImageIcon(logoImage));
payDayLogo.setBounds(0,0,840,240);
mainPanel.add(payDayLogo,0);
imagesPosition = new JLabel[32];
int element = 0;
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(boardImages.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 255, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(boardImages.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 400, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(boardImages.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 545, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(boardImages.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 690, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 4; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(boardImages.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 835, 120,140);
mainPanel.add(imagesPosition[element]);
}
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(mainPanel, GroupLayout.PREFERRED_SIZE,1333, GroupLayout.PREFERRED_SIZE));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(mainPanel, GroupLayout.PREFERRED_SIZE,1000, GroupLayout.PREFERRED_SIZE));
pack();
mainPanel.repaint();
}
/**
* <b>transformer</b>: Initialises the days on the board.<br/>
* <b>Post Condition</b>: Adds the days the the board.<br/>
*/
public void initDays(){
int thisDay = 0;
String dayName;
days = new JLabel[32];
days[thisDay] = new JLabel("Start",JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds(0,240,120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
thisDay++;
for(int counter = 1; counter < 7; counter++,thisDay++){
dayName = DayOfWeek.of(counter).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds((counter * 120), 240, 120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
}
dayName = DayOfWeek.of(7).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds(0, 385, 120,25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
thisDay++;
for(int counter = 1; counter < 7; counter++,thisDay++){
dayName = DayOfWeek.of(counter).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds((counter * 120), 385, 120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
}
dayName = DayOfWeek.of(7).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds(0,530,120,25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[14]);
thisDay++;
for(int counter = 1; counter < 7; counter++,thisDay++){
dayName = DayOfWeek.of(counter).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds((counter * 120), 530, 120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
}
dayName = DayOfWeek.of(7).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds(0,675,120,25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
thisDay++;
for(int counter = 1; counter < 7; counter++,thisDay++){
dayName = DayOfWeek.of(counter).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds((counter * 120), 675, 120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
}
dayName = DayOfWeek.of(7).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds(0,820,120,25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
thisDay++;
for(int counter = 1; counter < 4; counter++,thisDay++){
dayName = DayOfWeek.of(counter).toString().toLowerCase();
days[thisDay] = new JLabel(dayName.substring(0,1).toUpperCase()
+ dayName.substring(1) + " " + thisDay, JLabel.CENTER);
days[thisDay].setBackground(Color.YELLOW);
days[thisDay].setOpaque(true);
days[thisDay].setBounds((counter * 120), 820, 120, 25);
days[thisDay].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.LIGHT_GRAY));
days[thisDay].setFont(new Font(Font.MONOSPACED, Font.BOLD, 15));
mainPanel.add(days[thisDay]);
}
mainPanel.repaint();
}
/**
* <b>transformer</b>: Initialises the player card info panel with the current parameters.<br>
* <b>Pre condition</b>: player, money, loan, bills not 0.<br>
* <b>Post condition</b>: Initialises player card info.
* @param player_One_Name first Players Name.
* @param player_Two_Name second Players Name.
* @param money players money.
* @param loan players loan.
* @param bills players bills.
*/
public void initPlayerCards(String player_One_Name, String player_Two_Name, int money, int loan, int bills) {
player1Card = new JPanel();
player1Card.setLayout(null);
player1Card.setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.BLUE));
player1Card.setBackground(Color.decode("0xEEEEEE"));
player1Card.setBounds(885,30,395,320);
player1Name = new JLabel(player_One_Name);
player1Name.setBounds(155,0,300,30);
player1Name.setForeground(Color.BLACK);
player1Name.setFont(new Font(Font.MONOSPACED, Font.BOLD, 24));
player1Money = new JLabel("Money : " + money + " Ευρώ");
player1Money.setForeground(Color.BLACK);
player1Money.setBounds(5,50,300,30);
player1Money.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
player1Loan = new JLabel("Loan : " + loan + " Ευρώ");
player1Loan.setForeground(Color.BLACK);
player1Loan.setBounds(5,80,300,30);
player1Loan.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
player1Bills = new JLabel("Bills : " + bills + " Ευρώ");
player1Bills.setForeground(Color.BLACK);
player1Bills.setBounds(5,110,300,30);
player1Bills.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
player2Card = new JPanel();
player2Card.setLayout(null);
player2Card.setBackground(Color.decode("0xEEEEEE"));
player2Card.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.RED));
player2Card.setBounds(885,620,395,320);
player2Name = new JLabel(player_Two_Name);
player2Name.setBounds(155,0,300,30);
player2Name.setForeground(Color.BLACK);
player2Name.setFont(new Font(Font.MONOSPACED, Font.BOLD, 24));
player2Money = new JLabel("Money : " + money + " Ευρώ");
player2Money.setForeground(Color.BLACK);
player2Money.setBounds(5,50,300,30);
player2Money.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
player2Loan = new JLabel("Loan : " + loan + " Ευρώ");
player2Loan.setForeground(Color.BLACK);
player2Loan.setBounds(5,80,300,30);
player2Loan.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
player2Bills = new JLabel("Bills : " + bills + " Ευρώ");
player2Bills.setForeground(Color.BLACK);
player2Bills.setBounds(5,110,300,30);
player2Bills.setFont(new Font(Font.MONOSPACED, Font.BOLD, 20));
mainPanel.add(player1Card);
mainPanel.add(player2Card);
mainPanel.repaint();
}
/**
* <b>transformer</b>: Initialises the images of the pawns and the position.<br/>
* <b>Pre condition</b>: pathPawn1, pathPawn2, not null and position1, position2 == 0.<br/>
* <b>Post condition</b>: Creates the pawns.
*/
public void initPawns(){
bluePawn = new JLabel();
URL bluePawnURL = cldr.getResource("csd/uoc/gr/resources/gameImages/pawn_blue.png");
assert bluePawnURL != null;
Image bluePawnImage = new ImageIcon(bluePawnURL).getImage();
bluePawn.setIcon(new ImageIcon(bluePawnImage));
bluePawn.setBounds(imagesPosition[0].getX() + 55, imagesPosition[0].getY(), imagesPosition[0].getWidth(), imagesPosition[0].getHeight());
bluePawn.setOpaque(false);
mainPanel.add(bluePawn, 1);
yellowPawn = new JLabel();
URL yellowPawnURL = cldr.getResource("csd/uoc/gr/resources/gameImages/pawn_yellow.png");
assert yellowPawnURL != null;
Image yellowPawnImage = new ImageIcon(yellowPawnURL).getImage();
yellowPawn.setIcon(new ImageIcon(yellowPawnImage));
yellowPawn.setBounds(imagesPosition[0].getBounds());
yellowPawn.setOpaque(false);
mainPanel.add(yellowPawn, 1);
mainPanel.repaint();
}
/**
* <b>transformer</b>: if player == 1, initialises player1 dice image,
* if player == 2, initialises player 2 dice image.<br/>
* <b>Pre condition</b>:
* <b>Post condition</b>
* @param diceImagePath path of the dice image.
*/
public void initDiceImage(String diceImagePath) {
player1DiceImage = new JLabel();
URL player1DiceImageURL = cldr.getResource(diceImagePath);
assert player1DiceImageURL != null;
Image player1DiceIcon = new ImageIcon(player1DiceImageURL).getImage();
player1DiceImage.setIcon(new ImageIcon(player1DiceIcon));
player1DiceImage.setBounds(215,150,130,110);
player2DiceImage = new JLabel();
URL player2DiceImageURL = cldr.getResource(diceImagePath);
assert player2DiceImageURL != null;
Image player2DiceIcon = new ImageIcon(player2DiceImageURL).getImage();
player2DiceImage.setIcon(new ImageIcon(player2DiceIcon));
player2DiceImage.setBounds(215,150,130,110);
player1Card.add(player1DiceImage);
player2Card.add(player2DiceImage);
mainPanel.repaint();
}
/**
* <b>transformer</b>: initialises the info box.<br />
* <b>Post condition</b>: displays message in the info box.
* @param message message to display in the info box.
*/
public void initInfoBox(String message){
infobox = new JTextArea();
infobox.setEditable(false);
infobox.setBounds(885,370,395,115);
infobox.setFont(new Font("Plain", Font.PLAIN,16));
infobox.setForeground(Color.BLACK);
infobox.setBackground(Color.WHITE);
infobox.setBorder(BorderFactory.createMatteBorder(2,2,2,2, Color.BLACK));
infobox.setOpaque(true);
infobox.setText(message);
mainPanel.add(infobox);
mainPanel.repaint();
}
/**
* <b>transformer</b>: initialises jackpot prize.<br/>
* <b>Pre condition</b>: prize >= 0.<br/>
* <b>Post condition</b> sets jackpot prize to prize.
* @param prize jackpot starting prize
*/
public void initJackpot(int prize) {
JLabel jackpot = new JLabel();
jackpotPrize = new JLabel("Jackpot: " + prize + " Ευρώ");
URL jackpotURL = cldr.getResource("csd/uoc/gr/resources/gameImages/jackpot.png");
assert jackpotURL != null;
Image jackpotImage = new ImageIcon(jackpotURL).getImage();
jackpot.setIcon(new ImageIcon(jackpotImage));
jackpot.setBorder(BorderFactory.createMatteBorder(1,1,1,1,Color.BLACK));
jackpot.setBounds(530,825,213,110);
jackpotPrize.setBounds(530,935,270,30);
jackpotPrize.setFont(new Font(Font.DIALOG_INPUT, Font.BOLD, 18));
jackpotPrize.setForeground(Color.WHITE);
mainPanel.add(jackpot);
mainPanel.add(jackpotPrize);
mainPanel.repaint();
}
/**
* <b>transformer</b>: Updates the board tiles with new tiles<br/>
* <b>Pre condition</b>: newMonthBoardTiles != NULL<br/>
* <b>Post condition</b>: Updates current board tiles, with new shuffled tiles.
* @param newMonthBoardTiles the Tiles.
*/
public void updateBoardTiles(ArrayList<Tile> newMonthBoardTiles){
for(JLabel label : imagesPosition){
label.setVisible(false);
}
imagesPosition = new JLabel[32];
int element = 0;
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(newMonthBoardTiles.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 255, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(newMonthBoardTiles.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 400, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(newMonthBoardTiles.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 545, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 7; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(newMonthBoardTiles.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 690, 120,140);
mainPanel.add(imagesPosition[element]);
}
for(int counter = 0; counter < 4; counter++,element++){
imagesPosition[element] = new JLabel();
URL tileImageURL = cldr.getResource(newMonthBoardTiles.get(element).getImagePath());
assert tileImageURL != null;
Image image = new ImageIcon(tileImageURL).getImage();
imagesPosition[element].setIcon(new ImageIcon(image));
imagesPosition[element].setBounds((counter * 120), 835, 120,140);
mainPanel.add(imagesPosition[element]);
}
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(mainPanel, GroupLayout.PREFERRED_SIZE,1333, GroupLayout.PREFERRED_SIZE));
layout.setVerticalGroup(
layout.createParallelGroup(GroupLayout.Alignment.LEADING).addComponent(mainPanel, GroupLayout.PREFERRED_SIZE,1000, GroupLayout.PREFERRED_SIZE));
pack();
for(JLabel label : imagesPosition){
label.setVisible(true);
}
mainPanel.repaint();
}
/**
* <b>transformer</b>: Updates player card panel.<br>
* <b>Pre condition</b>: player ==1 or player == 2 and money, loan, bills >= 0.<br/>
* <b>Post condition</b>:Updates player card info panel with the new parameters.
* @param player current player(if == 1 player1, if == 2 player2).
* @param money new amount of money.
* @param loan new loan amount.
* @param bills new bills amount .
*/
public void updatePlayerCard(Player player, int money, int loan, int bills){
if (player instanceof Player1) {
player1Money.setText("Money : " + money + " Ευρώ");
player1Loan.setText("Loan : " + loan + " Ευρώ");
player1Bills.setText("Bills : " + bills + " Ευρώ");
}
else{
player2Money.setText("Money : " + money + " Ευρώ");
player2Loan.setText("Loan : " + loan + " Ευρώ");
player2Bills.setText("Bills : " + bills + " Ευρώ");
}
}
/**
* <b>transformer</b>: Updates dice image.<br/>
* <b>Pre condition</b>: player != NULL.<br/>
* <b>Post condition</b>: Changes the image of the dice.<br/>
* @param player player to update the image
* @param dice dice number.
*/
public void updateDiceImage(Player player, int dice){
URL diceImageURL = cldr.getResource("csd/uoc/gr/resources/gameImages/dice-" + dice + ".jpg");
assert diceImageURL != null;
Image diceImage = new ImageIcon(diceImageURL).getImage();
if (player instanceof Player1)
player1DiceImage.setIcon(new ImageIcon(diceImage));
else
player2DiceImage.setIcon(new ImageIcon(diceImage));
}
/**
* <b>transformer</b>: Updates the info box.<br />
* <b>Post condition</b>: Updates the info box, with a new message.
* @param message message to show in the info box.
*/
public void updateInfoBox(String message) {
this.infobox.setText(message);
mainPanel.repaint();
}
/**
* <b>transformer</b>: Updates jackpot prize.<br/>
* <b>Pre condition</b>: prize > 0.<br/>
* <b>Post condition</b>: Change the prize of jackpot.
* @param prize new prize for jackpot.
*/
public void updateJackpotPrize(int prize){
this.jackpotPrize.setText("Jackpot: " + prize + " Ευρώ");
mainPanel.repaint();
}
/**
* Open a new dialog with a text field so the user can enter the loan he wants.<br/>
* <b>Post condition</b>: Open new Dialog.
* @return int value of the user input.
*/
public int openLoanDialog(){
String input = JOptionPane.showInputDialog(mainPanel,"Πληκτρολόγησε το ποσό που θέλεις.", "Get Loan", JOptionPane.QUESTION_MESSAGE);
if (input == null || input.isEmpty())
return 0;
while(Integer.parseInt(input) % 1000 != 0 || Integer.parseInt(input) == 0){
input = JOptionPane.showInputDialog(mainPanel,"Λάθος τιμή!Αποδεκτές τιμές: Χ % 1000 == 0.\nΠληκτρολόγησε το ποσό που θέλεις.", "Get Loan",JOptionPane.ERROR_MESSAGE);
}
return Integer.parseInt(input);
}
/**
* <b>observer</b>: This method check if the player is on Sunday label.<br/>
* <b>Pre condition</b>: position > 0;<br/>
* <b>Post condition</b>: Returns true if the player is on Sunday label, else false.
* @return true/false.
*/
public boolean sundayFootball(int position){
return days[position].getText().equals("Sunday " + position);
}
/**
* Upon calling this method the user can choose to place a bet on a football match or not.<br/>
* <b>Post condition</b>: Opens a dialog so the user can choose if he wants to bet or not.
* @return choice of the user.
*/
public int betOnFootballMatch(){
Object[] options = {"Νίκη Μπαρτσελόνα" , "Ισοπαλία", "Νίκη Ρεαλ Μαδρίτης" , "Δεν θέλω να κάνω πρόβλεψη"};
URL imageURL = cldr.getResource("csd/uoc/gr/resources/gameImages/Barcelona_Real.jpg");
assert imageURL != null;
Image image = new ImageIcon(imageURL).getImage();
image = image.getScaledInstance(175,75,Image.SCALE_SMOOTH);
String tab = " ";
return JOptionPane.showOptionDialog(mainPanel,
"Στοιχιμάτησε 500 Ευρώ στο El Classico",
tab + "La Liga match",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(image),
options,
options[0]);
}
/**
* <b>observer</b>: This method checks if the player is on Thursday label.<br/>
* <b>Pre condition</b>: position > 0.<br/>
* <b>Post condition</b>: Returns true if the player is on Thursday label, else false.
* @return true/false.
*/
public boolean cryptoThursday(int position) {
return days[position].getText().equals("Thursday " + position);
}
/**
* Upon calling this method the user can invest on a cryptocurrency.<br/>
* <b>Post condition</b>: Opens a dialog and the user can choose to invest or not on a cryptocurrency.
* @return choice of the user.
*/
public int betOnCrypto(){
Object[] options = {"Πόνταρε 300 Ευρώ στο κρυπτονόμισμα" , "Παράβλεψε το ποντάρισμα"};
URL imageURL = cldr.getResource("csd/uoc/gr/resources/gameImages/crypto.jpeg");
assert imageURL != null;
Image image = new ImageIcon(imageURL).getImage();
image = image.getScaledInstance(120,115, Image.SCALE_SMOOTH);
return JOptionPane.showOptionDialog(mainPanel,
"Ποντάρισμα στο κρυπτονόμισα SHIBA INU",
"Crypto Thursday",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(image),
options,
options[0]);
}
/**
* <b>transformer</b>: Updates pawn images, "moves" pawn to new position.<br/>
* <b>Pre condition</b>: positionToMovePawn > 0, positionOfSecondPawn> 0, position player != NULL. Tiles != NULL.<br/>
* <b>Post condition</b>: Moves pawn to new Tile on the board.<br/>
* @param positionToMovePawn position of pawn.
* @param player current player.
* @param positionOfSecondPawn the position of the second Pawn.
* @param Tiles the tiles of the board.
* @return Tile to which the pawn is after moving.
*/
public Tile updatePawn(Player player, int positionToMovePawn, int positionOfSecondPawn, ArrayList<Tile> Tiles){
if(positionToMovePawn == positionOfSecondPawn){
if(player instanceof Player1) {
bluePawn.setBounds(imagesPosition[positionToMovePawn].getX() + 55
, imagesPosition[positionToMovePawn].getY()
, imagesPosition[positionToMovePawn].getWidth()
, imagesPosition[positionToMovePawn].getHeight());
}
else {
yellowPawn.setBounds(imagesPosition[positionToMovePawn].getX() + 55
, imagesPosition[positionToMovePawn].getY()
, imagesPosition[positionToMovePawn].getWidth()
, imagesPosition[positionToMovePawn].getHeight());
}
}
else {
if (player instanceof Player1)
bluePawn.setBounds(imagesPosition[positionToMovePawn].getBounds());
else
yellowPawn.setBounds(imagesPosition[positionToMovePawn].getBounds());
}
return Tiles.get(positionToMovePawn);
}
/**
* <b>transformer</b>: Reset the pawns at the first day of the month, to the Start Tile.<br/>
* <b>Post condition</b>: changes the position of the pawns.
*/
public void resetPawns(){
bluePawn.setBounds(imagesPosition[0].getX() + 55, imagesPosition[0].getY(), imagesPosition[0].getWidth(), imagesPosition[0].getHeight());
yellowPawn.setBounds(imagesPosition[0].getBounds());
mainPanel.repaint();
}
/**
* <b>transformer</b>: When starting the game this method is used to read from a dialog the players names.<br/>
* <b>Pre condition</b>: player != NULL.<br/>
* <b>Post condition</b>: returns the String the user entered.
* @param player current player.
* @return a String with the name of the player.
*/
public String readPlayersName(String player){
return JOptionPane.showInputDialog("Πληκτρολόγησε το ονομα του παίχτη " + player);
}
/**
* <b>transformer</b>: Opens a dialog so the user can choose how many months to play.<br/>
* <b>Post condition</b>: returns the users choice.
* @return users choice.
*/
public int enterMonthsToPlay(){
Integer[] options = {1,2,3};
return (Integer)JOptionPane.showInputDialog(mainPanel,"Επιλέξτε πόσους μήνες θέλετε να παίξετε:"
,"Μήνες",JOptionPane.QUESTION_MESSAGE,null,options,options[0]);
}
/**
* <b>observer</b>: Displaying a message through a dialog.<br/>
* <b>Pre condition</b>: message != NULL, amount >= 0.<br/>
* <b>Post condition</b>: Opens a dialog with a message and an amount of money.
* @param message message to display.
* @param amount amount of money to display.
*/
public void displayMessageThrowWindow(String message, int amount){
JOptionPane.showMessageDialog(mainPanel,message + " " + amount + " Ευρώ.");
}
/**
* Opens dialog and the players can choose a number from 1 to 6.
* the number the first player choose is being deleted from the options so
* the other player cannot choose the same number.<br/>
* <b>Pre condition</b>: player != NULL, number between 1-6.<br/>
* <b>Post condition</b>: returns the number the player choose.
* @param player current player.
* @param number number the last player choose.
* @return number the current player choose.
*/
public int lotteryChooseNumber(String player, int number) {
Integer[] options = {1, 2, 3, 4, 5, 6};
if (number != 0) {
Integer[] newOptions = new Integer[options.length - 1];
int cnt2 = 0;
for (Integer option : options) {
if (option != number) {
newOptions[cnt2] = option;
cnt2++;
}
}
return (Integer) JOptionPane.showInputDialog(mainPanel, player + " επέλεξε αριθμό."
, "Lottery", JOptionPane.INFORMATION_MESSAGE, null, newOptions, newOptions[0]);
}
return (Integer) JOptionPane.showInputDialog(mainPanel, player + " επέλεξε αριθμό."
, "Lottery", JOptionPane.INFORMATION_MESSAGE, null, options, options[0]);
}
/**
* This method is being called upon the player reaching PayDay Tile, opens a dialog and
* asks the user if he wants to repay his loan.<br/>
* <b>Pre condition</b>: amount > 0 <br/>
* <b>Post condition</b>: Opens a dialog.
* @param amount amount of the current loan.
* @return choice of the user.
*/
public int loanRepayment(int amount){
int result = JOptionPane.showConfirmDialog(mainPanel,"Θες να ξεπληρώσεις το δάνειο σου;"
,"Ξεπλήρωμα δανείου"
,JOptionPane.YES_NO_OPTION
,JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_NO_OPTION)
return openLoanDialog(amount);
return 0;
}
/**
* Opens a dialog so the user can enter amount of loan he wants to repay.<br/>
* <b>Pre condition</b>: amount > 0<br/>
* <b>Post condition</b>: opens a dialog for the user to repay loan.
* @param amount current loan.
* @return users input.
*/
public int openLoanDialog(int amount){
String input = JOptionPane.showInputDialog(mainPanel,"Πληκτρολόγησε το ποσό που θες να ξεπληρώσεις", "Ξεπλήρωμα δανείου", JOptionPane.QUESTION_MESSAGE);
if (input == null || input.isEmpty())
return 0;
while(Integer.parseInt(input) % 1000 != 0 || Integer.parseInt(input) == 0 || Integer.parseInt(input) > amount){
input = JOptionPane.showInputDialog(mainPanel,"Λάθος τιμή!\nΠληκτρολόγησε το ποσό που θες να ξεπληρώσεις", "Ξεπλήρωμα δανείου",JOptionPane.ERROR_MESSAGE);
}
return Integer.parseInt(input);
}
/**
* Opens a dialog so the user can take loan he must pay, or wishes to buy a deal Card
* and does not have enough money.<br/>
* <b>Pre condition</b>: amount > 0.<br/>
* <b>Post condition</b> Opens a dialog so the user can take loan.
* @param amount current amount of the card.
* @return users input.
*/
public int openLoanDialogForCard(int amount){
String input = JOptionPane.showInputDialog(mainPanel,"Πληκτρολόγησε το δάνειο που θέλεις", "Get Loan", JOptionPane.QUESTION_MESSAGE);
if (input == null || input.isEmpty())
return 0;
while(Integer.parseInt(input) % 1000 != 0 || Integer.parseInt(input) == 0 || Integer.parseInt(input) < amount){
input = JOptionPane.showInputDialog(mainPanel,"Λάθος τιμή\nΤο δάνειο πρεπει να είναι μεγαλύτερο απο " + amount + ".", "Get Loan",JOptionPane.ERROR_MESSAGE);
}
return Integer.parseInt(input);
}
/**
* <b>observer</b>: Displays a Deal card through a dialog. User can either buy or ignore the card.<br/>
* <b>Pre condition</b>: card != NULL<br/>
* <b>Post condition</b>: Displays the Deal Card.
* @param card card to display.
* @return users choice.
*/
public int showDealCard(DealCard card){
Object[] options = {card.getChoice1(), card.getChoice2()};
URL imageURL = cldr.getResource(card.getIconPath());
assert imageURL != null;
Image image = new ImageIcon(imageURL).getImage();
image = image.getScaledInstance(200,200, Image.SCALE_SMOOTH);
return JOptionPane.showOptionDialog(mainPanel,
card.getMessage() + "\nΤιμή αγοράς: " + card.getBuyCost() + " Ευρώ \n Τιμή πώλησης: " + card.getSaleCost() + " Ευρώ \n",
"Κάρτα Συμφωνίας",
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(image),
options,
options[0]);
}
/**
* <b>observer</b>: Displays a Mail card through a dialog.<br/>
* <b>Pre condition</b>: card != NULL<br/>
* <b>Post condition</b>: Displays the Mail Card.
* @param card card to display.
*/
public void showMailCard(MailCard card){
Object[] options = {card.getChoiceMessage()};
URL imageURL = cldr.getResource(card.iconPath());
assert imageURL != null;
Image image = new ImageIcon(imageURL).getImage();
image = image.getScaledInstance(200, 200, java.awt.Image.SCALE_SMOOTH);
JOptionPane.showOptionDialog(mainPanel,
card.getMessage(),
card.getType(),
JOptionPane.YES_NO_OPTION,
JOptionPane.INFORMATION_MESSAGE,
new ImageIcon(image),
options,
options[0]);
}
/**
* <b>accessor</b>: Displays through dialog the players Deal Cards.<br/>
* <b>Pre condition</b>: dealCards != NULL<br/>
* <b>Post condition</b>: Shows the player his deal Cards.
* @param dealCards players Deal cards.
*/
public void showMyDealCards(ArrayList<DealCard> dealCards){
JFrame dealFrame = new JFrame("My deal cards.");
dealFrame.setSize(350,250);
dealFrame.setLocation(860,440);
dealFrame.setVisible(true);
JPanel cardPanel = new JPanel();
JPanel buttonsPanel = new JPanel();
CardLayout cl = new CardLayout();
JPanel[] dealPanel = new JPanel[dealCards.size()];
JLabel[] dealLabels = new JLabel[dealCards.size()];
JLabel[] saleLabel = new JLabel[dealCards.size()];
JButton next = new JButton("Επόμενη");
JButton previous = new JButton("Προηγούμενη");
cardPanel.setLayout(cl);
for(int counter = 0; counter < dealCards.size(); counter++){
dealLabels[counter] = new JLabel();
URL imageURL = cldr.getResource(dealCards.get(counter).getIconPath());
assert imageURL != null;
Image image = new ImageIcon(imageURL).getImage();
image = image.getScaledInstance(150,150, Image.SCALE_SMOOTH);
dealLabels[counter].setIcon(new ImageIcon(image));
dealLabels[counter].setBorder(BorderFactory.createMatteBorder(1,1,1,1, Color.BLACK));
saleLabel[counter] = new JLabel(dealCards.get(counter).getSaleCost() + " Ευρώ");
dealPanel[counter] = new JPanel();
dealPanel[counter].add(dealLabels[counter]);
dealPanel[counter].add(saleLabel[counter]);
cardPanel.add(dealPanel[counter], String.valueOf(counter));
}
buttonsPanel.add(previous);
buttonsPanel.add(next);
next.addActionListener(event -> {
if(currentCard < dealCards.size()){
currentCard += 1;
cl.show(cardPanel, "" + (currentCard));
}
});
previous.addActionListener(event -> {
if (currentCard > 0){
currentCard -= 1;
cl.show(cardPanel, "" + (currentCard));
}
});
dealFrame.add((cardPanel), BorderLayout.NORTH);
dealFrame.add((buttonsPanel), BorderLayout.SOUTH);
}
/**
* <b>accessor</b>: Displays the players Deal cards so he can choose one of them to sell.<br/>
* <b>Pre condition</b>: dealCards != NULL<br/>
* <b>Post condition</b>: Players chooses a deal card and returns a String of the card he choose.
* @param dealCards Deal cards of the player.
* @return String of the card the player choose
*/
public String chooseDealCardToSell(ArrayList<DealCard> dealCards){
Object[] options = new Object[dealCards.size()];
for (int cnt1 = 0; cnt1 < dealCards.size(); cnt1++){
options[cnt1] = dealCards.get(cnt1).getMessage() +
", πούλησε την κάρτα για " +
dealCards.get(cnt1).getSaleCost() + " Ευρώ";
}
return (String)JOptionPane.showInputDialog(mainPanel, "Επέλεξε την κάρτα συμφωνίας που θες να πουλήσεις:"
,"My deal cards", JOptionPane.QUESTION_MESSAGE, null, options,options[0]);
}
/**
* Shows the winner throw dialog.<br/>
* <b>Pre condition</b>: player != NULL<br/>
* <b>Post condition</b>: shows the winner.
* @param player player who won.
*/
public void showWinner(Player player){
JOptionPane.showMessageDialog(mainPanel,
"Συγχαρητήρια " + player.getName() + " Νίκησες!\n",
"Winner winner chicken dinner",
JOptionPane.INFORMATION_MESSAGE);
}
/**
* Adds Listener to the Roll Dice buttons.<br/>
* <b>Pre condition</b>: roll != NULL<br/>
* <b>Post condition</b>: adds Listener to Roll Dice buttons.
* @param roll Listener
*/
public void addRollDiceListener(ActionListener roll){
this.player1RollDice.addActionListener(roll);
this.player2RollDice.addActionListener(roll);
}
/**
* Adds Listener to the My Deal Cards buttons.<br/>
* <b>Pre condition</b>: getDealCards != NULL<br/>
* <b>Post condition</b>: adds Listener to players My Deal Card buttons.
* @param getDealCards Listener.
*/
public void addMyDealCardsActionListener(ActionListener getDealCards){
this.player1MyDealCards.addActionListener(getDealCards);
this.player2MyDealCards.addActionListener(getDealCards);
}
/**
* Adds Listener to the Get Loan buttons.<br/>
* <b>Pre condition</b>: loan != NULL<br/>
* <b>Post condition</b>: adds Listener to Get Loan buttons.
* @param loan Listener
*/
public void addGetLoanListener(ActionListener loan){
this.player1GetLoan.addActionListener(loan);
this.player2GetLoan.addActionListener(loan);
}
/**
* Adds Listener to the End Turn buttons.<br/>
* <b>Pre condition</b>: endTurn != NULL<br/>
* <b>Post condition</b>: adds Listener to End Turn buttons.
* @param endTurn Listener
*/
public void addEndTurnListener(ActionListener endTurn){
this.player1EndTurn.addActionListener(endTurn);
this.player2EndTurn.addActionListener(endTurn);
}
/**
* Adds Listener to the Mail/Deal card buttons.<br/>
* <b>Pre condition</b>: cardListener != NULL<br/>
* <b>Post condition</b>: adds Listener Mail/Deal card buttons.
* @param cardListener Listener
*/
public void addCardListener(ActionListener cardListener){
this.getMailCard.addActionListener(cardListener);
this.getDealCard.addActionListener(cardListener);
}
} | ntavas/PayDay | src/csd/uoc/gr/view/GraphicUI.java |
1,862 | package com.example.uManage.activity_classes;
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
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 androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.example.uManage.R;
import com.example.uManage.database.WorkersDatabase;
import java.io.ByteArrayOutputStream;
public class AddWorker extends AppCompatActivity {
public Uri selectedImage;
Button button;
ImageButton imageButton;
TextView textView;
ImageView img;
EditText name;
EditText age;
EditText salary;
WorkersDatabase db;
String name1;
String username;
int age1;
int salary1;
int t = 0;
//χρησιμοποιώ Launcher για την είσοδο στην συλλογή, όταν η συλλογή κλείσει τότε κάνω μετατροπές στο αποτέλεσμα που πήρα και αποθηκεύω την φωτογραφία σε ένα αόρατο Imageview
ActivityResultLauncher<Intent> Launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
t = 1;
selectedImage = result.getData().getData();
Cursor returnCursor = getContentResolver().query(selectedImage, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
//αρχικοποιώ το textview με το όνομα της φωτογραφίας που χρησιμοποίησα
textView.setText(returnCursor.getString(nameIndex));
textView.setVisibility(View.VISIBLE);
img.setImageURI(selectedImage);
Log.d(TAG, "onActivityResult: " + img);
}
}
}
);
@Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.addworker_tab);
//παίρνω σαν extra το όνομα της εταιρίας για να κάνω τις εισαγωγές στην βάση
if (getIntent().getExtras() != null) {
Bundle extras = getIntent().getExtras();
username = extras.getString("name");
}
//init τα components
textView = findViewById(R.id.camera_text_add_tab);
imageButton = findViewById(R.id.camera_add_tab);
img = findViewById(R.id.image_for_bitmap_add_tab);
button = findViewById(R.id.button_add_tab);
name = findViewById(R.id.person_name_add_tab);
age = findViewById(R.id.age_add_tab);
salary = findViewById(R.id.salary_add_tab);
//δημιουργώ instance της βάσης εργαζόμενων
db = new WorkersDatabase(this);
//savedInstanceState σε περίπτωση που γυρίσει η οθόνη ή κλείσουμε προσωρινά την εφαρμογή χωρίς να την τερματίσουμε
if (savedInstanceState != null) {
name.setText(savedInstanceState.getString("wname"));
age.setText(savedInstanceState.getString("wage"));
salary.setText(savedInstanceState.getString("wsalary"));
if (savedInstanceState.getParcelable("wimguri") != null) {
selectedImage = savedInstanceState.getParcelable("wimguri");
img.setImageURI(selectedImage);
textView.setText(savedInstanceState.getString("wimgname"));
textView.setVisibility(View.VISIBLE);
t = 1;
}
}
super.onCreate(savedInstanceState);
//onclicklistener για το imagebutton που οδηγεί στην συλλογη
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sunarthsh();
}
});
//onclicklistener για το addbutton που αν όλοι οι έλεγχοι είναι οκ κάνει εισαγωγή του εργαζόμενου στην βάση
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (name.getText().toString().equals("") || age.getText().toString().equals("") || salary.getText().toString().equals("")) {
Toast.makeText(AddWorker.this, "Please fill all the gaps!", Toast.LENGTH_SHORT).show();
} else {
if (Integer.parseInt(age.getText().toString()) <= 17) {
Toast.makeText(AddWorker.this, "Age must be higher than 17!", Toast.LENGTH_SHORT).show();
} else {
//μετατρέπω την εικόνα σε byte[] για να την αποθηκεύσω στην βάση
byte[] image = bitmaptobyte();
name1 = name.getText().toString();
age1 = Integer.parseInt(age.getText().toString());
salary1 = Integer.parseInt(salary.getText().toString());
db.addEntry(name1, age1, salary1, textView.getText().toString(), image, username);
finish();
}
}
}
});
}
//η διαδικασία μετατροπής της εικόνας σε byte[]
private byte[] bitmaptobyte() {
byte[] image = null;
if (t == 1) {
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
int nh = (int) (bitmap.getHeight() * (1024.0 / bitmap.getWidth()));
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
scaled.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
image = byteArrayOutputStream.toByteArray();
} else {
textView.setText("");
}
return image;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
Log.d(TAG, "onSaveInstanceState: " + selectedImage);
outState.putString("wname", name.getText().toString());
outState.putString("wage", String.valueOf(age.getText()));
outState.putString("wsalary", String.valueOf(salary.getText()));
outState.putParcelable("wimguri", selectedImage);
outState.putString("wimgname", textView.getText().toString());
super.onSaveInstanceState(outState);
}
private ActivityResultLauncher<String> requestPermissionLauncher =
registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
if (isGranted) {
// Permission is granted. Continue the action or workflow in your
// app.
} else {
// Explain to the user that the feature is unavailable because the
// features requires a permission that the user has denied. At the
// same time, respect the user's decision. Don't link to system
// settings in an effort to convince the user to change their
// decision.
}
});
private void sunarthsh() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// You can use the API that requires the permission.
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Launcher.launch(intent);
} else
{
// You can directly ask for the permission.
// The registered ActivityResultCallback gets the result of this request.
requestPermissionLauncher.launch(Manifest.permission.READ_EXTERNAL_STORAGE);
}
}
}
| geor999/uManage-Android-App | app/src/main/java/com/example/uManage/activity_classes/AddWorker.java |
1,867 | //package gr.aueb.cf.ch10;
//
//import java.util.ArrayList;
//
//public class CryptoApp {
//
// public static void main(String[] args) {
// final int KEY = 300;
// String s = "Coding";
//
// String encrypted = encrypt(s, KEY).toString(); // το tostring μετατρέπει τα στοιχεία της λίστας σε string
// System.out.println(encrypted);
//
// String decrypted = decrypt(encrypt(s, KEY), KEY).toString();
// System.out.println(decrypted);
// }
//
// public static ArrayList<Integer> encrypt(String s, int key){
// ArrayList<Integer> encrypted = new ArrayList<>();
// char ch;
// int i;
//
// int prev = cipher(s.charAt(0), -1, key);
// encrypted.add(prev);
//
//
// //το string εισόδου τελειώνει με ένα #.
// //θα μπορούσε και με μία αέναη for --> for(;;)
// i = 1;
// while((ch = s.charAt(i)) != '#') {
// // και διαβάζω και συγκρίνω ταυτόχρονα
// encrypted.add(cipher(ch, prev, key));
// prev = cipher(ch, prev , key);
// i++;
// }
// encrypted.add(-1);
// return encrypted;
// }
//
// public static ArrayList<Character> decrypt(ArrayList<Integer> encrypted, int key){
// ArrayList<Character> decrypted = new ArrayList<>();
// int token;
// int i;
// int prevToken;
//
// //για να διαβάσω κάνω .get
// prevToken = decipher(encrypted.get(0), -1, key);
// decrypted.add((char) prevToken); // autocast σε wrapper κλάση
//
// i = 1;
// while((token = encrypted.get(i)) != -1){
// decrypted.add(decipher(token, prevToken, key));
// prevToken = token;
// i++;
// }
//
// return decrypted;
// }
// // παίρνει έναν χαρακτήρα και τον επιστρέφει κρυπτογραφημένο ώσ int
// public static int cipher(char ch, int prev, int key){
// if (prev == -1) return ch;
// return(ch + prev) % key;
// }
//
// public static char decipher(int cipher, int prev, int key){
// int de;
// if( prev == -1) return (char) cipher; //return ton cipher metatr;epontas to se char
//
// de = (cipher - prev + key) % key;
// return (char) de;
// }
//}
| Mariamakr/codingfactory23a | src/gr/aueb/cf/ch10/CryptoApp.java |
1,871 | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DeletePelates extends Fragment {
//ορισμος μεταβλητων που θα χρησιμοποιησω
EditText delete_txt;
Button deleteUser;
public DeletePelates() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Δημιουργια view και κάνω την ένωση των μεταβλητων με τα αντιστοιχα elements
//του fragment χρησιμοποιωντας την findViewById
View view = inflater.inflate(R.layout.fragment_delete, container, false);
delete_txt = view.findViewById(R.id.delete_txt);
deleteUser = view.findViewById(R.id.deleteUser);
deleteUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//setOnClickListener στο κουμπί deleteUser, δηλαδη τι θα γινει οταν παταει κανεις το κουμπι
//Παιρνω την Integer τιμή του EditText, ελέγχω για ερρορ και αμα πανε ολα καλα
//Δημιουργω ενα εντικειμενο της κλασης Pelates, του δινω το id που βρηκα πριν λιγο
//και καλωντας τη μεθοδο deletePelati που την εχω ορισει στο MyDao γίνεται η αντίστοιχη
//διαγραφή Πελάτη.Τελος εμφανιζω ενα Toast και μηδενιζω τη τιμή του EditText
int Var_id = 0;
try {
Var_id = Integer.parseInt(delete_txt.getText().toString());
} catch (NumberFormatException ex){
System.out.println("Could not parse" + ex);
}
Pelates pelates = new Pelates();
pelates.setId(Var_id);
MainActivity.myAppDatabase.myDao().deletePelati(pelates);
Toast.makeText(getActivity(), "Ο λογαριασμός διαγράφθηκε", Toast.LENGTH_LONG).show();
delete_txt.setText("");
}
});
return view;
}
}
| EfthimisKele/E_Shop | app/src/main/java/com/example/eshop3/DeletePelates.java |
1,872 | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class DeleteProionta extends Fragment {
//ορισμος μεταβλητων που θα χρησιμοποιησω
EditText delete_txtpr;
Button deletePr;
public DeleteProionta() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Δημιουργια view και κάνω την ένωση των μεταβλητων με τα αντιστοιχα elements
//του fragment χρησιμοποιωντας την findViewById
View view = inflater.inflate(R.layout.fragment_delete_proionta, container, false);
delete_txtpr = view.findViewById(R.id.delete_txtPr);
deletePr = view.findViewById(R.id.deletePr);
deletePr.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//setOnClickListener στο κουμπί deletePr, δηλαδη τι θα γινει οταν παταει κανεις το κουμπι
//Παιρνω την Integer τιμή του EditText, ελέγχω για ερρορ και αμα πανε ολα καλα
//Δημιουργω ενα εντικειμενο της κλασης Proionta, του δινω το id που βρηκα πριν λιγο
//και καλωντας τη μεθοδο deleteProion που την εχω ορισει στο MyDao γίνεται η αντίστοιχη
//διαγραφή Προιον.Τελος εμφανιζω ενα Toast και μηδενιζω τη τιμή του EditText
int Var_prid = 0;
try {
Var_prid = Integer.parseInt(delete_txtpr.getText().toString());
} catch (NumberFormatException ex){
System.out.println("Could not parse" + ex);
}
Proionta proionta = new Proionta();
proionta.setPid(Var_prid);
MainActivity.myAppDatabase.myDao().deleteProion(proionta);
Toast.makeText(getActivity(), "Το προιον διαγράφθηκε", Toast.LENGTH_LONG).show();
delete_txtpr.setText("");
}
});
return view;
}
}
| EfthimisKele/E_Shop | app/src/main/java/com/example/eshop3/DeleteProionta.java |
1,878 | package com.example.eshop3;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.util.List;
public class DeletePwliseis extends Fragment {
//ορισμος μεταβλητων που θα χρησιμοποιησω
EditText d1,d2,d3,d4,d5,d6;
Button deletePwl;
public DeletePwliseis() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//Δημιουργια view και κάνω την ένωση των μεταβλητων με τα αντιστοιχα elements
//του fragment χρησιμοποιωντας την findViewById
View view = inflater.inflate(R.layout.fragment_delete_pwliseis, container, false);
d1 = view.findViewById(R.id.del_textPwl1);
d2 = view.findViewById(R.id.del_textPwl2);
d3 = view.findViewById(R.id.del_textPwl3);
d4 = view.findViewById(R.id.del_textPwl4);
d5 = view.findViewById(R.id.del_textPwl5);
d6 = view.findViewById(R.id.del_textPwl6);
deletePwl = view.findViewById(R.id.deletePwl);
deletePwl.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//setOnClickListener στο κουμπί deletePwl και ελεγχος για καθε μεταβλητη μου
//αμα υπαρχει ερρορ.
int pwl_id = 0;
try {
pwl_id = Integer.parseInt(d1.getText().toString());
} catch (NumberFormatException ex) {
System.out.println("Could not parse" + ex);
}
String pwl_name = d2.getText().toString();
int pwlA = 0;
try {
pwlA = Integer.parseInt(d3.getText().toString());
} catch (NumberFormatException ex) {
System.out.println("Could not parse" + ex);
}
int pwlB = 0;
try {
pwlB = Integer.parseInt(d4.getText().toString());
} catch (NumberFormatException ex) {
System.out.println("Could not parse" + ex);
}
int pwlC = 0;
try {
pwlC = Integer.parseInt(d5.getText().toString());
} catch (NumberFormatException ex) {
System.out.println("Could not parse" + ex);
}
int pwlD = 0;
try {
pwlD = Integer.parseInt(d6.getText().toString());
} catch (NumberFormatException ex) {
System.out.println("Could not parse" + ex);
}
//ελεγχος αμα το ονομα ειναι κενό αλλιως δεν συνεχιζεται η διαδικασια,
//αμα αφησει κανεις κενα τα πεδια παιρνει σα default το 0, δεν υπαρχει θεμα για
//τα προιοντα ,για το id μπορει να εχει καποιος το 0
if (pwl_name.equals("")) {
String m = "Δεν έβαλες όνομα";
Toast.makeText(getActivity(), m, Toast.LENGTH_LONG).show();
} else {
try {
//παιρνω μια λιστα τυπου Προιοντα απο τη myDao
//και κανω ενα loop για καθε προιον που εχει αυτη η λιστα
//σκοπός είναι σε καθε διαγραφή αγορας το πληθος των προιοντων που αγορασε κανεις
//να επιστρεφει στον πινακα Προιοντα.
List<Proionta> proionta1 = MainActivity.myAppDatabase.myDao().getProionta();
for (Proionta i: proionta1) {
//βρισκω και αποθηκευω προσωρινα τις τιμες του καθε στοιχειου απο τη
//λιστα τυπου Προιοντα
Integer p_id = i.getPid();
Integer posotita = i.getPosotita();
Integer xronologia = i.getXronologia();
Integer timi = i.getTimi();
Integer diafora = 0;
//στη συνεχεια ελεγχω το p_id αμα ειναι 1 τοτε ειναι το προιον Α
//αμα 2 τοτε ειναι το Β κτλ. Οταν μπει σε καποιο απο τα if
//στη λιστα του πινακα που εχει το αποθεμα καθε προιοντος
//προσθετεται και η ποσοτητα που ειχε παραγγειλει ο πελατης.
//Και καλειται η μεθοδος updateProion για να γινει update
//ο πινακας.
if (p_id == 1) {
diafora = (posotita + pwlA);
Proionta proionta = new Proionta();
proionta.setPid(p_id);
proionta.setPosotita(diafora);
proionta.setXronologia(xronologia);
proionta.setTimi(timi);
MainActivity.myAppDatabase.myDao().updateProion(proionta);
}else if (p_id == 2){
diafora = (posotita + pwlB);
Proionta proionta = new Proionta();
proionta.setPid(p_id);
proionta.setPosotita(diafora);
proionta.setXronologia(xronologia);
proionta.setTimi(timi);
MainActivity.myAppDatabase.myDao().updateProion(proionta);
}else if (p_id == 3){
diafora = (posotita + pwlC);
Proionta proionta = new Proionta();
proionta.setPid(p_id);
proionta.setPosotita(diafora);
proionta.setXronologia(xronologia);
proionta.setTimi(timi);
MainActivity.myAppDatabase.myDao().updateProion(proionta);
}else if (p_id == 4){
diafora = (posotita + pwlD);
Proionta proionta = new Proionta();
proionta.setPid(p_id);
proionta.setPosotita(diafora);
proionta.setXronologia(xronologia);
proionta.setTimi(timi);
MainActivity.myAppDatabase.myDao().updateProion(proionta);
}
}
//Δημιουργια αντικειμενου τυπου Pwliseis
//κανω αντιστοιχηση με τις τιμες των EditText
//και καλω τη deletePwliseis για να γινει η καταλληλη διαγραφή
//στον πινακα αφου εχει γινει επιβαιβεωσει της αγορας και εχουν επιστραφεί
//τα προιοντα
Pwliseis pwliseis = new Pwliseis();
pwliseis.setOnoma(pwl_name);
pwliseis.setPosoA(pwlA);
pwliseis.setPosoB(pwlB);
pwliseis.setPosoC(pwlC);
pwliseis.setPosoD(pwlD);
pwliseis.setPpid(pwl_id);
MainActivity.myAppDatabase.myDao().deletePwliseis(pwliseis);
Toast.makeText(getActivity(), "Η αγορά με αυτό το id διαγράφθηκαν", Toast.LENGTH_LONG).show();
}catch (Exception e) {
String message = e.getMessage();
Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
}
//Στο τελος αδειαζω τα EditText
d1.setText("");
d2.setText("");
d3.setText("");
d4.setText("");
d5.setText("");
d6.setText("");
} }
});
return view;
}
}
| EfthimisKele/E_Shop | app/src/main/java/com/example/eshop3/DeletePwliseis.java |
1,880 | package com.example.uManage.activity_classes;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_NO;
import static androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_YES;
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.uManage.R;
import com.example.uManage.adapters.WorkerAdapter;
import com.example.uManage.database.PreferencesDatabase;
import com.example.uManage.database.WorkersDatabase;
import com.example.uManage.object_classes.Worker;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class ListActivity extends AppCompatActivity {
String sort,theme;//strings που χρησιμοποιούνται για να αποθηκέυσω το sorting pattern, και το theme της εφαρμογής(διαφοροποιείται ανά λογαριασμό)
PreferencesDatabase preferencesDatabase;
RecyclerView recyclerView;//recycler view για την εμφανισή των αντικειμένων
RecyclerView.LayoutManager layoutManager;//layout manager που χρησιμοποιείται για το recycler view
WorkerAdapter workerAdapter;//adapter που χρησιμοποιείται για το recycler view
//βάση για την αποθήκευση των εργαζόμενων και μια λίστα για την αποθηκευσή τους και την χρήση τους(sorting,εμφάνιση,επεξεργασία)
WorkersDatabase workersDatabase;
final List<Worker> workerList = new ArrayList<>();
//launcer που όπου και αν κληθεί μετά την επιστροφή του κάνει recreate το συγκεκριμένο activity
final ActivityResultLauncher<Intent> Launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> recreate());
String name;
//inits για τα Analytics
double avgage=0,avgsal=0,sumsalary;
int workers;
TextView avgAge,avgSal,sumSal,numWork;
@Override
public void onCreate( Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab);
//απόδοση τιμής στην μεταβλητή name που θα χρησιμοποιηθεί για τα addworker,updateworker
if(getIntent().getExtras()!=null)
{
Bundle extras = getIntent().getExtras();
name=extras.getString("name");
}
//δημιουργία instance βάσης preferences για sorting και theme
preferencesDatabase = new PreferencesDatabase(this);
//συνάρτηση preferences που παίρνει απτήν βάση πληροφορίες για το sorting και το theme
preferences();
//δημιουργία instance βάσης workers
workersDatabase = new WorkersDatabase(this);
//παίρνω όλους τους εργαζόμενους που δουλεύουν στην εταιρία με όνομα name
Cursor cursor = workersDatabase.allEntries();
if(cursor.getCount()!=0) {
while (cursor.moveToNext()) {
if (Objects.equals(cursor.getString(6), name)) {
Worker newWorker = new Worker(Integer.parseInt(cursor.getString(0)), cursor.getString(1), Integer.parseInt(cursor.getString(2)), Integer.parseInt(cursor.getString(3)), cursor.getString(4), cursor.getString(6), (cursor.getBlob(5)));
workerList.add(newWorker);
}
//αν δεν είναι null κάνω sorting, 1 για descending 0 για ascending
if (workerList != null) {
if (Objects.equals(sort, "1")) {
for (int i = 0; i < workerList.size(); i++) {
for (int j = 0; j < workerList.size()-i-1; j++) {
Worker tmp;
if (workerList.get(j).getSalary() < workerList.get(j+1).getSalary()) {
tmp = workerList.get(j);
workerList.set(j, workerList.get(j+1));
workerList.set(j+1, tmp);
}
}
}
} else {
for (int i = 0; i < workerList.size(); i++) {
for (int j = 0; j < workerList.size() - i - 1; j++) {
Worker tmp;
if (workerList.get(j).getSalary() > workerList.get(j + 1).getSalary()) {
tmp = workerList.get(j);
workerList.set(j, workerList.get(j + 1));
workerList.set(j + 1, tmp);
}
}
}
}
}
}
}
//κλήση της analytics για την δημιουργία του field των analytics
analytics();
//layoutmanager,adapter για το recycleview
recyclerView = findViewById(R.id.recycler_view_main_tab);
recyclerView.hasFixedSize();
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
workerAdapter = new WorkerAdapter(workerList, workersDatabase, this);
recyclerView.setAdapter(workerAdapter);
}
private void preferences() {
//παίρνω όλο τον πίνακα των preferences και ψάχνω για την εταιρία με όνομα name,αν αυτή δεν υπάρχει δεν κάνω τίποτα. Ουσιαστικά έχει default τιμή 0 και ascending
Cursor cursor = preferencesDatabase.allEntries();
if (cursor.getCount() != 0) {
while (cursor.moveToNext()) {
if (Objects.equals(cursor.getString(3), name)) {
if (cursor.getString(1) != (null)) {
theme = cursor.getString(1);
} else {
theme = "light";
}
if (cursor.getString(2) != (null)) {
sort = cursor.getString(2);
} else {
sort = "0";
}
if (theme.equals("light")) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_NO);
} else {
if (theme.equals("dark")) {
AppCompatDelegate.setDefaultNightMode(MODE_NIGHT_YES);
}
}
}
}
}
}
//δημιουργώ το menu που υπάρχει sto menu.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
//μέθοδος που χρησιμοποιείται για την διαχείρηση του μενου, η διαδικασία που ακολουθείται είναι η ίδια οπότε η εξήγηση είναι στο case R.id.ascending_menu_tab
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
Cursor cursor=preferencesDatabase.allEntries();
switch (item.getItemId()) {
//+ για την προσθήκη του εργαζόμενου
case R.id.add_new_worker_menu_tab:
Intent intent = new Intent(this, AddWorker.class);
//δίνω σαν extra όπως και πρίν το όνομα της εταιρίας
intent.putExtra("name",name);
Launcher.launch(intent);
return true;
//επιλογή για ascending sorting
case R.id.ascending_menu_tab:
//αν η βάση είναι άδεια τότε δημιουργεί το πρώτο field της, διαφορετικά ψάχνει να δεί αν το username(δηλαδή το όνομα της εταιρίας) είναι ίδιο με το τελευταίο field
//αν αυτό είναι τότε κάνει update και επομένως recreate ώστε να πάρουν μορφή οι αλλαγές διαφορετικά δημιουργεί νέο field στη βάση για την εταιρία αυτήν
if(cursor.getCount()!=0) {
while (cursor.moveToNext())
{
if (Objects.equals(cursor.getString(3), name))
{
preferencesDatabase.update(cursor.getInt(0),theme, name,"0");
recreate();
return true;
}
}
}
preferencesDatabase.addEntry(theme, name,"0");
recreate();
return true;
case R.id.descending_menu_tab:
if(cursor.getCount()!=0) {
while (cursor.moveToNext())
{
if (Objects.equals(cursor.getString(3), name))
{
preferencesDatabase.update(cursor.getInt(0),theme, name,"1");
recreate();
return true;
}
}
}
preferencesDatabase.addEntry(theme, name,"1");
recreate();
return true;
case R.id.dark_theme_menu_tab:
if(cursor.getCount()!=0) {
while (cursor.moveToNext())
{
if (Objects.equals(cursor.getString(3), name))
{
preferencesDatabase.update(cursor.getInt(0),"dark", name,sort);
recreate();
return true;
}
}
}
preferencesDatabase.addEntry("dark", name,sort);
recreate();
return true;
case R.id.light_theme_menu_tab:
if(cursor.getCount()!=0) {
while (cursor.moveToNext()) {
if (Objects.equals(cursor.getString(3), name)) {
preferencesDatabase.update(cursor.getInt(0), "light", name, sort);
recreate();
return true;
}
}
}
preferencesDatabase.addEntry("light", name,sort);
recreate();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
workerAdapter.onActivityResult(requestCode, resultCode, data);
if (resultCode == 8) {
recreate();
}
if (resultCode == 7) {
recreate();
}
}
@Override
public void onBackPressed() {
}
//init τα analytics και υπολογισμών τιμών για αυτά
public void analytics(){
for (int i = 0; i < workerList.size(); i++) {
avgage+=workerList.get(i).getAge();
avgsal+=workerList.get(i).getSalary();
}
sumsalary=avgsal;
avgage/=workerList.size();
avgsal/=workerList.size();
workers=workerList.size();
TextView avgAge,avgSal,sumSal,numWork;
avgAge=findViewById(R.id.avg_age_db_brief_main_tab);
avgSal=findViewById(R.id.avg_salary_db_brief_main_tab);
numWork=findViewById(R.id.total_workers_db_brief_main_tab);
sumSal=findViewById(R.id.salary_sum_db_brief_main_tab);
avgAge.setText(String.valueOf(avgage));
avgSal.setText(String.valueOf(avgsal));
numWork.setText(String.valueOf(workers));
sumSal.setText(String.valueOf(sumsalary));
}
}
| geor999/uManage-Android-App | app/src/main/java/com/example/uManage/activity_classes/ListActivity.java |
1,881 | package com.example.uManage.activity_classes;
import static androidx.constraintlayout.helper.widget.MotionEffect.TAG;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.util.Log;
import android.view.View;
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 androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import com.example.uManage.R;
import com.example.uManage.database.WorkersDatabase;
import java.io.ByteArrayOutputStream;
public class UpdateWorker extends AppCompatActivity {
Button button;
EditText name;
EditText age;
EditText salary;
TextView imagename;
ImageView img;
String username;
ImageButton imgbtn;
WorkersDatabase db;
int id;
String name1;
int age1;
int salary1;
byte[] image;
Bitmap instancebitmap;
Uri selectedImage;
//χρησιμοποιώ Launcher για την είσοδο στην συλλογή, όταν η συλλογή κλείσει τότε κάνω μετατροπές στο αποτέλεσμα που πήρα και αποθηκεύω την φωτογραφία σε ένα αόρατο Imageview
ActivityResultLauncher<Intent> Launcher= registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if(result.getResultCode()== RESULT_OK && result.getData() != null)
{
selectedImage=result.getData().getData();
Cursor returnCursor = getContentResolver().query(selectedImage, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
returnCursor.moveToFirst();
imagename.setText(returnCursor.getString(nameIndex));
img.setImageURI(selectedImage);
instancebitmap=((BitmapDrawable) img.getDrawable()).getBitmap();
}
}
}
);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
Bundle extras = getIntent().getExtras();
//παίρνω σαν extra το ID
if(extras!=null)
{
id=extras.getInt("ID");
}
//δημιουργώ ενα instance της βάσης των εργαζόμενων
db=new WorkersDatabase(this);
setContentView(R.layout.updateworker_tab);
//init components
button=findViewById(R.id.button_update_tab);
name=findViewById(R.id.person_name_update_tab);
age =findViewById(R.id.age_update_tab);
salary=findViewById(R.id.salary_update_tab);
img=findViewById(R.id.image_for_bitmap_update_tab);
imagename=findViewById(R.id.camera_text_update_tab);
imgbtn=findViewById(R.id.camera_update_tab);
//αν το savedInstanceState είναι null τότε κάνει καλεί την συνάρτηση initiatevariables() και εισάγει τιμές στις μεταβλητές,διαφορετικά παίρνει από το savedInstanceState
if(savedInstanceState==null) {
initiatevariables();
}
else
{
id=savedInstanceState.getInt("wid");
name.setText(savedInstanceState.getString("wname"));
age.setText(savedInstanceState.getString("wage"));
salary.setText(savedInstanceState.getString("wsalary"));
if(savedInstanceState.getParcelable("wimguri")!=null) {
instancebitmap = savedInstanceState.getParcelable("wimguri");
img.setImageBitmap(instancebitmap);
imagename.setText(savedInstanceState.getString("wimgname"));
}
else
{
img=null;
}
username=savedInstanceState.getString("wusername");
}
super.onCreate(savedInstanceState);
//onclicklistener για το imagebutton που οδηγεί στην συλλογη
imgbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent= new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
Launcher.launch(intent);
}
});
//onclicklistener για το addbutton που αν όλοι οι έλεγχοι είναι οκ κάνει ενημέρωση του εργαζόμενου στην βάση
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (name.getText().toString().equals("") || age.getText().toString().equals("") || salary.getText().toString().equals("")) {
Toast.makeText(UpdateWorker.this, "Please fill all the gaps!", Toast.LENGTH_SHORT).show();
} else {
if (Integer.parseInt(age.getText().toString()) <= 17) {
Toast.makeText(UpdateWorker.this, "Age must be higher than 17!", Toast.LENGTH_SHORT).show();
} else {
bitmaptobyte();
name1 = name.getText().toString();
age1 = Integer.parseInt(age.getText().toString());
salary1 = Integer.parseInt(salary.getText().toString());
db.update(id, name1, age1, salary1, imagename.getText().toString(), image, username);
setResult(8);
finish();
}
}
}
});
}
private void bitmaptobyte()
{
//η διαδικασία μετατροπής της εικόνας σε byte[]
if(img != null) {
Bitmap bitmap = ((BitmapDrawable) img.getDrawable()).getBitmap();
int nh = (int) ( bitmap.getHeight() * (1024.0 / bitmap.getWidth()) );
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 1024, nh, true);
scaled.compress(Bitmap.CompressFormat.PNG, 0, byteArrayOutputStream);
image = byteArrayOutputStream.toByteArray();
}
else
{
image= null;
}
}
private void initiatevariables() {
Cursor cursor = db.allEntries();
if (cursor.getCount() != 0) {
while (cursor.moveToNext()) {
if(id==Integer.parseInt(cursor.getString(0)))
{
name.setText(cursor.getString(1));
age.setText(cursor.getString(2));
salary.setText(cursor.getString(3));
imagename.setText(cursor.getString(4));
if(cursor.getBlob(5)!=null) {
img.setImageBitmap(getImage(cursor.getBlob(5)));
Log.d(TAG, "initiatevariables: "+img);
instancebitmap=((BitmapDrawable) img.getDrawable()).getBitmap();
}
else
{
img=null;
}
username=cursor.getString(6);
}
}
}
}
//μετατροπή απο byte[] σε bitmap για να πάρω την αρχική φωτογραφία από την βάση αν αυτή υπάρχει
public Bitmap getImage(byte[] imgByte){
if (imgByte != null) {
return Bitmap.createScaledBitmap(BitmapFactory.decodeByteArray(imgByte, 0 ,imgByte.length),50,50,false);
}
return null;
}
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putInt("wid",id);
outState.putString("wname",name.getText().toString());
outState.putString("wage", String.valueOf(age.getText()));
outState.putString("wsalary", String.valueOf(salary.getText()));
outState.putParcelable("wimguri",instancebitmap);
outState.putString("wimgname",imagename.getText().toString());
outState.putString("wusername",username);
super.onSaveInstanceState(outState);
}
}
| geor999/uManage-Android-App | app/src/main/java/com/example/uManage/activity_classes/UpdateWorker.java |
1,883 | import java.io.Serializable;
// Πρέπει να κάνω υλοποίηση της διασύνδεσης για να μπορούν να πάνε σε δυαδικό αρχείο (βγάζει σφάλμα αν δεν έχει)
public class Employee implements Serializable{
private String name;
private Car ownedCar;
public Employee(String name, Car aCar){
this.name = name;
this.ownedCar = aCar;
}
public String getName(){
return name;
}
public Car getCar(){
return ownedCar;
}
}
| iosifidis/UoM-Applied-Informatics | s3/object_oriented_programming/lectures/BinaryFiles_v5/src/Employee.java |
Subsets and Splits