List of usage examples for org.apache.commons.lang3.tuple Triple getLeft
public abstract L getLeft();
Gets the left element from this triple.
From source file:com.quancheng.saluki.gateway.zuul.filter.LimitAccessFilter.java
@Override public Object run() { RequestContext ctx = RequestContext.getCurrentContext(); HttpServletRequest request = ctx.getRequest(); String auth = request.getHeader("Authorization"); String accessToken = auth.split(" ")[1]; ctx.set("LimitAccess", Boolean.TRUE); try {/*from w w w . j a va 2 s . co m*/ Triple<Long, String, Long> clientTriple = databaseUserDetailService.loadClientByToken(accessToken); String user = clientTriple.getMiddle(); Long intervalInMills = clientTriple.getLeft(); Long limits = clientTriple.getRight(); if (intervalInMills != null && intervalInMills != 0l && limits != null && limits != 0l) { if (!access(user, intervalInMills, limits)) { ctx.set("LimitAccess", Boolean.FALSE); ctx.setSendZuulResponse(false); ctx.setResponseStatusCode(HttpServletResponse.SC_BAD_REQUEST); ctx.setResponseBody("The times of usage is limited"); } } } catch (Throwable e) { } return null; }
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 a 2 s.com*/ // 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:alfio.controller.api.support.TicketHelper.java
private Triple<ValidationResult, Event, Ticket> assignTicket(UpdateTicketOwnerForm updateTicketOwner, Optional<Errors> bindingResult, HttpServletRequest request, Optional<UserDetails> userDetails, Triple<Event, TicketReservation, Ticket> result) { Ticket t = result.getRight();/* w ww . ja v a 2 s . c o m*/ final Event event = result.getLeft(); if (t.getLockedAssignment()) { //in case of locked assignment, fullName and Email will be overwritten updateTicketOwner.setFirstName(t.getFirstName()); updateTicketOwner.setLastName(t.getLastName()); updateTicketOwner.setFullName(t.getFullName()); updateTicketOwner.setEmail(t.getEmail()); } final TicketReservation ticketReservation = result.getMiddle(); List<TicketFieldConfiguration> fieldConf = ticketFieldRepository .findAdditionalFieldsForEvent(event.getId()); ValidationResult validationResult = Validator .validateTicketAssignment(updateTicketOwner, fieldConf, bindingResult, event) .ifSuccess(() -> updateTicketOwner(updateTicketOwner, request, t, event, ticketReservation, userDetails)); return Triple.of(validationResult, event, ticketRepository.findByUUID(t.getUuid())); }
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; }/* ww w .j av a2 s.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: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 w w. ja va 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:de.ellpeck.actuallyadditions.mod.blocks.BlockGreenhouseGlass.java
@Override public void updateTick(World world, BlockPos pos, IBlockState state, Random rand) { if (world.isRemote) return;/*from w ww . jav a 2s . co m*/ if (world.canBlockSeeSky(pos) && world.isDaytime()) { Triple<BlockPos, IBlockState, IGrowable> trip = firstBlock(world, pos); boolean once = false; if (trip != null) for (int i = 0; i < 3; i++) { IBlockState growState = i == 0 ? trip.getMiddle() : world.getBlockState(trip.getLeft()); if (growState.getBlock() == trip.getRight() && trip.getRight().canGrow(world, trip.getLeft(), growState, false)) { trip.getRight().grow(world, rand, trip.getLeft(), growState); once = true; } } if (once) world.playEvent(2005, trip.getMiddle().isOpaqueCube() ? trip.getLeft().up() : trip.getLeft(), 0); } }
From source file:alfio.controller.TicketController.java
@RequestMapping(value = "/event/{eventName}/ticket/{ticketIdentifier}/code.png", method = RequestMethod.GET) public void generateTicketCode(@PathVariable("eventName") String eventName, @PathVariable("ticketIdentifier") String ticketIdentifier, HttpServletResponse response) throws IOException, WriterException { Optional<Triple<Event, TicketReservation, Ticket>> oData = ticketReservationManager .fetchCompleteAndAssigned(eventName, ticketIdentifier); if (!oData.isPresent()) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return;//from ww w. ja v a2 s . co m } Triple<Event, TicketReservation, Ticket> data = oData.get(); Event event = data.getLeft(); Ticket ticket = data.getRight(); String qrCodeText = ticket.ticketCode(event.getPrivateKey()); response.setContentType("image/png"); response.getOutputStream().write(ImageUtil.createQRCode(qrCodeText)); }
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: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 w ww . j a v a2 s.c o 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:alfio.controller.TicketController.java
private Ticket internalSendTicketByEmail(HttpServletRequest request, Triple<Event, TicketReservation, Ticket> data) throws IOException { Ticket ticket = data.getRight();//from w w w . j a 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; }