Example usage for org.joda.time DateTime plusSeconds

List of usage examples for org.joda.time DateTime plusSeconds

Introduction

In this page you can find the example usage for org.joda.time DateTime plusSeconds.

Prototype

public DateTime plusSeconds(int seconds) 

Source Link

Document

Returns a copy of this datetime plus the specified number of seconds.

Usage

From source file:net.tourbook.printing.DialogPrintTour.java

License:Open Source License

/**
 * Overwrite filename with the first tour date/time when the tour is not merged
 *///from  w  w  w  . j  a  v  a 2 s. co m
private void setFileName() {

    // search for the first tour
    TourData minTourData = null;
    final long minTourMillis = 0;

    for (final TourData tourData : _tourDataList) {
        final DateTime checkingTourDate = TourManager.getTourDateTime(tourData);

        if (minTourData == null) {
            minTourData = tourData;
        } else {

            final long tourMillis = checkingTourDate.getMillis();
            if (tourMillis < minTourMillis) {
                minTourData = tourData;
            }
        }
    }

    if ((_tourDataList.size() == 1) && (_tourStartIndex != -1) && (_tourEndIndex != -1)) {

        // display the start date/time

        final DateTime dtTour = new DateTime(minTourData.getStartYear(), minTourData.getStartMonth(),
                minTourData.getStartDay(), minTourData.getStartHour(), minTourData.getStartMinute(),
                minTourData.getStartSecond(), 0);

        final int startTime = minTourData.timeSerie[_tourStartIndex];
        final DateTime tourTime = dtTour.plusSeconds(startTime);

        _comboFile.setText(UI.format_yyyymmdd_hhmmss(tourTime.getYear(), tourTime.getMonthOfYear(),
                tourTime.getDayOfMonth(), tourTime.getHourOfDay(), tourTime.getMinuteOfHour(),
                tourTime.getSecondOfMinute()));
    } else {

        // display the tour date/time

        _comboFile.setText(UI.format_yyyymmdd_hhmmss(minTourData));
    }
}

From source file:net.tourbook.tour.DialogExtractTour.java

License:Open Source License

private void restoreState() {

    _txtTourTitle.setText(//from   w w w .j a v a 2s  .  c o  m
            Util.getStateString(_state, STATE_TOUR_TITLE, Messages.Dialog_SplitTour_Label_DefaultTitle));

    // tour title source
    Util.selectStateInCombo(_state, STATE_TOUR_TITLE_SOURCE, ALL_STATES_TOUR_TILE_SOURCE,
            STATE_TOUR_TITLE_SOURCE_FROM_TOUR, _cboTourTitleSource);

    // split method
    Util.selectStateInCombo(_state, STATE_EXTRACT_METHOD, ALL_STATES_EXTRACT_METHOD,
            STATE_EXTRACT_METHOD_REMOVE, _cboSplitMethod);

    // tour type source
    Util.selectStateInCombo(_state, STATE_TYPE_SOURCE, ALL_STATES_TOUR_TYPE,
            STATE_TYPE_SOURCE_FROM_SELECTED_TOURS, _cboTourTypeSource);

    // tour start date/time
    _chkKeepOriginalDateTime.setSelection(Util.getStateBoolean(_state, STATE_IS_KEEP_ORIGINAL_TIME, true));

    // description/marker/waypoints
    _chkIncludeDescription.setSelection(Util.getStateBoolean(_state, STATE_IS_INCLUDE_DESCRIPTION, true));
    _chkIncludeMarkerWaypoints
            .setSelection(Util.getStateBoolean(_state, STATE_IS_INCLUDE_MARKER_WAYPOINTS, true));

    /*
     * update UI from selected tours
     */

    final DateTime tourStartTime = new DateTime(_tourDataSource.getStartYear(), _tourDataSource.getStartMonth(),
            _tourDataSource.getStartDay(), _tourDataSource.getStartHour(), _tourDataSource.getStartMinute(),
            _tourDataSource.getStartSecond(), 0);

    int relativeExtractedStartTime = 0;

    final int[] tourTimeSerie = _tourDataSource.timeSerie;
    final boolean isTourTime = (tourTimeSerie != null) && (tourTimeSerie.length > 0);
    if (isTourTime) {
        relativeExtractedStartTime = tourTimeSerie[_extractStartIndex];
    }
    _extractedTourStartTime = tourStartTime.plusSeconds(relativeExtractedStartTime);

    // date/time
    _dtTourDate.setDate(_extractedTourStartTime.getYear(), _extractedTourStartTime.getMonthOfYear() - 1,
            _extractedTourStartTime.getDayOfMonth());

    _dtTourTime.setTime(_extractedTourStartTime.getHourOfDay(), _extractedTourStartTime.getMinuteOfHour(),
            _extractedTourStartTime.getSecondOfMinute());

    /*
     * fill person combo and reselect previous person
     */
    final long statePersonId = Util.getStateLong(_state, STATE_PERSON_ID, -1);

    if (_people == null) {
        final ArrayList<TourPerson> people = PersonManager.getTourPeople();
        _people = people.toArray(new TourPerson[people.size()]);
    }

    int index = 0;
    int personIndex = 0;

    for (final TourPerson person : _people) {

        _cboPerson.add(person.getName());

        if (person.getPersonId() == statePersonId) {
            personIndex = index;
        }

        index++;
    }

    _cboPerson.select(personIndex);

}

From source file:niche.newres.timedevents2owl.randomizer.TimedEvents2OWLRandomizer.java

public static DateTime plusRandomSeconds(DateTime dateTime, int minRange, int maxRange) {
    int randomSeconds = TimedEvents2OWLRandomizer.randInt(minRange, maxRange);

    return dateTime.plusSeconds(randomSeconds);
}

From source file:op.care.prescription.PnlPrescription.java

License:Open Source License

private JPanel getMenu(final Prescription prescription) {

    JPanel pnlMenu = new JPanel(new VerticalLayout());
    long numBHPs = BHPTools.getConfirmedBHPs(prescription);
    final MedInventory inventory = prescription.shouldBeCalculated()
            ? TradeFormTools.getInventory4TradeForm(prescription.getResident(), prescription.getTradeForm())
            : null;/*from   w  w w  . j av  a 2  s. c o  m*/
    final MedStock stockInUse = MedStockTools.getStockInUse(inventory);

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        /***
         *       ____ _
         *      / ___| |__   __ _ _ __   __ _  ___
         *     | |   | '_ \ / _` | '_ \ / _` |/ _ \
         *     | |___| | | | (_| | | | | (_| |  __/
         *      \____|_| |_|\__,_|_| |_|\__, |\___|
         *                              |___/
         */
        final JButton btnChange = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.btnChange.tooltip", SYSConst.icon22playerPlay, null);
        btnChange.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnChange.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgRegular(prescription.clone(), DlgRegular.MODE_CHANGE, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {

                            Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;

                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                em.lock(em.merge(resident), LockModeType.OPTIMISTIC);

                                // Fetch the new prescription from the PAIR
                                Prescription newPrescription = em.merge(returnPackage.getFirst());
                                Prescription oldPrescription = em.merge(prescription);
                                em.lock(oldPrescription, LockModeType.OPTIMISTIC);

                                // First close the old prescription
                                DateTime now = new DateTime();
                                oldPrescription.setTo(now.toDate());
                                oldPrescription.setUserOFF(em.merge(OPDE.getLogin().getUser()));
                                oldPrescription.setDocOFF(newPrescription.getDocON() == null ? null
                                        : em.merge(newPrescription.getDocON()));
                                oldPrescription.setHospitalOFF(newPrescription.getHospitalON() == null ? null
                                        : em.merge(newPrescription.getHospitalON()));

                                // the new prescription starts 1 second after the old one closes
                                newPrescription.setFrom(now.plusSeconds(1).toDate());

                                // create new BHPs according to the prescription
                                BHPTools.generate(em, newPrescription.getPrescriptionSchedule(),
                                        new LocalDate(), true);
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(oldPrescription);
                                lstPrescriptions.add(newPrescription);
                                Collections.sort(lstPrescriptions);

                                // Refresh Display
                                createCP4(oldPrescription);
                                final CollapsiblePane myNewCP = createCP4(newPrescription);
                                buildPanel();
                                GUITools.flashBackground(myNewCP, Color.YELLOW, 2);
                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                            //                                buildPanel();
                        }
                    }
                });
            }
        });
        btnChange.setEnabled(!prescription.isClosed() && !prescription.isOnDemand() && numBHPs != 0);
        pnlMenu.add(btnChange);

        /***
         *      ____  _
         *     / ___|| |_ ___  _ __
         *     \___ \| __/ _ \| '_ \
         *      ___) | || (_) | |_) |
         *     |____/ \__\___/| .__/
         *                    |_|
         */
        final JButton btnStop = GUITools.createHyperlinkButton("nursingrecords.prescription.btnStop.tooltip",
                SYSConst.icon22playerStop, null);
        btnStop.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnStop.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgDiscontinue(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                Prescription myPrescription = (Prescription) em.merge(o);
                                em.lock(myPrescription.getResident(), LockModeType.OPTIMISTIC);
                                em.lock(myPrescription, LockModeType.OPTIMISTIC);
                                myPrescription.setTo(new Date());
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);

                                buildPanel();

                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                new Closure() {
                                                    @Override
                                                    public void execute(Object o) {
                                                        GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                    }
                                                });
                                    }
                                });

                            } catch (OptimisticLockException ole) {
                                OPDE.warn(ole);
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                    OPDE.getMainframe().emptyFrame();
                                    OPDE.getMainframe().afterLogin();
                                }
                                OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            } catch (Exception e) {
                                em.getTransaction().rollback();
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });
            }
        });
        btnStop.setEnabled(!prescription.isClosed()); //  && numBHPs != 0
        pnlMenu.add(btnStop);

        /***
         *      _____    _ _ _
         *     | ____|__| (_) |_
         *     |  _| / _` | | __|
         *     | |__| (_| | | |_
         *     |_____\__,_|_|\__/
         *
         */
        final JButton btnEdit = GUITools.createHyperlinkButton("nursingrecords.prescription.btnEdit.tooltip",
                SYSConst.icon22edit3, null);
        btnEdit.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEdit.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                if (prescription.isOnDemand()) {
                    new DlgOnDemand(prescription, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    Prescription myPrescription = em.merge((Prescription) o);
                                    em.lock(myPrescription, LockModeType.OPTIMISTIC);

                                    Query queryDELBHP = em.createQuery(
                                            "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription");
                                    queryDELBHP.setParameter("prescription", myPrescription);
                                    queryDELBHP.executeUpdate();

                                    em.getTransaction().commit();

                                    lstPrescriptions.remove(prescription);
                                    lstPrescriptions.add(myPrescription);
                                    Collections.sort(lstPrescriptions);
                                    final CollapsiblePane myCP = createCP4(myPrescription);
                                    buildPanel();

                                    synchronized (listUsedCommontags) {
                                        boolean reloadSearch = false;
                                        for (Commontags ctag : myPrescription.getCommontags()) {
                                            if (!listUsedCommontags.contains(ctag)) {
                                                listUsedCommontags.add(ctag);
                                                reloadSearch = true;
                                            }
                                        }
                                        if (reloadSearch) {
                                            prepareSearchArea();
                                        }
                                    }
                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                    new Closure() {
                                                        @Override
                                                        public void execute(Object o) {
                                                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                        }
                                                    });
                                        }
                                    });

                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                                //                                    buildPanel();
                            }
                        }
                    });
                } else {
                    new DlgRegular(prescription, DlgRegular.MODE_EDIT, new Closure() {
                        @Override
                        public void execute(Object o) {
                            if (o != null) {

                                Pair<Prescription, java.util.List<PrescriptionSchedule>> returnPackage = (Pair<Prescription, List<PrescriptionSchedule>>) o;

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                    Prescription myPrescription = em.merge(returnPackage.getFirst());
                                    em.lock(myPrescription, LockModeType.OPTIMISTIC);

                                    // delete whats not in the new prescription anymore
                                    for (PrescriptionSchedule schedule : returnPackage.getSecond()) {
                                        em.remove(em.merge(schedule));
                                    }

                                    Query queryDELBHP = em.createQuery(
                                            "DELETE FROM BHP bhp WHERE bhp.prescription = :prescription");
                                    queryDELBHP.setParameter("prescription", myPrescription);
                                    queryDELBHP.executeUpdate();

                                    BHPTools.generate(em, myPrescription.getPrescriptionSchedule(),
                                            new LocalDate(), true);

                                    em.getTransaction().commit();

                                    lstPrescriptions.remove(prescription);
                                    lstPrescriptions.add(myPrescription);
                                    Collections.sort(lstPrescriptions);
                                    final CollapsiblePane myCP = createCP4(myPrescription);
                                    buildPanel();

                                    synchronized (listUsedCommontags) {
                                        boolean reloadSearch = false;
                                        for (Commontags ctag : myPrescription.getCommontags()) {
                                            if (!listUsedCommontags.contains(ctag)) {
                                                listUsedCommontags.add(ctag);
                                                reloadSearch = true;
                                            }
                                        }
                                        if (reloadSearch) {
                                            prepareSearchArea();
                                        }
                                    }

                                    SwingUtilities.invokeLater(new Runnable() {
                                        @Override
                                        public void run() {
                                            GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                    new Closure() {
                                                        @Override
                                                        public void execute(Object o) {
                                                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                        }
                                                    });
                                        }
                                    });

                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }
                                //                                    buildPanel();
                            }
                        }
                    });
                }
            }

        });
        btnEdit.setEnabled(!prescription.isClosed() && numBHPs == 0);
        pnlMenu.add(btnEdit);

        /***
         *      _     _       _____  _    ____
         *     | |__ | |_ _ _|_   _|/ \  / ___|___
         *     | '_ \| __| '_ \| | / _ \| |  _/ __|
         *     | |_) | |_| | | | |/ ___ \ |_| \__ \
         *     |_.__/ \__|_| |_|_/_/   \_\____|___/
         *
         */
        final JButton btnTAGs = GUITools.createHyperlinkButton("misc.msg.editTags", SYSConst.icon22tagPurple,
                null);
        btnTAGs.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnTAGs.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();

                final JPanel pnl = new JPanel(new BorderLayout(5, 5));
                final PnlCommonTags pnlCommonTags = new PnlCommonTags(prescription.getCommontags(), true, 3);
                pnl.add(new JScrollPane(pnlCommonTags), BorderLayout.CENTER);
                JButton btnApply = new JButton(SYSConst.icon22apply);
                pnl.add(btnApply, BorderLayout.SOUTH);
                btnApply.addActionListener(new ActionListener() {
                    @Override
                    public void actionPerformed(ActionEvent ae) {
                        EntityManager em = OPDE.createEM();
                        try {

                            em.getTransaction().begin();
                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            // merging is important, hence no addAll() for this one
                            ArrayList<Commontags> listTags2Add = new ArrayList<Commontags>();
                            for (Commontags tag2add : pnlCommonTags.getListSelectedTags()) {
                                listTags2Add.add(em.merge(tag2add));
                            }

                            // Annotations need to be added, tooo
                            // these are the remaining tags, that need to be disconnected
                            myPrescription.getCommontags().addAll(listTags2Add);
                            ArrayList<Commontags> listTags2Remove = new ArrayList<Commontags>(
                                    myPrescription.getCommontags());
                            listTags2Remove.removeAll(listTags2Add);

                            myPrescription.getCommontags().removeAll(listTags2Remove);

                            ArrayList<ResInfo> annotations2remove = new ArrayList<ResInfo>();
                            for (Commontags commontag : listTags2Remove) {
                                for (ResInfo annotation : myPrescription.getAnnotations()) {
                                    if (CommontagsTools.getTagForAnnotation(annotation).equals(commontag)) {
                                        annotations2remove.add(annotation);
                                        em.remove(annotation);
                                    }
                                }
                            }
                            myPrescription.getAnnotations().removeAll(annotations2remove);

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();

                            synchronized (listUsedCommontags) {
                                boolean reloadSearch = false;
                                for (Commontags ctag : myPrescription.getCommontags()) {
                                    if (!listUsedCommontags.contains(ctag)) {
                                        listUsedCommontags.add(ctag);
                                        reloadSearch = true;
                                    }
                                }
                                if (reloadSearch) {
                                    prepareSearchArea();
                                }
                            }

                            SwingUtilities.invokeLater(new Runnable() {
                                @Override
                                public void run() {
                                    GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                            new Closure() {
                                                @Override
                                                public void execute(Object o) {
                                                    GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                }
                                            });
                                }
                            });

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            } else {
                                reloadDisplay();
                            }
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });

                popup.setMovable(false);
                popup.getContentPane().setLayout(new BoxLayout(popup.getContentPane(), BoxLayout.LINE_AXIS));
                popup.setOwner(btnTAGs);
                popup.removeExcludedComponent(btnTAGs);
                pnl.setPreferredSize(new Dimension(350, 150));
                popup.getContentPane().add(pnl);
                popup.setDefaultFocusComponent(pnl);

                GUITools.showPopup(popup, SwingConstants.WEST);

            }
        });
        btnTAGs.setEnabled(!prescription.isClosed());
        pnlMenu.add(btnTAGs);

        /***
         *                              _        _
         *       __ _ _ __  _ __   ___ | |_ __ _| |_ ___
         *      / _` | '_ \| '_ \ / _ \| __/ _` | __/ _ \
         *     | (_| | | | | | | | (_) | || (_| | ||  __/
         *      \__,_|_| |_|_| |_|\___/ \__\__,_|\__\___|
         *
         */

        final JButton btnAnnotation = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.edit.annotations", SYSConst.icon22annotate, null);
        btnAnnotation.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnAnnotation.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                DlgAnnotations dlg = new DlgAnnotations(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();

                                ResInfo annotation = em.merge((ResInfo) o);

                                annotation.setHtml(ResInfoTools.getContentAsHTML(annotation));

                                Prescription myPrescription = em.merge(prescription);
                                em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                                myPrescription.getAnnotations().remove(annotation); // just in case, it was an EDIT rather than an ADD
                                myPrescription.getAnnotations().add(annotation);

                                em.lock(annotation, LockModeType.OPTIMISTIC);
                                em.getTransaction().commit();

                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);

                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                                buildPanel();

                                SwingUtilities.invokeLater(new Runnable() {
                                    @Override
                                    public void run() {
                                        GUITools.scroll2show(jspPrescription, myCP.getLocation().y - 100,
                                                new Closure() {
                                                    @Override
                                                    public void execute(Object o) {
                                                        GUITools.flashBackground(myCP, Color.YELLOW, 2);
                                                    }
                                                });
                                    }
                                });

                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                });

                OPDE.debug(lstPrescriptions);

                dlg.setVisible(true);

            }
        });
        btnAnnotation.setEnabled(!prescription.isClosed() && prescription.hasMed()
                && PrescriptionTools.isAnnotationNecessary(prescription));
        pnlMenu.add(btnAnnotation);
    }

    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.DELETE, internalClassID)) {
        /***
         *      ____       _      _
         *     |  _ \  ___| | ___| |_ ___
         *     | | | |/ _ \ |/ _ \ __/ _ \
         *     | |_| |  __/ |  __/ ||  __/
         *     |____/ \___|_|\___|\__\___|
         *
         */
        final JButton btnDelete = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.btnDelete.tooltip", SYSConst.icon22delete, null);
        btnDelete.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnDelete.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {

                new DlgYesNo(SYSTools.xx("misc.questions.delete1") + "<br/>"
                        + PrescriptionTools.toPrettyString(prescription) + "</br>"
                        + SYSTools.xx("misc.questions.delete2"), SYSConst.icon48delete, new Closure() {
                            @Override
                            public void execute(Object answer) {
                                if (answer.equals(JOptionPane.YES_OPTION)) {

                                    EntityManager em = OPDE.createEM();
                                    try {
                                        em.getTransaction().begin();
                                        Prescription myverordnung = em.merge(prescription);
                                        em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                                        em.lock(myverordnung, LockModeType.OPTIMISTIC);
                                        em.remove(myverordnung);

                                        Query delQuery = em.createQuery(
                                                "DELETE FROM BHP b WHERE b.prescription = :prescription");
                                        delQuery.setParameter("prescription", myverordnung);
                                        delQuery.executeUpdate();
                                        em.getTransaction().commit();

                                        OPDE.getDisplayManager().addSubMessage(
                                                new DisplayMessage(SYSTools.xx("misc.msg.Deleted") + ": "
                                                        + PrescriptionTools.toPrettyString(myverordnung)));
                                        lstPrescriptions.remove(prescription);
                                        buildPanel();
                                    } catch (OptimisticLockException ole) {
                                        OPDE.warn(ole);
                                        if (em.getTransaction().isActive()) {
                                            em.getTransaction().rollback();
                                        }
                                        if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                            OPDE.getMainframe().emptyFrame();
                                            OPDE.getMainframe().afterLogin();
                                        }
                                        OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                    } catch (Exception e) {
                                        em.getTransaction().rollback();
                                        OPDE.fatal(e);
                                    } finally {
                                        em.close();
                                    }
                                }
                            }
                        });
            }

        });
        btnDelete.setEnabled(numBHPs == 0 && !prescription.isClosed());
        pnlMenu.add(btnDelete);
    }
    // checked for acls
    if (OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, internalClassID)) {
        pnlMenu.add(new JSeparator());

        /***
         *      ____       _   _____            _            ____        _
         *     / ___|  ___| |_| ____|_  ___ __ (_)_ __ _   _|  _ \  __ _| |_ ___
         *     \___ \ / _ \ __|  _| \ \/ / '_ \| | '__| | | | | | |/ _` | __/ _ \
         *      ___) |  __/ |_| |___ >  <| |_) | | |  | |_| | |_| | (_| | ||  __/
         *     |____/ \___|\__|_____/_/\_\ .__/|_|_|   \__, |____/ \__,_|\__\___|
         *                               |_|           |___/
         */
        final JButton btnExpiry = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.tooltip.btnSetExpiry", SYSConst.icon22gotoEnd, null);
        btnExpiry.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                final JidePopup popup = new JidePopup();
                popup.setMovable(false);

                PnlExpiry pnlExpiry = new PnlExpiry(stockInUse.getExpires(),
                        SYSTools.xx("nursingrecords.inventory.pnlExpiry.title") + ": " + stockInUse.getID(),
                        new Closure() {
                            @Override
                            public void execute(Object o) {
                                popup.hidePopup();

                                EntityManager em = OPDE.createEM();
                                try {
                                    em.getTransaction().begin();
                                    MedStock myStock = em.merge(stockInUse);
                                    em.lock(em.merge(myStock.getInventory().getResident()),
                                            LockModeType.OPTIMISTIC);
                                    em.lock(em.merge(myStock.getInventory()), LockModeType.OPTIMISTIC);
                                    myStock.setExpires((Date) o);
                                    em.getTransaction().commit();
                                    createCP4(prescription);
                                    buildPanel();
                                } catch (OptimisticLockException ole) {
                                    OPDE.warn(ole);
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                        OPDE.getMainframe().emptyFrame();
                                        OPDE.getMainframe().afterLogin();
                                    }
                                    OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                                } catch (Exception e) {
                                    if (em.getTransaction().isActive()) {
                                        em.getTransaction().rollback();
                                    }
                                    OPDE.fatal(e);
                                } finally {
                                    em.close();
                                }

                            }
                        });
                popup.setOwner(btnExpiry);
                popup.setContentPane(pnlExpiry);
                popup.removeExcludedComponent(pnlExpiry);
                popup.setDefaultFocusComponent(pnlExpiry);
                GUITools.showPopup(popup, SwingConstants.WEST);
            }
        });
        btnExpiry.setEnabled(inventory != null && stockInUse != null);
        pnlMenu.add(btnExpiry);

        /***
         *       ____ _                ____  _             _
         *      / ___| | ___  ___  ___/ ___|| |_ ___   ___| | __
         *     | |   | |/ _ \/ __|/ _ \___ \| __/ _ \ / __| |/ /
         *     | |___| | (_) \__ \  __/___) | || (_) | (__|   <
         *      \____|_|\___/|___/\___|____/ \__\___/ \___|_|\_\
         *
         */
        final JButton btnCloseStock = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.stock.btnout.tooltip", SYSConst.icon22ledRedOn, null);
        btnCloseStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnCloseStock.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgCloseStock(stockInUse, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            // The prescription itself is not changed, but the stock in question.
                            // this information is requested by a single DB request every time
                            // the CP is created for that particular prescription.
                            // A new call to the createCP4 method will reuse the old
                            // CollapsiblePane and set a new TextContent to it.
                            // Now with the MedStock information.

                            // If this current stock was valid until the end of package
                            // it needs to be reread here.
                            if (prescription.isUntilEndOfPackage()) {
                                EntityManager em = OPDE.createEM();
                                Prescription myPrescription = em.merge(prescription);
                                em.refresh(myPrescription);
                                lstPrescriptions.remove(prescription);
                                lstPrescriptions.add(myPrescription);
                                Collections.sort(lstPrescriptions);
                                final CollapsiblePane myCP = createCP4(myPrescription);
                            } else {
                                final CollapsiblePane myCP = createCP4(prescription);
                                GUITools.flashBackground(myCP, Color.YELLOW, 2);
                            }
                            buildPanel();
                        }
                    }
                });
            }
        });
        btnCloseStock.setEnabled(inventory != null && stockInUse != null && !stockInUse.isToBeClosedSoon());
        pnlMenu.add(btnCloseStock);

        /***
         *       ___                   ____  _             _
         *      / _ \ _ __   ___ _ __ / ___|| |_ ___   ___| | __
         *     | | | | '_ \ / _ \ '_ \\___ \| __/ _ \ / __| |/ /
         *     | |_| | |_) |  __/ | | |___) | || (_) | (__|   <
         *      \___/| .__/ \___|_| |_|____/ \__\___/ \___|_|\_\
         *           |_|
         */
        final JButton btnOpenStock = GUITools.createHyperlinkButton(
                "nursingrecords.inventory.stock.btnopen.tooltip", SYSConst.icon22ledGreenOn, null);
        btnOpenStock.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnOpenStock.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgOpenStock(prescription.getTradeForm(), resident, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            final CollapsiblePane myCP = createCP4(prescription);
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                        }
                    }
                });
            }
        });
        btnOpenStock.setEnabled(inventory != null && stockInUse == null && !prescription.isClosed());
        pnlMenu.add(btnOpenStock);

        /***
         *      ____  _     _      _____  __  __           _
         *     / ___|(_) __| | ___| ____|/ _|/ _| ___  ___| |_ ___
         *     \___ \| |/ _` |/ _ \  _| | |_| |_ / _ \/ __| __/ __|
         *      ___) | | (_| |  __/ |___|  _|  _|  __/ (__| |_\__ \
         *     |____/|_|\__,_|\___|_____|_| |_|  \___|\___|\__|___/
         *
         */
        final JButton btnEditSideEffects = GUITools.createHyperlinkButton(
                "nursingrecords.prescription.edit.sideeffects", SYSConst.icon22sideeffects, null);
        btnEditSideEffects.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnEditSideEffects.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgYesNo(SYSConst.icon48sideeffects, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o != null) {
                            EntityManager em = OPDE.createEM();
                            try {
                                em.getTransaction().begin();
                                MedProducts myProduct = em.merge(prescription.getTradeForm().getMedProduct());
                                myProduct.setSideEffects(o.toString().trim());
                                for (TradeForm tf : myProduct.getTradeforms()) {
                                    em.lock(em.merge(tf), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                                    for (MedPackage mp : tf.getPackages()) {
                                        em.lock(em.merge(mp), LockModeType.OPTIMISTIC_FORCE_INCREMENT);
                                    }
                                }
                                em.lock(myProduct, LockModeType.OPTIMISTIC);
                                em.getTransaction().commit();
                                reload();
                            } catch (Exception e) {
                                if (em.getTransaction().isActive()) {
                                    em.getTransaction().rollback();
                                }
                                OPDE.fatal(e);
                            } finally {
                                em.close();
                            }
                        }
                    }
                }, "nursingrecords.prescription.edit.sideeffects",
                        prescription.getTradeForm().getMedProduct().getSideEffects(), null);
            }
        });
        // checked for acls
        btnEditSideEffects.setEnabled(prescription.hasMed()
                && OPDE.getAppInfo().isAllowedTo(InternalClassACL.UPDATE, "opde.medication"));
        pnlMenu.add(btnEditSideEffects);

        pnlMenu.add(new JSeparator());

        /***
         *      _     _         _____ _ _
         *     | |__ | |_ _ __ |  ___(_) | ___  ___
         *     | '_ \| __| '_ \| |_  | | |/ _ \/ __|
         *     | |_) | |_| | | |  _| | | |  __/\__ \
         *     |_.__/ \__|_| |_|_|   |_|_|\___||___/
         *
         */

        final JButton btnFiles = GUITools.createHyperlinkButton("misc.btnfiles.tooltip", SYSConst.icon22attach,
                null);
        btnFiles.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnFiles.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                Closure closure = null;
                if (!prescription.isClosed()) {
                    closure = new Closure() {
                        @Override
                        public void execute(Object o) {
                            EntityManager em = OPDE.createEM();
                            final Prescription myPrescription = em.find(Prescription.class,
                                    prescription.getID());
                            em.close();
                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);
                        }
                    };
                }
                btnFiles.setEnabled(OPDE.isFTPworking());
                new DlgFiles(prescription, closure);
            }
        });

        pnlMenu.add(btnFiles);

        /***
         *      _     _         ____
         *     | |__ | |_ _ __ |  _ \ _ __ ___   ___ ___  ___ ___
         *     | '_ \| __| '_ \| |_) | '__/ _ \ / __/ _ \/ __/ __|
         *     | |_) | |_| | | |  __/| | | (_) | (_|  __/\__ \__ \
         *     |_.__/ \__|_| |_|_|   |_|  \___/ \___\___||___/___/
         *
         */
        final JButton btnProcess = GUITools.createHyperlinkButton("misc.btnprocess.tooltip",
                SYSConst.icon22link, null);
        btnProcess.setAlignmentX(Component.RIGHT_ALIGNMENT);
        btnProcess.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                new DlgProcessAssign(prescription, new Closure() {
                    @Override
                    public void execute(Object o) {
                        if (o == null) {
                            return;
                        }
                        Pair<ArrayList<QProcess>, ArrayList<QProcess>> result = (Pair<ArrayList<QProcess>, ArrayList<QProcess>>) o;

                        ArrayList<QProcess> assigned = result.getFirst();
                        ArrayList<QProcess> unassigned = result.getSecond();

                        EntityManager em = OPDE.createEM();

                        try {
                            em.getTransaction().begin();

                            em.lock(em.merge(resident), LockModeType.OPTIMISTIC);
                            Prescription myPrescription = em.merge(prescription);
                            em.lock(myPrescription, LockModeType.OPTIMISTIC_FORCE_INCREMENT);

                            ArrayList<SYSPRE2PROCESS> attached = new ArrayList<SYSPRE2PROCESS>(
                                    prescription.getAttachedProcessConnections());
                            for (SYSPRE2PROCESS linkObject : attached) {
                                if (unassigned.contains(linkObject.getQProcess())) {
                                    linkObject.getQProcess().getAttachedNReportConnections().remove(linkObject);
                                    linkObject.getPrescription().getAttachedProcessConnections()
                                            .remove(linkObject);
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_REMOVE_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_REMOVE_ELEMENT,
                                            linkObject.getQProcess()));
                                    em.remove(linkObject);
                                }
                            }
                            attached.clear();

                            for (QProcess qProcess : assigned) {
                                List<QProcessElement> listElements = qProcess.getElements();
                                if (!listElements.contains(myPrescription)) {
                                    QProcess myQProcess = em.merge(qProcess);
                                    SYSPRE2PROCESS myLinkObject = em
                                            .merge(new SYSPRE2PROCESS(myQProcess, myPrescription));
                                    em.merge(new PReport(
                                            SYSTools.xx(PReportTools.PREPORT_TEXT_ASSIGN_ELEMENT) + ": "
                                                    + myPrescription.getTitle() + " ID: "
                                                    + myPrescription.getID(),
                                            PReportTools.PREPORT_TYPE_ASSIGN_ELEMENT, myQProcess));
                                    qProcess.getAttachedPrescriptionConnections().add(myLinkObject);
                                    myPrescription.getAttachedProcessConnections().add(myLinkObject);
                                }
                            }

                            em.getTransaction().commit();

                            lstPrescriptions.remove(prescription);
                            lstPrescriptions.add(myPrescription);
                            Collections.sort(lstPrescriptions);
                            final CollapsiblePane myCP = createCP4(myPrescription);
                            buildPanel();
                            GUITools.flashBackground(myCP, Color.YELLOW, 2);

                        } catch (OptimisticLockException ole) {
                            OPDE.warn(ole);
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (RollbackException ole) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            if (ole.getMessage().indexOf("Class> entity.info.Resident") > -1) {
                                OPDE.getMainframe().emptyFrame();
                                OPDE.getMainframe().afterLogin();
                            }
                            OPDE.getDisplayManager().addSubMessage(DisplayManager.getLockMessage());
                        } catch (Exception e) {
                            if (em.getTransaction().isActive()) {
                                em.getTransaction().rollback();
                            }
                            OPDE.fatal(e);
                        } finally {
                            em.close();
                        }
                    }
                });
            }
        });
        btnProcess.setEnabled(!prescription.isClosed());

        //            if (!prescription.getAttachedProcessConnections().isEmpty()) {
        //                JLabel lblNum = new JLabel(Integer.toString(prescription.getAttachedProcessConnections().size()), SYSConst.icon16redStar, SwingConstants.CENTER);
        //                lblNum.setFont(SYSConst.ARIAL10BOLD);
        //                lblNum.setForeground(Color.YELLOW);
        //                lblNum.setHorizontalTextPosition(SwingConstants.CENTER);
        //                DefaultOverlayable overlayableBtn = new DefaultOverlayable(btnProcess, lblNum, DefaultOverlayable.SOUTH_EAST);
        //                overlayableBtn.setOpaque(false);
        //                pnlMenu.add(overlayableBtn);
        //            } else {
        pnlMenu.add(btnProcess);
        //            }
    }
    return pnlMenu;
}

From source file:org.adeptnet.auth.saml.SAMLClient.java

License:Apache License

private void validate(final Response response) throws ValidationException {
    if (response.getStatus() == null || response.getStatus().getStatusCode() == null
            || !(StatusCode.SUCCESS_URI.equals(response.getStatus().getStatusCode().getValue()))) {
        throw new ValidationException("Response has an unsuccessful status code");
    }/*from   w  ww  .j a  v a  2 s. c o m*/

    // response destination must match ACS
    if (!config.getSPConfig().getAcs().equals(response.getDestination())) {
        throw new ValidationException("Response is destined for a different endpoint");
    }

    final DateTime now = DateTime.now();

    // issue instant must be within a day
    final DateTime issueInstant = response.getIssueInstant();

    if (issueInstant != null) {
        if (issueInstant.isBefore(now.minusDays(1).minusSeconds(slack))) {
            throw new ValidationException("Response IssueInstant is in the past");
        }

        if (issueInstant.isAfter(now.plusDays(1).plusSeconds(slack))) {
            throw new ValidationException("Response IssueInstant is in the future");
        }
    }

    for (Assertion assertion : response.getAssertions()) {

        // Assertion must be signed correctly
        if (!assertion.isSigned()) {
            throw new ValidationException("Assertion must be signed");
        }

        final Signature sig2 = assertion.getSignature();
        sigValidator.validate(sig2);

        // Assertion must contain an authnstatement
        // with an unexpired session
        if (assertion.getAuthnStatements().isEmpty()) {
            throw new ValidationException("Assertion should contain an AuthnStatement");
        }
        for (AuthnStatement as : assertion.getAuthnStatements()) {
            if (as.getSessionNotOnOrAfter() == null) {
                LOG.error("SessionNotOnOrAfter is null");
                continue;
            }
            final DateTime exp = as.getSessionNotOnOrAfter().plusSeconds(slack);
            if (exp != null && (now.isEqual(exp) || now.isAfter(exp))) {
                throw new ValidationException("AuthnStatement has expired");
            }
        }

        if (assertion.getConditions() == null) {
            throw new ValidationException("Assertion should contain conditions");
        }

        // Assertion IssueInstant must be within a day
        final DateTime instant = assertion.getIssueInstant();
        if (instant != null) {
            if (instant.isBefore(now.minusDays(1).minusSeconds(slack))) {
                throw new ValidationException("Response IssueInstant is in the past");
            }

            if (instant.isAfter(now.plusDays(1).plusSeconds(slack))) {
                throw new ValidationException("Response IssueInstant is in the future");
            }
        }

        // Conditions must be met by current time
        final Conditions conditions = assertion.getConditions();
        DateTime notBefore = conditions.getNotBefore();
        DateTime notOnOrAfter = conditions.getNotOnOrAfter();

        if (notBefore == null) {
            notBefore = now;
        }

        if (notBefore == null || notOnOrAfter == null) {
            throw new ValidationException("Assertion conditions must have limits");
        }

        notBefore = notBefore.minusSeconds(slack);
        notOnOrAfter = notOnOrAfter.plusSeconds(slack);

        if (now.isBefore(notBefore)) {
            throw new ValidationException("Assertion conditions is in the future");
        }

        if (now.isEqual(notOnOrAfter) || now.isAfter(notOnOrAfter)) {
            throw new ValidationException("Assertion conditions is in the past");
        }

        // If subjectConfirmationData is included, it must
        // have a recipient that matches ACS, with a valid
        // NotOnOrAfter
        final Subject subject = assertion.getSubject();
        if (subject != null && !subject.getSubjectConfirmations().isEmpty()) {
            boolean foundRecipient = false;
            for (SubjectConfirmation sc : subject.getSubjectConfirmations()) {
                if (sc.getSubjectConfirmationData() == null) {
                    continue;
                }

                final SubjectConfirmationData scd = sc.getSubjectConfirmationData();
                if (scd.getNotOnOrAfter() != null) {
                    final DateTime chkdate = scd.getNotOnOrAfter().plusSeconds(slack);
                    if (now.isEqual(chkdate) || now.isAfter(chkdate)) {
                        throw new ValidationException("SubjectConfirmationData is in the past");
                    }
                }

                if (config.getSPConfig().getAcs().equals(scd.getRecipient())) {
                    foundRecipient = true;
                }
            }

            if (!foundRecipient) {
                throw new ValidationException("No SubjectConfirmationData found for ACS");
            }
        }

        // audience must include intended SP issuer
        if (conditions.getAudienceRestrictions().isEmpty()) {
            throw new ValidationException("Assertion conditions must have audience restrictions");
        }

        // only one audience restriction supported: we can only
        // check against the single SP.
        if (conditions.getAudienceRestrictions().size() > 1) {
            throw new ValidationException("Assertion contains multiple audience restrictions");
        }

        final AudienceRestriction ar = conditions.getAudienceRestrictions().get(0);

        // at least one of the audiences must match our SP
        boolean foundSP = false;
        for (Audience a : ar.getAudiences()) {
            if (config.getSPConfig().getEntityId().equals(a.getAudienceURI())) {
                foundSP = true;
            }
        }
        if (!foundSP) {
            throw new ValidationException("Assertion audience does not include issuer");
        }
    }
}

From source file:org.apache.beam.sdk.extensions.sql.impl.interpreter.operator.date.BeamSqlDatetimePlusExpression.java

License:Apache License

private DateTime addInterval(DateTime dateTime, SqlTypeName intervalType, int numberOfIntervals) {
    switch (intervalType) {
    case INTERVAL_SECOND:
        return dateTime.plusSeconds(numberOfIntervals);
    case INTERVAL_MINUTE:
        return dateTime.plusMinutes(numberOfIntervals);
    case INTERVAL_HOUR:
        return dateTime.plusHours(numberOfIntervals);
    case INTERVAL_DAY:
        return dateTime.plusDays(numberOfIntervals);
    case INTERVAL_MONTH:
        return dateTime.plusMonths(numberOfIntervals);
    case INTERVAL_YEAR:
        return dateTime.plusYears(numberOfIntervals);
    default://ww w. j  av a2s. c o  m
        throw new IllegalArgumentException("Adding " + intervalType.getName() + " to date is not supported");
    }
}

From source file:org.apache.beam.sdk.io.kinesis.KinesisProducerMock.java

License:Apache License

@Override
public synchronized void flush() {
    DateTime arrival = DateTime.now();
    for (int i = 0; i < addedRecords.size(); i++) {
        UserRecord record = addedRecords.get(i);
        arrival = arrival.plusSeconds(1);
        kinesisService.addShardedData(record.getData(), arrival);
        addedRecords.remove(i);//from w ww. jav  a2s. c  o  m
    }
}

From source file:org.apache.cxf.fediz.core.processor.FederationProcessorImpl.java

License:Apache License

protected FedizResponse processSignInRequest(FedizRequest request, FedizContext config)
        throws ProcessingException {

    Document doc = null;/*from  w w w  . ja v a2  s  .c o m*/
    Element el = null;
    try {
        doc = DOMUtils.readXml(new StringReader(request.getResponseToken()));
        el = doc.getDocumentElement();

    } catch (Exception e) {
        LOG.warn("Failed to parse wresult: " + e.getMessage());
        throw new ProcessingException(TYPE.INVALID_REQUEST);
    }

    if ("RequestSecurityTokenResponseCollection".equals(el.getLocalName())) {
        el = DOMUtils.getFirstElement(el);
    }
    if (!"RequestSecurityTokenResponse".equals(el.getLocalName())) {
        LOG.warn("Unexpected root element of wresult: '" + el.getLocalName() + "'");
        throw new ProcessingException(TYPE.INVALID_REQUEST);
    }
    el = DOMUtils.getFirstElement(el);
    Element rst = null;
    Element lifetimeElem = null;
    String tt = null;

    while (el != null) {
        String ln = el.getLocalName();
        if (FederationConstants.WS_TRUST_13_NS.equals(el.getNamespaceURI())
                || FederationConstants.WS_TRUST_2005_02_NS.equals(el.getNamespaceURI())) {
            if ("Lifetime".equals(ln)) {
                lifetimeElem = el;
            } else if ("RequestedSecurityToken".equals(ln)) {
                rst = DOMUtils.getFirstElement(el);
            } else if ("TokenType".equals(ln)) {
                tt = DOMUtils.getContent(el);
            }
        }
        el = DOMUtils.getNextElement(el);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("RST: " + ((rst != null) ? rst.toString() : "null"));
        LOG.debug("Lifetime: " + ((lifetimeElem != null) ? lifetimeElem.toString() : "null"));
        LOG.debug("Tokentype: " + ((tt != null) ? tt.toString() : "null"));
    }
    if (rst == null) {
        LOG.warn("RequestedSecurityToken element not found in wresult");
        throw new ProcessingException(TYPE.BAD_REQUEST);
    }
    LifeTime lifeTime = null;
    if (lifetimeElem != null) {
        lifeTime = processLifeTime(lifetimeElem);
    }

    if (config.isDetectExpiredTokens() && lifeTime != null) {
        Date currentDate = new Date();
        if (currentDate.after(lifeTime.getExpires())) {
            LOG.warn("RSTR Lifetime expired");
            throw new ProcessingException(TYPE.TOKEN_EXPIRED);
        }
        DateTime currentTime = new DateTime();
        DateTime validFrom = new DateTime(lifeTime.created);
        currentTime = currentTime.plusSeconds(config.getMaximumClockSkew().intValue());
        if (validFrom.isAfter(currentTime)) {
            LOG.debug("RSTR Lifetime not yet valid");
            throw new ProcessingException(TYPE.TOKEN_INVALID);
        }
    }

    // Check to see if RST is encrypted
    if ("EncryptedData".equals(rst.getLocalName()) && WSConstants.ENC_NS.equals(rst.getNamespaceURI())) {
        Element decryptedRST = decryptEncryptedRST(rst, config);
        if (decryptedRST != null) {
            rst = decryptedRST;
        }
    }

    TokenValidatorResponse validatorResponse = validateToken(rst, tt, config, request.getCerts());

    // Check whether token already used for signin
    Date expires = null;
    if (lifeTime != null && lifeTime.getExpires() != null) {
        expires = lifeTime.getExpires();
    } else {
        expires = validatorResponse.getExpires();
    }
    testForReplayAttack(validatorResponse.getUniqueTokenId(), config, expires);

    Date created = validatorResponse.getCreated();
    if (lifeTime != null && lifeTime.getCreated() != null) {
        created = lifeTime.getCreated();
    }

    FedizResponse fedResponse = new FedizResponse(validatorResponse.getUsername(),
            validatorResponse.getIssuer(), validatorResponse.getRoles(), validatorResponse.getClaims(),
            validatorResponse.getAudience(), created, expires, rst, validatorResponse.getUniqueTokenId());

    return fedResponse;
}

From source file:org.apache.cxf.fediz.core.saml.SAMLTokenValidator.java

License:Apache License

/**
 * Check the Conditions of the Assertion.
 *///from   w  w w.  ja  v  a2s  . c om
protected boolean isConditionValid(SamlAssertionWrapper assertion, int maxClockSkew)
        throws WSSecurityException {
    DateTime validFrom = null;
    DateTime validTill = null;
    if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_20)
            && assertion.getSaml2().getConditions() != null) {
        validFrom = assertion.getSaml2().getConditions().getNotBefore();
        validTill = assertion.getSaml2().getConditions().getNotOnOrAfter();
    } else if (assertion.getSamlVersion().equals(SAMLVersion.VERSION_11)
            && assertion.getSaml1().getConditions() != null) {
        validFrom = assertion.getSaml1().getConditions().getNotBefore();
        validTill = assertion.getSaml1().getConditions().getNotOnOrAfter();
    }

    if (validFrom != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(maxClockSkew);
        if (validFrom.isAfter(currentTime)) {
            LOG.debug("SAML Token condition (Not Before) not met");
            return false;
        }
    }

    if (validTill != null && validTill.isBeforeNow()) {
        LOG.debug("SAML Token condition (Not On Or After) not met");
        return false;
    }
    return true;
}

From source file:org.apache.cxf.rs.security.saml.sso.SAMLProtocolResponseValidator.java

License:Apache License

/**
 * Validate a SAML 2 Protocol Response/* www  .j  a  v  a2s.c o m*/
 * @param samlResponse
 * @param sigCrypto
 * @param callbackHandler
 * @throws WSSecurityException
 */
public void validateSamlResponse(org.opensaml.saml.saml2.core.Response samlResponse, Crypto sigCrypto,
        CallbackHandler callbackHandler) throws WSSecurityException {
    // Check the Status Code
    if (samlResponse.getStatus() == null || samlResponse.getStatus().getStatusCode() == null) {
        LOG.fine("Either the SAML Response Status or StatusCode is null");
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }
    if (!SAML2_STATUSCODE_SUCCESS.equals(samlResponse.getStatus().getStatusCode().getValue())) {
        LOG.fine("SAML Status code of " + samlResponse.getStatus().getStatusCode().getValue()
                + "does not equal " + SAML2_STATUSCODE_SUCCESS);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    if (samlResponse.getIssueInstant() != null) {
        DateTime currentTime = new DateTime();
        currentTime = currentTime.plusSeconds(futureTTL);
        if (samlResponse.getIssueInstant().isAfter(currentTime)) {
            LOG.fine("SAML Response IssueInstant not met");
            throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
        }
    }

    if (SAMLVersion.VERSION_20 != samlResponse.getVersion()) {
        LOG.fine("SAML Version of " + samlResponse.getVersion() + "does not equal " + SAMLVersion.VERSION_20);
        throw new WSSecurityException(WSSecurityException.ErrorCode.FAILURE, "invalidSAMLsecurity");
    }

    validateResponseSignature(samlResponse, sigCrypto, callbackHandler);

    Document doc = samlResponse.getDOM().getOwnerDocument();
    // Decrypt any encrypted Assertions and add them to the Response (note that this will break any
    // signature on the Response)
    for (org.opensaml.saml.saml2.core.EncryptedAssertion assertion : samlResponse.getEncryptedAssertions()) {

        Element decAssertion = decryptAssertion(assertion, sigCrypto, callbackHandler);

        SamlAssertionWrapper wrapper = new SamlAssertionWrapper(decAssertion);
        samlResponse.getAssertions().add(wrapper.getSaml2());
    }

    // Validate Assertions
    for (org.opensaml.saml.saml2.core.Assertion assertion : samlResponse.getAssertions()) {
        SamlAssertionWrapper wrapper = new SamlAssertionWrapper(assertion);
        validateAssertion(wrapper, sigCrypto, callbackHandler, doc, samlResponse.isSigned());
    }
}