List of usage examples for com.google.common.collect ImmutableSet contains
boolean contains(Object o);
From source file:com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodecProcessor.java
private String findGetterForClass(VariableElement parameter, TypeElement type) { List<ExecutableElement> methods = ElementFilter.methodsIn(env.getElementUtils().getAllMembers(type)); ImmutableSet.Builder<String> possibleGetterNamesBuilder = ImmutableSet.<String>builder() .add(parameter.getSimpleName().toString()); if (parameter.asType().getKind() == TypeKind.BOOLEAN) { possibleGetterNamesBuilder.add(addCamelCasePrefix(parameter.getSimpleName().toString(), "is")); } else {/*www. j a v a 2 s. c o m*/ possibleGetterNamesBuilder.add(addCamelCasePrefix(parameter.getSimpleName().toString(), "get")); } ImmutableSet<String> possibleGetterNames = possibleGetterNamesBuilder.build(); for (ExecutableElement element : methods) { if (!element.getModifiers().contains(Modifier.STATIC) && !element.getModifiers().contains(Modifier.PRIVATE) && possibleGetterNames.contains(element.getSimpleName().toString()) && findRelationWithGenerics(parameter.asType(), element.getReturnType()) != Relation.UNRELATED_TO) { return element.getSimpleName().toString(); } } throw new IllegalArgumentException(type + ": No getter found corresponding to parameter " + parameter.getSimpleName() + ", " + parameter.asType()); }
From source file:vazkii.quark.vanity.feature.PanoramaMaker.java
@SubscribeEvent public void loadMainMenu(GuiOpenEvent event) { if (overrideMainMenu && !overridenOnce && event.getGui() instanceof GuiMainMenu) { File mcDir = ModuleLoader.configFile.getParentFile().getParentFile(); File panoramasDir = new File(mcDir, "/screenshots/panoramas"); List<File[]> validFiles = new ArrayList(); ImmutableSet<String> set = ImmutableSet.of("panorama_0.png", "panorama_1.png", "panorama_2.png", "panorama_3.png", "panorama_4.png", "panorama_5.png"); if (panoramasDir.exists()) { File[] subDirs;// w ww . jav a 2s . c o m File mainMenu = new File(panoramasDir, "main_menu"); if (mainMenu.exists()) subDirs = new File[] { mainMenu }; else subDirs = panoramasDir.listFiles((File f) -> f.isDirectory()); for (File f : subDirs) if (set.stream().allMatch((String s) -> new File(f, s).exists())) validFiles.add(f.listFiles((File f1) -> set.contains(f1.getName()))); } if (!validFiles.isEmpty()) { File[] files = validFiles.get(new Random().nextInt(validFiles.size())); Arrays.sort(files); Minecraft mc = Minecraft.getMinecraft(); ResourceLocation[] resources = new ResourceLocation[6]; for (int i = 0; i < resources.length; i++) { File f = files[i]; try { DynamicTexture tex = new DynamicTexture(ImageIO.read(f)); String name = "quark:" + f.getName(); resources[i] = mc.getTextureManager().getDynamicTextureLocation(name, tex); } catch (IOException e) { e.printStackTrace(); return; } } try { Field field = ReflectionHelper.findField(GuiMainMenu.class, LibObfuscation.TITLE_PANORAMA_PATHS); field.setAccessible(true); if (Modifier.isFinal(field.getModifiers())) { Field modfield = Field.class.getDeclaredField("modifiers"); modfield.setAccessible(true); modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL); } field.set(null, resources); } catch (Exception e) { e.printStackTrace(); } } overridenOnce = true; } }
From source file:com.example.appengine.Oauth2Filter.java
@Override public void doFilter(final ServletRequest servletReq, final ServletResponse servletResp, final FilterChain chain) throws IOException, ServletException { final String scope = "https://www.googleapis.com/auth/userinfo.email"; ImmutableSet<String> allowedClients = new ImmutableSet.Builder<String>() .add("407408718192.apps.googleusercontent.com") .add("755878275993-j4k7emq6rlupctce1c28enpcrr50vfo1.apps.googleusercontent.com").build(); HttpServletResponse resp = (HttpServletResponse) servletResp; OAuthService oauth = OAuthServiceFactory.getOAuthService(); // Only check Oauth2 when in production, skip if run in development. SystemProperty.Environment.Value env = SystemProperty.environment.value(); if (env == SystemProperty.Environment.Value.Production) { // APIs only work in Production try {/*from www .j a v a2 s .co m*/ String tokenAudience = oauth.getClientId(scope); // The line below is commented out for privacy. // context.log("tokenAudience: " + tokenAudience); // Account we match if (!allowedClients.contains(tokenAudience)) { throw new OAuthRequestException( "audience of token '" + tokenAudience + "' is not in allowed list " + allowedClients); } } catch (OAuthRequestException ex) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); // Not allowed return; } catch (OAuthServiceFailureException ex) { resp.sendError(HttpServletResponse.SC_NOT_FOUND); // some failure - reject context.log("oauth2 failure", ex); return; } } chain.doFilter(servletReq, servletResp); // continue processing }
From source file:dagger.internal.codegen.SubcomponentFactoryMethodValidation.java
private ImmutableSet<TypeElement> findMissingModules(ChildFactoryMethodEdge edge, BindingGraph graph) { ImmutableSet<TypeElement> factoryMethodParameters = subgraphFactoryMethodParameters(edge, graph); ComponentNode child = (ComponentNode) graph.incidentNodes(edge).target(); SetView<TypeElement> modulesOwnedByChild = ownedModules(child, graph); return graph.bindingNodes().stream() // bindings owned by child .filter(node -> node.componentPath().equals(child.componentPath())) // that require a module instance .filter(node -> node.binding() instanceof ContributionBinding && ((ContributionBinding) node.binding()).requiresModuleInstance()) .map(node -> node.binding().contributingModule().get()).distinct() // module owned by child .filter(module -> modulesOwnedByChild.contains(module)) // module not in the method parameters .filter(module -> !factoryMethodParameters.contains(module)) // module doesn't have an accessible no-arg constructor .filter(moduleType -> !componentCanMakeNewInstances(moduleType)).collect(toImmutableSet()); }
From source file:org.apache.flex.compiler.internal.scopes.ASProjectScope.java
private static boolean referenceMatchesQName(IWorkspace workspace, IResolvedQualifiersReference reference, String qualifiedName) {// w w w . j a v a2 s .c o m IResolvedQualifiersReference qualifiedNameReference = ReferenceFactory.packageQualifiedReference(workspace, qualifiedName, true); ImmutableSet<INamespaceDefinition> referenceQualifiers = reference.getQualifiers(); for (INamespaceDefinition qNameNS : qualifiedNameReference.getQualifiers()) { if (referenceQualifiers.contains(qNameNS)) return true; } return false; }
From source file:com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodecProcessor.java
private ExecutableElement findSetterGivenGetter(ExecutableElement getter, TypeElement builderType) { List<ExecutableElement> methods = ElementFilter.methodsIn(env.getElementUtils().getAllMembers(builderType)); String varName = getNameFromGetter(getter); TypeMirror type = getter.getReturnType(); ImmutableSet<String> setterNames = ImmutableSet.of(varName, addCamelCasePrefix(varName, "set")); ExecutableElement setterMethod = null; for (ExecutableElement method : methods) { if (!method.getModifiers().contains(Modifier.STATIC) && !method.getModifiers().contains(Modifier.PRIVATE) && setterNames.contains(method.getSimpleName().toString()) && method.getReturnType().equals(builderType.asType()) && method.getParameters().size() == 1 && env.getTypeUtils().isSubtype(type, Iterables.getOnlyElement(method.getParameters()).asType())) { if (setterMethod != null) { throw new IllegalArgumentException("Multiple setter methods for " + getter + " found in " + builderType + ": " + setterMethod + " and " + method); }/* ww w. j a va 2 s . co m*/ setterMethod = method; } } if (setterMethod != null) { return setterMethod; } throw new IllegalArgumentException( builderType + ": No setter found corresponding to getter " + getter.getSimpleName() + ", " + type); }
From source file:com.google.devtools.build.lib.remote.GrpcRemoteCache.java
/** * Upload enough of the tree metadata and data into remote cache so that the entire tree can be * reassembled remotely using the root digest. *//*from ww w . j a v a 2 s. c om*/ @Override public void ensureInputsPresent(TreeNodeRepository repository, Path execRoot, TreeNode root, Command command) throws IOException, InterruptedException { repository.computeMerkleDigests(root); Digest commandDigest = Digests.computeDigest(command); // TODO(olaola): avoid querying all the digests, only ask for novel subtrees. ImmutableSet<Digest> missingDigests = getMissingDigests( Iterables.concat(repository.getAllDigests(root), ImmutableList.of(commandDigest))); List<Chunker> toUpload = new ArrayList<>(); // Only upload data that was missing from the cache. ArrayList<ActionInput> missingActionInputs = new ArrayList<>(); ArrayList<Directory> missingTreeNodes = new ArrayList<>(); HashSet<Digest> missingTreeDigests = new HashSet<>(missingDigests); missingTreeDigests.remove(commandDigest); repository.getDataFromDigests(missingTreeDigests, missingActionInputs, missingTreeNodes); if (missingDigests.contains(commandDigest)) { toUpload.add(new Chunker(command.toByteArray())); } if (!missingTreeNodes.isEmpty()) { for (Directory d : missingTreeNodes) { toUpload.add(new Chunker(d.toByteArray())); } } if (!missingActionInputs.isEmpty()) { MetadataProvider inputFileCache = repository.getInputFileCache(); for (ActionInput actionInput : missingActionInputs) { toUpload.add(new Chunker(actionInput, inputFileCache, execRoot)); } } uploader.uploadBlobs(toUpload); }
From source file:vazkii.quark.misc.feature.PanoramaMaker.java
@SubscribeEvent public void loadMainMenu(GuiOpenEvent event) { if (overrideMainMenu && !overridenOnce && event.getGui() instanceof GuiMainMenu) { File mcDir = ModuleLoader.configFile.getParentFile().getParentFile(); File panoramasDir = new File(mcDir, "/screenshots/panoramas"); List<File[]> validFiles = new ArrayList(); ImmutableSet<String> set = ImmutableSet.of("panorama_0.png", "panorama_1.png", "panorama_2.png", "panorama_3.png", "panorama_4.png", "panorama_5.png"); if (panoramasDir.exists()) { File[] subDirs;/*from w ww. ja va 2 s.c om*/ File mainMenu = new File(panoramasDir, "main_menu"); if (mainMenu.exists()) subDirs = new File[] { mainMenu }; else subDirs = panoramasDir .listFiles((File f) -> f.isDirectory() && !f.getName().endsWith("fullres")); for (File f : subDirs) if (set.stream().allMatch((String s) -> new File(f, s).exists())) validFiles.add(f.listFiles((File f1) -> set.contains(f1.getName()))); } if (!validFiles.isEmpty()) { File[] files = validFiles.get(new Random().nextInt(validFiles.size())); Arrays.sort(files); Minecraft mc = Minecraft.getMinecraft(); ResourceLocation[] resources = new ResourceLocation[6]; for (int i = 0; i < resources.length; i++) { File f = files[i]; try { BufferedImage img = ImageIO.read(f); DynamicTexture tex = new DynamicTexture(img); String name = "quark:" + f.getName(); resources[i] = mc.getTextureManager().getDynamicTextureLocation(name, tex); } catch (IOException e) { e.printStackTrace(); return; } } try { Field field = ReflectionHelper.findField(GuiMainMenu.class, LibObfuscation.TITLE_PANORAMA_PATHS); field.setAccessible(true); if (Modifier.isFinal(field.getModifiers())) { Field modfield = Field.class.getDeclaredField("modifiers"); modfield.setAccessible(true); modfield.setInt(field, field.getModifiers() & ~Modifier.FINAL); } field.set(null, resources); } catch (Exception e) { e.printStackTrace(); } } overridenOnce = true; } }
From source file:org.eclipse.sw360.portal.portlets.admin.UserPortlet.java
@Override public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException { List<org.eclipse.sw360.datahandler.thrift.users.User> missingUsers = new ArrayList<>(); List<org.eclipse.sw360.datahandler.thrift.users.User> backEndUsers; List<User> liferayUsers; List<User> liferayUsers2; try {/*from w w w . j a v a2 s. co m*/ liferayUsers2 = UserLocalServiceUtil.getUsers(QueryUtil.ALL_POS, QueryUtil.ALL_POS); } catch (SystemException e) { log.error("Could not get user List from liferay", e); liferayUsers2 = Collections.emptyList(); } liferayUsers = FluentIterable.from(liferayUsers2).filter(new Predicate<User>() { @Override public boolean apply(User liferayUser) { String firstName = liferayUser.getFirstName(); String lastName = liferayUser.getLastName(); String emailAddress = liferayUser.getEmailAddress(); List<Organization> organizations; try { organizations = liferayUser.getOrganizations(); } catch (PortalException | SystemException e) { return false; } String department = ""; if (organizations != null && organizations.size() > 0) { department = organizations.get(0).getName(); } String userGroup = ""; List<Role> roles; try { roles = liferayUser.getRoles(); } catch (SystemException e) { return false; } List<String> roleNames = new ArrayList<>(); for (Role role : roles) { roleNames.add(role.getName()); } for (UserGroup group : UserGroup.values()) { String roleConstantFromUserGroup = getRoleConstantFromUserGroup(group); if (roleNames.contains(roleConstantFromUserGroup)) { userGroup = group.toString(); break; } } String gid = liferayUser.getOpenId(); String passwordHash = liferayUser.getPassword(); return !(isNullOrEmpty(firstName) || isNullOrEmpty(lastName) || isNullOrEmpty(emailAddress) || isNullOrEmpty(department) || isNullOrEmpty(userGroup) || isNullOrEmpty(gid) || isNullOrEmpty(passwordHash)); } }).toList(); try { UserService.Iface client = thriftClients.makeUserClient(); backEndUsers = CommonUtils.nullToEmptyList(client.searchUsers(null)); } catch (TException e) { log.error("Problem with user client", e); backEndUsers = Collections.emptyList(); } if (backEndUsers.size() > 0) { final ImmutableSet<String> lifeRayMails = FluentIterable.from(liferayUsers) .transform(new Function<User, String>() { @Override public String apply(User input) { return input.getEmailAddress(); } }).toSet(); missingUsers = FluentIterable.from(backEndUsers) .filter(new Predicate<org.eclipse.sw360.datahandler.thrift.users.User>() { @Override public boolean apply(org.eclipse.sw360.datahandler.thrift.users.User input) { return !lifeRayMails.contains(input.getEmail()); } }).toList(); } request.setAttribute(PortalConstants.USER_LIST, liferayUsers); request.setAttribute(PortalConstants.MISSING_USER_LIST, missingUsers); // Proceed with page rendering super.doView(request, response); }
From source file:org.sosy_lab.cpachecker.util.cwriter.PathToCWithLoopsTranslator.java
/** * Recreates the code of one (or more nested) loops with gotos. * @param pCFAEdge the edge into the loop * @param currentBlock the current block * @param loopsAfter the loops which we are in after the edge * @return the complete c-code for the recreated loop *//*from w w w.ja v a 2 s . co m*/ private Pair<String, CFAEdge> recreateLoop(CFAEdge pCFAEdge, BasicBlock currentBlock, List<Loop> loopsAfter) { // clear all necessary things resetLoopAndIfMaps(); CFAEdge lastEdge = null; // start actual loop recreation StringBuilder wholeLoopString = new StringBuilder(); // we go into a loop thus we have to uproll it right now, and add all // handled edges to the handledEdges list, so they wont occur twice in the // generated c code // this should be already handled by the handledEdges check at the beginning // of the processEdge method assert loopsAfter.get(loopsAfter.size() - 1).getIncomingEdges().contains(pCFAEdge); Loop loop = loopsAfter.get(loopsAfter.size() - 1); // create necessary mappings String labelStayInLoop = createFreshLabelForLoop(pCFAEdge, loop); // uproll loop and write code wholeLoopString.append(labelStayInLoop).append(": ;\n"); Deque<CFAEdge> edgesToHandle = new ArrayDeque<>(); edgesToHandle.offer(pCFAEdge); Deque<Loop> loopStack = new ArrayDeque<>(); loopStack.push(loop); Deque<CFAEdge> ifStack = new ArrayDeque<>(); Deque<CFAEdge> outOfLoopEdgesStack = new ArrayDeque<>(); while ((!edgesToHandle.isEmpty() || !outOfLoopEdgesStack.isEmpty() || !ifStack.isEmpty())) { // all nodes from the current loop handled, so we can go on to the // next one if (edgesToHandle.isEmpty()) { // at first we need to handle ifs if (!ifStack.isEmpty()) { edgesToHandle.offer(ifStack.pop()); wholeLoopString.append("goto ").append(ifOutLabels.get(edgesToHandle.peek())).append(";\n") .append(ifElseLabels.get(edgesToHandle.peek())).append(": ;\n"); } else { edgesToHandle.offer(outOfLoopEdgesStack.pop()); Loop oldLoop = loopStack.pop(); wholeLoopString.append("goto ").append(loopInLabels.get(oldLoop)).append(";\n") .append(loopOutLabels.get(oldLoop)).append(": ;\n"); } } CFANode currentEdgePredecessor = edgesToHandle.peek().getPredecessor(); handleIfOutLabels(wholeLoopString, currentEdgePredecessor); // only continue if we didn't already visit this edge if (handledEdges.contains(edgesToHandle.peek())) { edgesToHandle.pop(); continue; } CFAEdge currentEdge = edgesToHandle.pop(); handledEdges.add(currentEdge); FluentIterable<CFAEdge> leaving = CFAUtils.leavingEdges(currentEdge.getSuccessor()) .filter(not(instanceOf(FunctionCallEdge.class))); // there was a function call, we need to replace it with the correct successor // as we are sure that there is only one, this is safe, we also don't // need to update loops here if (leaving.isEmpty()) { CFAEdge realLeavingEdge = currentEdge.getSuccessor().getLeavingEdge(0); CFAEdge leavingSummaryEdge = currentEdge.getSuccessor().getLeavingSummaryEdge(); wholeLoopString.append(processSimpleWithLoop(realLeavingEdge, currentBlock, "")); handledFunctions.add(((CFunctionEntryNode) realLeavingEdge.getSuccessor()).getFunctionName()); leaving = leaving.append(leavingSummaryEdge); // no function call just and ordinary statement, add it as it is // to the loopString } else if (leaving.size() == 1) { wholeLoopString.append(processSimpleWithLoop(leaving.get(0), currentBlock, "")); } // only one successor, to handle // we need to check the loops so that we know if we need // to update the loopStack, or only the handledEdges if (leaving.size() == 1) { CFAEdge onlyEdge = leaving.get(0); // this is an edge from inside the loop back to the loop if (loopToHead.get(loopStack.peek()) == onlyEdge.getSuccessor() && !loopStack.peek().getIncomingEdges().contains(onlyEdge)) { handledEdges.add(onlyEdge); handleIfOutLabels(wholeLoopString, onlyEdge.getPredecessor()); } else { edgesToHandle.offer(onlyEdge); updateLoopStack(wholeLoopString, loopStack, onlyEdge); } // more sucessors, we have to add some gotos } else { // there can be at most two leaving edges assert leaving.size() == 2 : leaving.toString(); CFAEdge leaving1 = leaving.get(0); CFAEdge leaving2 = leaving.get(1); // outgoing edges have to be handled first, this way // we can create the goto easier ImmutableSet<CFAEdge> outOfCurrentLoop = loopStack.peek().getOutgoingEdges(); boolean isOutOfLoopContained = false; CFAEdge leavingLoopEdge = null; if (outOfCurrentLoop.contains(leaving1)) { handleOutOfLoopEdge(currentBlock, wholeLoopString, edgesToHandle, loopStack, leaving1, leaving2); leavingLoopEdge = leaving1; isOutOfLoopContained = true; } else if (outOfCurrentLoop.contains(leaving2)) { handleOutOfLoopEdge(currentBlock, wholeLoopString, edgesToHandle, loopStack, leaving2, leaving1); leavingLoopEdge = leaving2; isOutOfLoopContained = true; } if (isOutOfLoopContained) { // we are alredy in the outermost loop that should be handled // if we have an edge which is leaving this loop we just need // to create a goto if (loopStack.size() == 1) { lastEdge = leavingLoopEdge; handledEdges.add(leavingLoopEdge); // deeper loopstack, potentially the same code as above // we do only need to handle the successor of the outOfLoopEdge, too } else { outOfLoopEdgesStack.push(leavingLoopEdge); } // end this loop iteration here continue; } // now comes the case where both edges stay in the loop, this means // this is a "simple" if statement // we need to find the merging point of both branches, such that we // know where the gotos and labels have to go if (!handledEdges.contains(leaving1)) { wholeLoopString.append(processSimpleWithLoop(leaving1, currentBlock, createFreshLabelForIf(leaving2, findEndOfBranches(singletonList(loopToHead.get(loopStack.peek())), currentEdgePredecessor, leaving1.getSuccessor(), leaving2.getSuccessor())))); edgesToHandle.push(leaving1); ifStack.push(leaving2); } } } wholeLoopString.append("goto ").append(loopInLabels.get(loop)).append(";\n").append(loopOutLabels.get(loop)) .append(": ;\n"); // assert ifOutLabelEnd.isEmpty() && loopStack.isEmpty(); return Pair.of(wholeLoopString.toString(), lastEdge); }