Пример #1
0
 private ImmutableSetMultimap<String, String> parsePermissions(
     @Nullable String database, Ini.Section rolesSection, Ini.Section groupsSection) {
   ImmutableSetMultimap.Builder<String, String> resultBuilder = ImmutableSetMultimap.builder();
   Multimap<String, String> roleNameToPrivilegeMap = HashMultimap.create();
   List<? extends RoleValidator> validators =
       Lists.newArrayList(
           new ServersAllIsInvalid(),
           new DatabaseMustMatch(),
           new DatabaseRequiredInRole(),
           new ServerNameMustMatch(serverName));
   for (Map.Entry<String, String> entry : rolesSection.entrySet()) {
     String roleName = Strings.nullToEmpty(entry.getKey()).trim();
     String roleValue = Strings.nullToEmpty(entry.getValue()).trim();
     boolean invalidConfiguration = false;
     if (roleName.isEmpty()) {
       LOGGER.warn("Empty role name encountered in {}", resourcePath);
       invalidConfiguration = true;
     }
     if (roleValue.isEmpty()) {
       LOGGER.warn("Empty role value encountered in {}", resourcePath);
       invalidConfiguration = true;
     }
     if (roleNameToPrivilegeMap.containsKey(roleName)) {
       LOGGER.warn("Role {} defined twice in {}", roleName, resourcePath);
     }
     Set<String> roles = PermissionUtils.toPermissionStrings(roleValue);
     if (!invalidConfiguration && roles != null) {
       for (String role : roles) {
         for (RoleValidator validator : validators) {
           validator.validate(database, role.trim());
         }
       }
       roleNameToPrivilegeMap.putAll(roleName, roles);
     }
   }
   Splitter roleSplitter = ROLE_SPLITTER.omitEmptyStrings().trimResults();
   for (Map.Entry<String, String> entry : groupsSection.entrySet()) {
     String groupName = Strings.nullToEmpty(entry.getKey()).trim();
     String groupPrivileges = Strings.nullToEmpty(entry.getValue()).trim();
     Collection<String> resolvedGroupPrivileges = Sets.newHashSet();
     for (String roleName : roleSplitter.split(groupPrivileges)) {
       if (roleNameToPrivilegeMap.containsKey(roleName)) {
         resolvedGroupPrivileges.addAll(roleNameToPrivilegeMap.get(roleName));
       } else {
         LOGGER.warn(
             "Role {} for group {} does not exist in privileges section in {}",
             new Object[] {roleName, groupName, resourcePath});
       }
     }
     resultBuilder.putAll(groupName, resolvedGroupPrivileges);
   }
   return resultBuilder.build();
 }
Пример #2
0
  /**
   * Method returns list of checks
   *
   * @param ast the node to notify for
   * @param astState state of AST.
   * @return list of visitors
   */
  private Collection<Check> getListOfChecks(DetailAST ast, AstState astState) {
    Collection<Check> visitors = null;
    final String tokenType = Utils.getTokenName(ast.getType());

    if (astState == AstState.WITH_COMMENTS) {
      if (tokenToCommentChecks.containsKey(tokenType)) {
        visitors = tokenToCommentChecks.get(tokenType);
      }
    } else {
      if (tokenToOrdinaryChecks.containsKey(tokenType)) {
        visitors = tokenToOrdinaryChecks.get(tokenType);
      }
    }
    return visitors;
  }
Пример #3
0
  @SuppressWarnings("unchecked")
  private static void addRRset(
      Name name, final Message response, Record[] records, final int section) {
    Multimap<RequestType, Record> rrsets = ArrayListMultimap.create();
    for (Record r : records) {
      RequestType type = RequestType.typeOf(r.getType());
      rrsets.get(type).addAll(Collections2.filter(Arrays.asList(records), type));
    }
    Predicate<Record> checkNewRecord =
        new Predicate<Record>() {

          @Override
          public boolean apply(Record input) {
            for (int s = 1; s <= section; s++) {
              if (response.findRecord(input, s)) {
                return false;
              }
            }
            return true;
          }
        };
    if (rrsets.containsKey(RequestType.CNAME)) {
      for (Record cnames : Iterables.filter(rrsets.removeAll(RequestType.CNAME), checkNewRecord)) {
        response.addRecord(cnames, section);
      }
    }
    for (Record sectionRecord : Iterables.filter(rrsets.values(), checkNewRecord)) {
      response.addRecord(sectionRecord, section);
    }
  }
Пример #4
0
 private void checkAssignment(AbstractElement object, String feature) {
   if (assignedFeatures.containsKey(feature)) {
     Collection<AbstractElement> sources = Lists.newArrayList(assignedFeatures.get(feature));
     assignedFeatures.replaceValues(feature, Collections.<AbstractElement>emptyList());
     if (sources != null && sources.equals(Collections.singletonList(object))) {
       if (getNestingLevel() == 0)
         acceptWarning(
             "The assigned value of feature '"
                 + feature
                 + "' will possibly override itself because it is used inside of a loop.",
             object,
             null);
     } else {
       if (sources != null) {
         if (getNestingLevel() == 0)
           for (AbstractElement source : sources)
             acceptWarning(
                 "The possibly assigned value of feature '"
                     + feature
                     + "' may be overridden by subsequent assignments.",
                 source,
                 null);
       }
       if (getNestingLevel() == 0)
         acceptWarning(
             "This assignment will override the possibly assigned value of feature '"
                 + feature
                 + "'.",
             object,
             null);
     }
   } else {
     assignedFeatures.put(feature, object);
   }
 }
Пример #5
0
 @AddCuries
 @Override
 public Response apply(ContainerRequestContext context) {
   logger.fine("Serving dynamic request");
   Multimap<String, Object> paramMap = MultivaluedMapUtils.merge(context.getUriInfo());
   paramMap = resolveCuries(paramMap);
   try (Transaction tx = graphDb.beginTx()) {
     long start = System.currentTimeMillis();
     start = System.currentTimeMillis();
     Result result = cypherUtil.execute(config.getQuery(), paramMap);
     logger.fine((System.currentTimeMillis() - start) + " to execute query");
     start = System.currentTimeMillis();
     TinkerGraph graph = TinkerGraphUtil.resultToGraph(result);
     logger.fine((System.currentTimeMillis() - start) + " to convert to graph");
     start = System.currentTimeMillis();
     for (String key : aspectMap.keySet()) {
       if ("true".equals(getFirst(paramMap.get(key), "false"))) {
         aspectMap.get(key).invoke(graph);
       }
     }
     if (paramMap.containsKey("project")) {
       @SuppressWarnings("unchecked")
       Collection<String> projection =
           (Collection<String>) (Collection<?>) paramMap.get("project");
       TinkerGraphUtil.project(graph, projection);
     }
     ArrayPropertyTransformer.transform(graph);
     tx.success();
     return Response.ok(graph).cacheControl(config.getCacheControl()).build();
   }
 }
Пример #6
0
 private ImmutableList<Path> conditionallyCopy(ImmutableList<Path> roots) throws IOException {
   final Builder<Path> builder = ImmutableList.builder();
   for (Path root : roots) {
     Preconditions.checkArgument(
         root.startsWith(workingDirectory),
         root + " must start with root " + workingDirectory + " from " + roots);
     Preconditions.checkArgument(
         !root.equals(workingDirectory),
         "Cannot deduplicate root directory: " + root + " from " + roots);
     if (!seen.containsKey(root)) {
       seen.put(root, null);
       final Path newRoot = out.resolve(workingDirectory.relativize(root));
       Files.walkFileTree(
           root,
           ImmutableSet.of(FileVisitOption.FOLLOW_LINKS),
           Integer.MAX_VALUE,
           new ConditionalCopyVisitor(newRoot, root, seen, hashFunction));
       builder.add(newRoot);
     } else {
       // Duplicated directories are ok -- multiple files from different libraries
       // can reside in the same directory, but duplicate files should not be seen mulitple times.
     }
   }
   return builder.build();
 }
  /**
   * get a task editor extension for a specific task attribute
   *
   * @param taskRepository
   * @param taskAttribute
   * @return the extension, or null if there is none
   * @see #getTaskEditorExtension(TaskRepository);
   * @since 3.11
   */
  public static AbstractTaskEditorExtension getTaskEditorExtension(
      TaskRepository taskRepository, TaskAttribute taskAttribute) {
    init();
    String input = taskAttribute.getMetaData().getMediaType();
    if (input != null) {
      try {
        MediaType media = MediaType.parse(input);
        Multimap<String, String> parameters = media.parameters();
        if (parameters.containsKey(MARKUP_KEY)) {
          Iterator<String> iter = parameters.get(MARKUP_KEY).iterator();
          String markup = iter.next();
          Iterator<String> baseMarkupIterator = parameters.get(BASE_MARKUP_KEY).iterator();
          String baseMarkup =
              (baseMarkupIterator.hasNext() ? baseMarkupIterator.next() : ""); // $NON-NLS-1$

          SortedSet<RegisteredTaskEditorExtension> extensions = getTaskEditorExtensions();
          for (RegisteredTaskEditorExtension extension : extensions) {
            if (markup.equals(extension.getName()) || baseMarkup.equals(extension.getName())) {
              return extension.getExtension();
            }
          }
        }
      } catch (IllegalArgumentException e) {
        StatusHandler.log(
            new Status(
                IStatus.ERROR,
                TasksUiPlugin.ID_PLUGIN,
                String.format(
                    "Unable to parse markup type for attribute %s", taskAttribute.toString()),
                e)); //$NON-NLS-1$
      }
    }
    return getTaskEditorExtension(taskRepository);
  }
Пример #8
0
 private List<I_C_RfQResponseLine> getActiveRfqResponseLines_ForBPartnerId(final int bpartnerId) {
   final Multimap<Integer, I_C_RfQResponseLine> bpartnerId2activeRfqResponseLines =
       getActiveRfqResponseLines_IndexedByBPartnerId();
   if (!bpartnerId2activeRfqResponseLines.containsKey(bpartnerId)) {
     final List<I_C_RfQResponseLine> rfqResponseLines =
         pmmRfQDAO.retrieveActiveResponseLines(getCtx(), bpartnerId);
     bpartnerId2activeRfqResponseLines.putAll(bpartnerId, rfqResponseLines);
   }
   return ImmutableList.copyOf(bpartnerId2activeRfqResponseLines.get(bpartnerId));
 }
Пример #9
0
  private List<I_C_Flatrate_Term> getC_Flatrate_Terms_ForBPartnerId(final int bpartnerId) {
    final Multimap<Integer, I_C_Flatrate_Term> bpartnerId2contract =
        getC_Flatrate_Terms_IndexedByBPartnerId();
    if (!bpartnerId2contract.containsKey(bpartnerId)) {
      final List<I_C_Flatrate_Term> contracts =
          pmmContractsDAO.retrieveRunningContractsOnDateForBPartner(date, bpartnerId);
      bpartnerId2contract.putAll(bpartnerId, contracts);
    }

    return ImmutableList.copyOf(bpartnerId2contract.get(bpartnerId));
  }
  /**
   * Gets the site links from a feed.
   *
   * @return a map of feed item ID to SiteLinkFromFeed
   */
  private static Map<Long, SiteLinkFromFeed> getSiteLinksFromFeed(
      AdWordsServices adWordsServices, AdWordsSession session, Feed feed) throws Exception {
    // Retrieve the feed's attribute mapping.
    Multimap<Long, Integer> feedMappings =
        getFeedMapping(adWordsServices, session, feed, PLACEHOLDER_SITELINKS);

    Map<Long, SiteLinkFromFeed> feedItems = Maps.newHashMap();

    for (FeedItem feedItem : getFeedItems(adWordsServices, session, feed)) {
      SiteLinkFromFeed siteLinkFromFeed = new SiteLinkFromFeed();

      for (FeedItemAttributeValue attributeValue : feedItem.getAttributeValues()) {
        // Skip this attribute if it hasn't been mapped to a field.
        if (!feedMappings.containsKey(attributeValue.getFeedAttributeId())) {
          continue;
        }

        for (Integer fieldId : feedMappings.get(attributeValue.getFeedAttributeId())) {
          switch (fieldId) {
            case PLACEHOLDER_FIELD_SITELINK_LINK_TEXT:
              siteLinkFromFeed.text = attributeValue.getStringValue();
              break;
            case PLACEHOLDER_FIELD_SITELINK_URL:
              siteLinkFromFeed.url = attributeValue.getStringValue();
              break;
            case PLACEHOLDER_FIELD_FINAL_URLS:
              siteLinkFromFeed.finalUrls = attributeValue.getStringValues();
              break;
            case PLACEHOLDER_FIELD_FINAL_MOBILE_URLS:
              siteLinkFromFeed.finalMobileUrls = attributeValue.getStringValues();
              break;
            case PLACEHOLDER_FIELD_TRACKING_URL_TEMPLATE:
              siteLinkFromFeed.trackingUrlTemplate = attributeValue.getStringValue();
              break;
            case PLACEHOLDER_FIELD_LINE_2_TEXT:
              siteLinkFromFeed.line2 = attributeValue.getStringValue();
              break;
            case PLACEHOLDER_FIELD_LINE_3_TEXT:
              siteLinkFromFeed.line3 = attributeValue.getStringValue();
              break;
            default:
              // Ignore attributes that do not map to a predefined placeholder field.
              break;
          }
        }
      }
      siteLinkFromFeed.scheduling = feedItem.getScheduling();

      feedItems.put(feedItem.getFeedItemId(), siteLinkFromFeed);
    }

    return feedItems;
  }
Пример #11
0
 public boolean isTextFile(String fileName) {
   String extension = Files.getFileExtension(fileName);
   if (mimeFileMap.containsKey(extension)) {
     Collection<String> names = mimeFileMap.get(extension);
     for (String name : names) {
       if (name.contains("text")) {
         return true;
       }
     }
   } else {
     logger.warn("Currently we do not support extension :" + extension);
   }
   return false;
 }
 @Override
 public Multimap<String, String> process(Multimap<String, String> input) {
   String pname = matchRule.getPname();
   if (!input.containsKey(pname)) return input;
   String oldOvalue = input.get(pname).iterator().next();
   String newOvalue = oldOvalue.replaceAll(change.otrim, "");
   String[] split_triples = newOvalue.split(change.osplitTag);
   input.removeAll(pname);
   for (String split_triple : split_triples) {
     input.put(change.pnewName, "\"" + split_triple.trim() + "\"");
   }
   input.removeAll(pname);
   return input;
 }
Пример #13
0
  @Override
  public boolean add(MetabolicReaction rxn) {

    if (rxn == null) return false;

    if (reactionMap.containsKey(rxn.getIdentifier())) return false;

    for (MetabolicParticipant m : rxn.getParticipants()) {
      participantMap.get(m.getMolecule().getIdentifier()).add(rxn);
    }

    reactionMap.put(rxn.getIdentifier(), rxn);

    return super.add(rxn);
  }
Пример #14
0
  private void doAsserts(ModulePrefs prefs) {
    assertEquals("title", prefs.getTitle());
    assertEquals(SPEC_URL.resolve(Uri.parse("title_url")), prefs.getTitleUrl());
    assertEquals("description", prefs.getDescription());
    assertEquals("author", prefs.getAuthor());
    assertEquals("author_email", prefs.getAuthorEmail());
    assertEquals(SPEC_URL.resolve(Uri.parse("screenshot")), prefs.getScreenshot());
    assertEquals(SPEC_URL.resolve(Uri.parse("thumbnail")), prefs.getThumbnail());
    assertEquals("directory_title", prefs.getDirectoryTitle());
    assertEquals(1, prefs.getWidth());
    assertEquals(2, prefs.getHeight());
    assertTrue(prefs.getScrolling());
    assertFalse(prefs.getScaling());
    assertEquals("category", prefs.getCategories().get(0));
    assertEquals("category2", prefs.getCategories().get(1));
    assertEquals("author_affiliation", prefs.getAuthorAffiliation());
    assertEquals("author_location", prefs.getAuthorLocation());
    assertEquals(SPEC_URL.resolve(Uri.parse("author_photo")), prefs.getAuthorPhoto());
    assertEquals(SPEC_URL.resolve(Uri.parse("author_link")), prefs.getAuthorLink());
    assertEquals("author_aboutme", prefs.getAuthorAboutme());
    assertEquals("author_quote", prefs.getAuthorQuote());
    assertTrue(prefs.getShowStats());
    assertTrue(prefs.getShowInDirectory());
    assertTrue(prefs.getSingleton());

    assertTrue(prefs.getFeatures().get("require").getRequired());
    assertFalse(prefs.getFeatures().get("optional").getRequired());

    assertEquals("http://example.org", prefs.getPreloads().get(0).getHref().toString());

    assertEquals(1, prefs.getIcons().size());

    assertEquals(1, prefs.getLocales().size());

    assertEquals(Uri.parse("http://example.org/link"), prefs.getLinks().get("link").getHref());

    OAuthService oauth = prefs.getOAuthSpec().getServices().get("serviceOne");
    assertEquals(Uri.parse("http://www.example.com/request"), oauth.getRequestUrl().url);
    assertEquals(OAuthService.Method.GET, oauth.getRequestUrl().method);
    assertEquals(OAuthService.Method.GET, oauth.getAccessUrl().method);
    assertEquals(OAuthService.Location.HEADER, oauth.getAccessUrl().location);
    assertEquals(Uri.parse("http://www.example.com/authorize"), oauth.getAuthorizationUrl());

    Multimap<String, Node> extra = prefs.getExtraElements();

    assertTrue(extra.containsKey("NavigationItem"));
    assertEquals(1, extra.get("NavigationItem").iterator().next().getChildNodes().getLength());
  }
Пример #15
0
  public void transform() {
    //		@Deprecated final Multimap<ImFunction, ImError> errorPrints = LinkedListMultimap.create();
    final Multimap<ImFunction, ImGetStackTrace> stackTraceGets = LinkedListMultimap.create();
    final Multimap<ImFunction, ImFunctionCall> calls = LinkedListMultimap.create();
    final Multimap<ImFunction, ImFunction> callRelation = LinkedListMultimap.create();
    final List<ImFuncRef> funcRefs = Lists.newArrayList();
    prog.accept(
        new ImProg.DefaultVisitor() {

          @Override
          public void visit(ImGetStackTrace e) {
            stackTraceGets.put(e.getNearestFunc(), e);
          }

          @Override
          public void visit(ImFunctionCall c) {
            calls.put(c.getFunc(), c);
            ImFunction caller = c.getNearestFunc();
            callRelation.put(caller, c.getFunc());
          }

          @Override
          public void visit(ImFuncRef imFuncRef) {
            funcRefs.add(imFuncRef);
          }
        });

    Multimap<ImFunction, ImFunction> callRelationTr = Utils.transientClosure(callRelation);

    // find affected functions
    Set<ImFunction> affectedFuncs = Sets.newHashSet(stackTraceGets.keySet());
    for (Entry<ImFunction, ImFunction> e : callRelationTr.entries()) {
      if (stackTraceGets.containsKey(e.getValue())) {
        affectedFuncs.add(e.getKey());
      }
    }

    addStackTraceParams(affectedFuncs);
    passStacktraceParams(calls, affectedFuncs);
    rewriteFuncRefs(funcRefs, affectedFuncs);
    rewriteErrorStatements(stackTraceGets);
  }
  /** Obtains stop words for a field from the associated {@link StopFilterFactory}, if any. */
  private Collection<CharArraySet> getSolrStopWordsForField(String fieldName) {
    // No need to synchronize here, Carrot2 ensures that instances
    // of this class are not used by multiple threads at a time.
    if (!solrStopWords.containsKey(fieldName)) {
      final Analyzer fieldAnalyzer = core.getLatestSchema().getFieldType(fieldName).getAnalyzer();
      if (fieldAnalyzer instanceof TokenizerChain) {
        final TokenFilterFactory[] filterFactories =
            ((TokenizerChain) fieldAnalyzer).getTokenFilterFactories();
        for (TokenFilterFactory factory : filterFactories) {
          if (factory instanceof StopFilterFactory) {
            // StopFilterFactory holds the stop words in a CharArraySet
            solrStopWords.put(fieldName, ((StopFilterFactory) factory).getStopWords());
          }

          if (factory instanceof CommonGramsFilterFactory) {
            solrStopWords.put(fieldName, ((CommonGramsFilterFactory) factory).getCommonWords());
          }
        }
      }
    }
    return solrStopWords.get(fieldName);
  }
Пример #17
0
  /** @inheritDoc */
  public boolean update(MetabolicReaction reaction) {

    Identifier identifier = reaction.getIdentifier();

    if (reactionMap.containsKey(identifier)) {

      PARTICIPANTS:
      for (MetabolicParticipant p : reaction.getParticipants()) {

        Identifier id = p.getMolecule().getIdentifier();

        boolean found = false;
        for (MetabolicReaction rxn : participantMap.get(id)) {
          if (rxn == reaction) continue PARTICIPANTS; // continue to next participant
        }

        participantMap.put(id, reaction);
      }
      return true;
    }

    return false;
  }
Пример #18
0
 @Subscribe
 public void propogateStateMessage(FMLEvent stateEvent) {
   if (stateEvent instanceof FMLPreInitializationEvent) {
     modObjectList = buildModObjectList();
   }
   for (ModContainer mc : activeModList) {
     activeContainer = mc;
     String modId = mc.getModId();
     stateEvent.applyModContainer(activeContainer());
     FMLLog.log(
         modId, Level.FINEST, "Sending event %s to mod %s", stateEvent.getEventType(), modId);
     eventChannels.get(modId).post(stateEvent);
     FMLLog.log(modId, Level.FINEST, "Sent event %s to mod %s", stateEvent.getEventType(), modId);
     activeContainer = null;
     if (stateEvent instanceof FMLStateEvent) {
       if (!errors.containsKey(modId)) {
         modStates.put(modId, ((FMLStateEvent) stateEvent).getModState());
       } else {
         modStates.put(modId, ModState.ERRORED);
       }
     }
   }
 }
Пример #19
0
  private void assertCompilationResultIs(
      Multimap<Diagnostic.Kind, Pattern> expectedDiagnostics, List<String> testSourceCode)
      throws IOException {
    assertFalse(testSourceCode.isEmpty());

    StringWriter compilerOut = new StringWriter();

    List<String> options =
        ImmutableList.of(
            "-sourcepath",
            tmpDir.getPath(),
            "-d",
            tmpDir.getPath(),
            "-processor",
            AutoValueProcessor.class.getName(),
            "-Xlint");
    javac.getTask(compilerOut, fileManager, diagnosticCollector, options, null, null);
    // This doesn't compile anything but communicates the paths to the JavaFileManager.

    // Convert the strings containing the source code of the test classes into files that we
    // can feed to the compiler.
    List<String> classNames = Lists.newArrayList();
    List<JavaFileObject> sourceFiles = Lists.newArrayList();
    for (String source : testSourceCode) {
      ClassName className = ClassName.extractFromSource(source);
      File dir = new File(tmpDir, className.sourceDirectoryName());
      dir.mkdirs();
      assertTrue(dir.isDirectory()); // True if we just made it, or it was already there.
      String sourceName = className.simpleName + ".java";
      Files.write(source, new File(dir, sourceName), Charset.forName("UTF-8"));
      classNames.add(className.fullName());
      JavaFileObject sourceFile =
          fileManager.getJavaFileForInput(
              StandardLocation.SOURCE_PATH, className.fullName(), Kind.SOURCE);
      sourceFiles.add(sourceFile);
    }
    assertEquals(classNames.size(), sourceFiles.size());

    // Compile the classes.
    JavaCompiler.CompilationTask javacTask =
        javac.getTask(
            compilerOut, fileManager, diagnosticCollector, options, classNames, sourceFiles);
    boolean compiledOk = javacTask.call();

    // Check that there were no compilation errors unless we were expecting there to be.
    // We ignore "notes", typically debugging output from the annotation processor
    // when that is enabled.
    Multimap<Diagnostic.Kind, String> diagnostics = ArrayListMultimap.create();
    for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
      boolean ignore =
          (diagnostic.getKind() == Diagnostic.Kind.NOTE
              || (diagnostic.getKind() == Diagnostic.Kind.WARNING
                  && diagnostic
                      .getMessage(null)
                      .contains("No processor claimed any of these annotations")));
      if (!ignore) {
        diagnostics.put(diagnostic.getKind(), diagnostic.getMessage(null));
      }
    }
    assertEquals(diagnostics.containsKey(Diagnostic.Kind.ERROR), !compiledOk);
    assertEquals(
        "Diagnostic kinds should match: " + diagnostics,
        expectedDiagnostics.keySet(),
        diagnostics.keySet());
    for (Map.Entry<Diagnostic.Kind, Pattern> expectedDiagnostic : expectedDiagnostics.entries()) {
      Collection<String> actualDiagnostics = diagnostics.get(expectedDiagnostic.getKey());
      assertTrue(
          "Diagnostics should contain " + expectedDiagnostic + ": " + diagnostics,
          Iterables.any(actualDiagnostics, Predicates.contains(expectedDiagnostic.getValue())));
    }
  }
Пример #20
0
 public boolean containsKey(String label) {
   return cells.containsKey(label);
 }
Пример #21
0
  public Multimap<Long, BigDecimal> getQuantitiesInWarehouse(
      final Entity warehouse, Multimap<Entity, Entity> productsAndPositions) {
    Multimap<Long, BigDecimal> result = ArrayListMultimap.create();

    String algorithm = warehouse.getStringField(LocationFieldsMFR.ALGORITHM);

    for (Map.Entry<Entity, Entity> productAndPosition : productsAndPositions.entries()) {
      Entity resource = productAndPosition.getValue().getBelongsToField(PositionFields.RESOURCE);

      if (algorithm.equalsIgnoreCase(WarehouseAlgorithm.MANUAL.getStringValue())
          && resource != null) {
        result.put(
            productAndPosition.getKey().getId(),
            resource.getDecimalField(ResourceFields.AVAILABLE_QUANTITY));
      } else {
        Entity additionalCode =
            productAndPosition.getValue().getBelongsToField(PositionFields.ADDITIONAL_CODE);
        BigDecimal conversion =
            productAndPosition.getValue().getDecimalField(PositionFields.CONVERSION);
        Entity reservation =
            reservationsService.getReservationForPosition(productAndPosition.getValue());
        List<Entity> resources = Lists.newArrayList();

        if (additionalCode != null) {
          SearchCriteriaBuilder scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources =
              scb.add(SearchRestrictions.belongsTo(ResourceFields.ADDITIONAL_CODE, additionalCode))
                  .list()
                  .getEntities();

          scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources.addAll(
              scb.add(
                      SearchRestrictions.or(
                          SearchRestrictions.isNull(ResourceFields.ADDITIONAL_CODE),
                          SearchRestrictions.ne("additionalCode.id", additionalCode.getId())))
                  .list()
                  .getEntities());
        }

        if (resources.isEmpty()) {
          SearchCriteriaBuilder scb =
              getSearchCriteriaForResourceForProductAndWarehouse(
                  productAndPosition.getKey(), warehouse);

          if (!StringUtils.isEmpty(
              productAndPosition.getKey().getStringField(ProductFields.ADDITIONAL_UNIT))) {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, conversion));
          } else {
            scb.add(SearchRestrictions.eq(ResourceFields.CONVERSION, BigDecimal.ONE));
          }

          resources = scb.list().getEntities();
        }

        BigDecimal reservedQuantity = BigDecimal.ZERO;
        if (reservation != null) {
          reservedQuantity = reservation.getDecimalField(ReservationFields.QUANTITY);
        }
        if (result.containsKey(productAndPosition.getKey().getId())) {
          BigDecimal currentQuantity =
              result
                  .get(productAndPosition.getKey().getId())
                  .stream()
                  .reduce(reservedQuantity, BigDecimal::add);

          result.put(
              productAndPosition.getKey().getId(),
              (resources
                      .stream()
                      .map(res -> res.getDecimalField(ResourceFields.AVAILABLE_QUANTITY))
                      .reduce(BigDecimal.ZERO, BigDecimal::add))
                  .add(currentQuantity));
        } else {
          result.put(
              productAndPosition.getKey().getId(),
              resources
                  .stream()
                  .map(res -> res.getDecimalField(ResourceFields.AVAILABLE_QUANTITY))
                  .reduce(reservedQuantity, BigDecimal::add));
        }
      }
    }

    return result;
  }
Пример #22
0
  @Override
  public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null) {
      return null;
    }

    if (DEBUG) {
      FMLRelaunchLog.fine("Considering all methods and fields on %s (%s)\n", name, transformedName);
    }
    if (!modifiers.containsKey(name)) {
      return bytes;
    }

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    Collection<Modifier> mods = modifiers.get(name);
    for (Modifier m : mods) {
      if (m.modifyClassVisibility) {
        classNode.access = getFixedAccess(classNode.access, m);
        if (DEBUG) {
          System.out.println(
              String.format(
                  "Class: %s %s -> %s", name, toBinary(m.oldAccess), toBinary(m.newAccess)));
        }
        continue;
      }
      if (m.desc.isEmpty()) {
        for (FieldNode n : classNode.fields) {
          if (n.name.equals(m.name) || m.name.equals("*")) {
            n.access = getFixedAccess(n.access, m);
            if (DEBUG) {
              System.out.println(
                  String.format(
                      "Field: %s.%s %s -> %s",
                      name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)));
            }

            if (!m.name.equals("*")) {
              break;
            }
          }
        }
      } else {
        for (MethodNode n : classNode.methods) {
          if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*")) {
            n.access = getFixedAccess(n.access, m);
            if (DEBUG) {
              System.out.println(
                  String.format(
                      "Method: %s.%s%s %s -> %s",
                      name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)));
            }

            if (!m.name.equals("*")) {
              break;
            }
          }
        }
      }
    }

    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
  }
Пример #23
0
  @Override
  public byte[] transform(String name, String transformedName, byte[] bytes) {
    if (bytes == null) {
      return null;
    }
    boolean makeAllPublic = FMLDeobfuscatingRemapper.INSTANCE.isRemappedClass(name);

    if (DEBUG) {
      FMLRelaunchLog.fine(
          "Considering all methods and fields on %s (%s): %b\n",
          name, transformedName, makeAllPublic);
    }
    if (!makeAllPublic && !modifiers.containsKey(name)) {
      return bytes;
    }

    ClassNode classNode = new ClassNode();
    ClassReader classReader = new ClassReader(bytes);
    classReader.accept(classNode, 0);

    if (makeAllPublic) {
      // class
      Modifier m = new Modifier();
      m.targetAccess = ACC_PUBLIC;
      m.modifyClassVisibility = true;
      modifiers.put(name, m);
      // fields
      m = new Modifier();
      m.targetAccess = ACC_PUBLIC;
      m.name = "*";
      modifiers.put(name, m);
      // methods
      m = new Modifier();
      m.targetAccess = ACC_PUBLIC;
      m.name = "*";
      m.desc = "<dummy>";
      modifiers.put(name, m);
      if (DEBUG) {
        System.out.printf("Injected all public modifiers for %s (%s)\n", name, transformedName);
      }
    }

    Collection<Modifier> mods = modifiers.get(name);
    for (Modifier m : mods) {
      if (m.modifyClassVisibility) {
        classNode.access = getFixedAccess(classNode.access, m);
        if (DEBUG) {
          System.out.println(
              String.format(
                  "Class: %s %s -> %s", name, toBinary(m.oldAccess), toBinary(m.newAccess)));
        }
        continue;
      }
      if (m.desc.isEmpty()) {
        for (FieldNode n : classNode.fields) {
          if (n.name.equals(m.name) || m.name.equals("*")) {
            n.access = getFixedAccess(n.access, m);
            if (DEBUG) {
              System.out.println(
                  String.format(
                      "Field: %s.%s %s -> %s",
                      name, n.name, toBinary(m.oldAccess), toBinary(m.newAccess)));
            }

            if (!m.name.equals("*")) {
              break;
            }
          }
        }
      } else {
        for (MethodNode n : classNode.methods) {
          if ((n.name.equals(m.name) && n.desc.equals(m.desc)) || m.name.equals("*")) {
            n.access = getFixedAccess(n.access, m);
            if (DEBUG) {
              System.out.println(
                  String.format(
                      "Method: %s.%s%s %s -> %s",
                      name, n.name, n.desc, toBinary(m.oldAccess), toBinary(m.newAccess)));
            }

            if (!m.name.equals("*")) {
              break;
            }
          }
        }
      }
    }

    ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
    classNode.accept(writer);
    return writer.toByteArray();
  }
Пример #24
0
  public HttpRemoteTask(
      Session session,
      TaskId taskId,
      String nodeId,
      URI location,
      PlanFragment planFragment,
      Multimap<PlanNodeId, Split> initialSplits,
      OutputBuffers outputBuffers,
      HttpClient httpClient,
      Executor executor,
      ScheduledExecutorService errorScheduledExecutor,
      Duration minErrorDuration,
      Duration refreshMaxWait,
      JsonCodec<TaskInfo> taskInfoCodec,
      JsonCodec<TaskUpdateRequest> taskUpdateRequestCodec,
      SplitCountChangeListener splitCountChangeListener) {
    requireNonNull(session, "session is null");
    requireNonNull(taskId, "taskId is null");
    requireNonNull(nodeId, "nodeId is null");
    requireNonNull(location, "location is null");
    requireNonNull(planFragment, "planFragment1 is null");
    requireNonNull(outputBuffers, "outputBuffers is null");
    requireNonNull(httpClient, "httpClient is null");
    requireNonNull(executor, "executor is null");
    requireNonNull(taskInfoCodec, "taskInfoCodec is null");
    requireNonNull(taskUpdateRequestCodec, "taskUpdateRequestCodec is null");
    requireNonNull(splitCountChangeListener, "splitCountChangeListener is null");

    try (SetThreadName ignored = new SetThreadName("HttpRemoteTask-%s", taskId)) {
      this.taskId = taskId;
      this.session = session;
      this.nodeId = nodeId;
      this.planFragment = planFragment;
      this.outputBuffers.set(outputBuffers);
      this.httpClient = httpClient;
      this.executor = executor;
      this.errorScheduledExecutor = errorScheduledExecutor;
      this.taskInfoCodec = taskInfoCodec;
      this.taskUpdateRequestCodec = taskUpdateRequestCodec;
      this.updateErrorTracker =
          new RequestErrorTracker(
              taskId, location, minErrorDuration, errorScheduledExecutor, "updating task");
      this.getErrorTracker =
          new RequestErrorTracker(
              taskId, location, minErrorDuration, errorScheduledExecutor, "getting info for task");
      this.splitCountChangeListener = splitCountChangeListener;

      for (Entry<PlanNodeId, Split> entry :
          requireNonNull(initialSplits, "initialSplits is null").entries()) {
        ScheduledSplit scheduledSplit =
            new ScheduledSplit(nextSplitId.getAndIncrement(), entry.getValue());
        pendingSplits.put(entry.getKey(), scheduledSplit);
      }
      if (initialSplits.containsKey(planFragment.getPartitionedSource())) {
        pendingSourceSplitCount = initialSplits.get(planFragment.getPartitionedSource()).size();
        fireSplitCountChanged(pendingSourceSplitCount);
      }

      List<BufferInfo> bufferStates =
          outputBuffers
              .getBuffers()
              .keySet()
              .stream()
              .map(outputId -> new BufferInfo(outputId, false, 0, 0, PageBufferInfo.empty()))
              .collect(toImmutableList());

      TaskStats taskStats = new TaskStats(DateTime.now(), null);

      taskInfo =
          new StateMachine<>(
              "task " + taskId,
              executor,
              new TaskInfo(
                  taskId,
                  Optional.empty(),
                  TaskInfo.MIN_VERSION,
                  TaskState.PLANNED,
                  location,
                  DateTime.now(),
                  new SharedBufferInfo(BufferState.OPEN, true, true, 0, 0, 0, 0, bufferStates),
                  ImmutableSet.<PlanNodeId>of(),
                  taskStats,
                  ImmutableList.<ExecutionFailureInfo>of()));

      continuousTaskInfoFetcher = new ContinuousTaskInfoFetcher(refreshMaxWait);
    }
  }
Пример #25
0
 @Override
 public boolean containsKey(final Object key) {
   return _forward.containsKey(key);
 }
Пример #26
0
 public boolean containsHeader(String name) {
   return headers.containsKey(name.toLowerCase());
 }
Пример #27
0
 public boolean containsIdentity(ClassIdentity identity) {
   return m_forest.containsKey(identity);
 }