Search in sources :

Example 76 with IOError

use of java.io.IOError in project LAMSADE-tools by LAntoine.

the class MainProgram method main.

/**
 * The main that display the whole LAMSADE-Tools application The application
 * needs at least that the user enters his login or his Firstname + Lastname
 *
 * @param args
 * @throws SQLException
 */
public static void main(String[] args) throws SQLException {
    Preferences prefs = Preferences.userRoot().node("graphical_prefs :");
    System.setProperty("SWT_GTK3", "0");
    Display display = new Display();
    shell = new Shell(display);
    shell.setText("Conference List");
    GridLayout gridLayout = new GridLayout();
    shell.setLayout(gridLayout);
    shell.setLocation(400, 200);
    shell.layout(true, true);
    final Point newSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT, true);
    shell.setSize(new Point(912, 796));
    Menu bar = display.getMenuBar();
    if (bar == null) {
        bar = new Menu(shell, SWT.BAR);
        shell.setMenuBar(bar);
    }
    // File menu
    MenuItem fileItem = new MenuItem(bar, SWT.CASCADE);
    fileItem.setText("&File");
    Menu submenu = new Menu(shell, SWT.DROP_DOWN);
    fileItem.setMenu(submenu);
    MenuItem item = new MenuItem(submenu, SWT.PUSH);
    item.addListener(SWT.Selection, e -> PreferencesWindow.open(display));
    item.setText("Preferences");
    // Help menu
    MenuItem helpItem = new MenuItem(bar, SWT.CASCADE);
    helpItem.setText("&Help");
    Menu submenu2 = new Menu(shell, SWT.DROP_DOWN);
    helpItem.setMenu(submenu2);
    MenuItem help = new MenuItem(submenu2, SWT.PUSH);
    help.addListener(SWT.Selection, e -> Util.openURL("https://github.com/LAntoine/LAMSADE-tools"));
    help.setText("Help");
    MenuItem about = new MenuItem(submenu2, SWT.PUSH);
    about.addListener(SWT.Selection, e -> AboutWindow.open(display));
    about.setText("About");
    /*
		 * Initialize Group userDetails which will include : -The Grid data
		 * which will display the information on the user
		 *
		 * -The button that will allow the user to fill in his user information
		 * using Dauphine's yearbook -The button that will allow him to generate
		 * a document with his information
		 */
    Group grpUserDetails = new Group(shell, SWT.NONE);
    GridData gd_grpUserDetails = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_grpUserDetails.widthHint = 860;
    gd_grpUserDetails.heightHint = 244;
    grpUserDetails.setLayoutData(gd_grpUserDetails);
    grpUserDetails.setText("User Details");
    Label lblFirstname = new Label(grpUserDetails, SWT.NONE);
    lblFirstname.setBounds(10, 26, 70, 15);
    lblFirstname.setText("First Name");
    Label lblNewLabel_1 = new Label(grpUserDetails, SWT.NONE);
    lblNewLabel_1.setBounds(10, 53, 70, 15);
    lblNewLabel_1.setText("Last Name");
    Label lblLogin = new Label(grpUserDetails, SWT.NONE);
    lblLogin.setText("Login");
    lblLogin.setBounds(9, 85, 70, 15);
    txt_firstname = new Text(grpUserDetails, SWT.BORDER);
    txt_firstname.setBounds(86, 23, 98, 21);
    txt_firstname.setText(Prefs.getSurname());
    txt_firstname.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            Prefs.setSurname(txt_firstname.getText());
        }
    });
    txt_lastname = new Text(grpUserDetails, SWT.BORDER);
    txt_lastname.setBounds(86, 50, 98, 21);
    txt_lastname.setText(Prefs.getName());
    txt_lastname.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            Prefs.setName(txt_lastname.getText());
        }
    });
    txt_login = new Text(grpUserDetails, SWT.BORDER);
    txt_login.setBounds(85, 82, 98, 21);
    txt_login.setText(Prefs.getLogin());
    txt_login.addModifyListener(new ModifyListener() {

        @Override
        public void modifyText(ModifyEvent e) {
            Prefs.setLogin(txt_login.getText());
        }
    });
    /*
		 * Handle the User Info's Search Throws exception if firstname or
		 * lastname is wrong
		 */
    Button btn_searchInfo = new Button(grpUserDetails, SWT.NONE);
    btn_searchInfo.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            try {
                LOGGER.debug("Launching GetInfosFromYearbook.getUserDetails with : " + txt_lastname.getText() + " and " + txt_firstname.getText());
                UserDetails user = null;
                if (!txt_login.getText().isEmpty()) {
                    user = GetInfosFromYearbook.getUserDetails(txt_login.getText());
                    txt_firstname.setText(user.getFirstName());
                    txt_lastname.setText(user.getName());
                } else {
                    user = GetInfosFromYearbook.getUserDetails(txt_lastname.getText(), txt_firstname.getText());
                }
                txt_function.setText(user.getFunction());
                txt_number.setText(user.getNumber());
                txt_email.setText(user.getEmail());
                txt_group.setText(user.getGroup());
                txt_fax.setText(user.getFax());
                txt_office.setText(user.getOffice());
                txt_city_ud.setText(user.getCity());
                txt_country_ud.setText(user.getCountry());
            } catch (Exception e) {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Error");
                mb.setMessage("Please verify firstname and lastname");
                mb.open();
            }
        }
    });
    btn_searchInfo.setBounds(26, 111, 158, 25);
    btn_searchInfo.setText("Search My Info");
    Label lbl_function = new Label(grpUserDetails, SWT.NONE);
    lbl_function.setBounds(224, 26, 55, 15);
    lbl_function.setText("Function");
    Label lbl_number = new Label(grpUserDetails, SWT.NONE);
    lbl_number.setBounds(224, 56, 55, 15);
    lbl_number.setText("Phone");
    Label lbl_email = new Label(grpUserDetails, SWT.NONE);
    lbl_email.setBounds(224, 92, 55, 15);
    lbl_email.setText("E-mail");
    Label lbl_group = new Label(grpUserDetails, SWT.NONE);
    lbl_group.setBounds(224, 124, 55, 15);
    lbl_group.setText("Group");
    txt_function = new Text(grpUserDetails, SWT.BORDER);
    txt_function.setBounds(285, 20, 219, 21);
    txt_number = new Text(grpUserDetails, SWT.BORDER);
    txt_number.setBounds(285, 53, 219, 21);
    txt_email = new Text(grpUserDetails, SWT.BORDER);
    txt_email.setBounds(285, 87, 219, 21);
    txt_group = new Text(grpUserDetails, SWT.BORDER);
    txt_group.setBounds(285, 121, 219, 21);
    Label lbl_fax = new Label(grpUserDetails, SWT.NONE);
    lbl_fax.setText("Fax");
    lbl_fax.setBounds(535, 26, 55, 15);
    Label lbl_office = new Label(grpUserDetails, SWT.NONE);
    lbl_office.setText("Office");
    lbl_office.setBounds(535, 59, 55, 15);
    Label lbl_city = new Label(grpUserDetails, SWT.NONE);
    lbl_city.setText("City");
    lbl_city.setBounds(535, 92, 55, 15);
    Label lbl_country = new Label(grpUserDetails, SWT.NONE);
    lbl_country.setText("Country");
    lbl_country.setBounds(535, 124, 55, 15);
    txt_fax = new Text(grpUserDetails, SWT.BORDER);
    txt_fax.setBounds(596, 23, 219, 21);
    txt_office = new Text(grpUserDetails, SWT.BORDER);
    txt_office.setBounds(596, 56, 219, 21);
    txt_city_ud = new Text(grpUserDetails, SWT.BORDER);
    txt_city_ud.setBounds(596, 89, 219, 21);
    txt_country_ud = new Text(grpUserDetails, SWT.BORDER);
    txt_country_ud.setBounds(596, 121, 219, 21);
    Button btnGeneratePapierEn = new Button(grpUserDetails, SWT.NONE);
    btnGeneratePapierEn.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            LOGGER.debug("Button clicked : Paper with header");
            UserDetails user = getUserDetails();
            if (user != null) {
                try {
                    MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                    mb.setText("Success");
                    mb.setMessage("File saved in : " + SetCoordinates.fillPapierEnTete(user, FileSystems.getDefault().getPath(Prefs.getSaveDir())));
                    LOGGER.debug("SetCoordinates.fillPapierEnTete completed");
                    mb.open();
                } catch (Exception e2) {
                    throw new IllegalStateException(e2);
                }
            } else {
                LOGGER.error("Could not run SetCoordinates.fillPapierEnTete");
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Information missing");
                mb.setMessage("Please fill name and first name");
                mb.open();
            }
        }
    });
    Label lblPlaceholder = new Label(grpUserDetails, SWT.NONE);
    lblPlaceholder.setBounds(197, 217, 658, 14);
    lblPlaceholder.setText("");
    btnGeneratePapierEn.setBounds(25, 142, 159, 28);
    btnGeneratePapierEn.setText("Generate Papier");
    /*
		 * Initialize Group conferencesInfos which will include : -The Grid data
		 * which will display conferences
		 *
		 * -The buttons that will allow the user to add a new conference in the
		 * database, [the following operations are available for a selected
		 * conference] to export an event as a calendar file, to display an
		 * itinerary from Paris to the conference City And an other button to
		 * check the available flights
		 */
    // Group Conferences informations
    Group grp_conferencesInfos = new Group(shell, SWT.NONE);
    GridData gd_conferencesInfos = new GridData(SWT.LEFT, SWT.CENTER, false, false, 1, 1);
    gd_conferencesInfos.heightHint = 214;
    gd_conferencesInfos.widthHint = 860;
    grp_conferencesInfos.setLayoutData(gd_conferencesInfos);
    grp_conferencesInfos.setText("Conferences");
    Table table = new Table(grp_conferencesInfos, SWT.V_SCROLL | SWT.SINGLE | SWT.FULL_SELECTION);
    table.setBounds(165, 16, 502, 134);
    table.setHeaderVisible(true);
    fillConferenceTable(table);
    Button btn_addNewConf = new Button(grp_conferencesInfos, SWT.NONE);
    btn_addNewConf.setBounds(165, 156, 149, 25);
    btn_addNewConf.setText("Create conference");
    Label lblTitle = new Label(grp_conferencesInfos, SWT.NONE);
    lblTitle.setAlignment(SWT.RIGHT);
    lblTitle.setBounds(25, 16, 50, 15);
    lblTitle.setText("Title");
    Text txt_title = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_title.setBounds(81, 15, 78, 21);
    Label lblUrl = new Label(grp_conferencesInfos, SWT.NONE);
    lblUrl.setAlignment(SWT.RIGHT);
    lblUrl.setText("URL");
    lblUrl.setBounds(25, 45, 50, 15);
    Text txt_url = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_url.setBounds(81, 42, 78, 21);
    Label lblStartDate = new Label(grp_conferencesInfos, SWT.NONE);
    lblStartDate.setAlignment(SWT.RIGHT);
    lblStartDate.setText("Start Date");
    lblStartDate.setBounds(10, 72, 65, 15);
    Text txt_startDate = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_startDate.setBounds(81, 69, 78, 21);
    Label lblEndDate = new Label(grp_conferencesInfos, SWT.NONE);
    lblEndDate.setAlignment(SWT.RIGHT);
    lblEndDate.setText("End Date");
    lblEndDate.setBounds(10, 99, 65, 15);
    Text txt_endDate = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_endDate.setBounds(81, 96, 78, 21);
    Label lblFee = new Label(grp_conferencesInfos, SWT.NONE);
    lblFee.setText("Fee");
    lblFee.setBounds(42, 126, 33, 15);
    Text txt_fee = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_fee.setBounds(81, 123, 78, 21);
    // add news fields
    Label lblCity = new Label(grp_conferencesInfos, SWT.NONE);
    lblCity.setAlignment(SWT.RIGHT);
    lblCity.setBounds(25, 153, 50, 15);
    lblCity.setText("City");
    Text txt_city = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_city.setBounds(81, 150, 78, 21);
    Label lblCountry = new Label(grp_conferencesInfos, SWT.NONE);
    lblCountry.setAlignment(SWT.RIGHT);
    lblCountry.setBounds(25, 180, 50, 15);
    lblCountry.setText("Country");
    Text txt_address = new Text(grp_conferencesInfos, SWT.BORDER);
    txt_address.setBounds(81, 177, 78, 21);
    /**
     * Create new Conference object, assign it values from selection, then
     * pass it function to export to desktop public Conference(int id,
     * String title, String url, LocalDate start_date, LocalDate end_date,
     * double entry_fee)
     */
    Button btnExportEvent = new Button(grp_conferencesInfos, SWT.NONE);
    btnExportEvent.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/M/yyyy");
            TableItem[] ti = table.getSelection();
            if (ti.length == 0) {
            // TODO: Put somewhere that an event should be selected
            } else {
                Conference conf = new Conference(ti[0].getText(0), ti[0].getText(1), LocalDate.parse(ti[0].getText(2), formatter), LocalDate.parse(ti[0].getText(3), formatter), Double.parseDouble(ti[0].getText(4)), ti[0].getText(5), ti[0].getText(6));
                try {
                    FileDialog dialog = new FileDialog(shell, SWT.SAVE);
                    dialog.setFilterNames(new String[] { "Calendar Files", "All Files (*.*)" });
                    // Windows
                    dialog.setFilterExtensions(new String[] { "*.ics", "*.*" });
                    switch(Util.getOS()) {
                        case WINDOWS:
                            dialog.setFilterPath("c:\\");
                            break;
                        case LINUX:
                            dialog.setFilterPath("/");
                            break;
                        case MAC:
                            dialog.setFilterPath("/");
                            break;
                        case SOLARIS:
                            dialog.setFilterPath("/");
                            break;
                        default:
                            dialog.setFilterPath("/");
                    }
                    dialog.setFileName("conference.ics");
                    String path = dialog.open();
                    File pathToFile = new File(path);
                    if (pathToFile.exists()) {
                        LOGGER.info("Duplicate Detected");
                        MessageBox mBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
                        mBox.setText("Duplicate detected");
                        mBox.setMessage("A file with that name already exists. Would you like to replace it?");
                        int returnCode = mBox.open();
                        if (returnCode == 256) {
                            LOGGER.info("User chose not to replace the existing file");
                        } else {
                            LOGGER.info("User chose to replace the existing file");
                            LOGGER.info(pathToFile.getAbsolutePath());
                            conf.generateCalendarFile(pathToFile.getAbsolutePath());
                        }
                    } else {
                        conf.generateCalendarFile(pathToFile.getAbsolutePath());
                    }
                } catch (ValidationException | ParserException e2) {
                    e2.printStackTrace();
                } catch (Exception e1) {
                    throw new IllegalStateException(e1);
                }
            }
        }
    });
    btnExportEvent.setBounds(320, 154, 104, 28);
    btnExportEvent.setText("Export Event");
    Button btnSaveOrdreMission = new Button(grp_conferencesInfos, SWT.NONE);
    btnSaveOrdreMission.setBounds(684, 32, 176, 28);
    btnSaveOrdreMission.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            FileDialog dialog = new FileDialog(shell, SWT.OPEN);
            LOGGER.info("Opening the file dialog for user to choose a file to save to the app");
            String dialogResult = dialog.open();
            LOGGER.info("File chosen: " + dialogResult);
            if (dialogResult == null) {
                LOGGER.info("User closed the file save dialog");
            } else {
                // Check if there exists a file with the same name in our
                // missions directory
                Path path = FileSystems.getDefault().getPath("");
                String pathToTargetFile = path.toAbsolutePath() + "/missions/" + new File(dialogResult).getName();
                File pathToProject = new File(pathToTargetFile);
                boolean exists = pathToProject.exists();
                if (exists == true) {
                    LOGGER.info("Duplicate Detected");
                    MessageBox mBox = new MessageBox(shell, SWT.ICON_QUESTION | SWT.OK | SWT.CANCEL);
                    mBox.setText("Duplicate detected");
                    mBox.setMessage("A file with that name already exists. Would you like to replace it?");
                    int returnCode = mBox.open();
                    if (returnCode == 256) {
                        LOGGER.info("User chose not to replace the existing file");
                    } else {
                        LOGGER.info("User chose to replace the existing file");
                        Util.saveFile(dialogResult);
                        try {
                            MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            mb.setText("Success");
                            mb.setMessage("File saved in : " + pathToTargetFile);
                            LOGGER.debug("SetCoordinates.fillPapierEnTete completed");
                            mb.open();
                        } catch (Exception e2) {
                            throw new IllegalStateException(e2);
                        }
                    }
                } else {
                    LOGGER.info("Calling saveFile(String) to save the file to disk");
                    Util.saveFile(dialogResult);
                    try {
                        MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                        mb.setText("Success");
                        mb.setMessage("File saved in : " + pathToTargetFile);
                        LOGGER.debug("SetCoordinates.fillPapierEnTete completed");
                        mb.open();
                    } catch (Exception e2) {
                        throw new IllegalStateException(e2);
                    }
                }
            }
        }
    });
    btnSaveOrdreMission.setText("Save Ordre Mission");
    Button btnYoungSearcher = new Button(grp_conferencesInfos, SWT.CHECK);
    btnYoungSearcher.setBounds(684, 114, 125, 16);
    btnYoungSearcher.setText("Young searcher");
    btnYoungSearcher.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent event) {
            Button btn = (Button) event.getSource();
            tabHisto.removeAll();
            fillHistoricTable(tabHisto, btn.getSelection());
        }
    });
    /**
     * Handle here the GenerateOrderMission button because it needs the
     * table to be set This button handles order mission generations for
     * both searcher and young searcher, depending on the checkbox
     * "btnYoungSearcher" status
     */
    Button btnGenerateOM = new Button(grp_conferencesInfos, SWT.NONE);
    btnGenerateOM.setBounds(684, 72, 176, 28);
    btnGenerateOM.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            UserDetails user = getUserDetails();
            if (user != null && table.getSelection().length != 0) {
                TableItem[] items = table.getSelection();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/M/yyyy");
                Conference conf = new Conference(items[0].getText(0), items[0].getText(1), LocalDate.parse(items[0].getText(2), formatter), LocalDate.parse(items[0].getText(3), formatter), Double.valueOf(items[0].getText(4)), items[0].getText(5), items[0].getText(6));
                LOGGER.debug(items[0].getText(5) + " " + items[0].getText(6));
                if (btnYoungSearcher.getSelection()) {
                    try {
                        String fileName = Prefs.getSaveDir() + "\\DJC_" + conf.getCity() + "-" + conf.getCountry() + "_" + conf.getStart_date() + ".fodt";
                        GenerateMissionOrderYS.fillYSOrderMission(user, conf, fileName);
                        try {
                            MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            mb.setText("Success");
                            mb.setMessage("File saved in : " + fileName);
                            LOGGER.debug("SetCoordinates.fillPapierEnTete completed");
                            mb.open();
                        } catch (Exception e2) {
                            throw new IllegalStateException(e2);
                        }
                        tabHisto.removeAll();
                        fillHistoricTable(tabHisto, true);
                    } catch (IllegalArgumentException | IOException | SAXException | ParserConfigurationException e1) {
                        LOGGER.error("Error : ", e1);
                        throw new IllegalStateException(e1);
                    }
                } else {
                    try {
                        String fileName = Prefs.getSaveDir() + "\\OM_" + conf.getCity() + "-" + conf.getCountry() + "_" + conf.getStart_date() + ".ods";
                        GenerateMissionOrder.generateSpreadsheetDocument(user, conf, fileName);
                        try {
                            MessageBox mb = new MessageBox(shell, SWT.ICON_INFORMATION | SWT.OK);
                            mb.setText("Success");
                            mb.setMessage("File saved in : " + fileName);
                            LOGGER.debug("SetCoordinates.fillPapierEnTete completed");
                            mb.open();
                        } catch (Exception e2) {
                            throw new IllegalStateException(e2);
                        }
                        tabHisto.removeAll();
                        fillHistoricTable(tabHisto, false);
                    } catch (Exception e1) {
                        LOGGER.error("Error : ", e1);
                        throw new IllegalStateException(e1);
                    }
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Information missing");
                mb.setMessage("Please fill user information and select a conference");
                mb.open();
            }
        }
    });
    btnGenerateOM.setText("Generate Order Mission");
    Button btnItinerary = new Button(grp_conferencesInfos, SWT.NONE);
    btnItinerary.setBounds(440, 156, 115, 25);
    btnItinerary.setText("Itinerary");
    /**
     * This button allow the user to check the available flights to get to
     * his conference The departure point is always set to Paris
     */
    Button btnFlight = new Button(grp_conferencesInfos, SWT.NONE);
    btnFlight.setBounds(561, 156, 84, 25);
    btnFlight.setText("Flights");
    btnFlight.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent e) {
            if (table.getSelection().length != 0) {
                try {
                    TableItem[] items = table.getSelection();
                    String city = items[0].getText(5);
                    String url = "https://www.google.fr/flights/flights-from-paris-to-" + city + ".html";
                    // LOGGER.info(url);
                    try {
                        Util.openURL(url);
                    } catch (IllegalStateException e4) {
                        LOGGER.error("The city name is not valid");
                        MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                        mb.setText("Validation Error");
                        mb.setMessage("The city name is not valid");
                        mb.open();
                    }
                } catch (IllegalArgumentException e2) {
                    LOGGER.error("Error : ", e2);
                } catch (Exception e1) {
                    throw new IllegalStateException(e1);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Information missing");
                mb.setMessage("Please choose a conference");
                mb.open();
            }
        }
    });
    /**
     * This Button allows the user to check his itinerary from the departure
     * point (set to Paris) to the conference destination Needs a conference
     * to be selected It will open Google maps on the browser with the
     * itinerary set
     */
    btnItinerary.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            if (table.getSelection().length != 0) {
                try {
                    TableItem[] items = table.getSelection();
                    GoogleItineraryMap itinerary = new GoogleItineraryMap("Paris", items[0].getText(5));
                    String url = itinerary.setMapUrl();
                    LOGGER.debug(url);
                    itinerary.openMapUrl(url);
                } catch (IllegalArgumentException e) {
                    LOGGER.error("Error : ", e);
                } catch (Exception e) {
                    throw new IllegalStateException(e);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Information missing");
                mb.setMessage("Please Choose a Conference");
                mb.open();
            }
        }
    });
    /**
     * Behavior of a click on the add new conference button
     */
    btn_addNewConf.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            System.out.println("Appui sur le bouton");
            if (!txt_title.getText().isEmpty() && !txt_url.getText().isEmpty() && !txt_startDate.getText().isEmpty() && !txt_startDate.getText().isEmpty() && !txt_endDate.getText().isEmpty() && !txt_fee.getText().isEmpty()) {
                try {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
                    LocalDate startDate = LocalDate.parse(txt_startDate.getText(), formatter);
                    LocalDate endDate = LocalDate.parse(txt_endDate.getText(), formatter);
                    Conference conf = new Conference(txt_title.getText(), txt_url.getText(), startDate, endDate, Double.parseDouble(txt_fee.getText()), txt_city.getText(), txt_address.getText());
                    ConferenceDatabase.insertInDatabase(conf);
                    /*
						 * Reload the conference table
						 */
                    table.removeAll();
                    fillConferenceTable(table);
                } catch (DateTimeParseException e1) {
                    MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                    mb.setText("Date format error");
                    mb.setMessage("Please fill the dates in the following format : dd/MM/YYYY");
                    mb.open();
                } catch (SQLException e2) {
                    throw new IllegalStateException(e2);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("Information missing");
                mb.setMessage("Please fill in the information regarding the conference");
                mb.open();
            }
        }
    });
    /**
     * This group handles all the Mission order history
     */
    Group grp_bottom = new Group(shell, SWT.NONE);
    grp_bottom.setLayout(new RowLayout(SWT.HORIZONTAL));
    GridData gd_grp_bottom = new GridData(SWT.LEFT, SWT.CENTER, false, true, 1, 1);
    gd_grp_bottom.heightHint = 236;
    gd_grp_bottom.widthHint = 857;
    grp_bottom.setLayoutData(gd_grp_bottom);
    Group grpHistoric = new Group(grp_bottom, SWT.NONE);
    grpHistoric.setLayoutData(new RowData(455, 183));
    grpHistoric.setText("Historic");
    tabHisto = new Table(grpHistoric, SWT.BORDER | SWT.FULL_SELECTION);
    tabHisto.setBounds(10, 25, 233, 166);
    tabHisto.setHeaderVisible(true);
    tabHisto.setLinesVisible(true);
    // display arbitrary the OM historic
    fillHistoricTable(tabHisto, false);
    Button btnDeleteFile = new Button(grpHistoric, SWT.NONE);
    btnDeleteFile.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            if (tabHisto.getSelection().length != 0) {
                Boolean isYC;
                if (btnYoungSearcher.getSelection()) {
                    isYC = true;
                } else {
                    isYC = false;
                }
                TableItem[] item = tabHisto.getSelection();
                History.deleteFile(item[0].getText(0), isYC);
                tabHisto.removeAll();
                if (btnYoungSearcher.getSelection()) {
                    fillHistoricTable(tabHisto, true);
                } else {
                    fillHistoricTable(tabHisto, false);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("No File selected");
                mb.setMessage("Please Choose a file in the list");
                mb.open();
            }
        }
    });
    btnDeleteFile.setText("Delete");
    btnDeleteFile.setBounds(276, 86, 103, 32);
    Button btnOpen = new Button(grpHistoric, SWT.NONE);
    btnOpen.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            if (tabHisto.getSelection().length != 0) {
                Boolean isYC;
                if (btnYoungSearcher.getSelection()) {
                    isYC = true;
                } else {
                    isYC = false;
                }
                TableItem[] item = tabHisto.getSelection();
                try {
                    History.openFile(item[0].getText(0), isYC);
                } catch (IOError | IOException e) {
                    throw new IOError(e);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("No File selected");
                mb.setMessage("Please Choose a file in the list");
                mb.open();
            }
        }
    });
    btnOpen.setText("Open");
    btnOpen.setBounds(276, 38, 103, 32);
    /**
     * Send Email Be careful modification for presentation
     */
    Button btnSendTo = new Button(grpHistoric, SWT.NONE);
    btnSendTo.addSelectionListener(new SelectionAdapter() {

        @Override
        public void widgetSelected(SelectionEvent arg0) {
            if (tabHisto.getSelection().length != 0) /*
													 * || txt_email.getText() ==
													 * "" || txt_email.getText()
													 * == null
													 */
            {
                Boolean isYC;
                if (btnYoungSearcher.getSelection()) {
                    isYC = true;
                } else {
                    isYC = false;
                }
                TableItem[] item = tabHisto.getSelection();
                String pathToFile = History.getFilePath(item[0].getText(0), isYC);
                try {
                    // Be Careful ! Only for demonstration !!
                    // sendEmail(txt_email.getText(), path);
                    Util.sendEmail("lamsadetoolsuser@gmail.com", pathToFile);
                } catch (IOError e) {
                    throw new IOError(e);
                }
            } else {
                MessageBox mb = new MessageBox(shell, SWT.ICON_ERROR | SWT.OK);
                mb.setText("No File selected or no mail adress");
                mb.setMessage("Please Choose a file in the list");
                mb.open();
            }
        }
    });
    btnSendTo.setText("Send To");
    btnSendTo.setBounds(276, 142, 103, 32);
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch()) {
            display.sleep();
        }
    }
    display.dispose();
}
Also used : Group(org.eclipse.swt.widgets.Group) ModifyListener(org.eclipse.swt.events.ModifyListener) SQLException(java.sql.SQLException) Label(org.eclipse.swt.widgets.Label) Conference(com.github.lantoine.lamsadetools.conferences.Conference) LocalDate(java.time.LocalDate) Shell(org.eclipse.swt.widgets.Shell) GridLayout(org.eclipse.swt.layout.GridLayout) ModifyEvent(org.eclipse.swt.events.ModifyEvent) GoogleItineraryMap(com.github.lantoine.lamsadetools.map.GoogleItineraryMap) RowData(org.eclipse.swt.layout.RowData) UserDetails(com.github.lantoine.lamsadetools.setCoordinates.UserDetails) Button(org.eclipse.swt.widgets.Button) RowLayout(org.eclipse.swt.layout.RowLayout) SelectionEvent(org.eclipse.swt.events.SelectionEvent) Menu(org.eclipse.swt.widgets.Menu) Preferences(java.util.prefs.Preferences) Path(java.nio.file.Path) Table(org.eclipse.swt.widgets.Table) SelectionAdapter(org.eclipse.swt.events.SelectionAdapter) MenuItem(org.eclipse.swt.widgets.MenuItem) Text(org.eclipse.swt.widgets.Text) Point(org.eclipse.swt.graphics.Point) YearbookDataException(com.github.lantoine.lamsadetools.yearbookInfos.YearbookDataException) ParserException(net.fortuna.ical4j.data.ParserException) DateTimeParseException(java.time.format.DateTimeParseException) SAXException(org.xml.sax.SAXException) ValidationException(net.fortuna.ical4j.model.ValidationException) SQLException(java.sql.SQLException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) MessageBox(org.eclipse.swt.widgets.MessageBox) DateTimeParseException(java.time.format.DateTimeParseException) IOError(java.io.IOError) GridData(org.eclipse.swt.layout.GridData) DateTimeFormatter(java.time.format.DateTimeFormatter) FileDialog(org.eclipse.swt.widgets.FileDialog) File(java.io.File) Display(org.eclipse.swt.widgets.Display)

Example 77 with IOError

use of java.io.IOError in project apex-malhar by apache.

the class FlumeSink method process.

/* Begin implementing Flume Sink interface */
@Override
@SuppressWarnings({ "BroadCatchBlock", "TooBroadCatch", "UseSpecificCatch", "SleepWhileInLoop" })
public Status process() throws EventDeliveryException {
    Slice slice;
    synchronized (server.requests) {
        for (Request r : server.requests) {
            logger.debug("found {}", r);
            switch(r.type) {
                case SEEK:
                    lastCommitEventTimeMillis = System.currentTimeMillis();
                    slice = r.getAddress();
                    playback = storage.retrieve(Arrays.copyOfRange(slice.buffer, slice.offset, slice.offset + slice.length));
                    client = r.client;
                    break;
                case COMMITTED:
                    lastCommitEventTimeMillis = System.currentTimeMillis();
                    slice = r.getAddress();
                    storage.clean(Arrays.copyOfRange(slice.buffer, slice.offset, slice.offset + slice.length));
                    break;
                case CONNECTED:
                    logger.debug("Connected received, ignoring it!");
                    break;
                case DISCONNECTED:
                    if (r.client == client) {
                        client = null;
                        outstandingEventsCount = 0;
                    }
                    break;
                case WINDOWED:
                    lastConsumedEventsCount = r.getEventCount();
                    idleCount = r.getIdleCount();
                    outstandingEventsCount -= lastConsumedEventsCount;
                    break;
                case SERVER_ERROR:
                    throw new IOError(null);
                default:
                    logger.debug("Cannot understand the request {}", r);
                    break;
            }
        }
        server.requests.clear();
    }
    if (client == null) {
        logger.info("No client expressed interest yet to consume the events.");
        return Status.BACKOFF;
    } else if (System.currentTimeMillis() - lastCommitEventTimeMillis > commitEventTimeoutMillis) {
        logger.info("Client has not processed the workload given for the last {} milliseconds, so backing off.", System.currentTimeMillis() - lastCommitEventTimeMillis);
        return Status.BACKOFF;
    }
    int maxTuples;
    // the following logic needs to be fixed... this is a quick put together.
    if (outstandingEventsCount < 0) {
        if (idleCount > 1) {
            maxTuples = (int) ((1 + throughputAdjustmentFactor * idleCount) * lastConsumedEventsCount);
        } else {
            maxTuples = (int) ((1 + throughputAdjustmentFactor) * lastConsumedEventsCount);
        }
    } else if (outstandingEventsCount > lastConsumedEventsCount) {
        maxTuples = (int) ((1 - throughputAdjustmentFactor) * lastConsumedEventsCount);
    } else {
        if (idleCount > 0) {
            maxTuples = (int) ((1 + throughputAdjustmentFactor * idleCount) * lastConsumedEventsCount);
            if (maxTuples <= 0) {
                maxTuples = minimumEventsPerTransaction;
            }
        } else {
            maxTuples = lastConsumedEventsCount;
        }
    }
    if (maxTuples >= maximumEventsPerTransaction) {
        maxTuples = maximumEventsPerTransaction;
    } else if (maxTuples <= 0) {
        maxTuples = minimumEventsPerTransaction;
    }
    if (maxTuples > 0) {
        if (playback != null) {
            try {
                int i = 0;
                do {
                    if (!client.write(playback)) {
                        retryWrite(playback, null);
                    }
                    outstandingEventsCount++;
                    playback = storage.retrieveNext();
                } while (++i < maxTuples && playback != null);
            } catch (Exception ex) {
                logger.warn("Playback Failed", ex);
                if (ex instanceof NetletThrowable) {
                    try {
                        eventloop.disconnect(client);
                    } finally {
                        client = null;
                        outstandingEventsCount = 0;
                    }
                }
                return Status.BACKOFF;
            }
        } else {
            int storedTuples = 0;
            Transaction t = getChannel().getTransaction();
            try {
                t.begin();
                Event e;
                while (storedTuples < maxTuples && (e = getChannel().take()) != null) {
                    Slice event = codec.toByteArray(e);
                    byte[] address = storage.store(event);
                    if (address != null) {
                        if (!client.write(address, event)) {
                            retryWrite(address, event);
                        }
                        outstandingEventsCount++;
                    } else {
                        logger.debug("Detected the condition of recovery from flume crash!");
                    }
                    storedTuples++;
                }
                if (storedTuples > 0) {
                    storage.flush();
                }
                t.commit();
                if (storedTuples > 0) {
                    /* log less frequently */
                    logger.debug("Transaction details maxTuples = {}, storedTuples = {}, outstanding = {}", maxTuples, storedTuples, outstandingEventsCount);
                }
            } catch (Error er) {
                t.rollback();
                throw er;
            } catch (Exception ex) {
                logger.error("Transaction Failed", ex);
                if (ex instanceof NetletRuntimeException && client != null) {
                    try {
                        eventloop.disconnect(client);
                    } finally {
                        client = null;
                        outstandingEventsCount = 0;
                    }
                }
                t.rollback();
                return Status.BACKOFF;
            } finally {
                t.close();
            }
            if (storedTuples == 0) {
                sleep();
            }
        }
    }
    return Status.READY;
}
Also used : NetletThrowable(com.datatorrent.netlet.NetletThrowable) Transaction(org.apache.flume.Transaction) IOError(java.io.IOError) Slice(com.datatorrent.netlet.util.Slice) Request(org.apache.apex.malhar.flume.sink.Server.Request) Event(org.apache.flume.Event) ServiceConfigurationError(java.util.ServiceConfigurationError) IOError(java.io.IOError) NetletRuntimeException(com.datatorrent.netlet.NetletThrowable.NetletRuntimeException) EventDeliveryException(org.apache.flume.EventDeliveryException) IOException(java.io.IOException) NetletRuntimeException(com.datatorrent.netlet.NetletThrowable.NetletRuntimeException)

Example 78 with IOError

use of java.io.IOError in project qpid-broker-j by apache.

the class BrokerLoggerStatusListenerTest method testAddStatusEventForIOError.

@Test
public void testAddStatusEventForIOError() {
    Status event = createEvent(new IOError(new IOException("Mocked: No disk space left")), Status.ERROR);
    _statusListener.addStatusEvent(event);
    verify(_systemConfig).closeAsync();
}
Also used : Status(ch.qos.logback.core.status.Status) IOError(java.io.IOError) IOException(java.io.IOException) Test(org.junit.Test)

Aggregations

IOError (java.io.IOError)78 IOException (java.io.IOException)58 File (java.io.File)11 ArrayList (java.util.ArrayList)8 Path (java.nio.file.Path)5 Status (ch.qos.logback.core.status.Status)4 BufferedReader (java.io.BufferedReader)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Console (java.io.Console)4 DataInputStream (java.io.DataInputStream)4 IPartitioner (org.apache.cassandra.dht.IPartitioner)4 FastByteArrayInputStream (org.apache.cassandra.io.util.FastByteArrayInputStream)4 Test (org.junit.Test)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 InputStream (java.io.InputStream)3 ByteBuffer (java.nio.ByteBuffer)3 AtomicReference (java.util.concurrent.atomic.AtomicReference)3 QueryPath (org.apache.cassandra.db.filter.QueryPath)3 CorruptSSTableException (org.apache.cassandra.io.sstable.CorruptSSTableException)3 SSTableReader (org.apache.cassandra.io.sstable.format.SSTableReader)3