List of usage examples for java.util Collections binarySearch
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
From source file:com.openteach.diamond.repository.client.cache.FileLRUCache.java
/** * /*w ww .j a v a 2 s. c om*/ * @param size * @return */ private Index findFree(int size) { if (frees.isEmpty()) { return null; } Index index = new Index(null, 0, size); int offset = Collections.binarySearch(frees, index); if (offset >= 0) { // return frees.remove(offset); } else { // int i = -offset - 2; for (; i >= 0; i--) { index = frees.get(i); if (index.length < size) { break; } } if (i + 1 < frees.size()) { index = frees.remove(i + 1); insertFree(new Index(null, index.offset + size, index.length - size)); return new Index(null, index.offset, size); } return null; } }
From source file:org.jfree.data.ComparableObjectSeries.java
/** * Adds a data item to the series and, if requested, sends a * {@link SeriesChangeEvent} to all registered listeners. * * @param item the (x, y) item (<code>null</code> not permitted). * @param notify a flag that controls whether or not a * {@link SeriesChangeEvent} is sent to all registered * listeners.//w ww. j a v a 2 s.c o m */ protected void add(ComparableObjectItem item, boolean notify) { ParamChecks.nullNotPermitted(item, "item"); if (this.autoSort) { int index = Collections.binarySearch(this.data, item); if (index < 0) { this.data.add(-index - 1, item); } else { if (this.allowDuplicateXValues) { // need to make sure we are adding *after* any duplicates int size = this.data.size(); while (index < size && item.compareTo(this.data.get(index)) == 0) { index++; } if (index < this.data.size()) { this.data.add(index, item); } else { this.data.add(item); } } else { throw new SeriesException("X-value already exists."); } } } else { if (!this.allowDuplicateXValues) { // can't allow duplicate values, so we need to check whether // there is an item with the given x-value already int index = indexOf(item.getComparable()); if (index >= 0) { throw new SeriesException("X-value already exists."); } } this.data.add(item); } if (getItemCount() > this.maximumItemCount) { this.data.remove(0); } if (notify) { fireSeriesChanged(); } }
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
/** * Prepares CSV file for MACE (see http://www.isi.edu/publications/licensed-sw/mace/) * * @param argumentPairs annotated data// w w w . jav a 2 s. co m * @param turkerIDs sorted list of turker IDs * @return single string in the proper MACE format */ public static String prepareCSV(List<AnnotatedArgumentPair> argumentPairs, List<String> turkerIDs) { System.out.println(turkerIDs); // for each item we need an array of annotations, i.e. // label1,,,label1,label2,label1,,, // whose size is number of annotators and annotators are identified by position (array index) // storing the resulting lines List<String> result = new ArrayList<>(); for (AnnotatedArgumentPair argumentPair : argumentPairs) { // for storing individual assignments String[] assignmentsArray = new String[turkerIDs.size()]; // fill with empty strings Arrays.fill(assignmentsArray, ""); for (AnnotatedArgumentPair.MTurkAssignment assignment : argumentPair.mTurkAssignments) { // do we want to include this annotation at all? // get the turker index int turkerIndex = Collections.binarySearch(turkerIDs, assignment.getTurkID()); // and set the label on the correct position in the array assignmentsArray[turkerIndex] = assignment.getValue(); } // concatenate with comma String line = StringUtils.join(assignmentsArray, ","); System.out.println(line); result.add(line); } // add empty line at the end result.add(""); return StringUtils.join(result, "\n"); }
From source file:org.openmrs.module.personalhr.PhrPatient.java
/** * Save relationship changes into database *///from www . j av a 2 s . c om public void save() { PhrSharingTokenService svc = Context.getService(PhrSharingTokenService.class); final List<PhrSharingToken> oldTokens = svc.getSharingTokenByPatient(this.patient); //check non-deleted relationships if (this.sharingTokens != null) { for (final PhrSharingToken token : this.sharingTokens) { if (token.getId() > 0) { //check changed relationship boolean isChanged = false; final PhrSharingToken oldToken = svc.getPhrSharingToken(token.getId()); if (!oldToken.getRelatedPersonEmail().equals(token.getRelatedPersonEmail())) { oldToken.setRelatedPersonEmail(token.getRelatedPersonEmail()); isChanged = true; } if (!oldToken.getRelatedPersonName().equals(token.getRelatedPersonName())) { oldToken.setRelatedPersonName(token.getRelatedPersonName()); isChanged = true; } if (!oldToken.getRelationType().equals(token.getRelationType())) { oldToken.setRelationType(token.getRelationType()); isChanged = true; } if (!oldToken.getShareType().equals(token.getShareType())) { oldToken.setShareType(token.getShareType()); isChanged = true; } if (isChanged) { //save changed relationship this.numberChanged++; svc.savePhrSharingToken(token); this.log.debug("Changed token id: " + token.getId()); } } else { //save added relationship this.numberAdded++; final PhrSharingToken addedToken = svc.savePhrSharingToken(token); this.log.debug("Newly added token id: " + addedToken.getId()); } } Collections.sort(this.sharingTokens); } //check deleted relationships if (oldTokens != null) { for (final PhrSharingToken token : oldTokens) { if (Collections.binarySearch(this.sharingTokens, token) < 0) { svc.deletePhrSharingToken(token); this.numberDeleted++; this.log.debug("Deleted token id: " + token.getId()); } } } //check newly added relationship if ((this.newSharingToken != null) && (this.newSharingToken.getRelatedPersonName() != null)) { final PhrSharingToken token = this.newSharingToken; final String tokenString = PersonalhrUtil.getRandomToken(); token.setSharingToken(tokenString); token.setRelatedPersonEmail(token.getRelatedPersonEmail()); token.setRelatedPersonName(token.getRelatedPersonName()); token.setShareType(token.getShareType()); token.setRelationType(token.getRelationType()); final Date startDate = new Date(); token.setStartDate(startDate); token.setDateCreated(startDate); token.setExpireDate(PersonalhrUtil.getExpireDate(startDate)); token.setCreator(Context.getAuthenticatedUser()); svc.savePhrSharingToken(token); this.numberAdded++; if (this.log.isDebugEnabled()) { this.log.debug("Newly added token id: " + svc.getSharingToken(tokenString).getId()); } } }
From source file:org.unitils.dbmaintainer.script.impl.DefaultScriptSource.java
/** * Returns true if one or more scripts that have a version index equal to or lower than * the index specified by the given version object has been modified since the timestamp specfied by * the given version.//from ww w . j ava 2 s .co m * * @param currentVersion The current database version, not null * @return True if an existing script has been modified, false otherwise */ public boolean isExistingIndexedScriptModified(Version currentVersion, Set<ExecutedScript> alreadyExecutedScripts, String dialect, String databaseName, boolean defaultDatabase) { Map<String, Script> alreadyExecutedScriptMap = convertToScriptNameScriptMap(alreadyExecutedScripts); List<Script> incrementalScripts = getIncrementalScripts(dialect, databaseName, defaultDatabase); // Search for indexed scripts that have been executed but don't appear in the current indexed scripts anymore for (ExecutedScript alreadyExecutedScript : alreadyExecutedScripts) { if (alreadyExecutedScript.getScript().isIncremental() && Collections.binarySearch(incrementalScripts, alreadyExecutedScript.getScript()) < 0) { logger.warn("Existing indexed script found that was executed, which has been removed: " + alreadyExecutedScript.getScript().getFileName()); return true; } } // Search for indexed scripts whose version < the current version, which are new or whose contents have changed for (Script indexedScript : incrementalScripts) { if (indexedScript.getVersion().compareTo(currentVersion) <= 0) { Script alreadyExecutedScript = alreadyExecutedScriptMap.get(indexedScript.getFileName()); if (alreadyExecutedScript == null) { logger.warn( "New index script has been added, with at least one already executed script having an higher index." + indexedScript.getFileName()); return true; } if (!alreadyExecutedScript.isScriptContentEqualTo(indexedScript, useScriptFileLastModificationDates())) { logger.warn("Script found of which the contents have changed: " + indexedScript.getFileName()); return true; } } } return false; }
From source file:com.openteach.diamond.repository.client.cache.FileLRUCache.java
/** * /*from www. j a va 2 s . co m*/ * @param index */ private void insertFree(Index index) { int offset = Collections.binarySearch(frees, index); if (offset >= 0) { // frees.add(offset + 1, index); } else { // frees.add(-offset - 1, index); } }
From source file:com.wizecommerce.hecuba.hector.HectorBasedHecubaClientManager.java
/** * Deletes a given column value of a row identified by the key. * * @param key - key of the row.// ww w . j a v a2 s . co m * @param columnName - name of the column to be deleted. */ public void deleteColumn(K key, String columnName) { final ColumnFamilyTemplate<K, String> columnFamily1 = getColumnFamily(); final HColumn<String, String> oldValue = readColumn(key, columnName); // is this insertion involves a change to secondary indexes if (isSecondaryIndexByColumnNameAndValueEnabled && Collections.binarySearch(columnsToIndexOnColumnNameAndValue, columnName) >= 0 && oldValue != null) { secondaryIndexedColumnFamilyTemplate.deleteColumn(getSecondaryIndexKey(columnName, oldValue.getValue()), key); } if (isSecondaryIndexesByColumnNamesEnabled && columnName.matches(secondaryIdxByColumnPattern)) { secondaryIndexedColumnFamilyTemplate.deleteColumn(getSecondaryIndexKey(columnName, ""), key); } columnFamily1.deleteColumn(key, columnName); }
From source file:oscar.oscarEncounter.pageUtil.EctIncomingEncounterAction.java
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { UtilDateUtilities dateConvert = new UtilDateUtilities(); oscar.oscarSecurity.CookieSecurity cs = new oscar.oscarSecurity.CookieSecurity(); EctSessionBean bean = new EctSessionBean(); if (cs.FindThisCookie(request.getCookies(), CookieSecurity.providerCookie)) { //pass security??? if (request.getParameter("appointmentList") != null) { bean = (EctSessionBean) request.getSession().getAttribute("EctSessionBean"); bean.setUpEncounterPage(request.getParameter("appointmentNo")); bean.template = ""; } else if (request.getParameter("demographicSearch") != null) { //Coming in from the demographicSearch page bean = (EctSessionBean) request.getSession().getAttribute("EctSessionBean"); //demographicNo is passed from search screen bean.demographicNo = request.getParameter("demographicNo"); //no curProviderNo when viewing eCharts from search screen //bean.curProviderNo=""; //no reason when viewing eChart from search screen bean.reason = ""; //userName is already set //bean.userName=request.getParameter("userName"); //no appointmentDate from search screen keep old date //bean.appointmentDate=""; //no startTime from search screen bean.startTime = ""; //no status from search screen bean.status = ""; //no date from search screen-keep old date //bean.date=""; bean.check = "myCheck"; bean.setUpEncounterPage();/*from w w w . ja v a 2 s. c om*/ request.getSession().setAttribute("EctSessionBean", bean); } else { bean = new EctSessionBean(); bean.currentDate = UtilDateUtilities.StringToDate(request.getParameter("curDate")); if (bean.currentDate == null) { bean.currentDate = UtilDateUtilities.Today(); } bean.providerNo = request.getParameter("providerNo"); if (bean.providerNo == null) { bean.providerNo = (String) request.getSession().getAttribute("user"); } bean.demographicNo = request.getParameter("demographicNo"); bean.appointmentNo = request.getParameter("appointmentNo"); bean.curProviderNo = request.getParameter("curProviderNo"); bean.reason = request.getParameter("reason"); bean.encType = request.getParameter("encType"); bean.userName = request.getParameter("userName"); if (bean.userName == null) { bean.userName = ((String) request.getSession().getAttribute("userfirstname")) + " " + ((String) request.getSession().getAttribute("userlastname")); } bean.myoscarMsgId = request.getParameter("myoscarmsg"); if (request.getParameter("myoscarmsg") != null) { ResourceBundle props = ResourceBundle.getBundle("oscarResources", request.getLocale()); try { MessageTransfer messageTransfer = MyOscarMessagesHelper.readMessage(request.getSession(), Long.parseLong(bean.myoscarMsgId)); String messageBeingRepliedTo = ""; String dateStr = ""; if (request.getParameter("remyoscarmsg") != null) { MessageTransfer messageTransferOrig = MyOscarMessagesHelper.readMessage( request.getSession(), Long.parseLong(request.getParameter("remyoscarmsg"))); dateStr = StringEscapeUtils.escapeHtml(DateUtils .formatDateTime(messageTransferOrig.getSendDate(), request.getLocale())); messageBeingRepliedTo = props.getString("myoscar.msg.From") + ": " + StringEscapeUtils.escapeHtml(messageTransferOrig.getSenderPersonLastName() + ", " + messageTransferOrig.getSenderPersonFirstName()) + " (" + dateStr + ")\n" + messageTransferOrig.getContents() + "\n-------------\n" + props.getString("myoscar.msg.Reply") + ":\n"; } else { dateStr = StringEscapeUtils.escapeHtml( DateUtils.formatDateTime(messageTransfer.getSendDate(), request.getLocale())); messageBeingRepliedTo = props.getString("myoscar.msg.From") + ": " + StringEscapeUtils.escapeHtml(messageTransfer.getSenderPersonLastName() + ", " + messageTransfer.getSenderPersonFirstName()) + " (" + dateStr + ")\n"; } bean.reason = props.getString("myoscar.msg.SubjectPrefix") + " - " + messageTransfer.getSubject(); bean.myoscarMsgId = messageBeingRepliedTo + StringEscapeUtils.escapeHtml(messageTransfer.getContents()) + "\n"; } catch (Exception myoscarEx) { bean.oscarMsg = "myoscar message was not retrieved"; log.error("ERROR retrieving message", myoscarEx); } } bean.appointmentDate = request.getParameter("appointmentDate"); bean.startTime = request.getParameter("startTime"); bean.status = request.getParameter("status"); bean.date = request.getParameter("date"); bean.check = "myCheck"; bean.oscarMsgID = request.getParameter("msgId"); bean.setUpEncounterPage(); request.getSession().setAttribute("EctSessionBean", bean); request.getSession().setAttribute("eChartID", bean.eChartId); if (request.getParameter("source") != null) { bean.source = request.getParameter("source"); } } } else { return (mapping.findForward("failure")); } ArrayList newDocArr = (ArrayList) request.getSession().getServletContext().getAttribute("newDocArr"); Boolean useNewEchart = (Boolean) request.getSession().getServletContext().getAttribute("useNewEchart"); String proNo = (String) request.getSession().getAttribute("user"); if (proNo != null && newDocArr != null && Collections.binarySearch(newDocArr, proNo) >= 0) { return (mapping.findForward("success2")); } else if (useNewEchart != null && useNewEchart.equals(Boolean.TRUE)) { return (mapping.findForward("success2")); } else { return (mapping.findForward("success")); } }
From source file:com.emergya.siradmin.invest.InvestmentUpdater.java
public void getWsDataAndUpdateDB(List<LlaveBean> wsProjectList) { // 1. Get an iterator of all Chileindica // 2. Traverse the list of LlaveBean // 3. For every LlaveBean mark database element as no removable // 4. If llaveBean is Updatable, create or update element in DataBase. // 5. If there is any problem cheking with the web service, mark the // element as update error. List<Long> projectDbIds = service.getAllProjectDbIds(); Collections.sort(wsProjectList); for (Iterator<Long> iterator = projectDbIds.iterator(); iterator.hasNext();) { Long dbId = iterator.next(); ChileindicaInversionDataDto dto = (ChileindicaInversionDataDto) service.getById(dbId); LlaveBean keyToSearch = new LlaveBean(); keyToSearch.setAno(dto.getAno()); keyToSearch.setRegion(dto.getRegion()); keyToSearch.setcFicha(dto.getCFicha()); keyToSearch.setcInstitucion(dto.getCInstitucion()); keyToSearch.setcPreinversion(dto.getCPreinversion()); if (LOGGER.isInfoEnabled()) { LOGGER.info("Tratando proyecto existente BBDD " + keyToSearch); }//from www .j a va 2 s.c o m // Buscamos si el proyecto existe entre las claves actuales int foundKeyIndex = Collections.binarySearch(wsProjectList, keyToSearch); if (foundKeyIndex >= 0) { LlaveBean foundKey = wsProjectList.get(foundKeyIndex); iterator.remove(); wsProjectList.remove(foundKeyIndex); if (LOGGER.isInfoEnabled()) { LOGGER.info("El proyecto sigue existiendo en el servicio web de consulta de llaves"); } // Si el proyecto ha sido actualizado en Chileindica recuperamos // los detalles del servicio web, borramos el proyecto original // de // la base de datos y creamos una entrada nueva en BD if (foundKey.isUpdatable()) { try { ConsultaInversionPorLlaveGeorefResponse response = this.wsConsultaInversion .getWSConsultaInversionPorLlaveGeorefPort() .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(foundKey.getRegion()), BigInteger.valueOf(foundKey.getAno()), BigInteger.valueOf(foundKey.getcInstitucion()), BigInteger.valueOf(foundKey.getcPreinversion()), BigInteger.valueOf(foundKey.getcFicha())); com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response .getRespuesta(); BigInteger codRespuesta = respuesta.getCodigoRespuesta(); if (BigInteger.ZERO.equals(codRespuesta)) { // delete from DB and create new instance service.delete(dto); ChileindicaInversionDataDto updatedProject = createDtoFromWsResponse(response, foundKey); service.create(updatedProject); foundKey.setStatus(UpdateStatus.OK); if (LOGGER.isInfoEnabled()) { LOGGER.info("Proyecto en BBDD actualizado"); } } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("Error obteniendo informacin del proyecto " + foundKey + ". Cdigo de repuesta = " + codRespuesta + ". Mensaje = " + respuesta.getTextoRespuesta()); } // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); foundKey.setStatus(UpdateStatus.WS_ERROR); service.update(dto); } } catch (DataAccessException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error almacenando proyecto " + foundKey + " en base de datos", e); } foundKey.setStatus(UpdateStatus.DB_ERROR); } catch (RemoteException e) { // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } catch (ServiceException e) { // Guardamos el proyecto en BBDD con estado error dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } catch (Throwable e) { dto.setUpdateStatus(UpdateStatus.WS_ERROR); dto.setLastUpdateTry(Calendar.getInstance().getTime()); service.update(dto); foundKey.setStatus(UpdateStatus.WS_ERROR); } } else { if (LOGGER.isInfoEnabled()) { LOGGER.info("El proyecto no necesita ser actualizado en BBDD"); } } } else { // si el proyecto no ha sido devuleto por el WS Consulta de // llaves, se borra de la base de datos service.delete(dto); if (LOGGER.isInfoEnabled()) { LOGGER.info("Se elimina el proyecto por no existir en la consulta de llaves " + keyToSearch); } } } // En este punto los elementos que quedan en projectDbIds pueden ser // eliminados de la base de datos puesto que no han sido devueltos por // el servicio web de consulta de llaves // for (Long id : projectDbIds) { // service.deleteById(id); // } // Ahora se crean los proyectos que queden en la lista de llaves // devueltas // por el servicio web. for (LlaveBean llave : wsProjectList) { ConsultaInversionPorLlaveGeorefResponse response; try { response = this.wsConsultaInversion.getWSConsultaInversionPorLlaveGeorefPort() .WSConsultaInversionPorLlaveGeoref(BigInteger.valueOf(llave.getRegion()), BigInteger.valueOf(llave.getAno()), BigInteger.valueOf(llave.getcInstitucion()), BigInteger.valueOf(llave.getcPreinversion()), BigInteger.valueOf(llave.getcFicha())); com.emergya.siradmin.invest.client.investmentdata.Respuesta respuesta = response.getRespuesta(); BigInteger codRespuesta = respuesta.getCodigoRespuesta(); if (BigInteger.ZERO.equals(codRespuesta)) { ChileindicaInversionDataDto newProject = createDtoFromWsResponse(response, llave); service.create(newProject); llave.setStatus(UpdateStatus.OK); if (LOGGER.isInfoEnabled()) { LOGGER.info("Creada nueva entrada en BBDD"); } } else { if (LOGGER.isErrorEnabled()) { LOGGER.error( "Error obteniendo informacin del proyecto " + llave + ". Cdigo de repuesta = " + codRespuesta + ". Mensaje = " + respuesta.getTextoRespuesta()); } llave.setStatus(UpdateStatus.WS_ERROR); } } catch (DataAccessException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error almacenando proyecto " + llave + " en base de datos", e); } llave.setStatus(UpdateStatus.DB_ERROR); } catch (RemoteException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } catch (ServiceException e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } catch (Throwable e) { if (LOGGER.isErrorEnabled()) { LOGGER.error("Error obteniendo informacin del proyecto " + llave, e); } llave.setStatus(UpdateStatus.WS_ERROR); } } }
From source file:edu.ku.brc.specify.ui.db.PickListTableAdapter.java
@Override public PickListItemIFace addItem(final String title, final String value) { // this should never happen! if (pickList.getType() != PickListDBAdapterIFace.Type.TableField.value()) { throw new RuntimeException("This type of PickList cannot be added to"); }// ww w . j av a 2s . com int sizeLimit = 50; // arbitrary size could be a pref (XXX PREF) Integer sizeLimitInt = pickList.getSizeLimit(); if (sizeLimitInt != null) { sizeLimit = sizeLimitInt.intValue(); } searchablePLI.setTitle(title); int index = Collections.binarySearch(items, searchablePLI); if (index < 0) { // find oldest item and remove it if (items.size() >= sizeLimit && sizeLimit > 0) { PickListItemIFace oldest = null; for (PickListItemIFace pli : items) { if (oldest == null || pli.getTimestampCreated().getTime() < oldest.getTimestampCreated().getTime()) { oldest = pli; } } items.remove(oldest); pickList.removeItem(oldest); } PickListItem item = new PickListItem(title, value, new Timestamp(System.currentTimeMillis())); items.add(item); if (pickList != null) { pickList.addItem(item); item.setPickList(pickList); pickList.reorder(); } Collections.sort(items); super.fireContentsChanged(this, 0, items.size() - 1); for (ChangeListener cl : changeListeners) { cl.stateChanged(new ChangeEvent(this)); } return item; } // else return items.elementAt(index); }