List of usage examples for java.util UUID equals
public boolean equals(Object obj)
From source file:org.apache.bookkeeper.mledger.impl.OffloadPrefixTest.java
@Test public void testOffloadConflict() throws Exception { Set<Pair<Long, UUID>> deleted = ConcurrentHashMap.newKeySet(); CompletableFuture<Set<Long>> errorLedgers = new CompletableFuture<>(); Set<Pair<Long, UUID>> failedOffloads = ConcurrentHashMap.newKeySet(); MockLedgerOffloader offloader = new MockLedgerOffloader() { @Override/*from ww w . ja v a 2 s. c om*/ public CompletableFuture<Void> offload(ReadHandle ledger, UUID uuid, Map<String, String> extraMetadata) { return errorLedgers.thenCompose((errors) -> { if (errors.remove(ledger.getId())) { failedOffloads.add(Pair.of(ledger.getId(), uuid)); CompletableFuture<Void> future = new CompletableFuture<>(); future.completeExceptionally(new Exception("Some kind of error")); return future; } else { return super.offload(ledger, uuid, extraMetadata); } }); } @Override public CompletableFuture<Void> deleteOffloaded(long ledgerId, UUID uuid, Map<String, String> offloadDriverMetadata) { deleted.add(Pair.of(ledgerId, uuid)); return super.deleteOffloaded(ledgerId, uuid, offloadDriverMetadata); } }; ManagedLedgerConfig config = new ManagedLedgerConfig(); config.setMaxEntriesPerLedger(10); config.setMinimumRolloverTime(0, TimeUnit.SECONDS); config.setRetentionTime(10, TimeUnit.MINUTES); config.setLedgerOffloader(offloader); ManagedLedgerImpl ledger = (ManagedLedgerImpl) factory.open("my_test_ledger", config); for (int i = 0; i < 15; i++) { String content = "entry-" + i; ledger.addEntry(content.getBytes()); } Set<Long> errorSet = ConcurrentHashMap.newKeySet(); errorSet.add(ledger.getLedgersInfoAsList().get(0).getLedgerId()); errorLedgers.complete(errorSet); try { ledger.offloadPrefix(ledger.getLastConfirmedEntry()); } catch (ManagedLedgerException e) { // expected } Assert.assertTrue(errorSet.isEmpty()); Assert.assertEquals(failedOffloads.size(), 1); Assert.assertEquals(deleted.size(), 0); long expectedFailedLedger = ledger.getLedgersInfoAsList().get(0).getLedgerId(); UUID expectedFailedUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); Assert.assertEquals(failedOffloads.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); Assert.assertFalse(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); // try offload again ledger.offloadPrefix(ledger.getLastConfirmedEntry()); Assert.assertEquals(failedOffloads.size(), 1); Assert.assertEquals(deleted.size(), 1); Assert.assertEquals(deleted.stream().findFirst().get(), Pair.of(expectedFailedLedger, expectedFailedUUID)); UUID successUUID = new UUID(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidMsb(), ledger.getLedgersInfoAsList().get(0).getOffloadContext().getUidLsb()); Assert.assertFalse(successUUID.equals(expectedFailedUUID)); Assert.assertTrue(ledger.getLedgersInfoAsList().get(0).getOffloadContext().getComplete()); }
From source file:org.pentaho.reporting.platform.plugin.async.ExecutorIT.java
@Test public void testRecalc() throws IOException, ExecutionException, InterruptedException { try {// ww w .ja va 2 s .c om final IPluginManager pluginManager = mock(IPluginManager.class); PentahoSystem.registerObject(pluginManager, IPluginManager.class); when(pluginManager.getPluginSetting("reporting", "settings/query-limit", "0")).thenReturn("50"); final StandaloneSession session = new StandaloneSession("test"); PentahoSessionHolder.setSession(session); final UUID uuid = UUID.randomUUID(); final AsyncJobFileStagingHandler asyncJobFileStagingHandler = new AsyncJobFileStagingHandler(session); simpleReportingComponent .setReportDefinitionPath("target/test/resource/solution/test/reporting/100rows.prpt"); simpleReportingComponent.setInputs(Collections.singletonMap("query-limit", 500)); executor.addTask( new PentahoAsyncReportExecution("target/test/resource/solution/test/reporting/100rows.prpt", simpleReportingComponent, asyncJobFileStagingHandler, session, UUID.randomUUID().toString(), new AuditWrapper()), session, uuid); IAsyncReportState reportState = executor.getReportState(uuid, session); while (reportState.getTotalRows() < 1) { reportState = executor.getReportState(uuid, session); } assertEquals(100, reportState.getTotalRows()); final UUID recalculate = executor.recalculate(uuid, session); assertFalse(uuid.equals(recalculate)); IAsyncReportState recalcState = executor.getReportState(recalculate, session); while (recalcState.getTotalRows() < 1) { recalcState = executor.getReportState(recalculate, session); } assertEquals(100, recalcState.getTotalRows()); } finally { PentahoSessionHolder.removeSession(); } }
From source file:org.gridgain.grid.kernal.managers.deployment.GridDeploymentClassLoader.java
/** * Creates a new peer class loader.// w ww . jav a2 s. c o m * <p> * If there is a security manager, its * {@link SecurityManager#checkCreateClassLoader()} * method is invoked. This may result in a security exception. * * @param id Class loader ID. * @param usrVer User version. * @param depMode Deployment mode. * @param singleNode {@code True} for single node. * @param ctx Kernal context. * @param parent Parent class loader. * @param clsLdrId Remote class loader identifier. * @param nodeId ID of node that have initiated task. * @param comm Communication manager loader will work through. * @param p2pTimeout Timeout for class-loading requests. * @param log Logger. * @param p2pExclude List of P2P loaded packages. * @param missedResourcesCacheSize Size of the missed resources cache. * @param clsBytesCacheEnabled Flag to enable class byte cache. * @param quiet {@code True} to omit output to log. * @throws SecurityException If a security manager exists and its * {@code checkCreateClassLoader} method doesn't allow creation * of a new class loader. */ GridDeploymentClassLoader(GridUuid id, String usrVer, GridDeploymentMode depMode, boolean singleNode, GridKernalContext ctx, ClassLoader parent, GridUuid clsLdrId, UUID nodeId, GridDeploymentCommunication comm, long p2pTimeout, GridLogger log, String[] p2pExclude, int missedResourcesCacheSize, boolean clsBytesCacheEnabled, boolean quiet) throws SecurityException { super(parent); assert id != null; assert depMode != null; assert ctx != null; assert comm != null; assert p2pTimeout > 0; assert log != null; assert clsLdrId != null; assert nodeId.equals(clsLdrId.globalId()); this.id = id; this.usrVer = usrVer; this.depMode = depMode; this.singleNode = singleNode; this.ctx = ctx; this.comm = comm; this.p2pTimeout = p2pTimeout; this.log = log; this.p2pExclude = p2pExclude; nodeList = new LinkedList<>(); nodeList.add(nodeId); Map<UUID, GridUuid> map = U.newHashMap(1); map.put(nodeId, clsLdrId); nodeLdrMap = singleNode ? Collections.unmodifiableMap(map) : map; missedRsrcs = missedResourcesCacheSize > 0 ? new GridBoundedLinkedHashSet<String>(missedResourcesCacheSize) : null; byteMap = clsBytesCacheEnabled ? new ConcurrentHashMap8<String, byte[]>() : null; this.quiet = quiet; }
From source file:org.jasig.ssp.service.impl.EarlyAlertServiceImpl.java
@Override @Transactional(rollbackFor = { ObjectNotFoundException.class, ValidationException.class }) public EarlyAlert create(@NotNull final EarlyAlert earlyAlert) throws ObjectNotFoundException, ValidationException { // Validate objects if (earlyAlert == null) { throw new IllegalArgumentException("EarlyAlert must be provided."); }/*from w w w . j a va 2s .c o m*/ if (earlyAlert.getPerson() == null) { throw new ValidationException("EarlyAlert Student data must be provided."); } final Person student = earlyAlert.getPerson(); // Figure student advisor or early alert coordinator final UUID assignedAdvisor = getEarlyAlertAdvisor(earlyAlert); if (assignedAdvisor == null) { throw new ValidationException( "Could not determine the Early Alert Advisor for student ID " + student.getId()); } if (student.getCoach() == null || assignedAdvisor.equals(student.getCoach().getId())) { student.setCoach(personService.get(assignedAdvisor)); } ensureValidAlertedOnPersonStateNoFail(student); // Create alert final EarlyAlert saved = getDao().save(earlyAlert); // Send e-mail to assigned advisor (coach) try { sendMessageToAdvisor(saved, earlyAlert.getEmailCC()); } catch (final SendFailedException e) { LOGGER.warn("Could not send Early Alert message to advisor.", e); throw new ValidationException( "Early Alert notification e-mail could not be sent to advisor. Early Alert was NOT created.", e); } // Send e-mail CONFIRMATION to faculty try { sendConfirmationMessageToFaculty(saved); } catch (final SendFailedException e) { LOGGER.warn("Could not send Early Alert confirmation to faculty.", e); throw new ValidationException( "Early Alert confirmation e-mail could not be sent. Early Alert was NOT created.", e); } return saved; }
From source file:org.apache.ignite.internal.managers.deployment.GridDeploymentClassLoader.java
/** * Creates a new peer class loader.//w w w.j a v a 2 s . com * <p> * If there is a security manager, its * {@link SecurityManager#checkCreateClassLoader()} * method is invoked. This may result in a security exception. * * @param id Class loader ID. * @param usrVer User version. * @param depMode Deployment mode. * @param singleNode {@code True} for single node. * @param ctx Kernal context. * @param parent Parent class loader. * @param clsLdrId Remote class loader identifier. * @param nodeId ID of node that have initiated task. * @param comm Communication manager loader will work through. * @param p2pTimeout Timeout for class-loading requests. * @param log Logger. * @param p2pExclude List of P2P loaded packages. * @param missedResourcesCacheSize Size of the missed resources cache. * @param clsBytesCacheEnabled Flag to enable class byte cache. * @param quiet {@code True} to omit output to log. * @throws SecurityException If a security manager exists and its * {@code checkCreateClassLoader} method doesn't allow creation * of a new class loader. */ GridDeploymentClassLoader(IgniteUuid id, String usrVer, DeploymentMode depMode, boolean singleNode, GridKernalContext ctx, ClassLoader parent, IgniteUuid clsLdrId, UUID nodeId, GridDeploymentCommunication comm, long p2pTimeout, IgniteLogger log, String[] p2pExclude, int missedResourcesCacheSize, boolean clsBytesCacheEnabled, boolean quiet) throws SecurityException { super(parent); assert id != null; assert depMode != null; assert ctx != null; assert comm != null; assert p2pTimeout > 0; assert log != null; assert clsLdrId != null; assert nodeId.equals(clsLdrId.globalId()); this.id = id; this.usrVer = usrVer; this.depMode = depMode; this.singleNode = singleNode; this.ctx = ctx; this.comm = comm; this.p2pTimeout = p2pTimeout; this.log = log; this.p2pExclude = p2pExclude; nodeList = new LinkedList<>(); nodeList.add(nodeId); Map<UUID, IgniteUuid> map = U.newHashMap(1); map.put(nodeId, clsLdrId); nodeLdrMap = singleNode ? Collections.unmodifiableMap(map) : map; missedRsrcs = missedResourcesCacheSize > 0 ? new GridBoundedLinkedHashSet<String>(missedResourcesCacheSize) : null; byteMap = clsBytesCacheEnabled ? new ConcurrentHashMap8<String, byte[]>() : null; this.quiet = quiet; }
From source file:com.bigdata.bop.BOpContext.java
/** * Return the {@link IRunningQuery} associated with the specified queryId. * //from w w w . j a va 2 s . c o m * @param queryId * The {@link UUID} of some {@link IRunningQuery}. * * @return The {@link IRunningQuery}. * * @throws RuntimeException * if the {@link IRunningQuery} has halted. * @throws RuntimeException * if the {@link IRunningQuery} is not found. */ public IRunningQuery getRunningQuery(final UUID queryId) { // Lookup the query by its UUID. final IRunningQuery runningQuery; try { if (queryId.equals(this.runningQuery.getQueryId())) { runningQuery = this.runningQuery; } else { runningQuery = getRunningQuery().getQueryEngine().getRunningQuery(queryId); } } catch (RuntimeException ex) { throw new RuntimeException("Query halted? : " + ex, ex); } if (runningQuery == null) { // We could not locate the query. throw new RuntimeException("IRunningQuery not found."); } return runningQuery; }
From source file:org.apache.usergrid.persistence.Results.java
public Results startingFrom(UUID entityId) { if (entities != null) { for (int i = 0; i < entities.size(); i++) { Entity entity = entities.get(i); if (entityId.equals(entity.getUuid())) { if (i == 0) { return this; }//ww w . j a v a 2 s .c o m return Results.fromEntities(entities.subList(i, entities.size())); } } } if (refs != null) { for (int i = 0; i < refs.size(); i++) { EntityRef entityRef = refs.get(i); if (entityId.equals(entityRef.getUuid())) { if (i == 0) { return this; } return Results.fromRefList(refs.subList(i, refs.size())); } } } if (ids != null) { for (int i = 0; i < ids.size(); i++) { UUID uuid = ids.get(i); if (entityId.equals(uuid)) { if (i == 0) { return this; } return Results.fromIdList(ids.subList(i, ids.size())); } } } return this; }
From source file:org.wwscc.storage.SQLDataInterface.java
@Override public Dialins loadDialins(int eventid) { String sql = "SELECT c.classcode,c.indexcode,c.useclsmult,r.* " + "FROM runs AS r JOIN cars AS c ON c.carid=r.carid WHERE r.eventid=? ORDER BY r.carid,r.course"; try {/*from w w w . j a v a2 s .co m*/ Event e = executeSelect("select * from events where eventid=?", newList(eventid), Event.class.getConstructor(ResultSet.class)).get(0); ResultSet rs = executeSelect(sql, newList(eventid)); Dialins ret = new Dialins(); UUID currentid = IdGenerator.nullid; String classcode = ""; String indexcode = ""; boolean useclsmult = false; double index = 1.0; double bestraw[] = new double[2]; double bestnet[] = new double[2]; // 1. load all runs // 2. calculate best raw/net/sum for each carid // 3. set personal dialin while (rs.next()) { Run r = new Run(rs); double net = 999.999; if (!currentid.equals(r.getCarId())) // next car, process previous { ret.setEntrant(currentid, classcode, bestraw[0] + bestraw[1], bestnet[0] + bestnet[1], index); currentid = r.getCarId(); bestraw[0] = bestraw[1] = bestnet[0] = bestnet[1] = 999.999; } classcode = rs.getString("classcode"); indexcode = rs.getString("indexcode"); useclsmult = rs.getBoolean("useclsmult"); index = getClassData().getEffectiveIndex(classcode, indexcode, useclsmult); if (r.isOK()) // we ignore non-OK runs { int idx = r.course() - 1; if (r.raw < bestraw[idx]) bestraw[idx] = r.raw; net = (r.getRaw() + (e.getConePenalty() * r.getCones()) + (e.getGatePenalty() * r.getGates())) * index; if (net < bestnet[idx]) bestnet[idx] = net; } } // 4. order and set class dialins ret.finalize(); closeLeftOvers(); return ret; } catch (Exception ioe) { logError("loadDialins", ioe); return null; } }
From source file:gov.va.isaac.gui.preferences.plugins.ViewCoordinatePreferencesPluginViewController.java
public Region getContent() { Task<Void> task = new Task<Void>() { @Override/*ww w .ja v a 2 s. co m*/ protected Void call() throws Exception { log.debug("initializing content"); try { if (!contentLoaded) { contentLoaded = true; // Populate selectableModules final ConceptVersionBI moduleRootConcept = OTFUtility.getConceptVersion( IsaacMetadataAuxiliaryBinding.MODULE.getPrimodialUuid(), panelViewCoordinate); final Set<ConceptVersionBI> moduleConcepts = new HashSet<>(); try { moduleConcepts.addAll(OTFUtility.getAllChildrenOfConcept(moduleRootConcept.getNid(), panelViewCoordinate, false)); } catch (Exception e) { log.error("Failed loading module concepts as children of " + moduleRootConcept, e); e.printStackTrace(); AppContext.getCommonDialogs() .showErrorDialog("Failed loading module concepts as children of " + moduleRootConcept + ". See logs.", e); } List<SelectableModule> modules = new ArrayList<>(); for (ConceptVersionBI cv : moduleConcepts) { modules.add(new SelectableModule(cv.getNid())); } selectableModules.clear(); selectableModules.addAll(modules); allModulesMarker.selected.addListener((observable, oldValue, newValue) -> { if (newValue) { for (SelectableModule module : selectableModules) { module.selectedProperty().set(false); } } }); selectableModules.forEach(selectableModule -> selectableModule.selectedProperty() .addListener((observable, wasSelected, isSelected) -> { if (isSelected) { if (!wasSelected) { //log.debug("Adding module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription()); selectedModules.add(selectableModule.getUuid()); allModulesMarker.selectedProperty().set(false); } } else { if (wasSelected) { //log.debug("Removing module nid={}, uuid={}, desc={}", selectableModule.getNid(), selectableModule.getUuid(), selectableModule.getDescription()); selectedModules.remove(selectableModule.getUuid()); if (selectedModules.size() == 0) { allModulesMarker.selectedProperty().set(true); } } } })); selectableModuleListView.getItems().clear(); selectableModuleListView.getItems().add(allModulesMarker); Collections.sort(selectableModules); selectableModuleListView.getItems().addAll(selectableModules); runLaterIfNotFXApplicationThread( () -> pathComboBox.setTooltip(new Tooltip("Default path is \"" + OTFUtility.getDescription(getDefaultPath(), panelViewCoordinate) + "\""))); pathComboBox.getItems().clear(); pathComboBox.getItems().addAll(getPathOptions()); } // Reload persisted values every time UserProfile loggedIn = ExtendedAppContext.getCurrentlyLoggedInUserProfile(); pathComboBox.getSelectionModel().select(loggedIn.getViewCoordinatePath()); // Reload storedStatedInferredOption loadStoredStatedInferredOption(); // Reload storedStatuses loadStoredStatuses(); // Reload storedModules final Set<UUID> storedModuleUuids = getStoredModules(); if (storedModuleUuids.size() == 0) { allModulesMarker.setSelected(true); } else { // Check to make sure that stored UUID refers to an existing, known module for (UUID storedModuleUuid : storedModuleUuids) { boolean foundStoredUuidModuleInSelectableModules = false; for (SelectableModule selectableModule : selectableModules) { if (storedModuleUuid.equals(selectableModule.getUuid())) { foundStoredUuidModuleInSelectableModules = true; break; } } if (!foundStoredUuidModuleInSelectableModules) { log.error( "Loaded module (uuid={}) from user preferences that does not currently exist", storedModuleUuid); AppContext.getCommonDialogs().showErrorDialog("Unsupported Module", "Loaded a module UUID from UserProfile that does not correspond to existing module", "Concept (UUID=" + storedModuleUuid + ") not a valid module. Must be one of " + Arrays.toString(selectableModules.toArray())); } } for (SelectableModule module : selectableModules) { if (storedModuleUuids.contains(module.getUuid())) { module.setSelected(true); } else { module.setSelected(false); } } } Long storedTime = getStoredTime(); if (storedTime.equals(Long.MAX_VALUE)) { dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.USE_LATEST); currentTimeProperty.set(Long.MAX_VALUE); runLaterIfNotFXApplicationThread(() -> datePicker.setValue(LocalDate.now())); } else { dateSelectionMethodComboBox.getSelectionModel().select(DateSelectionMethod.SPECIFY); currentTimeProperty.set(storedTime); setDatePickerFromCurrentTimeProperty(); } return null; } catch (Exception e) { log.error("initContent() task caught " + e.getClass().getName() + " " + e.getLocalizedMessage(), e); e.printStackTrace(); throw e; } } @Override protected void succeeded() { log.debug("Content initialization succeeded"); removeProgressIndicator(); } @Override protected void failed() { removeProgressIndicator(); Throwable ex = getException(); log.error("loadContent() caught " + ex.getClass().getName() + " " + ex.getLocalizedMessage(), ex); AppContext.getCommonDialogs().showErrorDialog("Failed loading content. See logs.", ex); } }; addProgressIndicator(); Utility.execute(task); return gridPaneInRootStackPane; }
From source file:net.sf.maltcms.chromaui.project.spi.project.ChromAUIProject.java
/** * * @param <T> the IContainer type to query for * @param containerId the requested id of the container * @param containerClass the explicit class of the container * @throws ConstraintViolationException if more than one object with the * requested id was found/*from w ww . ja v a2s . c o m*/ * @throws ResourceNotAvailableException if no object with the requested id * was found * @throws IllegalStateException if the database was not yet initialized * @return */ @Override public <T extends IContainer> T getContainerById(final UUID containerId, Class<? extends T> containerClass) { if (icp != null) { ICrudSession ics = icp.createSession(); try { IQuery<? extends T> query = ics.newQuery(containerClass); Collection<T> results = query.retrieve(new Predicate<T>() { private static final long serialVersionUID = -7402207122617612419L; @Override public boolean match(T et) { return containerId.equals(et.getId()); } }); if (results.isEmpty()) { throw new ResourceNotAvailableException( "Object with id=" + containerId.toString() + " not found in database!"); } if (results.size() > 1) { throw new ConstraintViolationException("Query by unique id=" + containerId.toString() + " returned " + results.size() + " instances. Expected 1!"); } return results.iterator().next(); } finally { ics.close(); } } throw new IllegalStateException("Database not initialized!"); }