@Override
 public Number countBooksForCatalog(
     Set<String> categories, Set<String> subcategories, BookStatusesEnum status)
     throws ForbiddenException, AuthRequiredException {
   bookAvailabilityService.areBooksWithStatusAvailable(status);
   if (CollectionUtils.isEmpty(categories) && CollectionUtils.isEmpty(subcategories)) {
     return bookDao.countBooks(status);
   }
   Collection<Integer> integers =
       subcategoryDao.collectSubcategoryIdsByPriority(categories, subcategories);
   return bookDao.countBySubCategories(integers, status);
 }
 public List<String> getDimensions(
     String collection, MultivaluedMap<String, String> selectedDimensionValues) throws Exception {
   CollectionSchema schema = dataCache.getCollectionSchema(serverUri, collection);
   Set<String> selectedDimensions =
       (selectedDimensionValues == null ? null : selectedDimensionValues.keySet());
   if (CollectionUtils.isEmpty(selectedDimensions)) {
     return schema.getDimensions();
   }
   List<String> filteredDimensions =
       new ArrayList<>(CollectionUtils.subtract(schema.getDimensions(), selectedDimensions));
   Collections.sort(filteredDimensions);
   return filteredDimensions;
 }
 public static String[] buildLookupAttributeIds(
     BinaryAttributeDetector binaryAttrDetector, @Nullable Set<Attribute> attrs) {
   // noinspection ConstantConditions
   return (!CollectionUtils.isEmpty(attrs)
       ? ToolCollectionUtils.toArray(
           CollectionUtils.select(
               IteratorUtils.asIterable(
                   ToolIteratorUtils.chainedArrayIterator(
                       CollectionUtils.collect(
                           attrs, new LdapAttributeIdTransformer(binaryAttrDetector)))),
               PredicateUtils.uniquePredicate()),
           String.class)
       : ArrayUtils.EMPTY_STRING_ARRAY);
 }
示例#4
0
  private static boolean isValueEquals(
      final AbstractField<?> field, final Object orginalValue, final Object currentValue) {
    if (Set.class.equals(field.getType())) {
      return CollectionUtils.isEqualCollection(
          CollectionUtils.emptyIfNull((Collection<?>) orginalValue),
          CollectionUtils.emptyIfNull((Collection<?>) currentValue));
    }

    if (String.class.equals(field.getType())) {
      return Objects.equals(
          Strings.emptyToNull((String) orginalValue), Strings.emptyToNull((String) currentValue));
    }

    return Objects.equals(orginalValue, currentValue);
  }
示例#5
0
 @Override
 public void setValue(Collection<M> value) {
   this.value = CollectionUtils.emptyIfNull(value).stream().collect(Collectors.toSet());
   getListForm()
       .setFilter(DaoUtils.createInCriterion(BaseModel.ID, ModelUtils.getIds(getValue())));
   getListForm().refresh();
 }
示例#6
0
 private void initRef() {
   listForm =
       BaseListForm.class.cast(Validate.notNull(beanFactory.getBean(getReference().listForm())));
   getListForm().getContent().setPrefHeight(DEFAULT_HEIGHT);
   getListForm().getContent().setMaxHeight(DEFAULT_HEIGHT);
   getListForm().setRowDblClickConsumer(null);
   getListForm().getToolBar().getController().removeAll();
   // Удалить
   getListForm()
       .getToolBar()
       .getController()
       .registerAction(refDeleteAction)
       .setActionCallback(
           () ->
               Optional.ofNullable(getListForm().getSelectedModel())
                   .ifPresent(
                       item -> {
                         setValue(
                             CollectionUtils.emptyIfNull(getValue())
                                 .stream()
                                 .filter(item0 -> !Objects.equals(item0, item))
                                 .collect(Collectors.toSet()));
                       }));
   getListForm().getToolBar().setPrefHeight(DEFAULT_ACTION_HEIGHT + 2);
   getListForm().getToolBar().getController().setActionsHeight(DEFAULT_ACTION_HEIGHT);
   getListForm().getToolBar().getController().setActionsWidth(DEFAULT_BTN_WIDTH);
   setContent(getListForm().getContent());
 }
  @Override
  public List<ILocationMatch> match(Topology topology) throws LocationMatchingException {
    List<ILocationMatch> matched = Lists.newArrayList();

    try {
      // get all enabled orchestrators
      List<Orchestrator> enabledOrchestrators = orchestratorService.getAll();
      if (CollectionUtils.isEmpty(enabledOrchestrators)) {
        return matched;
      }

      Map<String, Orchestrator> orchestratorMap =
          AlienUtils.fromListToMap(enabledOrchestrators, "id", true);
      List<Location> locations =
          locationService.getOrchestratorsLocations(orchestratorMap.keySet());
      for (Location location : locations) {
        matched.add(
            new LocationMatch(location, orchestratorMap.get(location.getOrchestratorId()), null));
      }

      // filter on supported artifacts
      locationMatchNodeFilter.filter(matched, topology);

      return matched;
    } catch (Exception e) {
      throw new LocationMatchingException(
          "Failed to match topology <" + topology.getId() + "> against locations. ", e);
    }
  }
  /*
   * if questionnaire is associated with Amendment/renewal submodulecode.
   * if this protocol is normal protocol, then it has to check whether the A/R of this
   * questionnaire has merged to this protocol yet.
   */
  private boolean isCurrentAorRQn(AnswerHeader answerHeader) {
    boolean isCurrentQn = false;
    if (getProtocol().isAmendment() || getProtocol().isRenewal()) {
      // if this is A/R, then just match sequencenumber and modulesubitemkey
      isCurrentQn =
          answerHeader.getModuleSubItemKey().equals(getProtocol().getSequenceNumber().toString());
    } else {
      // if this is a regular protocol, then get this A/R associated this this Qn and see if
      // A/R has been merged to this version of protocol
      Map keyValues = new HashMap();
      keyValues.put("protocolNumber", answerHeader.getModuleItemKey());

      ProtocolBase protocol =
          ((List<ProtocolBase>)
                  getBusinessObjectService()
                      .findMatchingOrderBy(
                          getProtocolBOClassHook(), keyValues, "sequenceNumber", false))
              .get(0);

      isCurrentQn =
          answerHeader.getModuleSubItemKey().equals(protocol.getSequenceNumber().toString())
              && !CollectionUtils.isEmpty(protocol.getProtocolSubmissions())
              && isMergedToProtocol(getProtocol(), protocol);
    }
    return isCurrentQn;
  }
  @Override
  public boolean hasDerivedRole(
      String principalId,
      List<String> groupIds,
      String namespaceCode,
      String roleName,
      Map<String, String> qualification) {
    validateRequiredAttributesAgainstReceived(qualification);

    String protocolNumber = qualification.get(KcKimAttributes.PROTOCOL);

    ProtocolBase protocol = getProtocol(protocolNumber);

    if (protocol != null && CollectionUtils.isNotEmpty(protocol.getProtocolPersons())) {
      for (ProtocolPersonBase person : protocol.getProtocolPersons()) {
        // Find protocol person that matches the principal id
        if (StringUtils.equals(principalId, person.getPersonId())) {
          if (StringUtils.equals(roleName, person.getProtocolPersonRoleId())) {
            return true;
          }
        }
      }
    }

    return false;
  }
示例#10
0
 protected boolean isJobCodeValid(BudgetPerson budgetPerson) {
   if (CollectionUtils.isNotEmpty(getMappedCostElements(budgetPerson))) {
     return validateJobCodeChange(budgetPerson, "jobCode");
   } else {
     return validateJobCodeValue(budgetPerson, "jobCode");
   }
 }
  private Collection<File> extractUnusedTraceFiles(Collection<File> traceFiles)
      throws ServletException {
    try {
      final List<SelectOptionDTO> usedTraceFileDTOs =
          Arrays.asList(new Gson().fromJson(new FileReader(tracesFile), SelectOptionDTO[].class));

      Collection<File> unusedTraceFiles =
          CollectionUtils.select(
              traceFiles,
              new Predicate<File>() {
                @Override
                public boolean evaluate(final File f) {
                  return IterableUtils.find(
                          usedTraceFileDTOs,
                          new Predicate<SelectOptionDTO>() {
                            @Override
                            public boolean evaluate(SelectOptionDTO so) {
                              return so.value.contains(f.getName());
                            }
                          })
                      == null;
                }
              });

      // TODO cleaning up -- should be taken out to an admin command
      for (File f : unusedTraceFiles) {
        f.renameTo(new File(unusedTraceDirectory, f.getName()));
      }

      return unusedTraceFiles;
    } catch (Exception e) {
      throw new ServletException("JSON decode error", e);
    }
  }
示例#12
0
 /**
  * 获取唯一文件
  *
  * @param fieldName
  * @return
  */
 public FileParam getFile(String fieldName) {
   List<FileParam> fileParamList = getFileList(fieldName);
   if (CollectionUtils.isNotEmpty(fileParamList) && fileParamList.size() == 1) {
     return fileParamList.get(0);
   }
   return null;
 }
示例#13
0
文件: GCVote.java 项目: devykm/cgeo
  /**
   * Get user ratings from gcvote.com
   *
   * @param guids
   * @param geocodes
   * @return
   */
  @NonNull
  private static Map<String, GCVoteRating> getRating(
      final List<String> guids, final List<String> geocodes) {
    if (guids == null && geocodes == null) {
      return Collections.emptyMap();
    }

    final Parameters params = new Parameters("version", "cgeo");
    final ImmutablePair<String, String> login = Settings.getGCvoteLogin();
    if (login != null) {
      params.put("userName", login.left, "password", login.right);
    }

    // use guid or gccode for lookup
    final boolean requestByGuids = CollectionUtils.isNotEmpty(guids);
    if (requestByGuids) {
      params.put("cacheIds", StringUtils.join(guids, ','));
    } else {
      params.put("waypoints", StringUtils.join(geocodes, ','));
    }
    final InputStream response =
        Network.getResponseStream(Network.getRequest("http://gcvote.com/getVotes.php", params));
    if (response == null) {
      return Collections.emptyMap();
    }
    try {
      return getRatingsFromXMLResponse(response, requestByGuids);
    } finally {
      IOUtils.closeQuietly(response);
    }
  }
  /** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    System.out.println(request.getRequestURI());

    Collection<File> traceFiles =
        Arrays.asList(
            traceDirectory.listFiles(
                (FilenameFilter) new WildcardFileFilter("*.json", IOCase.INSENSITIVE)));

    if (request.getRequestURI().endsWith("unusedTraces")) {
      traceFiles = extractUnusedTraceFiles(traceFiles);
    }

    Collection<SelectOptionDTO> traceFileDTOs =
        CollectionUtils.collect(
            traceFiles,
            new Transformer<File, SelectOptionDTO>() {
              @Override
              public SelectOptionDTO transform(File f) {
                SelectOptionDTO dto = new SelectOptionDTO();
                dto.value = MessageFormat.format(TRACE_URL_FORMAT, f.getName());
                dto.text = f.getName().replace(".json", "");
                return dto;
              }
            });

    String json = new GsonBuilder().setPrettyPrinting().create().toJson(traceFileDTOs);

    response.setCharacterEncoding("UTF-8");
    response.getWriter().append(json);
  }
 @Override
 public void addFileToIndex(IndexFile indexFile) throws Exception {
   // TODO Auto-generated method stub
   if (CollectionUtils.isNotEmpty(indexFile.getTextStrings())) {
     for (String token : indexFile.getTextStrings()) {
       Document document = new Document();
       document.add(new TextField(TITLE_FIELD, indexFile.getFileName().trim(), Field.Store.YES));
       document.add(new TextField(CONTENTS_FIELD, token.trim(), Field.Store.YES));
       document.add(new StringField(ID_FIELD, indexFile.getFileId().trim(), Field.Store.YES));
       document.add(new StringField(USER_FIELD, indexFile.getUserIdentifier(), Field.Store.YES));
       document.add(
           new StringField(CONTENT_TYPE_FIELD, indexFile.getFileContent(), Field.Store.YES));
       document.add(new StringField(DATE_FIELD, DateUtil.getCurrentDate(), Field.Store.YES));
       document.add(new StringField(TIME_FIELD, DateUtil.getCurrentTime(), Field.Store.YES));
       getWriter().addDocument(document);
     }
   } else {
     Document document = new Document();
     document.add(new TextField(TITLE_FIELD, indexFile.getFileName().trim(), Field.Store.YES));
     document.add(new StringField(ID_FIELD, indexFile.getFileId().trim(), Field.Store.YES));
     document.add(new StringField(USER_FIELD, indexFile.getUserIdentifier(), Field.Store.YES));
     document.add(
         new StringField(CONTENT_TYPE_FIELD, indexFile.getFileContent(), Field.Store.YES));
     document.add(new StringField(DATE_FIELD, DateUtil.getCurrentDate(), Field.Store.YES));
     document.add(new StringField(TIME_FIELD, DateUtil.getCurrentTime(), Field.Store.YES));
     getWriter().addDocument(document);
   }
   getWriter().commit();
   LOGGER.info("File Indexed Successfully..............");
   indexFile.getSuggestStrings().add(indexFile.getFileName().trim());
   addDocumentToSuggest(indexFile);
   LOGGER.info("File Name added to Suggestions..............");
 }
  /**
   * Get available configuration properties.
   *
   * @param instance connector instance.
   * @return configuration properties.
   */
  @Override
  protected final List<ConnConfProperty> getConnProperties(final ConnInstanceTO instance) {

    final List<ConnConfProperty> res =
        CollectionUtils.collect(
            ConnectorModal.getBundle(instance, bundles).getProperties(),
            new Transformer<ConnConfPropSchema, ConnConfProperty>() {

              @Override
              public ConnConfProperty transform(final ConnConfPropSchema key) {
                final ConnConfProperty property = new ConnConfProperty();
                property.setSchema(key);

                if (instance.getKey() != null
                    && instance.getConfMap().containsKey(key.getName())
                    && instance.getConfMap().get(key.getName()).getValues() != null) {

                  property.getValues().addAll(instance.getConfMap().get(key.getName()).getValues());
                  property.setOverridable(instance.getConfMap().get(key.getName()).isOverridable());
                }

                if (property.getValues().isEmpty() && !key.getDefaultValues().isEmpty()) {
                  property.getValues().addAll(key.getDefaultValues());
                }
                return property;
              }
            },
            new ArrayList<ConnConfProperty>());

    return res;
  }
  @Override
  public boolean preHandle(
      HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
      throws Exception {
    HttpSession session = httpServletRequest.getSession();
    User user = (User) session.getAttribute("user");
    if (user == null || user.getStatus() != UserConstant.Status.ACTIVE.value()) {
      return false;
    }

    Map<Privilege, Integer> map = PrivilegeHelper.getPrivilegeMap();

    Privilege privilege =
        new Privilege(
            httpServletRequest
                .getRequestURI()
                .substring(httpServletRequest.getContextPath().length()),
            httpServletRequest.getMethod());
    System.out.println("privilege = " + privilege);

    if (CollectionUtils.isEmpty(user.getPrivilegeIds())) {
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error/low.html");
      return false;
    }

    if (MapUtils.isNotEmpty(map)
        && map.containsKey(privilege)
        && !user.getPrivilegeIds().contains(map.get(privilege))) {
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/error/low.html");
      return false;
    }

    return true;
  }
 /**
  * Handle received selection keys.
  *
  * @param selectionKeys the selection keys.
  * @throws IOException
  */
 private void handleSelectionKeys(Set<SelectionKey> selectionKeys) throws IOException {
   if (CollectionUtils.isEmpty(selectionKeys)) {
     // nothing happened
     return;
   }
   int size = selectionKeys.size();
   this.logger.info("Handling [{}] selection keys", size);
   // something happened
   Iterator<SelectionKey> iterator = selectionKeys.iterator();
   while (iterator.hasNext()) {
     SelectionKey selectionKey = iterator.next();
     iterator.remove();
     this.logger.debug("Remaining [{}] selection keys", selectionKeys.size());
     // remove as to not process again.
     try {
       if (!selectionKey.isValid()) {
         continue;
       }
       SelectionKeyCommand selectionKeyCommand =
           this.selectionKeyCommandFactory.getSelectionKeyCommand(selectionKey);
       selectionKeyCommand.execute(selectionKey);
     } catch (Exception ex) {
       StringBuffer buffer = new StringBuffer("Error [");
       buffer.append(ex.getMessage());
       buffer.append("] on [");
       buffer.append(selectionKey.channel());
       buffer.append("] channel");
       this.logger.error(buffer.toString(), ex);
       SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
       socketChannel.close();
     }
   }
   this.logger.info("Handled [{}] selection keys", size);
 }
示例#19
0
  @Transactional(propagation = Propagation.REQUIRES_NEW, readOnly = true)
  @Override
  public Collection<Group> findAllGroups(final User user) {
    return CollectionUtils.union(
        CollectionUtils.collect(
            user.getMemberships(),
            new Transformer<UMembership, Group>() {

              @Override
              public Group transform(final UMembership input) {
                return input.getRightEnd();
              }
            },
            new ArrayList<Group>()),
        findDynGroupMemberships(user));
  }
  // find all elements using pattern
  private static void testSelect() {
    Collection<String> collection = Lists.newArrayList("2", "14", "3", "13", "43");
    MutableCollection<String> mutableCollection = FastList.newListWith("2", "14", "3", "13", "43");
    Iterable<String> iterable = collection;

    // find all elements using pattern
    List<String> jdk =
        collection
            .stream()
            .filter((s) -> s.contains("1"))
            .collect(Collectors.toList()); // using JDK
    Iterable<String> guava = Iterables.filter(iterable, (s) -> s.contains("1")); // using guava
    Collection<String> apache =
        CollectionUtils.select(iterable, (s) -> s.contains("1")); // using Apache
    MutableCollection<String> gs = mutableCollection.select((s) -> s.contains("1")); // using GS

    System.out.println(
        "select = "
            + jdk
            + ":"
            + guava
            + ":"
            + apache
            + ":"
            + gs); // print select = [14, 13]:[14, 13]:[14, 13]:[14, 13]
  }
  @Override
  public List<String> findGuestNamesByCompany(final String company) {
    List<Guest> all = repository.findAll();
    List<Guest> filtered =
        ListUtils.select(
            all,
            new Predicate<Guest>() {
              public boolean evaluate(Guest g) {
                return company.equals(g.getCompany());
              }
            });

    Collections.sort(
        filtered,
        new Comparator<Guest>() {
          @Override
          public int compare(Guest o1, Guest o2) {
            return Integer.compare(o1.getGrade(), o2.getGrade());
          }
        });

    Collection<String> names =
        CollectionUtils.collect(
            filtered,
            new Transformer<Guest, String>() {
              public String transform(Guest g) {
                return g.getName();
              }
            });

    return new ArrayList<>(names);
  }
 @Override
 public List<BookEntity> getBooksForCatalog(
     int offset,
     int limit,
     Set<String> categories,
     Set<String> subcategories,
     BookStatusesEnum status)
     throws NotSupportedFieldException, NoSuchEntityException, ForbiddenException,
         AuthRequiredException {
   bookAvailabilityService.areBooksWithStatusAvailable(status);
   if (CollectionUtils.isEmpty(categories) && CollectionUtils.isEmpty(subcategories)) {
     return getBooks(offset, limit, status);
   }
   Collection<Integer> integers =
       subcategoryDao.collectSubcategoryIdsByPriority(categories, subcategories);
   return bookDao.getBySubCategories(offset, limit, integers, status);
 }
示例#23
0
  /**
   * Determines whether the person has valid unit
   *
   * @param person
   * @return boolean
   */
  @SuppressWarnings("unchecked")
  public boolean isValidHomeUnit(ProposalPerson person, String unitId) {
    Map valueMap = new HashMap();
    valueMap.put("unitNumber", unitId);
    Collection<Unit> units = getBusinessObjectService().findMatching(Unit.class, valueMap);

    return CollectionUtils.isNotEmpty(units);
  }
示例#24
0
 @Transactional
 public boolean activateCommunicationsInstantaneously(String day, List<String> communicationIds) {
   List<String> ids = arrowService.pushActivation(communicationIds);
   if (CollectionUtils.isEmpty(ids)) {
     return false;
   }
   return true;
 }
  public String buildQuery(ReporteDTO datosConsulta) {
    StringBuilder queryString = new StringBuilder();
    queryString.append(
        "select case when mov.idservicio IS NULL then 'Paquete' else 'Servicio' END as tipo, ");
    queryString.append(
        "case when mov.idservicio IS NULL then paq.nombrepaquete else ser.nombre END as nombre, ");
    queryString.append(
        "mov.fecha as fecha, us.primernombre as primernombre, us.primerapellido as primerapellido  from tr_movimiento as mov ");
    queryString.append("LEFT JOIN tp_usuario as us ");
    queryString.append("ON mov.idusuario = us.id ");
    queryString.append("LEFT JOIN tp_servicio ser ");
    queryString.append("ON mov.idservicio = ser.id ");
    queryString.append("LEFT JOIN tp_paquete as paq ");
    queryString.append("ON mov.idpaquete = paq.id ");

    if (StringUtils.isNotEmpty(datosConsulta.getFechaInical())) {
      queryString.append(
          "where (mov.fecha BETWEEN '"
              + datosConsulta.getFechaInical()
              + "' and '"
              + datosConsulta.getFechaFinal()
              + "') and ");
    } else {
      queryString.append("where");
    }

    if (CollectionUtils.isNotEmpty(datosConsulta.getListaServicios())) {
      queryString.append("(ser.id IN (" + buildList(datosConsulta.getListaServicios()) + ")");
    } else {
      queryString.append("(ser.id IN (select id from tp_servicio)");
    }

    if (CollectionUtils.isNotEmpty(datosConsulta.getListaPaquetes())) {
      queryString.append(
          " or  paq.id IN (" + buildList(datosConsulta.getListaPaquetes()) + ")) and ");
    } else {
      queryString.append(" or  paq.id IN (select id from tp_paquete) ) and ");
    }

    queryString.append("  mov.accion = '" + datosConsulta.getTipo() + "' ");

    queryString.append("ORDER BY mov.fecha ASC ");

    return queryString.toString();
  }
  @Test
  public void testSettings() throws Exception {
    doReturn(null).when(service).update(anyObject());

    ObjectMapper mapper = new ObjectMapper();
    // prepare data
    NestDataDto dto = new NestDataDto();
    dto.setThermostats(Lists.newArrayList(new Thermostat("t1")));
    dto.setAlarms(Lists.newArrayList(new Alarm("a1")));
    Structure structure = new Structure("s1");
    // set to structure same alarms list
    structure.setAlarms(dto.getAlarms());
    // set to structure same thermostats list
    structure.setThermostats(dto.getThermostats());
    dto.setStructures(Lists.newArrayList(structure));

    String jsonContent = mapper.writeValueAsString(dto);
    String response =
        mockMvc
            .perform(post("/api/data").contentType(MediaType.APPLICATION_JSON).content(jsonContent))
            .andExpect(status().isOk())
            .andReturn()
            .getResponse()
            .getContentAsString();

    verify(service).update(captor.capture());

    NestDataDto value = captor.getValue();
    assertTrue("structure list", CollectionUtils.isNotEmpty(value.getStructures()));
    Structure structure0 = value.getStructures().get(0);
    assertEquals("structure", "s1", structure0.getId());

    assertTrue(
        "structure thermostat list", CollectionUtils.isNotEmpty(structure0.getThermostats()));
    assertEquals("structure thermostat", "t1", structure0.getThermostats().get(0).getId());

    assertTrue("structure alarm list", CollectionUtils.isNotEmpty(structure0.getAlarms()));
    assertEquals("structure alarm", "a1", structure0.getAlarms().get(0).getId());

    assertTrue("thermostat list", CollectionUtils.isNotEmpty(value.getThermostats()));
    assertEquals("thermostat in list", "t1", value.getThermostats().get(0).getId());

    assertTrue("alarm list", CollectionUtils.isNotEmpty(value.getAlarms()));
    assertEquals("alarm in list", "a1", value.getAlarms().get(0).getId());
  }
示例#27
0
  private boolean hasOldData() {
    boolean result = false;

    result = CollectionUtils.isNotEmpty(ItemFactory.getFactory(this).getItems());

    Log.d(TAG, "hasOldData: " + result);

    return result;
  }
示例#28
0
  /**
   * This method executes the job code change validation rules against the budget document for a
   * specific budget period.
   *
   * @return true is valid false if not valid
   * @throws NullPointerException if the budgetDocument is null
   * @throws IllegalArgumentException if the viewBudgetPeriod < 1
   */
  @KcEventMethod
  public boolean processCheckForJobCodeChange(BudgetSavePersonnelEvent event) {
    if (event.getBudget() == null) {
      throw new NullPointerException("the budgetDocument is null");
    }

    if (event.getCurrentBudgetPeriod() == null) {
      throw new NullPointerException("the currentBudgetPeriod is invalid");
    }

    boolean valid = true;

    GlobalVariables.getMessageMap().addToErrorPath("document");

    final BudgetPeriod selectedBudgetPeriod = event.getCurrentBudgetPeriod();

    final Collection<Integer> budgetPersonSequences =
        this.getBudgetPersonSequencesFromPersonnelDetails(
            selectedBudgetPeriod.getBudgetLineItems());

    if (CollectionUtils.isNotEmpty(budgetPersonSequences)) {
      int personIndex = 0;
      List<BudgetPerson> budgetPersons = event.getBudget().getBudgetPersons();
      for (BudgetPerson person : budgetPersons) {
        String errorKey =
            BUDGET_PERSONS_FIELD_NAME_START + personIndex + BUDGET_PERSONS_FIELD_NAME_JOBCODE;
        if (budgetPersonSequences.contains(person.getPersonSequenceNumber())) {
          if (CollectionUtils.isNotEmpty(this.getMappedCostElements(person))) {
            valid &= this.validateJobCodeChange(person, errorKey);
          } else {
            valid &= this.validateJobCodeValue(person, errorKey);
            this.updateJobCodeOnDetailsFromPerson(
                selectedBudgetPeriod.getBudgetLineItems(), person);
          }
        }
        personIndex++;
      }
    }

    GlobalVariables.getMessageMap().removeFromErrorPath("document");
    return valid;
  }
  // get third element
  private static void testGetByIndex() {
    Collection<String> collection = Lists.newArrayList("a1", "a2", "a3", "a1");
    MutableCollection<String> orderedIterable = FastList.newListWith("a1", "a2", "a3", "a1");
    Iterable<String> iterable = collection;

    // get third element
    String jdk = collection.stream().skip(2).findFirst().get(); // using JDK
    String guava = Iterables.get(iterable, 2); // using guava
    String apache = CollectionUtils.get(iterable, 2); // using Apache
    System.out.println("third = " + jdk + ":" + guava + ":" + apache); // print third = a3:a3:a3
  }
 @Override
 @Transactional(propagation = Propagation.REQUIRED)
 public Boolean deleteBook(
     Set<Integer> books_id, Set<Integer> authors_id, Set<Integer> publishers_id)
     throws NoSuchEntityException, ForbiddenException {
   List<BookEntity> booksToDelete = Lists.newArrayList();
   if (CollectionUtils.isNotEmpty(books_id)) {
     booksToDelete.addAll(bookDao.get(books_id));
   }
   if (CollectionUtils.isNotEmpty(authors_id)) {
     booksToDelete.addAll(bookDao.getBooksByAuthor(authors_id));
   }
   if (CollectionUtils.isNotEmpty(publishers_id)) {
     booksToDelete.addAll(bookDao.getBooksByPublisher(publishers_id));
   }
   if (CollectionUtils.isEmpty(booksToDelete)) {
     throw new NoSuchEntityException(BookEntity.class.getName());
   }
   return setStatusAndUpdate(booksToDelete, BookStatusesEnum.DELETED);
 }