List of usage examples for org.apache.commons.lang3.tuple Triple getRight
public abstract R getRight();
Gets the right element from this triple.
From source file:alluxio.master.file.replication.ReplicationChecker.java
private void check(Set<Long> inodes, ReplicationHandler handler, Mode mode) { Set<Long> lostBlocks = mBlockMaster.getLostBlocks(); Set<Triple<AlluxioURI, Long, Integer>> requests = new HashSet<>(); for (long inodeId : inodes) { // TODO(binfan): calling lockFullInodePath locks the entire path from root to the target // file and may increase lock contention in this tree. Investigate if we could avoid // locking the entire path but just the inode file since this access is read-only. try (LockedInodePath inodePath = mInodeTree.lockFullInodePath(inodeId, LockPattern.READ)) { InodeFileView file = inodePath.getInodeFile(); for (long blockId : file.getBlockIds()) { BlockInfo blockInfo = null; try { blockInfo = mBlockMaster.getBlockInfo(blockId); } catch (BlockInfoException e) { // Cannot find this block in Alluxio from BlockMaster, possibly persisted in UFS } catch (UnavailableException e) { // The block master is not available, wait for the next heartbeat LOG.warn("The block master is not available: {}", e.getMessage()); return; }//from www . ja v a2s .c om int currentReplicas = (blockInfo == null) ? 0 : blockInfo.getLocations().size(); switch (mode) { case EVICT: int maxReplicas = file.getReplicationMax(); if (file.getPersistenceState() == PersistenceState.TO_BE_PERSISTED && file.getReplicationDurable() > maxReplicas) { maxReplicas = file.getReplicationDurable(); } if (currentReplicas > maxReplicas) { requests.add(new ImmutableTriple<>(inodePath.getUri(), blockId, currentReplicas - maxReplicas)); } break; case REPLICATE: int minReplicas = file.getReplicationMin(); if (file.getPersistenceState() == PersistenceState.TO_BE_PERSISTED && file.getReplicationDurable() > minReplicas) { minReplicas = file.getReplicationDurable(); } if (currentReplicas < minReplicas) { // if this file is not persisted and block master thinks it is lost, no effort made if (!file.isPersisted() && lostBlocks.contains(blockId)) { continue; } requests.add(new ImmutableTriple<>(inodePath.getUri(), blockId, minReplicas - currentReplicas)); } break; default: LOG.warn("Unexpected replication mode {}.", mode); } } } catch (FileDoesNotExistException e) { LOG.warn("Failed to check replication level for inode id {} : {}", inodeId, e.getMessage()); } } for (Triple<AlluxioURI, Long, Integer> entry : requests) { AlluxioURI uri = entry.getLeft(); long blockId = entry.getMiddle(); int numReplicas = entry.getRight(); try { switch (mode) { case EVICT: handler.evict(uri, blockId, numReplicas); mQuietPeriodSeconds /= 2; break; case REPLICATE: handler.replicate(uri, blockId, numReplicas); mQuietPeriodSeconds /= 2; break; default: LOG.warn("Unexpected replication mode {}.", mode); } } catch (JobDoesNotExistException | ResourceExhaustedException e) { LOG.warn("The job service is busy, will retry later. {}", e.toString()); mQuietPeriodSeconds = (mQuietPeriodSeconds == 0) ? 1 : Math.min(MAX_QUIET_PERIOD_SECONDS, mQuietPeriodSeconds * 2); return; } catch (UnavailableException e) { LOG.warn("Unable to complete the replication check: {}, will retry later.", e.getMessage()); return; } catch (Exception e) { LOG.warn("Unexpected exception encountered when starting a replication / eviction job (uri={}," + " block ID={}, num replicas={}) : {}", uri, blockId, numReplicas, e.getMessage()); LOG.debug("Exception: ", e); } } }
From source file:com.minlia.cloud.framework.client.util.SearchUriBuilder.java
public final SearchUriBuilder consume(final Triple<String, ClientOperation, String> constraint) { final ClientOperation operation = (constraint == null) ? null : constraint.getMiddle(); final boolean negated = (constraint == null) ? false : constraint.getMiddle().isNegated(); final String key = (constraint == null) ? null : constraint.getLeft(); final String value = (constraint == null) ? null : constraint.getRight(); return consume(operation, key, value, negated); }
From source file:blusunrize.immersiveengineering.api.ApiUtils.java
public static Connection raytraceWires(World world, Vec3d start, Vec3d end, @Nullable Connection ignored) { Map<BlockPos, ImmersiveNetHandler.BlockWireInfo> inDim = ImmersiveNetHandler.INSTANCE.blockWireMap .lookup(world.provider.getDimension()); AtomicReference<Connection> ret = new AtomicReference<>(); AtomicDouble minDistSq = new AtomicDouble(Double.POSITIVE_INFINITY); if (inDim != null) { Utils.rayTrace(start, end, world, (pos) -> { if (inDim.containsKey(pos)) { ImmersiveNetHandler.BlockWireInfo info = inDim.get(pos); for (int i = 0; i < 2; i++) { Set<Triple<Connection, Vec3d, Vec3d>> conns = i == 0 ? info.in : info.near; for (Triple<Connection, Vec3d, Vec3d> conn : conns) { Connection c = conn.getLeft(); if (ignored == null || !c.hasSameConnectors(ignored)) { Vec3d startRelative = start.add(-pos.getX(), -pos.getY(), -pos.getZ()); Vec3d across = conn.getRight().subtract(conn.getMiddle()); double t = Utils.getCoeffForMinDistance(startRelative, conn.getMiddle(), across); t = MathHelper.clamp(0, t, 1); Vec3d closest = conn.getMiddle().add(t * across.x, t * across.y, t * across.z); double distSq = closest.squareDistanceTo(startRelative); if (distSq < minDistSq.get()) { ret.set(c); minDistSq.set(distSq); }//from w w w .jav a 2 s . c o m } } } } }); } return ret.get(); }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java
private void testSetGetAttribute(MBeanServerConnection connection, ObjectName name) throws Exception { for (Triple<String, String, String> pair : mbeanAttributes) { String attrName = pair.getLeft(); String attrType = pair.getRight(); Object attrValue;//from w w w . ja va 2s . c o m if (attrType.equals("int")) attrValue = RandomUtils.nextInt(30000, 65535); else if (attrType.equals("long")) attrValue = RandomUtils.nextLong(10, 1000); else attrValue = RandomStringUtils.randomAlphabetic(10); Attribute attr1 = new Attribute(attrName, attrValue); server.setAttribute(name, attr1); Object attr2 = server.getAttribute(name, attrName); assertEquals("Attribute values do not match", attrValue, attr2); } }
From source file:at.gridtec.lambda4j.function.tri.TriFunction.java
/** * Applies this function to the given tuple. * * @param tuple The tuple to be applied to the function * @return The return value from the function, which is its result. * @throws NullPointerException If given argument is {@code null} * @see org.apache.commons.lang3.tuple.Triple *//*w ww . j a v a 2s .c om*/ default R apply(@Nonnull Triple<T, U, V> tuple) { Objects.requireNonNull(tuple); return apply(tuple.getLeft(), tuple.getMiddle(), tuple.getRight()); }
From source file:alfio.controller.TicketController.java
@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/update", method = RequestMethod.GET) public String showTicketForUpdate(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, Model model, Locale locale) { Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager .fetchCompleteAndAssigned(eventName, ticketIdentifier); if (!oData.isPresent()) { return "redirect:/event/" + eventName; }/*from ww w . j a v a2s. co m*/ Triple<Event, TicketReservation, Ticket> data = oData.get(); Event event = data.getLeft(); TicketCategory ticketCategory = ticketCategoryRepository.getByIdAndActive(data.getRight().getCategoryId(), event.getId()); Organization organization = organizationRepository.getById(event.getOrganizationId()); boolean enableFreeCancellation = configurationManager .getBooleanConfigValue(Configuration.from(event.getOrganizationId(), event.getId(), ticketCategory.getId(), ALLOW_FREE_TICKETS_CANCELLATION), false); Ticket ticket = data.getRight(); model.addAttribute("ticketAndCategory", Pair.of(eventManager.getTicketCategoryById(ticket.getCategoryId(), event.getId()), new TicketDecorator(ticket, enableFreeCancellation, eventManager.checkTicketCancellationPrerequisites().apply(ticket), "ticket/" + ticket.getUuid() + "/view", ticketHelper.findTicketFieldConfigurationAndValue(event.getId(), ticket, locale), true, "")))// .addAttribute("reservation", data.getMiddle())// .addAttribute("reservationId", ticketReservationManager.getShortReservationID(event, data.getMiddle().getId())) .addAttribute("event", event)// .addAttribute("ticketCategory", ticketCategory)// .addAttribute("countries", TicketHelper.getLocalizedCountries(locale)) .addAttribute("organization", organization)// .addAttribute("pageTitle", "show-ticket.header.title") .addAttribute("useFirstAndLastName", event.mustUseFirstAndLastName()); return "/event/update-ticket"; }
From source file:blusunrize.immersiveengineering.common.blocks.cloth.TileEntityBalloon.java
@Override public void onEntityCollision(World world, Entity entity) { if (entity instanceof EntityArrow || entity instanceof EntityRevolvershot) { Vec3d pos = new Vec3d(getPos()).add(.5, .5, .5); world.playSound(null, pos.x, pos.y, pos.z, SoundEvents.ENTITY_FIREWORK_BLAST, SoundCategory.BLOCKS, 1.5f, 0.7f);/*w w w . j a v a2 s . c om*/ world.setBlockToAir(getPos()); world.spawnParticle(EnumParticleTypes.EXPLOSION_NORMAL, pos.x, pos.y, pos.z, 0, .05, 0); Triple<ItemStack, ShaderRegistryEntry, ShaderCase> shader = ShaderRegistry .getStoredShaderAndCase(this.shader); if (shader != null) shader.getMiddle().getEffectFunction().execute(world, shader.getLeft(), null, shader.getRight().getShaderType(), pos, null, .375f); } }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java
/** * Set the Configuration property via REST interface and check whether the JMX interface returns the same value * * @throws Exception/*from w ww .j a va2s. c om*/ */ //TODO: Use the web target JAXRS API to execute these request possibly ? @Ignore @Test public void testSetRESTGetMBeanLocal() throws Exception { LOGGER.debug("testSetRESTGetMBeanLocal"); ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME); ServletTester tester = new ServletTester(); tester.addServlet(LaxConfigServlet.class, "/config"); tester.start(); for (Triple<String, String, String> triple : mbeanAttributes) { String attrName = triple.getLeft(); String attrType = triple.getRight(); String attrValueStr; if (attrType.equals("int")) attrValueStr = Integer.toString(RandomUtils.nextInt(30000, 65535)); else if (attrType.equals("long")) attrValueStr = Long.toString(RandomUtils.nextLong(10, 1000)); else attrValueStr = RandomStringUtils.randomAlphabetic(10); String str = constructGson(triple.getMiddle(), attrValueStr); HttpTester request = new HttpTester(); request.setMethod("POST"); request.setHeader("Host", "tester"); request.setContent(str); request.setHeader("Content-Type", "application/json"); request.setURI("/config"); HttpTester response = new HttpTester(); //response = response.parse(tester.getResponses(request.generate())); response.parse(tester.getResponses(request.generate())); assertEquals("Values do not match", server.getAttribute(name, triple.getLeft()).toString(), attrValueStr); } }
From source file:com.magnet.mmx.server.plugin.mmxmgmt.util.MMXConfigurationTest.java
/** * Set the Configuration property via JMX and check whether the REST interface returns the same value * * @throws Exception/*from w w w . ja va2 s . c o m*/ */ //TODO: Use the web target JAXRS API to execute these request possibly ? @Ignore @Test public void testSetMBeanLocalGetREST() throws Exception { ObjectName name = new ObjectName(MMX_MBEAN_OBJECT_NAME); ServletTester tester = new ServletTester(); tester.addServlet(LaxConfigServlet.class, "/config"); tester.start(); for (Triple<String, String, String> triple : mbeanAttributes) { String attrName = triple.getLeft(); String attrType = triple.getRight(); Object attrValue; if (attrType.equals("int")) { attrValue = RandomUtils.nextInt(30000, 65535); } else if (attrType.equals("long")) { attrValue = RandomUtils.nextLong(10, 1000); } else { attrValue = RandomStringUtils.randomAlphabetic(10); } Attribute attr1 = new Attribute(attrName, attrValue); server.setAttribute(name, attr1); Object attr2 = server.getAttribute(name, attrName); assertEquals("Attribute values do not match", attrValue, attr2); HttpTester request = new HttpTester(); // HttpTester.Request request = HttpTester.newRequest(); request.setMethod("GET"); request.setHeader("Host", "tester"); request.setURI("/config"); request.setContent(""); HttpTester response = new HttpTester(); response.parse(tester.getResponses(request.generate())); JsonElement jelement = new JsonParser().parse(response.getContent()); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("configs"); String attrValueRest = jobject.get(triple.getMiddle()).getAsString(); if (attrType.equals("int")) assertEquals("Values do not match", attrValue, Integer.parseInt(attrValueRest)); else if (attrType.equals("long")) assertEquals("Values do not match", attrValue, Long.parseLong(attrValueRest)); else assertEquals("Values do not match", attrValue, attrValueRest); } }
From source file:co.rsk.peg.RepositoryBlockStoreTest.java
@Test public void test() throws Exception { // This Is how I produced RepositoryBlockStore_data.ser. I had a bitcoind in regtest with 613 blocks + genesis block // NetworkParameters params = RegTestParams.get(); // Context context = new Context(params); // Wallet wallet = new Wallet(context); // BlockStore store = new SPVBlockStore(params, new File("spvBlockstore")); // AbstractBlockChain chain = new BlockChain(context, wallet, store); // PeerGroup peerGroup = new PeerGroup(context, chain); // peerGroup.start(); // final DownloadProgressTracker listener = new DownloadProgressTracker(); // peerGroup.startBlockChainDownload(listener); // listener.await(); // peerGroup.stop(); // StoredBlock storedBlock = chain.getChainHead(); // FileOutputStream fos = new FileOutputStream("RepositoryBlockStore_data.ser"); // ObjectOutputStream oos = new ObjectOutputStream(fos); // for (int i = 0; i < 614; i++) { // Triple<byte[], BigInteger , Integer> tripleStoredBlock = new ImmutableTriple<>(storedBlock.getHeader().bitcoinSerialize(), storedBlock.getChainWork(), storedBlock.getHeight()); // oos.writeObject(tripleStoredBlock); // storedBlock = store.get(storedBlock.getHeader().getPrevBlockHash()); // }/*w w w .j a va 2s . co m*/ // oos.close(); // Read original store InputStream fileInputStream = ClassLoader.getSystemResourceAsStream("peg/RepositoryBlockStore_data.ser"); ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream); Repository repository = new RepositoryImplForTesting(); RepositoryBlockStore store = new RepositoryBlockStore(repository, PrecompiledContracts.BRIDGE_ADDR); for (int i = 0; i < 614; i++) { Triple<byte[], BigInteger, Integer> tripleStoredBlock = (Triple<byte[], BigInteger, Integer>) objectInputStream .readObject(); BtcBlock header = RegTestParams.get().getDefaultSerializer().makeBlock(tripleStoredBlock.getLeft()); StoredBlock storedBlock = new StoredBlock(header, tripleStoredBlock.getMiddle(), tripleStoredBlock.getRight()); if (i == 0) { store.setChainHead(storedBlock); } store.put(storedBlock); } // Create a new instance of the store RepositoryBlockStore store2 = new RepositoryBlockStore(repository, PrecompiledContracts.BRIDGE_ADDR); // Check a specific block that used to fail when we had a bug assertEquals(store.get(Sha256Hash.wrap("373941fe83961cf70e181e468abc5f9f7cc440c711c3d06948fa66f3912ed27a")), store2.get(Sha256Hash.wrap("373941fe83961cf70e181e468abc5f9f7cc440c711c3d06948fa66f3912ed27a"))); //Check new instance content is identical to the original one StoredBlock storedBlock = store.getChainHead(); StoredBlock storedBlock2 = store2.getChainHead(); int headHeight = storedBlock.getHeight(); for (int i = 0; i < headHeight; i++) { assertNotNull(storedBlock); assertEquals(storedBlock, storedBlock2); Sha256Hash prevBlockHash = storedBlock.getHeader().getPrevBlockHash(); storedBlock = store.get(prevBlockHash); storedBlock2 = store2.get(prevBlockHash); } }