@NotNull
  private static Set<PsiClassType> filterInProjectExceptions(
      @Nullable PsiMethod targetMethod, @NotNull List<PsiClassType> unhandledExceptions) {
    if (targetMethod == null) return Collections.emptySet();

    Set<PsiClassType> result = new HashSet<PsiClassType>();

    if (targetMethod.getManager().isInProject(targetMethod)) {
      PsiMethod[] superMethods = targetMethod.findSuperMethods();
      for (PsiMethod superMethod : superMethods) {
        Set<PsiClassType> classTypes = filterInProjectExceptions(superMethod, unhandledExceptions);
        result.addAll(classTypes);
      }

      if (superMethods.length == 0) {
        result.addAll(unhandledExceptions);
      }
    } else {
      PsiClassType[] referencedTypes = targetMethod.getThrowsList().getReferencedTypes();
      for (PsiClassType referencedType : referencedTypes) {
        PsiClass psiClass = referencedType.resolve();
        if (psiClass == null) continue;
        for (PsiClassType exception : unhandledExceptions) {
          if (referencedType.isAssignableFrom(exception)) result.add(exception);
        }
      }
    }

    return result;
  }
  private Collection<File> getClasspathFiles(
      ModuleChunk chunk,
      JpsJavaClasspathKind kind,
      final boolean excludeMainModuleOutput,
      ClasspathPart classpathPart,
      final boolean exportedOnly) {
    final Set<File> files = new LinkedHashSet<File>();
    for (JpsModule module : chunk.getModules()) {
      JpsJavaDependenciesEnumerator enumerator =
          JpsJavaExtensionService.dependencies(module).includedIn(kind).recursively();
      if (exportedOnly) {
        enumerator = enumerator.exportedOnly();
      }
      if (classpathPart == ClasspathPart.BEFORE_JDK) {
        enumerator = enumerator.satisfying(new BeforeJavaSdkItemFilter(module));
      } else if (classpathPart == ClasspathPart.AFTER_JDK) {
        enumerator = enumerator.satisfying(new AfterJavaSdkItemFilter(module));
      }
      JpsJavaDependenciesRootsEnumerator rootsEnumerator = enumerator.classes();
      if (excludeMainModuleOutput) {
        rootsEnumerator = rootsEnumerator.withoutSelfModuleOutput();
      }
      files.addAll(rootsEnumerator.getRoots());
    }

    if (classpathPart == ClasspathPart.BEFORE_JDK) {
      for (JpsModule module : chunk.getModules()) {
        JpsSdk<JpsDummyElement> sdk = module.getSdk(JpsJavaSdkType.INSTANCE);
        if (sdk != null) {
          files.addAll(sdk.getParent().getFiles(JpsOrderRootType.COMPILED));
        }
      }
    }
    return files;
  }
    public Set<File> getFiles(Spec<Dependency> dependencySpec) {
      rethrowFailure();
      Set<ModuleDependency> allDependencies =
          configuration.getAllDependencies(ModuleDependency.class);
      Set<ModuleDependency> selectedDependencies =
          Specs.filterIterable(allDependencies, dependencySpec);

      Set<ResolvedArtifact> artifacts = new LinkedHashSet<ResolvedArtifact>();

      for (ModuleDependency moduleDependency : selectedDependencies) {
        Set<ResolvedDependency> resolvedDependencies =
            conversionResult.getFirstLevelResolvedDependencies().get(moduleDependency);
        for (ResolvedDependency resolvedDependency : resolvedDependencies) {
          artifacts.addAll(resolvedDependency.getParentArtifacts(conversionResult.getRoot()));
          walker.add(resolvedDependency);
        }
      }

      artifacts.addAll(walker.findValues());

      Set<File> files = new LinkedHashSet<File>();
      for (ResolvedArtifact artifact : artifacts) {
        File depFile = artifact.getFile();
        if (depFile != null) {
          files.add(depFile);
        } else {
          logger.debug(String.format("Resolved artifact %s contains a null value.", artifact));
        }
      }
      return files;
    }
  protected void handleAdd() {
    ElementListSelectionDialog dialog =
        new ElementListSelectionDialog(getShell(), new StyledBundleLabelProvider(false, false));

    try {
      dialog.setElements(getValidBundles());
    } catch (CoreException e) {
      dialog.setMessage(e.getMessage());
    }

    dialog.setTitle(PDEUIMessages.PluginSelectionDialog_title);
    dialog.setMessage(PDEUIMessages.PluginSelectionDialog_message);
    dialog.setMultipleSelection(true);
    if (dialog.open() == Window.OK) {

      Object[] models = dialog.getResult();
      ArrayList<NameVersionDescriptor> pluginsToAdd = new ArrayList<NameVersionDescriptor>();
      for (int i = 0; i < models.length; i++) {
        BundleInfo desc = ((BundleInfo) models[i]);
        pluginsToAdd.add(new NameVersionDescriptor(desc.getSymbolicName(), null));
      }
      Set<NameVersionDescriptor> allDependencies = new HashSet<NameVersionDescriptor>();
      allDependencies.addAll(pluginsToAdd);
      NameVersionDescriptor[] currentBundles = getTargetDefinition().getImplicitDependencies();
      if (currentBundles != null) {
        allDependencies.addAll(Arrays.asList(currentBundles));
      }
      getTargetDefinition()
          .setImplicitDependencies(
              allDependencies.toArray(new NameVersionDescriptor[allDependencies.size()]));
      fElementViewer.refresh();
      updateImpButtons();
    }
  }
  /**
   * Constructor.
   *
   * @param ee comma separated list of execution environments names.
   * @throws PlatformException - If encountered during reading of profiles - If profile cannot be
   *     found or determined
   */
  ExecutionEnvironment(final String ee) throws PlatformException {
    // we make an union of the packages form each ee so let's have a unique set for it
    final Set<String> uniquePackages = new TreeSet<String>();
    final Set<String> uniqueEE = new TreeSet<String>();

    for (String segment : ee.split(",")) {
      try {
        final Properties profile = new Properties();
        profile.load(discoverExecutionEnvironmentURL(segment).openStream());

        final String systemPackagesProp =
            profile.getProperty(Constants.FRAMEWORK_SYSTEMPACKAGES, "");
        if (systemPackagesProp != null && systemPackagesProp.trim().length() > 0) {
          uniquePackages.addAll(Arrays.asList(systemPackagesProp.split(",")));
        }

        final String eeProp = profile.getProperty(Constants.FRAMEWORK_EXECUTIONENVIRONMENT, "");
        if (eeProp != null && eeProp.trim().length() > 0) {
          uniqueEE.addAll(Arrays.asList(eeProp.split(",")));
        }
      } catch (IOException e) {
        throw new PlatformException("Could not read execution environment profile", e);
      }
    }
    m_systemPackages = join(uniquePackages, ",");
    m_executionEnvironment = join(uniqueEE, ",");
  }
Пример #6
0
  @NotNull
  private static Set<DeclarationDescriptor> getTopLevelDescriptorsByFqName(
      @NotNull KotlinCodeAnalyzer resolveSession, @NotNull FqName fqName) {
    FqName parentFqName = fqName.parent();

    Set<DeclarationDescriptor> descriptors = new HashSet<DeclarationDescriptor>();

    LazyPackageDescriptor parentFragment = resolveSession.getPackageFragment(parentFqName);
    if (parentFragment != null) {
      // Filter out extension properties
      descriptors.addAll(
          KotlinPackage.filter(
              parentFragment.getMemberScope().getProperties(fqName.shortName()),
              new Function1<VariableDescriptor, Boolean>() {
                @Override
                public Boolean invoke(VariableDescriptor descriptor) {
                  return descriptor.getReceiverParameter() == null;
                }
              }));
    }

    ContainerUtil.addIfNotNull(descriptors, resolveSession.getPackageFragment(fqName));

    descriptors.addAll(resolveSession.getTopLevelClassDescriptors(fqName));
    return descriptors;
  }
Пример #7
0
 public Set<Participant> resolveParticipantsFromResourceName(String anyName) {
   Set<Participant> pSet = new HashSet<Participant>();
   Participant p = getParticipantFromUserID(anyName);
   if (p != null) {
     pSet.add(p);
     return pSet;
   }
   Role r = getRoleByName(anyName);
   if (r != null) {
     pSet.addAll(getRoleParticipants(r.getID()));
     return pSet;
   }
   Position pos = getPositionByLabel(anyName);
   if (pos != null) {
     pSet.addAll(getPositionParticipants(pos.getID()));
     return pSet;
   }
   OrgGroup o = getOrgGroupByLabel(anyName);
   if (o != null) {
     pSet.addAll(getOrgGroupParticipants(o.getID()));
     return pSet;
   }
   Capability c = getCapabilityByLabel(anyName);
   if (c != null) {
     pSet.addAll(getCapabilityParticipants(c.getID()));
   }
   return pSet;
 }
 public static Set<Integer> withNoDuplicatesMerge(
     List<Integer> leftArray, List<Integer> rightArray) {
   Set<Integer> list = new LinkedHashSet<>();
   list.addAll(leftArray);
   list.addAll(rightArray);
   return list;
 }
Пример #9
0
 public void addMatchingSetters() {
   check(implInterface || !dataTypeIn.isInterface());
   Set<String> usedFields = new HashSet<>();
   if (constructorParams != null) {
     usedFields.addAll(constructorParams);
   }
   if (factoryParams != null) {
     usedFields.addAll(factoryParams);
   }
   for (List<String> list : setters.values()) {
     usedFields.addAll(list);
   }
   for (String fieldName : fields.keySet()) {
     FieldGen fieldGen = fields.get(fieldName);
     Method getter = fieldGen.method;
     if (getter == null) continue;
     if (usedFields.contains(fieldName)) continue;
     String setterName =
         "set" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
     try {
       Method setter;
       if (implInterface) setter = dataTypeOut.getMethod(setterName, getter.getReturnType());
       else setter = dataTypeIn.getMethod(setterName, getter.getReturnType());
       if (!isPrivate(setter.getModifiers())) {
         addSetter(setter, asList(fieldName));
       }
     } catch (NoSuchMethodException e) {
       throw new RuntimeException(e);
     }
   }
 }
Пример #10
0
  /**
   * Given a set of SCC nodes make this the lead member of the SCC and reroute all incoming and
   * outgoing links accordingly. This eager rewrite is based on the assumption that there are few
   * cycles so it is better to rewrite once and keep the graph easy to traverse.
   */
  public void makeLeadNodeFor(Set<GraphNode> members) {
    // Accumulate all successors
    Set<GraphNode> newSucc = new HashSet<>();
    Set<GraphNode> newSuccClosed = new HashSet<>();
    for (GraphNode n : members) {
      newSucc.addAll(n.succ);
      newSuccClosed.addAll(n.succClosed);
    }
    newSucc.removeAll(members);
    newSuccClosed.removeAll(members);
    succ = newSucc;
    succClosed = newSuccClosed;

    // Rewrite all direct successors to have us as predecessor
    for (GraphNode n : succ) {
      n.pred.removeAll(members);
      n.pred.add(this);
    }

    // Find all predecessor nodes and relink link them to point to us
    Set<GraphNode> done = new HashSet<>();
    Set<GraphNode> newAliases = new HashSet<>();
    for (GraphNode member : members) {
      addSiblings(newAliases, member);
    }
    becomeLeaderOf(newAliases);
    for (GraphNode n : members) {
      if (n != this) {
        pred.addAll(n.pred);
        n.relocateAllRefTo(this, done);
        n.becomeSubordinateOf(this);
      }
    }
    pred.removeAll(members);
  }
Пример #11
0
 /**
  * Prints a usage message to the given stream.
  *
  * @param out The output stream to write to.
  */
 public void printUsage(OutputStream out) {
   Formatter formatter = new Formatter(out);
   Set<CommandLineOption> orderedOptions = new TreeSet<CommandLineOption>(new OptionComparator());
   orderedOptions.addAll(optionsByString.values());
   Map<String, String> lines = new LinkedHashMap<String, String>();
   for (CommandLineOption option : orderedOptions) {
     Set<String> orderedOptionStrings = new TreeSet<String>(new OptionStringComparator());
     orderedOptionStrings.addAll(option.getOptions());
     List<String> prefixedStrings = new ArrayList<String>();
     for (String optionString : orderedOptionStrings) {
       if (optionString.length() == 1) {
         prefixedStrings.add("-" + optionString);
       } else {
         prefixedStrings.add("--" + optionString);
       }
     }
     lines.put(GUtil.join(prefixedStrings, ", "), GUtil.elvis(option.getDescription(), ""));
   }
   int max = 0;
   for (String optionStr : lines.keySet()) {
     max = Math.max(max, optionStr.length());
   }
   for (Map.Entry<String, String> entry : lines.entrySet()) {
     if (entry.getValue().length() == 0) {
       formatter.format("%s%n", entry.getKey());
     } else {
       formatter.format("%-" + max + "s  %s%n", entry.getKey(), entry.getValue());
     }
   }
   formatter.flush();
 }
  private static OrderEntry[] calcOrderEntries(
      @NotNull RootInfo info,
      @NotNull MultiMap<VirtualFile, OrderEntry> depEntries,
      @NotNull MultiMap<VirtualFile, OrderEntry> libClassRootEntries,
      @NotNull MultiMap<VirtualFile, OrderEntry> libSourceRootEntries,
      @NotNull List<VirtualFile> hierarchy) {
    @Nullable VirtualFile libraryClassRoot = info.findLibraryRootInfo(hierarchy, false);
    @Nullable VirtualFile librarySourceRoot = info.findLibraryRootInfo(hierarchy, true);
    Set<OrderEntry> orderEntries = ContainerUtil.newLinkedHashSet();
    orderEntries.addAll(
        info.getLibraryOrderEntries(
            hierarchy,
            libraryClassRoot,
            librarySourceRoot,
            libClassRootEntries,
            libSourceRootEntries));
    for (VirtualFile root : hierarchy) {
      orderEntries.addAll(depEntries.get(root));
    }
    VirtualFile moduleContentRoot = info.findModuleRootInfo(hierarchy);
    if (moduleContentRoot != null) {
      ContainerUtil.addIfNotNull(
          orderEntries,
          info.getModuleSourceEntry(hierarchy, moduleContentRoot, libClassRootEntries));
    }
    if (orderEntries.isEmpty()) {
      return null;
    }

    OrderEntry[] array = orderEntries.toArray(new OrderEntry[orderEntries.size()]);
    Arrays.sort(array, BY_OWNER_MODULE);
    return array;
  }
 public List<ObjectSetUse> getObjectSetUses(SystemObjectType type) {
   Set<ObjectSetUse> objectSetUses = new HashSet<ObjectSetUse>();
   objectSetUses.addAll(getDirectObjectSetUses(type));
   for (SystemObjectType superType : getSuperTypes(type)) {
     objectSetUses.addAll(getObjectSetUses(superType));
   }
   return new ArrayList(objectSetUses);
 }
Пример #14
0
 private Set<OrderRootType> getAllRootTypes() {
   Set<OrderRootType> rootTypes = new HashSet<OrderRootType>();
   rootTypes.addAll(Arrays.asList(OrderRootType.getAllTypes()));
   if (myKind != null) {
     rootTypes.addAll(Arrays.asList(myKind.getAdditionalRootTypes()));
   }
   return rootTypes;
 }
Пример #15
0
 /**
  * Get jet non-extension top-level function names. Method is allowed to give invalid names - all
  * result should be checked with getTopLevelFunctionDescriptorsByName().
  *
  * @return
  */
 @NotNull
 public Collection<String> getAllTopLevelFunctionNames() {
   Set<String> functionNames = new HashSet<String>();
   functionNames.addAll(JetShortFunctionNameIndex.getInstance().getAllKeys(project));
   functionNames.addAll(
       JetFromJavaDescriptorHelper.getPossiblePackageDeclarationsNames(
           project, GlobalSearchScope.allScope(project)));
   return functionNames;
 }
 public static List<String> createMustacheKeys(FacesContext context, UIComponentBase component)
     throws IOException {
   final Set<String> mustacheKeys = new HashSet<>();
   mustacheKeys.addAll(createMustacheKeysFromTemplate(context, component, "template"));
   mustacheKeys.addAll(createMustacheKeysFromTemplate(context, component, "emptyEntryTemplate"));
   mustacheKeys.addAll(
       createMustacheKeysFromTemplate(context, component, "selectedEntryTemplate"));
   return new ArrayList<>(mustacheKeys);
 }
Пример #17
0
  @Override
  public String[] getWorlds() {
    Set<String> worlds = new HashSet<String>();

    worlds.addAll(worldsOptions.keySet());
    worlds.addAll(worldsPermissions.keySet());
    worlds.addAll(parents.keySet());

    return worlds.toArray(new String[0]);
  }
Пример #18
0
 public Set<E> edgesOf(V vertex) {
   Set<E> res = new HashSet<E>();
   if (g1.containsVertex(vertex)) {
     res.addAll(g1.edgesOf(vertex));
   }
   if (g2.containsVertex(vertex)) {
     res.addAll(g2.edgesOf(vertex));
   }
   return Collections.unmodifiableSet(res);
 }
 public Set<E> outgoingEdgesOf(V vertex) {
   Set<E> res = new HashSet<E>();
   if (getG1().containsVertex(vertex)) {
     res.addAll(getG1().outgoingEdgesOf(vertex));
   }
   if (getG2().containsVertex(vertex)) {
     res.addAll(getG2().outgoingEdgesOf(vertex));
   }
   return Collections.unmodifiableSet(res);
 }
Пример #20
0
  /**
   * Get jet extensions top-level function names. Method is allowed to give invalid names - all
   * result should be checked with getAllJetExtensionFunctionsByName().
   *
   * @return
   */
  @NotNull
  public Collection<String> getAllJetExtensionFunctionsNames(@NotNull GlobalSearchScope scope) {
    Set<String> extensionFunctionNames = new HashSet<String>();

    extensionFunctionNames.addAll(JetExtensionFunctionNameIndex.getInstance().getAllKeys(project));
    extensionFunctionNames.addAll(
        JetFromJavaDescriptorHelper.getTopExtensionFunctionNames(project, scope));

    return extensionFunctionNames;
  }
Пример #21
0
 public Set<E> getAllEdges(V sourceVertex, V targetVertex) {
   Set<E> res = new HashSet<E>();
   if (g1.containsVertex(sourceVertex) && g1.containsVertex(targetVertex)) {
     res.addAll(g1.getAllEdges(sourceVertex, targetVertex));
   }
   if (g2.containsVertex(sourceVertex) && g2.containsVertex(targetVertex)) {
     res.addAll(g2.getAllEdges(sourceVertex, targetVertex));
   }
   return Collections.unmodifiableSet(res);
 }
Пример #22
0
  /** Evaluate the Insert(X, Y, T) operator (Definition 12 from Chickering, 2002). */
  private double insertEval(Node x, Node y, List<Node> t, List<Node> naYX, Graph graph) {
    Set<Node> set1 = new HashSet<Node>(naYX);
    set1.addAll(t);
    List<Node> paY = graph.getParents(y);
    set1.addAll(paY);
    Set<Node> set2 = new HashSet<Node>(set1);
    set1.add(x);

    return scoreGraphChange(y, set1, set2);
  }
Пример #23
0
  @Override
  protected Set<ResourceActivity> getResourceActivities() {
    final Set<ResourceActivity> activities = new HashSet<ResourceActivity>();

    activities.addAll(super.getResourceActivities());
    activities.addAll(Util.filter(publishers, ResourceActivity.class));
    activities.addAll(Util.filter(buildWrappers, ResourceActivity.class));

    return activities;
  }
Пример #24
0
 public static Counter PersonalizedPageRank(Counter seedVector, SparseMatrix transitionMat) {
   double trimEps = 0.0;
   int iterLimit = 200;
   transitionMat = transitionMat.stochasticizeRows();
   double beta = 0.85;
   long start;
   long end;
   Counter vector = new Counter(seedVector);
   double svCard = 0;
   for (int i : seedVector.keySet()) {
     svCard += seedVector.get(i);
   }
   Counter oldVector = new Counter(vector);
   vector = transitionMat.multiply(vector);
   double diff = 1;
   int t = 0;
   start = System.currentTimeMillis();
   while (diff > Math.pow(10.0, -10.0) && (diff < 3.99999 || diff > 4.00001) && t < iterLimit) {
     t += 1;
     vector.trimKeys(trimEps);
     vector = transitionMat.multiply(vector);
     Set<Integer> vecSeedUnion = vector.concreteKeySet();
     vecSeedUnion.addAll(seedVector.concreteKeySet());
     for (int i : vecSeedUnion) {
       //				vector.set(i,
       // beta*vector.get(i)/norm+(1-beta)*seedVector.get(i));///Math.max(norm,1.0));
       vector.set(
           i,
           beta * vector.get(i)
               + (1 - beta) * seedVector.get(i) / svCard); // /Math.max(norm,1.0));
     }
     double norm = 0;
     for (int i : vector.keySet()) {
       //				norm += vector.get(i)*vector.get(i);
       //				norm += Math.abs(vector.get(i));
       norm += vector.get(i);
     }
     //			norm = Math.sqrt(norm);
     diff = 0;
     Set<Integer> vecOldUnion = vector.concreteKeySet();
     vecOldUnion.addAll(oldVector.concreteKeySet());
     for (int i : vecOldUnion) {
       diff += (oldVector.get(i) - vector.get(i)) * (oldVector.get(i) - vector.get(i));
     }
     System.out.println(diff + " " + norm);
     //			System.out.println(vector.toString());
     // System.out.println(oldVector.toString());
     oldVector = new Counter(vector);
   }
   //		System.out.println(transitionMat.toStringValues());
   end = System.currentTimeMillis();
   System.out.println("Time: " + (end - start) + " iterations: " + t);
   return vector;
 }
Пример #25
0
  public Set<Service> grabServiceSet() {
    Set<Service> services = new HashSet<Service>();

    for (SiteRecord siteRecord : siteRecordSet)
      services.addAll(siteRecord.getRecord().getServiceSet());

    for (CassandraSiteCluster cassandraSiteCluster : cassandraSiteClusterSet)
      services.addAll(cassandraSiteCluster.getCassandraCluster().getServiceSet());

    return services;
  }
Пример #26
0
  public boolean relabelsTo(Policy pol, Set s) {
    if (this == pol || this.equals(pol)) return true;

    Set temp = new HashSet();
    // this == c1 join ... join cn
    // this <= pol if for all Ci, Ci <= pol
    boolean sat = true;
    for (Iterator i = components.iterator(); i.hasNext(); ) {
      Policy Ci = (Policy) i.next();
      if (!labelUtil.relabelsTo(Ci, pol, temp)) {
        sat = false;
        break;
      }
    }
    if (sat) {
      s.addAll(temp);
      return true;
    }

    temp.clear();

    // failed so far, try taking advantage of structure on the RHS
    if (pol instanceof MeetPolicy) {
      // this <= d1 meet ... meet dn if for all di
      // we have this <= di
      MeetPolicy mp = (MeetPolicy) pol;
      sat = true;
      for (Iterator i = mp.meetComponents().iterator(); i.hasNext(); ) {
        Policy Di = (Policy) i.next();
        if (!labelUtil.relabelsTo(this, Di, temp)) {
          sat = false;
          break;
        }
      }
      if (sat) {
        s.addAll(temp);
        return true;
      }
    }
    if (pol instanceof JoinPolicy) {
      // this <= d1 join ... join dn if there is some di
      // such that this <= di
      JoinPolicy jp = (JoinPolicy) pol;
      for (Iterator i = jp.joinComponents().iterator(); i.hasNext(); ) {
        temp.clear();
        Policy Di = (Policy) i.next();
        if (labelUtil.relabelsTo(this, Di, temp)) {
          s.addAll(temp);
          return true;
        }
      }
    }
    return false;
  }
Пример #27
0
 /**
  * A Set of all allowed relations of a certain role between two builders. Distinction is made
  * between source and destination depending on passed directionality.
  *
  * @since MMBase-1.6.2
  */
 public Set<MMObjectNode> getAllowedRelations(
     int builder1, int builder2, int role, int directionality) {
   Set<MMObjectNode> res = new HashSet<MMObjectNode>();
   if (directionality != RelationStep.DIRECTIONS_SOURCE) {
     res.addAll(typeRelNodes.getBySourceDestinationRole(builder1, builder2, role));
   }
   if (directionality != RelationStep.DIRECTIONS_DESTINATION
       && (directionality != RelationStep.DIRECTIONS_EITHER || res.isEmpty())) {
     res.addAll(inverseTypeRelNodes.getByDestinationSourceRole(builder2, builder1, role));
   }
   return res;
 }
  @Transactional(propagation = Propagation.SUPPORTS)
  public boolean hasAccessToDevice(AccessKey accessKey, String deviceGuid) {
    Set<AccessKeyPermission> permissions = accessKey.getPermissions();
    Set<String> allowedDevices = new HashSet<>();
    Set<Long> allowedNetworks = new HashSet<>();

    User accessKeyUser = userService.findUserWithNetworks(accessKey.getUser().getId());
    Set<AccessKeyPermission> toRemove = new HashSet<>();

    Device device =
        genericDAO
            .createNamedQuery(Device.class, "Device.findByUUID", of(CacheConfig.refresh()))
            .setParameter("guid", deviceGuid)
            .getSingleResult();

    for (AccessKeyPermission currentPermission : permissions) {
      if (currentPermission.getDeviceGuidsAsSet() == null) {
        allowedDevices.add(null);
      } else {
        if (!currentPermission.getDeviceGuidsAsSet().contains(deviceGuid)) {
          toRemove.add(currentPermission);
        } else {
          allowedDevices.addAll(currentPermission.getDeviceGuidsAsSet());
        }
      }
      if (currentPermission.getNetworkIdsAsSet() == null) {
        allowedNetworks.add(null);
      } else {
        if (device.getNetwork() != null) {
          if (!currentPermission.getNetworkIdsAsSet().contains(device.getNetwork().getId())) {
            toRemove.add(currentPermission);
          } else {
            allowedNetworks.addAll(currentPermission.getNetworkIdsAsSet());
          }
        }
      }
    }
    permissions.removeAll(toRemove);
    boolean hasAccess;
    hasAccess =
        allowedDevices.contains(null)
            ? userService.hasAccessToDevice(accessKeyUser, device.getGuid())
            : allowedDevices.contains(device.getGuid())
                && userService.hasAccessToDevice(accessKeyUser, device.getGuid());

    hasAccess =
        hasAccess && allowedNetworks.contains(null)
            ? accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork())
            : (accessKeyUser.isAdmin() || accessKeyUser.getNetworks().contains(device.getNetwork()))
                && allowedNetworks.contains(device.getNetwork().getId());

    return hasAccess;
  }
Пример #29
0
  @Override
  public void dispatch(String o, final Callback callback) {
    ContainerRoot model = modelService.getCurrentModel().getModel();
    Channel thisChan = (Channel) model.findByPath(context.getPath());
    Set<String> outputPaths = Helper.getRequiredPortsPath(thisChan, context.getNodeName());

    // create a list of destination paths
    Set<String> destPaths = new HashSet<>();
    // process remote paths in order to add _<chanName> to the paths
    // (WsMsgBroker protocol)
    // add processed remote path to dest
    destPaths.addAll(
        channelContext
            .getRemotePortPaths()
            .stream()
            .map(remotePath -> remotePath + "_" + context.getInstanceName())
            .collect(Collectors.toList()));
    // add local connected inputs to dest
    Set<String> providedPaths =
        Helper.getProvidedPortsPath(thisChan, context.getNodeName())
            .stream()
            .map(s -> s + "_" + context.getInstanceName())
            .collect(Collectors.toSet());

    destPaths.addAll(providedPaths);
    // create the array that will store the dest
    String[] dest = new String[destPaths.size()];
    // convert list to array
    destPaths.toArray(dest);

    for (final String outputPath : outputPaths) {
      WSMsgBrokerClient client = this.clients.get(outputPath + "_" + context.getInstanceName());
      if (client != null) {
        if (callback != null) {
          client.send(
              o,
              dest,
              (from, o1) -> {
                CallbackResult result = new CallbackResult();
                result.setPayload(o1.toString());
                result.setOriginChannelPath(context.getPath());
                result.setOriginPortPath(outputPath);
                callback.onSuccess(result);
              });
        } else {
          client.send(o, dest);
        }
      } else {
        createInputClient(outputPath + "_" + context.getInstanceName());
      }
    }
  }
  /*
   * Validate if all imports for a feature are being matched with exports
   */
  private void validateImportsExports(Feature feature) throws Exception {
    Map<Clause, String> imports = new HashMap<Clause, String>();
    Set<Clause> exports = new HashSet<Clause>();
    for (Dependency dependency : feature.getDependencies()) {
      if (featureExports.containsKey(dependency.getName())) {
        exports.addAll(featureExports.get(dependency.getName()));
      } else {
        validateImportsExports(features.get(dependency.getName(), dependency.getVersion()));
      }
    }
    for (String bundle : getBundleLocations(feature)) {
      Manifest meta = manifests.get(bundles.get(bundle));
      exports.addAll(getExports(meta));
      for (Clause clause : getMandatoryImports(meta)) {
        imports.put(clause, bundle);
      }
    }

    // setting up the set of required imports
    Set<Clause> requirements = new HashSet<Clause>();
    requirements.addAll(imports.keySet());

    // now, let's remove requirements whenever we find a matching export for them
    for (Clause element : imports.keySet()) {
      if (systemExports.contains(element.getName())) {
        debug("%s is resolved by a system bundle export or provided bundle", element);
        requirements.remove(element);
        continue;
      }
      for (Clause export : exports) {
        if (matches(element, export)) {
          debug("%s is resolved by export %s", element, export);
          requirements.remove(element);
          continue;
        }
        debug("%s is not resolved by export %s", element, export);
      }
    }

    // if there are any more requirements left here, there's a problem with the feature
    if (!requirements.isEmpty()) {
      warn("Failed to validate feature %s", feature.getName());
      for (Clause entry : requirements) {
        warn("No export found to match %s (imported by %s)", entry, imports.get(entry));
      }
      throw new Exception(
          String.format(
              "%d unresolved imports in feature %s", requirements.size(), feature.getName()));
    }
    info("    OK: imports resolved for %s", feature.getName());
    featureExports.put(feature.getName(), exports);
  }