List of usage examples for org.apache.commons.lang3.tuple Pair getKey
@Override public final L getKey()
Gets the key from this pair.
This method implements the Map.Entry interface returning the left element as the key.
From source file:net.minecraftforge.items.VanillaInventoryCodeHooks.java
/** * Copied from BlockDropper#dispense and added capability support */// w w w.j a va2 s .c o m public static boolean dropperInsertHook(World world, BlockPos pos, TileEntityDispenser dropper, int slot, @Nonnull ItemStack stack) { EnumFacing enumfacing = world.getBlockState(pos).getValue(BlockDropper.FACING); BlockPos blockpos = pos.offset(enumfacing); Pair<IItemHandler, Object> destinationResult = getItemHandler(world, (double) blockpos.getX(), (double) blockpos.getY(), (double) blockpos.getZ(), enumfacing.getOpposite()); if (destinationResult == null) { return true; } else { IItemHandler itemHandler = destinationResult.getKey(); Object destination = destinationResult.getValue(); ItemStack dispensedStack = stack.copy().splitStack(1); ItemStack remainder = putStackInInventoryAllSlots(dropper, destination, itemHandler, dispensedStack); if (remainder.isEmpty()) { remainder = stack.copy(); remainder.shrink(1); } else { remainder = stack.copy(); } dropper.setInventorySlotContents(slot, remainder); return false; } }
From source file:com.helion3.prism.api.query.QueryBuilder.java
/** * Builds a {@link Query} by parsing an array of arguments. * * @param parameters String[] Parameter:value list * @return {@link Query} Database query object *///from ww w. j a v a 2 s . c om public static CompletableFuture<Query> fromArguments(QuerySession session, @Nullable String[] arguments) throws ParameterException { checkNotNull(session); Query query = new Query(); CompletableFuture<Query> future = new CompletableFuture<Query>(); // Track all parameter pairs Map<String, String> definedParameters = new HashMap<String, String>(); if (arguments.length > 0) { List<ListenableFuture<?>> futures = new ArrayList<ListenableFuture<?>>(); for (String arg : arguments) { Optional<ListenableFuture<?>> listenable; if (flagPattern.matcher(arg).matches()) { listenable = parseFlagFromArgument(session, query, arg); } else { // Get alias/value pair Pair<String, String> pair = getParameterKeyValue(arg); // Parse for handler listenable = parseParameterFromArgument(session, query, pair); // Add to list of defined definedParameters.put(pair.getKey(), pair.getValue()); } if (listenable.isPresent()) { futures.add(listenable.get()); } } if (!futures.isEmpty()) { ListenableFuture<List<Object>> combinedFuture = Futures.allAsList(futures); combinedFuture.addListener(new Runnable() { @Override public void run() { future.complete(query); } }, MoreExecutors.sameThreadExecutor()); } else { future.complete(query); } } else { future.complete(query); } if (Prism.getConfig().getNode("defaults", "enabled").getBoolean()) { // Require any parameter defaults String defaultsUsed = ""; for (ParameterHandler handler : Prism.getParameterHandlers()) { boolean aliasFound = false; for (String alias : handler.getAliases()) { if (definedParameters.containsKey(alias)) { aliasFound = true; break; } } if (!aliasFound) { Optional<Pair<String, String>> pair = handler.processDefault(session, query); if (pair.isPresent()) { defaultsUsed += pair.get().getKey() + ":" + pair.get().getValue() + " "; } } } // @todo should move this if (!defaultsUsed.isEmpty()) { session.getCommandSource().get().sendMessage( Format.subduedHeading(Text.of(String.format("Defaults used: %s", defaultsUsed)))); } } return future; }
From source file:blusunrize.immersiveengineering.client.render.TileRenderAutoWorkbench.java
public static BlueprintLines getBlueprintDrawable(ItemStack stack, World world) { if (stack.isEmpty()) return null; EntityPlayer player = ClientUtils.mc().player; ArrayList<BufferedImage> images = new ArrayList<>(); try {/*from w ww.j av a 2 s .com*/ IBakedModel ibakedmodel = ClientUtils.mc().getRenderItem().getItemModelWithOverrides(stack, world, player); HashSet<String> textures = new HashSet(); Collection<BakedQuad> quads = ibakedmodel.getQuads(null, null, 0); for (BakedQuad quad : quads) if (quad != null && quad.getSprite() != null) textures.add(quad.getSprite().getIconName()); for (String s : textures) { ResourceLocation rl = new ResourceLocation(s); rl = new ResourceLocation(rl.getNamespace(), String.format("%s/%s%s", "textures", rl.getPath(), ".png")); IResource resource = ClientUtils.mc().getResourceManager().getResource(rl); BufferedImage bufferedImage = TextureUtil.readBufferedImage(resource.getInputStream()); if (bufferedImage != null) images.add(bufferedImage); } } catch (Exception e) { } if (images.isEmpty()) return null; ArrayList<Pair<TexturePoint, TexturePoint>> lines = new ArrayList(); HashSet testSet = new HashSet(); HashMultimap<Integer, TexturePoint> area = HashMultimap.create(); int wMax = 0; for (BufferedImage bufferedImage : images) { Set<Pair<TexturePoint, TexturePoint>> temp_lines = new HashSet<>(); int w = bufferedImage.getWidth(); int h = bufferedImage.getHeight(); if (h > w) h = w; if (w > wMax) wMax = w; for (int hh = 0; hh < h; hh++) for (int ww = 0; ww < w; ww++) { int argb = bufferedImage.getRGB(ww, hh); float r = (argb >> 16 & 255) / 255f; float g = (argb >> 8 & 255) / 255f; float b = (argb & 255) / 255f; float intesity = (r + b + g) / 3f; int alpha = (argb >> 24) & 255; if (alpha > 0) { boolean added = false; //Check colour sets for similar colour to shade it later TexturePoint tp = new TexturePoint(ww, hh, w); if (!testSet.contains(tp)) { for (Integer key : area.keySet()) { for (TexturePoint p : area.get(key)) { float mod = w / (float) p.scale; int pColour = bufferedImage.getRGB((int) (p.x * mod), (int) (p.y * mod)); float dR = (r - (pColour >> 16 & 255) / 255f); float dG = (g - (pColour >> 8 & 255) / 255f); float dB = (b - (pColour & 255) / 255f); double delta = Math.sqrt(dR * dR + dG * dG + dB * dB); if (delta < .25) { area.put(key, tp); added = true; break; } } if (added) break; } if (!added) area.put(argb, tp); testSet.add(tp); } //Compare to direct neighbour for (int i = 0; i < 4; i++) { int xx = (i == 0 ? -1 : i == 1 ? 1 : 0); int yy = (i == 2 ? -1 : i == 3 ? 1 : 0); int u = ww + xx; int v = hh + yy; int neighbour = 0; float delta = 1; boolean notTransparent = false; if (u >= 0 && u < w && v >= 0 && v < h) { neighbour = bufferedImage.getRGB(u, v); notTransparent = ((neighbour >> 24) & 255) > 0; if (notTransparent) { float neighbourIntesity = ((neighbour >> 16 & 255) + (neighbour >> 8 & 255) + (neighbour & 255)) / 765f; float intesityDelta = Math.max(0, Math.min(1, Math.abs(intesity - neighbourIntesity))); float rDelta = Math.max(0, Math.min(1, Math.abs(r - (neighbour >> 16 & 255) / 255f))); float gDelta = Math.max(0, Math.min(1, Math.abs(g - (neighbour >> 8 & 255) / 255f))); float bDelta = Math.max(0, Math.min(1, Math.abs(b - (neighbour & 255) / 255f))); delta = Math.max(intesityDelta, Math.max(rDelta, Math.max(gDelta, bDelta))); delta = delta < .25 ? 0 : delta > .4 ? 1 : delta; } } if (delta > 0) { Pair<TexturePoint, TexturePoint> l = Pair.of( new TexturePoint(ww + (i == 0 ? 0 : i == 1 ? 1 : 0), hh + (i == 2 ? 0 : i == 3 ? 1 : 0), w), new TexturePoint(ww + (i == 0 ? 0 : i == 1 ? 1 : 1), hh + (i == 2 ? 0 : i == 3 ? 1 : 1), w)); temp_lines.add(l); } } } } lines.addAll(temp_lines); } ArrayList<Integer> lumiSort = new ArrayList<>(area.keySet()); Collections.sort(lumiSort, (rgb1, rgb2) -> Double.compare(getLuminance(rgb1), getLuminance(rgb2))); HashMultimap<ShadeStyle, Point> complete_areaMap = HashMultimap.create(); int lineNumber = 2; int lineStyle = 0; for (Integer i : lumiSort) { complete_areaMap.putAll(new ShadeStyle(lineNumber, lineStyle), area.get(i)); ++lineStyle; lineStyle %= 3; if (lineStyle == 0) lineNumber += 1; } Set<Pair<Point, Point>> complete_lines = new HashSet<>(); for (Pair<TexturePoint, TexturePoint> line : lines) { TexturePoint p1 = line.getKey(); TexturePoint p2 = line.getValue(); complete_lines.add(Pair.of( new Point((int) (p1.x / (float) p1.scale * wMax), (int) (p1.y / (float) p1.scale * wMax)), new Point((int) (p2.x / (float) p2.scale * wMax), (int) (p2.y / (float) p2.scale * wMax)))); } return new BlueprintLines(wMax, complete_lines, complete_areaMap); }
From source file:com.evolveum.midpoint.schema.util.WfContextUtil.java
@NotNull public static List<TriggerType> createTriggers(int escalationLevel, Date workItemCreateTime, Date workItemDeadline, List<WorkItemTimedActionsType> timedActionsList, PrismContext prismContext, Trace logger, @Nullable String workItemId, @NotNull String handlerUri) throws SchemaException { List<TriggerType> triggers = new ArrayList<>(); for (WorkItemTimedActionsType timedActionsEntry : timedActionsList) { Integer levelFrom;// ww w. ja v a 2s . c o m Integer levelTo; if (timedActionsEntry.getEscalationLevelFrom() == null && timedActionsEntry.getEscalationLevelTo() == null) { levelFrom = levelTo = 0; } else { levelFrom = timedActionsEntry.getEscalationLevelFrom(); levelTo = timedActionsEntry.getEscalationLevelTo(); } if (levelFrom != null && escalationLevel < levelFrom) { logger.trace("Current escalation level is before 'escalationFrom', skipping timed actions {}", timedActionsEntry); continue; } if (levelTo != null && escalationLevel > levelTo) { logger.trace("Current escalation level is after 'escalationTo', skipping timed actions {}", timedActionsEntry); continue; } // TODO evaluate the condition List<TimedActionTimeSpecificationType> timeSpecifications = CloneUtil .cloneCollectionMembers(timedActionsEntry.getTime()); if (timeSpecifications.isEmpty()) { timeSpecifications.add(new TimedActionTimeSpecificationType()); } for (TimedActionTimeSpecificationType timeSpec : timeSpecifications) { if (timeSpec.getValue().isEmpty()) { timeSpec.getValue().add(XmlTypeConverter.createDuration(0)); } for (Duration duration : timeSpec.getValue()) { XMLGregorianCalendar mainTriggerTime = computeTriggerTime(duration, timeSpec.getBase(), workItemCreateTime, workItemDeadline); TriggerType mainTrigger = createTrigger(mainTriggerTime, timedActionsEntry.getActions(), null, prismContext, workItemId, handlerUri); triggers.add(mainTrigger); List<Pair<Duration, AbstractWorkItemActionType>> notifyInfoList = getNotifyBefore( timedActionsEntry); for (Pair<Duration, AbstractWorkItemActionType> notifyInfo : notifyInfoList) { XMLGregorianCalendar notifyTime = (XMLGregorianCalendar) mainTriggerTime.clone(); notifyTime.add(notifyInfo.getKey().negate()); TriggerType notifyTrigger = createTrigger(notifyTime, null, notifyInfo, prismContext, workItemId, handlerUri); triggers.add(notifyTrigger); } } } } return triggers; }
From source file:flens.filter.RenameFilter.java
public Collection<Record> process(Record in) { Map vals = in.getValues();//ww w . ja v a 2s . c o m for (Pair ren : this.names) { Object val = vals.remove(ren.getKey()); if (val != null) { if (!((String) ren.getRight()).isEmpty()) vals.put(ren.getRight(), val); if (ren.getRight().equals(Constants.TIME)) { vals.put(Constants.TIME, in.getTimestamp()); } } } tag(in); return Collections.EMPTY_LIST; }
From source file:com.vmware.photon.controller.common.dcp.ServiceHostUtils.java
public static void waitForNodeGroupConvergence(ServiceHost localHost, Collection<Pair<String, Integer>> remoteHostIpAndPortPairs, String nodeGroupPath, int maxRetries, int retryInterval) throws Throwable { checkArgument(localHost != null, "localHost cannot be null"); checkArgument(remoteHostIpAndPortPairs != null, "remoteHostIpAndPortPairs cannot be null"); checkArgument(!Strings.isNullOrEmpty(nodeGroupPath), "nodeGroupPath cannot be null or empty"); checkArgument(maxRetries > 0, "maxRetries must be > 0"); if (remoteHostIpAndPortPairs.size() == 1) { // nothing to synchronize if we only have one host return;/*from w w w .ja v a 2 s.c o m*/ } for (Pair<String, Integer> remoteHostIpAndPortPair : remoteHostIpAndPortPairs) { int checkRetries = maxRetries; int checksToConvergence = REQUIRED_STABLE_STATE_COUNT; while (checkRetries > 0 && checksToConvergence > 0) { // update retry count and sleep checkRetries--; Thread.sleep(retryInterval * checksToConvergence); // check the host response NodeGroupService.NodeGroupState response = getNodeGroupState(localHost, remoteHostIpAndPortPair.getKey(), remoteHostIpAndPortPair.getValue(), nodeGroupPath); if (response.nodes.size() < remoteHostIpAndPortPairs.size()) { continue; } // check host status checksToConvergence--; for (NodeState nodeState : response.nodes.values()) { if (nodeState.status != NodeState.NodeStatus.AVAILABLE) { checksToConvergence = REQUIRED_STABLE_STATE_COUNT; break; // Note that we are not breaking from the above while loop where checksToConvergence is done // This is because the nodes might switch between AVAILABLE and SYNCHRONIZING as the other nodes join } } } if (checkRetries == 0) { throw new TimeoutException("nodes did not converge"); } } }
From source file:com.galenframework.speclang2.specs.SpecComponentProcessor.java
private Map<String, Object> processArguments(List<Pair<String, String>> unprocessedArguments) { Map<String, Object> arguments = new HashMap<>(); for (Pair<String, String> textArgument : unprocessedArguments) { arguments.put(textArgument.getKey(), processArgumentValue(textArgument.getValue())); }//from w ww .j av a 2s. c om return arguments; }
From source file:lineage2.gameserver.network.clientpackets.ConfirmDlg.java
/** * Method runImpl./*from w w w . j av a 2 s .c om*/ */ @Override protected void runImpl() { Player activeChar = getClient().getActiveChar(); if (activeChar == null) { return; } Pair<Integer, OnAnswerListener> entry = activeChar.getAskListener(true); if ((entry == null) || (entry.getKey() != _requestId)) { return; } OnAnswerListener listener = entry.getValue(); if (_answer == 1) { listener.sayYes(); } else { listener.sayNo(); } }
From source file:com.microsoft.tooling.msservices.serviceexplorer.azure.vm.VMServiceModule.java
@Override protected void refresh(@NotNull EventStateHandle eventState) throws AzureCmdException { // remove all child nodes removeAllChildNodes();//ww w. j a va2s. c o m AzureManager azureManager = AzureManagerImpl.getManager(getProject()); // load all VMs List<Subscription> subscriptionList = azureManager.getSubscriptionList(); List<Pair<String, String>> failedSubscriptions = new ArrayList<>(); for (Subscription subscription : subscriptionList) { try { List<VirtualMachine> virtualMachines = azureManager.getVirtualMachines(subscription.getId()); for (VirtualMachine vm : virtualMachines) { addChildNode(new VMNode(this, vm)); } if (eventState.isEventTriggered()) { return; } } catch (Exception ex) { failedSubscriptions.add(new ImmutablePair<>(subscription.getName(), ex.getMessage())); continue; } } if (!failedSubscriptions.isEmpty()) { StringBuilder errorMessage = new StringBuilder( "An error occurred when trying to load VMs for the subscriptions:\n\n"); for (Pair error : failedSubscriptions) { errorMessage.append(error.getKey()).append(": ").append(error.getValue()).append("\n"); } DefaultLoader.getUIHelper() .logError("An error occurred when trying to load VMs\n\n" + errorMessage.toString(), null); } }
From source file:gndata.app.ui.util.converter.JenaPropertyClassStringConverter.java
@Override public String toString(Pair<ObjectProperty, OntClass> pcPair) { return pcPair == null ? null : pcPair.getValue().getLocalName() + " (link by " + pcPair.getKey().getLocalName() + ")"; }