List of usage examples for org.apache.commons.lang3.tuple Triple getMiddle
public abstract M getMiddle();
Gets the middle element from this triple.
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);/*from ww w. j a va 2 s.com*/ 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: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 .j a va 2s. c o m 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.drisoftie.action.async.AsyncAction.java
@Override public void registerAction(List<ActionBinding<ViewT>> bindings) { ClassLoader cl = this.getClass().getClassLoader(); for (ActionBinding<ViewT> binding : bindings) { Class<?>[] actions = new Class<?>[binding.registrations.size()]; for (int i = 0; i < actions.length; i++) { actions[i] = binding.registrations.get(i).getLeft(); }//from ww w .ja v a2 s . c o m binding.actionHandler = Proxy.newProxyInstance(cl, actions, this); } for (ActionBinding<ViewT> actionBinding : bindings) { if (actionBinding.view != null) { for (Triple<Class<?>, String, String[]> reg : actionBinding.registrations) { if (StringUtils.isNotEmpty(reg.getMiddle())) { try { Method regMethod = actionBinding.view.getClass().getMethod(reg.getMiddle(), reg.getLeft()); if (regMethod != null) { regMethod.invoke(actionBinding.view, actionBinding.actionHandler); } } catch (NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) { // do nothing if binding fails if (BuildConfig.DEBUG) { Log.v(getClass().getSimpleName(), e.getClass().getName() + " for callback" + reg.getLeft().getName()); } } } } } } this.bindings = bindings; }
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 *///from ww w . j av a 2 s . co m default R apply(@Nonnull Triple<T, U, V> tuple) { Objects.requireNonNull(tuple); return apply(tuple.getLeft(), tuple.getMiddle(), tuple.getRight()); }
From source file:com.netflix.genie.agent.execution.statemachine.StateMachineAutoConfiguration.java
private void configureTransitions(final StateMachineBuilder.Builder<States, Events> builder, final Collection<Triple<States, Events, States>> eventDrivenTransitions, final Collection<States> statesWithErrorTransition) throws Exception { final StateMachineTransitionConfigurer<States, Events> transitionConfigurer = builder .configureTransitions();/*from w w w . j a v a2 s . c o m*/ // Set up event-driven transitions for (Triple<States, Events, States> transition : eventDrivenTransitions) { final States sourceState = transition.getLeft(); final States targetState = transition.getRight(); final Events event = transition.getMiddle(); transitionConfigurer.withExternal().source(sourceState).target(targetState).event(event).and(); log.info("Configured event-driven transition: ({}) -> [{}] -> ({})", sourceState, event, targetState); } // Set up transitions to HANDLE_ERROR state. for (States state : statesWithErrorTransition) { transitionConfigurer.withExternal().source(state).target(States.HANDLE_ERROR).event(Events.ERROR).and(); log.info("Configured error transition: ({}) -> ({})", state, States.HANDLE_ERROR); } // Add transition from HANDLE_ERROR to END transitionConfigurer.withExternal().source(States.HANDLE_ERROR).target(States.END) .event(Events.HANDLE_ERROR_COMPLETE); }
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()); // }/*from w ww . j a v a 2 s . 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); } }
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); }// www .j ava 2 s . c o m } } } } }); } return ret.get(); }
From source file:at.gridtec.lambda4j.consumer.tri.ThrowableTriConsumer.java
/** * Applies this consumer to the given tuple. * * @param tuple The tuple to be applied to the consumer * @throws NullPointerException If given argument is {@code null} * @throws X Any throwable from this consumers action * @see org.apache.commons.lang3.tuple.Triple *///from w w w . j a v a 2s. c o m default void acceptThrows(@Nonnull Triple<T, U, V> tuple) throws X { Objects.requireNonNull(tuple); acceptThrows(tuple.getLeft(), tuple.getMiddle(), tuple.getRight()); }
From source file:com.quartercode.jtimber.rh.agent.asm.InsertJAXBTweaksClassAdapter.java
private void generateAfterUnmarshalMethod(Method method) { GeneratorAdapter mg = new GeneratorAdapter(ACC_PUBLIC, method, null, null, cv); /*//from w ww. j av a 2 s .c o m * Iterate through all fields annotated with "SubstituteWithWrapper" and replace their current value with their current value wrapped inside a wrapper. * This section first reads the current field value, then creates a new wrapper which wraps around that field value, and finally sets the field to the wrapper. */ for (Triple<String, Type, Type> field : fieldsForWrapperSubstitution) { String fieldName = field.getLeft(); Type fieldType = fields.get(fieldName); Type wrapperType = field.getMiddle(); // Null means "default"; in that case, the field type is used as the type of the first argument of the wrapper constructor Type wrapperConstructorArgType = field.getRight() == null ? fieldType : field.getRight(); // Note that this reference will be used for the PUTFIELD instruction later on mg.loadThis(); // ----- Stack: [this] // Creates the wrapper using the current field value { // Create a new instance of the wrapper type and duplicate it for the constructor call later on mg.newInstance(wrapperType); mg.dup(); // ----- Stack: [this, wrapper, wrapper] // Retrieve the current field value ASMUtils.generateGetField(mg, classType, fieldName, fieldType); // ----- Stack: [this, wrapper, wrapper, fieldValue] // Call the constructor of the new wrapper using the current field value as the first argument mg.invokeConstructor(wrapperType, Method.getMethod("void <init> (" + wrapperConstructorArgType.getClassName() + ")")); // ----- Stack: [this, wrapper] } // Store the new wrapper in the field the value has been retrieved from before // The substitution is complete mg.putField(classType, fieldName, fieldType); // ----- Stack: [] } /* * Iterate through all fields. * For each field, call the addParent() method with "this" as parent if the current field value is parent-aware */ for (Entry<String, Type> field : fields.entrySet()) { String fieldName = field.getKey(); Type fieldType = field.getValue(); ASMUtils.generateGetField(mg, classType, fieldName, fieldType); // ----- Stack: [fieldValue] ASMUtils.generateAddOrRemoveThisAsParent(mg, "addParent"); } // End the method mg.returnValue(); mg.endMethod(); }
From source file:alfio.controller.TicketController.java
private Ticket internalSendTicketByEmail(HttpServletRequest request, Triple<Event, TicketReservation, Ticket> data) throws IOException { Ticket ticket = data.getRight();/* ww w. ja va 2 s . co m*/ Event event = data.getLeft(); Locale locale = LocaleUtil.getTicketLanguage(ticket, request); TicketReservation reservation = data.getMiddle(); Organization organization = organizationRepository.getById(event.getOrganizationId()); TicketCategory category = ticketCategoryRepository.getById(ticket.getCategoryId()); notificationManager.sendTicketByEmail(ticket, event, locale, TemplateProcessor.buildPartialEmail(event, organization, reservation, category, templateManager, ticketReservationManager.ticketUpdateUrl(event, ticket.getUuid()), request), reservation, ticketCategoryRepository.getByIdAndActive(ticket.getCategoryId(), event.getId())); return ticket; }