Advertisement
Guest User

Untitled

a guest
Jun 26th, 2017
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.02 KB | None | 0 0
  1. package opencm.domain.service;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Comparator;
  6. import java.util.Iterator;
  7. import java.util.List;
  8. import java.util.Stack;
  9.  
  10. import opencm.domain.interfaces.ConsultaRepository;
  11. import opencm.domain.model.Consulta;
  12. import opencm.domain.model.HorarioAtendimento;
  13.  
  14. import org.joda.time.Interval;
  15.  
  16. public final class AgendamentoService {
  17.  
  18.     private ConsultaRepository consultaRepository;
  19.    
  20.     public AgendamentoService(ConsultaRepository consultaRepository) {
  21.         this.consultaRepository = consultaRepository;
  22.     }
  23.  
  24.     private List<Interval> consultaIntervals(List<Consulta> consultas) {
  25.         List<Interval> result = new ArrayList<Interval>();
  26.        
  27.         for (Consulta consulta : consultas) {
  28.             result.add(new Interval(consulta.getInicio(), consulta.getDuracao()));         
  29.         }
  30.        
  31.         return mergeIntervals(result);
  32.     }
  33.    
  34.     private List<Interval> atendimentoIntervals(List<HorarioAtendimento> horarios) {
  35.         List<Interval> result = new ArrayList<Interval>();
  36.        
  37.         for (HorarioAtendimento horario : horarios) {
  38.             result.add(new Interval(horario.getHoraInicial().toDateTimeToday(), horario.getHoraFinal().toDateTimeToday()));
  39.         }
  40.        
  41.         return mergeIntervals(result);
  42.     }
  43.    
  44.     private List<Interval> mergeIntervals(List<Interval> intervals) {
  45.         List<Interval> sortedIntervals = new ArrayList<Interval>(intervals);
  46.        
  47.         Collections.sort(sortedIntervals, new Comparator<Interval>() { public int compare(Interval a, Interval b) {
  48.                 return a.getStart().compareTo(b.getStart());
  49.         }});
  50.        
  51.         Iterator<Interval> sortedIntervalsIt = sortedIntervals.iterator();
  52.        
  53.         Stack<Interval> mergedIntervals = new Stack<Interval>();
  54.        
  55.         while (sortedIntervalsIt.hasNext()) {
  56.             Interval current = sortedIntervalsIt.next();
  57.            
  58.             if (!mergedIntervals.empty() && current.abuts(mergedIntervals.peek())) {
  59.                 mergedIntervals.push(new Interval(mergedIntervals.pop().getStart(), current.getEnd()));
  60.             } else {
  61.                 mergedIntervals.push(current);
  62.             }
  63.         }
  64.  
  65.         return mergedIntervals;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement