Esempio n. 1
0
 @NotNull
 private static List<DiagnosticDescriptor> getSortedDiagnosticDescriptors(
     @NotNull Collection<Diagnostic> diagnostics) {
   LinkedListMultimap<TextRange, Diagnostic> diagnosticsGroupedByRanges =
       LinkedListMultimap.create();
   for (Diagnostic diagnostic : diagnostics) {
     if (!diagnostic.isValid()) continue;
     for (TextRange textRange : diagnostic.getTextRanges()) {
       diagnosticsGroupedByRanges.put(textRange, diagnostic);
     }
   }
   List<DiagnosticDescriptor> diagnosticDescriptors = Lists.newArrayList();
   for (TextRange range : diagnosticsGroupedByRanges.keySet()) {
     diagnosticDescriptors.add(
         new DiagnosticDescriptor(
             range.getStartOffset(), range.getEndOffset(), diagnosticsGroupedByRanges.get(range)));
   }
   Collections.sort(
       diagnosticDescriptors,
       new Comparator<DiagnosticDescriptor>() {
         @Override
         public int compare(@NotNull DiagnosticDescriptor d1, @NotNull DiagnosticDescriptor d2) {
           // Start early -- go first; start at the same offset, the one who end later is the
           // outer, i.e. goes first
           return (d1.start != d2.start) ? d1.start - d2.start : d2.end - d1.end;
         }
       });
   return diagnosticDescriptors;
 }
Esempio n. 2
0
  public Multimap<String, Class<?>> getIncludes() {
    if (includes == null) {
      includes = LinkedListMultimap.create();
    }

    return includes;
  }
Esempio n. 3
0
  public Multimap<String, Class<?>> getExcludes() {
    if (excludes == null) {
      excludes = LinkedListMultimap.create();
    }

    return excludes;
  }
  /**
   * Returns a new instance of this class based on the collection of ad group criteria provided.
   *
   * <p>NOTE: If retrieving existing criteria for use with this method, you must include all of the
   * fields in {@link #REQUIRED_SELECTOR_FIELDS} in your {@link Selector}.
   *
   * @param adGroupId the ID of the ad group
   * @param biddingStrategyConfig the {@link BiddingStrategyConfiguration} for the ad group
   * @param adGroupCriteria the non-null (but possibly empty) list of ad group criteria
   * @throws NullPointerException if any argument is null, any element in {@code adGroupCriteria} is
   *     null, or any required field from {@link #REQUIRED_SELECTOR_FIELDS} is missing from an
   *     element in {@code adGroupCriteria}
   * @throws IllegalArgumentException if {@code adGroupCriteria} does not include the root criterion
   *     of the product partition tree
   */
  public static ProductPartitionTree createAdGroupTree(
      Long adGroupId,
      BiddingStrategyConfiguration biddingStrategyConfig,
      List<AdGroupCriterion> adGroupCriteria) {
    Preconditions.checkNotNull(adGroupId, "Null ad group ID");
    Preconditions.checkNotNull(biddingStrategyConfig, "Null bidding strategy configuration");
    Preconditions.checkNotNull(adGroupCriteria, "Null criteria list");
    if (adGroupCriteria.isEmpty()) {
      return createEmptyAdGroupTree(adGroupId, biddingStrategyConfig);
    }

    ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
    for (AdGroupCriterion adGroupCriterion : adGroupCriteria) {
      Preconditions.checkNotNull(
          adGroupCriterion.getCriterion(), "AdGroupCriterion has a null criterion");
      if (adGroupCriterion instanceof BiddableAdGroupCriterion) {
        BiddableAdGroupCriterion biddableCriterion = (BiddableAdGroupCriterion) adGroupCriterion;
        Preconditions.checkNotNull(
            biddableCriterion.getUserStatus(),
            "User status is null for criterion ID %s",
            biddableCriterion.getCriterion().getId());
        if (UserStatus.REMOVED.equals(biddableCriterion.getUserStatus())) {
          // Skip REMOVED criteria.
          continue;
        }
      }
      if (adGroupCriterion.getCriterion() instanceof ProductPartition) {
        ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
        parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
      }
    }

    return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
  }
 private static Multimap<String, Symbol> sortByName(List<Symbol> members) {
   Multimap<String, Symbol> membersByName = LinkedListMultimap.create();
   for (Symbol member : members) {
     membersByName.put(member.name(), member);
   }
   return membersByName;
 }
 private Query<MongoSensor> applyFilters(Query<MongoSensor> q, Set<PropertyFilter> filters) {
   if (filters == null || filters.isEmpty()) {
     return q;
   }
   Multimap<String, Object> map = LinkedListMultimap.create();
   for (PropertyFilter f : filters) {
     String field = f.getField();
     String value = f.getValue();
     // "123" != 123 && "true" != true in MongoDB...
     if (field != null && value != null) {
       field = MongoUtils.path(MongoSensor.PROPERTIES, field);
       if (isTrue(value)) {
         map.put(field, true);
       } else if (isFalse(value)) {
         map.put(field, false);
       } else if (isNumeric(value)) {
         map.put(field, Double.valueOf(value));
       } else {
         map.put(field, value);
       }
     }
   }
   q.disableValidation();
   map.keySet()
       .stream()
       .forEach(
           (field) -> {
             q.field(field).in(map.get(field));
           });
   return q.enableValidation();
 }
Esempio n. 7
0
 @Override
 public String toString() {
   List<ITextSegment> list = toTokenAndGapList();
   if (list.isEmpty()) return "(empty)";
   Multimap<IHiddenRegion, IEObjectRegion> hiddens = LinkedListMultimap.create();
   List<String> errors = Lists.newArrayList();
   ITextRegionAccess access = list.get(0).getTextRegionAccess();
   TreeIterator<EObject> all = EcoreUtil2.eAll(access.regionForRootEObject().getSemanticElement());
   while (all.hasNext()) {
     EObject element = all.next();
     IEObjectRegion obj = access.regionForEObject(element);
     if (obj == null) continue;
     IHiddenRegion previous = obj.getPreviousHiddenRegion();
     IHiddenRegion next = obj.getNextHiddenRegion();
     if (previous == null)
       errors.add("ERROR: " + EmfFormatter.objPath(element) + " has no leading HiddenRegion.");
     else hiddens.put(previous, obj);
     if (previous != next) {
       if (next == null)
         errors.add("ERROR: " + EmfFormatter.objPath(element) + " has no trailing HiddenRegion.");
       else hiddens.put(next, obj);
     }
   }
   TextRegionListToString result = new TextRegionListToString();
   if (!hideColumnExplanation) {
     result.add("Columns: 1:offset 2:length 3:kind 4: text 5:grammarElement", false);
     result.add("Kind: H=IHiddenRegion S=ISemanticRegion B/E=IEObjectRegion", false);
     result.add("", false);
   }
   for (String error : errors) result.add(error, false);
   int indentation = 0;
   for (ITextSegment region : list) {
     List<IEObjectRegion> previous = Lists.newArrayList();
     List<IEObjectRegion> next = Lists.newArrayList();
     List<String> middle = Lists.newArrayList(toString(region));
     if (region instanceof IHiddenRegion) {
       Collection<IEObjectRegion> found = hiddens.get((IHiddenRegion) region);
       for (IEObjectRegion obj : found) {
         boolean p = obj.getNextHiddenRegion().equals(region);
         boolean n = obj.getPreviousHiddenRegion().equals(region);
         if (p && n) middle.add(EMPTY_TITLE + "Semantic " + toString(obj));
         else if (p) previous.add(obj);
         else if (n) next.add(obj);
       }
       Collections.sort(previous, AstRegionComparator.CHILDREN_FIRST);
       Collections.sort(next, AstRegionComparator.CONTAINER_FIRST);
     }
     for (IEObjectRegion obj : previous) {
       indentation--;
       result.add(indent(indentation) + EOBJECT_END_PADDED + toString(obj));
     }
     String indent = indent(indentation);
     result.add(region, indent + Joiner.on("\n").join(middle).replace("\n", "\n" + indent));
     for (IEObjectRegion obj : next) {
       result.add(indent(indentation) + EOBJECT_BEGIN_PADDED + toString(obj));
       indentation++;
     }
   }
   return result.toString();
 }
Esempio n. 8
0
  @Override
  public void serialize(final MapGenerator gen) {
    final ListMultimap<String, MultipartItem> items = LinkedListMultimap.create();
    for (MultipartItem item : this.getItems()) {
      items.put(item.getName(), item);
    }

    for (final String name : items.keySet()) {
      final List<MultipartItem> values = items.get(name);
      if (values.size() == 1) {
        gen.map(name);
        MultipartItemMapper.serialize(gen, values.get(0));
        gen.end();
      } else {
        gen.array(name);
        values.forEach(
            (item) -> {
              gen.map();
              MultipartItemMapper.serialize(gen, item);
              gen.end();
            });
        gen.end();
      }
    }
  }
  public void upload(
      @Observes ControllerFound event,
      MutableRequest request,
      MultipartConfig config,
      Validator validator) {

    if (!ServletFileUpload.isMultipartContent(request)) {
      return;
    }

    logger.info("Request contains multipart data. Try to parse with commons-upload.");

    final Multiset<String> indexes = HashMultiset.create();
    final Multimap<String, String> params = LinkedListMultimap.create();

    ServletFileUpload uploader = createServletFileUpload(config);

    UploadSizeLimit uploadSizeLimit =
        event.getMethod().getMethod().getAnnotation(UploadSizeLimit.class);
    uploader.setSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.sizeLimit() : config.getSizeLimit());
    uploader.setFileSizeMax(
        uploadSizeLimit != null ? uploadSizeLimit.fileSizeLimit() : config.getFileSizeLimit());
    logger.debug(
        "Setting file sizes: total={}, file={}", uploader.getSizeMax(), uploader.getFileSizeMax());

    try {
      final List<FileItem> items = uploader.parseRequest(request);
      logger.debug(
          "Found {} attributes in the multipart form submission. Parsing them.", items.size());

      for (FileItem item : items) {
        String name = item.getFieldName();
        name = fixIndexedParameters(name, indexes);

        if (item.isFormField()) {
          logger.debug("{} is a field", name);
          params.put(name, getValue(item, request));

        } else if (isNotEmpty(item)) {
          logger.debug("{} is a file", name);
          processFile(item, name, request);

        } else {
          logger.debug("A file field is empty: {}", item.getFieldName());
        }
      }

      for (String paramName : params.keySet()) {
        Collection<String> paramValues = params.get(paramName);
        request.setParameter(paramName, paramValues.toArray(new String[paramValues.size()]));
      }

    } catch (final SizeLimitExceededException e) {
      reportSizeLimitExceeded(e, validator);

    } catch (FileUploadException e) {
      reportFileUploadException(e, validator);
    }
  }
Esempio n. 10
0
 private Multimap<String, IndexAction> makeBulkByType(
     ArrayListMultimap<String, IndexAction> actions) {
   Multimap<String, IndexAction> bulks = LinkedListMultimap.create();
   for (IndexAction action : actions.values()) {
     bulks.put(action.getIndexType(), action);
   }
   return bulks;
 }
Esempio n. 11
0
/**
 * This supports the monitoring of various system properties, such as free memory.
 *
 * <p>Think of it like a logger, except that it can be read from inside the system and it supports
 * tracking max values as well as a list of notes. The use pattern, when monitoring is expensive, is
 * to check isMonitoring before computing anything.
 *
 * <p>TODO: allow registering special case monitoring for complex cases like long queries.
 *
 * @author novalis
 */
public class MonitoringStore {

  private HashSet<String> monitoring = new HashSet<String>();

  private HashMap<String, Long> longs = new HashMap<String, Long>();

  private ListMultimap<String, String> notes = LinkedListMultimap.create();

  public void addNote(String k, String v) {
    if (!monitoring.contains(k)) return;
    notes.put(k, v);
  }

  public void clearNotes(String k) {
    notes.removeAll(k);
  }

  public Long getLong(String k) {
    return longs.get(k);
  }

  public List<String> getNotes(String k) {
    return notes.get(k);
  }

  public boolean isMonitoring(String k) {
    return monitoring.contains(k);
  }

  public void monitor(String k) {
    monitoring.add(k);
  }

  public void setLong(String k, long v) {
    if (!monitoring.contains(k)) return;
    longs.put(k, v);
  }

  public synchronized void setLongMax(String k, long v) {
    if (!monitoring.contains(k)) return;
    Long old = longs.get(k);
    if (old == null || old < v) {
      longs.put(k, v);
    }
  }

  public void stopMonitoring(String k) {
    monitoring.remove(k);
  }

  public void setMonitoring(String key, boolean on) {
    if (on) {
      monitoring.add(key);
    } else {
      monitoring.remove(key);
    }
  }
}
Esempio n. 12
0
 private void setup() {
   mMovies = new ArrayList<Movie>();
   mTmdbIdRowIdMap = LinkedListMultimap.create();
   rowId = new StringBuilder();
   mMovieCollection = new HashSet<String>();
   mWatchedMovies = new HashSet<String>();
   mMovieFavorites = new HashSet<String>();
   mWatchlist = new HashSet<String>();
 }
Esempio n. 13
0
  public void save() {
    Multimap<String, Multimap<String, String>> sections = LinkedListMultimap.create();
    for (Entry<Location, TrackedSign> entry : trackedSigns.entrySet()) {
      final TrackedSign trackedSign = entry.getValue();

      sections.put("sign", trackedSign.save());
    }

    Ini.save(plugin.getConfigFileName("signs.txt"), sections);
  }
  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);
  }
Esempio n. 15
0
  @Before
  public void setUp() throws Exception {
    Multimap<String, String> headers = LinkedListMultimap.<String, String>create();

    headers.put("content-type", "image/png");
    headers.put("filename", "x.png");
    headers.put("x-rftest", "set");
    headers.put("x-rftest", "of");
    headers.put("x-rftest", "values");

    uploadResource = environment.createMock(MockUploadResource.class);
    uploadedFile = new UploadedFile25("form:fileUpload", uploadResource, headers);
  }
  /**
   * @return JSON {@code [{basisViewName: basisViewName1, snapshots: [{id: snapshot1Id, name:
   *     snapshot1Name}, ...]}, ...]}
   */
  @GET
  @Produces(MediaType.APPLICATION_JSON)
  public String getMarketDataSnapshotList() {
    MarketDataSnapshotSearchRequest snapshotSearchRequest = new MarketDataSnapshotSearchRequest();
    snapshotSearchRequest.setIncludeData(false);

    Multimap<String, ManageableMarketDataSnapshot> snapshotsByBasisView =
        LinkedListMultimap.create();
    for (MarketDataSnapshotDocument doc :
        MarketDataSnapshotSearchIterator.iterable(_snapshotMaster, snapshotSearchRequest)) {
      ManageableMarketDataSnapshot snapshot = doc.getSnapshot();
      if (snapshot.getUniqueId() == null) {
        s_logger.warn("Ignoring snapshot with null unique identifier {}", snapshot.getName());
        continue;
      }
      if (StringUtils.isBlank(snapshot.getName())) {
        s_logger.warn("Ignoring snapshot {} with no name", snapshot.getUniqueId());
        continue;
      }
      if (s_guidPattern.matcher(snapshot.getName()).find()) {
        s_logger.debug(
            "Ignoring snapshot which appears to have an auto-generated name: {}",
            snapshot.getName());
        continue;
      }
      String basisViewName =
          snapshot.getBasisViewName() != null ? snapshot.getBasisViewName() : "unknown";
      snapshotsByBasisView.put(basisViewName, snapshot);
    }
    // list of maps for each basis view: {"basisViewName": basisViewName, "snapshots", [...]}
    List<Map<String, Object>> basisViewSnapshotList = new ArrayList<Map<String, Object>>();
    for (String basisViewName : snapshotsByBasisView.keySet()) {
      Collection<ManageableMarketDataSnapshot> viewSnapshots =
          snapshotsByBasisView.get(basisViewName);
      // list of maps containing snapshot IDs and names: {"id", snapshotId, "name", snapshotName}
      List<Map<String, Object>> snapshotsList =
          new ArrayList<Map<String, Object>>(viewSnapshots.size());
      for (ManageableMarketDataSnapshot viewSnapshot : viewSnapshots) {
        // map for a single snapshot: {"id", snapshotId, "name", snapshotName}
        Map<String, Object> snapshotMap =
            ImmutableMap.<String, Object>of(
                ID, viewSnapshot.getUniqueId(), NAME, viewSnapshot.getName());
        snapshotsList.add(snapshotMap);
      }
      basisViewSnapshotList.add(
          ImmutableMap.of(BASIS_VIEW_NAME, basisViewName, SNAPSHOTS, snapshotsList));
    }
    return new JSONArray(basisViewSnapshotList).toString();
  }
  /**
   * Returns a new instance of this class by retrieving the product partitions of the specified ad
   * group. All parameters are required.
   */
  public static ProductPartitionTree createAdGroupTree(
      AdWordsServices services, AdWordsSession session, Long adGroupId)
      throws ApiException, RemoteException {
    // Get the AdGroupCriterionService.
    AdGroupCriterionServiceInterface criterionService =
        services.get(session, AdGroupCriterionServiceInterface.class);

    SelectorBuilder selectorBuilder =
        new SelectorBuilder()
            .fields(
                REQUIRED_SELECTOR_FIELD_ENUMS.toArray(
                    new AdGroupCriterionField[REQUIRED_SELECTOR_FIELD_ENUMS.size()]))
            .equals(AdGroupCriterionField.AdGroupId, adGroupId.toString())
            .equals(AdGroupCriterionField.CriteriaType, "PRODUCT_PARTITION")
            .in(
                AdGroupCriterionField.Status,
                UserStatus.ENABLED.getValue(),
                UserStatus.PAUSED.getValue())
            .limit(PAGE_SIZE);

    AdGroupCriterionPage adGroupCriterionPage;

    // A multimap from each product partition ID to its direct children.
    ListMultimap<Long, AdGroupCriterion> parentIdMap = LinkedListMultimap.create();
    int offset = 0;
    do {
      // Get the next page of results.
      adGroupCriterionPage = criterionService.get(selectorBuilder.build());

      if (adGroupCriterionPage != null && adGroupCriterionPage.getEntries() != null) {
        for (AdGroupCriterion adGroupCriterion : adGroupCriterionPage.getEntries()) {
          ProductPartition partition = (ProductPartition) adGroupCriterion.getCriterion();
          parentIdMap.put(partition.getParentCriterionId(), adGroupCriterion);
        }
        offset += adGroupCriterionPage.getEntries().length;
        selectorBuilder.increaseOffsetBy(PAGE_SIZE);
      }
    } while (offset < adGroupCriterionPage.getTotalNumEntries());

    // Construct the ProductPartitionTree from the parentIdMap.
    if (!parentIdMap.containsKey(null)) {
      Preconditions.checkState(
          parentIdMap.isEmpty(), "No root criterion found in the tree but the tree is not empty");
      return createEmptyAdGroupTree(
          adGroupId, getAdGroupBiddingStrategyConfiguration(services, session, adGroupId));
    }

    return createNonEmptyAdGroupTree(adGroupId, parentIdMap);
  }
Esempio n. 18
0
 /**
  * Constructor
  *
  * @param serializationClassName serialization class to be used
  * @param key key class name
  * @param val value class name
  * @param comparator to be used
  * @param correctComparator (real comparator to be used for correct results)
  * @param testResult expected result
  * @throws IOException
  */
 public TestValuesIterator(
     String serializationClassName,
     Class key,
     Class val,
     TestWithComparator comparator,
     TestWithComparator correctComparator,
     boolean testResult)
     throws IOException {
   this.keyClass = key;
   this.valClass = val;
   this.comparator = getComparator(comparator);
   this.correctComparator =
       (correctComparator == null) ? this.comparator : getComparator(correctComparator);
   this.expectedTestResult = testResult;
   originalData = LinkedListMultimap.create();
   setupConf(serializationClassName);
 }
Esempio n. 19
0
  private Multimap<String, ChildRef> getChildRefs(Container container) {
    Multimap<String, ChildRef> seriesChildRefs = LinkedListMultimap.create();

    ResolvedContent resolvedEpisodes =
        resolver.findByCanonicalUris(
            Iterables.transform(container.getChildRefs(), ChildRef.TO_URI));
    for (Item item : Iterables.filter(resolvedEpisodes.getAllResolvedResults(), Item.class)) {
      if (!item.isActivelyPublished()) {
        continue;
      }

      ChildRef childRef = item.childRef();
      if (item instanceof Episode && ((Episode) item).getSeriesRef() != null) {
        String seriesUri = ((Episode) item).getSeriesRef().getUri();
        seriesChildRefs.put(seriesUri, childRef);
      } else {
        seriesChildRefs.put("none", childRef);
      }
    }
    return seriesChildRefs;
  }
  private void reportExceptions(List<Exception> exceptionList, List<Exception> ignoredExceptions) {
    Multimap<Class<? extends Exception>, Exception> exceptionMultimap = LinkedListMultimap.create();
    for (Exception exception : exceptionList) {
      exceptionMultimap.put(exception.getClass(), exception);
    }
    for (Exception exception : ignoredExceptions) {
      exceptionMultimap.put(exception.getClass(), exception);
    }

    for (Class<? extends Exception> exceptionType : exceptionMultimap.keySet()) {
      TestSetStats testSuiteData = new TestSetStats(false, false);
      for (Exception exception : exceptionMultimap.get(exceptionType)) {
        if (ignoredExceptions.contains(exception)) {
          testSuiteData.testSkipped(testCase(exception, ReportEntryType.skipped));
        } else {
          testSuiteData.testError(testCase(exception, ReportEntryType.error));
        }
      }
      reportTestSuite(exceptionType.getSimpleName(), testSuiteData);
    }
  }
Esempio n. 21
0
  void createGraph(Component tier, InstanceGraph graph, Node root) {
    Node thisNode = null;
    if (root != null) {
      thisNode = graph.getNode(root.name);
    } else {
      thisNode = graph.addNode(tier.getName(), tier);
    }

    if (thisNode == null) return;

    if (root == null) root = thisNode;
    if (thisNode.mark) {
      return;
    }
    graph.mark(thisNode);

    for (Dependency rel : dependencies.get(tier)) {
      Node initiator = graph.addNode(rel.initiator);
      Node upstream = graph.addNode(rel.upstream);
      graph.addLink(initiator, upstream, rel);
      createGraph(rel.upstream, graph, upstream);
    }
  }
  AutoRegisterModules discover() throws InvalidPluginException {
    sysSingletons = Sets.newHashSet();
    sysListen = LinkedListMultimap.create();

    if (sshGen != null) {
      sshGen.setPluginName(pluginName);
    }
    if (httpGen != null) {
      httpGen.setPluginName(pluginName);
    }

    scan();

    if (!sysSingletons.isEmpty() || !sysListen.isEmpty()) {
      sysModule = makeSystemModule();
    }
    if (sshGen != null) {
      sshModule = sshGen.create();
    }
    if (httpGen != null) {
      httpModule = httpGen.create();
    }
    return this;
  }
  @Override
  public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {
      if (roundEnv.processingOver()) {
        return false;
      }

      // collect all exposed properties
      Multimap<TypeElement, Element /*member decls*/> props = LinkedListMultimap.create();

      for (Element exported : roundEnv.getElementsAnnotatedWith(Exported.class)) {
        props.put((TypeElement) exported.getEnclosingElement(), exported);
      }

      Set<String> exposedBeanNames = scanExisting();

      for (Entry<TypeElement, Collection<Element>> e : props.asMap().entrySet()) {
        exposedBeanNames.add(e.getKey().getQualifiedName().toString());

        final Properties javadocs = new Properties();
        for (Element md : e.getValue()) {
          switch (md.getKind()) {
            case FIELD:
            case METHOD:
              String javadoc = getJavadoc(md);
              if (javadoc != null) javadocs.put(md.getSimpleName().toString(), javadoc);
              break;
            default:
              throw new AssertionError("Unexpected element type: " + md);
          }
          // TODO: possibly a proper method signature generation, but it's too tedious
          // way too tedious.
          // private String getSignature(MethodDeclaration m) {
          //    final StringBuilder buf = new StringBuilder(m.getSimpleName());
          //    buf.append('(');
          //    boolean first=true;
          //    for (ParameterDeclaration p : m.getParameters()) {
          //        if(first)   first = false;
          //        else        buf.append(',');
          //        p.getType().accept(new SimpleTypeVisitor() {
          //            public void visitPrimitiveType(PrimitiveType pt) {
          //                buf.append(pt.getKind().toString().toLowerCase());
          //            }
          //            public void visitDeclaredType(DeclaredType dt) {
          //                buf.append(dt.getDeclaration().getQualifiedName());
          //            }
          //
          //            public void visitArrayType(ArrayType at) {
          //                at.getComponentType().accept(this);
          //                buf.append("[]");
          //            }
          //
          //            public void visitTypeVariable(TypeVariable tv) {
          //
          //                // TODO
          //                super.visitTypeVariable(typeVariable);
          //            }
          //
          //            public void visitVoidType(VoidType voidType) {
          //                // TODO
          //                super.visitVoidType(voidType);
          //            }
          //        });
          //    }
          //    buf.append(')');
          //    // TODO
          //    return null;
          // }
        }

        String javadocFile =
            e.getKey().getQualifiedName().toString().replace('.', '/') + ".javadoc";
        notice("Generating " + javadocFile, e.getKey());
        writePropertyFile(javadocs, javadocFile);
      }

      FileObject beans = createResource(STAPLER_BEAN_FILE);
      PrintWriter w = new PrintWriter(new OutputStreamWriter(beans.openOutputStream(), "UTF-8"));
      for (String beanName : exposedBeanNames) w.println(beanName);
      w.close();

    } catch (IOException x) {
      error(x);
    } catch (RuntimeException e) {
      // javac sucks at reporting errors in annotation processors
      e.printStackTrace();
      throw e;
    } catch (Error e) {
      e.printStackTrace();
      throw e;
    }
    return false;
  }
Esempio n. 24
0
 /**
  * Adds a request parameter with the given name and value.
  *
  * @param name the name of the parameter
  * @param value the additional header value. If it contains octet string, it should be encoded
  *     according to RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt)
  */
 public Builder addParam(final String name, final String value) {
   if (params == null) params = LinkedListMultimap.create();
   params.put(name, value);
   return this;
 }
Esempio n. 25
0
 /**
  * Adds a request header with the given name and value. This method allows response headers to
  * have multiple values.
  *
  * @param name the name of the header
  * @param value the additional header value. If it contains octet string, it should be encoded
  *     according to RFC 2047 (http://www.ietf.org/rfc/rfc2047.txt)
  */
 public Builder addHeader(final String name, final String value) {
   if (headers == null) headers = LinkedListMultimap.create();
   headers.put(name, value);
   return this;
 }
public final class LogCommitTransaction<T> {

  private final Eventloop eventloop;
  private final LogManager<T> logManager;
  private final String log;
  private final Map<String, LogPosition> oldPositions;

  private final ListMultimap<Aggregation, AggregationChunk.NewChunk> newChunks =
      LinkedListMultimap.create();
  private final Map<String, LogPosition> newPositions = new LinkedHashMap<>();

  private int commitCallbacks;
  private int logCallbacks;

  private final LogCommitCallback callback;

  private static final Logger logger = LoggerFactory.getLogger(LogCommitTransaction.class);

  public LogCommitTransaction(
      Eventloop eventloop,
      LogManager<T> logManager,
      String log,
      Map<String, LogPosition> oldPositions,
      LogCommitCallback callback) {
    this.eventloop = eventloop;
    this.logManager = logManager;
    this.log = log;
    this.oldPositions = new LinkedHashMap<>(oldPositions);
    this.callback = callback;
  }

  public CommitCallback addCommitCallback() {
    commitCallbacks++;
    logger.trace(
        "Added commit callback. Commit callbacks: {}. Log callbacks: {}",
        commitCallbacks,
        logCallbacks);
    return new CommitCallback() {
      @Override
      public void onCommit(Multimap<Aggregation, AggregationChunk.NewChunk> resultChunks) {
        newChunks.putAll(resultChunks);
        commitCallbacks--;
        logger.trace(
            "Commit callback onCommit called. Commit callbacks: {}. Log callbacks: {}",
            commitCallbacks,
            logCallbacks);
        tryCommit();
      }

      @Override
      public void onException(Exception exception) {
        logger.error(
            "Commit callback onException called. Commit callbacks: {}. Log callbacks: {}",
            commitCallbacks,
            logCallbacks,
            exception);
      }
    };
  }

  public ResultCallback<Map<String, LogPosition>> addLogCallback() {
    logCallbacks++;
    logger.trace(
        "Added log callback. Commit callbacks: {}. Log callbacks: {}",
        commitCallbacks,
        logCallbacks);
    return new ResultCallback<Map<String, LogPosition>>() {
      @Override
      public void onResult(Map<String, LogPosition> resultPositions) {
        logCallbacks--;
        logger.trace(
            "Log callback onResult called. Commit callbacks: {}. Log callbacks: {}",
            commitCallbacks,
            logCallbacks);
        newPositions.putAll(resultPositions);
        tryCommit();
      }

      @Override
      public void onException(Exception exception) {
        logger.error(
            "Log callback onException called. Commit callbacks: {}. Log callbacks: {}",
            commitCallbacks,
            logCallbacks,
            exception);
        callback.onException(exception);
      }
    };
  }

  private void tryCommit() {
    logger.trace("tryCommit called.");
    if (commitCallbacks != 0 || logCallbacks != 0) {
      logger.trace(
          "Exiting tryCommit. Commit callbacks: {}. Log callbacks: {}",
          commitCallbacks,
          logCallbacks);
      return;
    }
    eventloop.post(
        new Runnable() {
          @Override
          public void run() {
            callback.onCommit(log, oldPositions, newPositions, newChunks);
          }
        });
  }

  @SuppressWarnings("unchecked")
  public StreamProducer<T> logProducer(final String logPartition, final LogPosition logPosition) {
    final ResultCallback<Map<String, LogPosition>> logCallback = addLogCallback();
    return logManager.producer(
        logPartition,
        logPosition.getLogFile(),
        logPosition.getPosition(),
        new ResultCallback<LogPosition>() {
          @Override
          public void onResult(LogPosition result) {
            Map<String, LogPosition> map = new HashMap<>();
            map.put(logPartition, result);
            logCallback.onResult(map);
          }

          @Override
          public void onException(Exception exception) {
            logCallback.onException(exception);
            logger.error(
                "Log producer exception. Log partition: {}. Log position: {}",
                logPartition,
                logPosition);
          }
        });
  }
}
Esempio n. 27
0
public class DefaultTestLauncher extends AbstractLongRunningOperation<DefaultTestLauncher>
    implements TestLauncher {

  private final AsyncConsumerActionExecutor connection;
  private final Set<TestOperationDescriptor> operationDescriptors =
      new LinkedHashSet<TestOperationDescriptor>();
  private final Set<String> testClassNames = new LinkedHashSet<String>();

  private final Multimap<String, String> testMethods = LinkedListMultimap.create();

  public DefaultTestLauncher(
      AsyncConsumerActionExecutor connection, ConnectionParameters parameters) {
    super(parameters);
    operationParamsBuilder.setTasks(Collections.<String>emptyList());
    operationParamsBuilder.setEntryPoint("TestLauncher API");
    this.connection = connection;
  }

  @Override
  protected DefaultTestLauncher getThis() {
    return this;
  }

  @Override
  public TestLauncher withTests(TestOperationDescriptor... testDescriptors) {
    operationDescriptors.addAll(Arrays.asList(testDescriptors));
    return this;
  }

  @Override
  public TestLauncher withTests(Iterable<? extends TestOperationDescriptor> descriptors) {
    operationDescriptors.addAll(CollectionUtils.toList(descriptors));
    return this;
  }

  @Override
  public TestLauncher withJvmTestClasses(String... classNames) {
    testClassNames.addAll(CollectionUtils.toList(classNames));
    return this;
  }

  @Override
  public TestLauncher withJvmTestClasses(Iterable<String> testClasses) {
    testClassNames.addAll(CollectionUtils.toList(testClasses));
    return this;
  }

  @Override
  public TestLauncher withJvmTestMethods(String testClass, String... methods) {
    withJvmTestMethods(testClass, CollectionUtils.toList(methods));
    return this;
  }

  @Override
  public TestLauncher withJvmTestMethods(String testClass, Iterable<String> methods) {
    this.testMethods.putAll(testClass, methods);
    return this;
  }

  public void run() {
    BlockingResultHandler<Void> handler = new BlockingResultHandler<Void>(Void.class);
    run(handler);
    handler.getResult();
  }

  public void run(final ResultHandler<? super Void> handler) {
    if (operationDescriptors.isEmpty() && testClassNames.isEmpty() && testMethods.isEmpty()) {
      throw new TestExecutionException("No test declared for execution.");
    }
    final ConsumerOperationParameters operationParameters =
        operationParamsBuilder.setParameters(connectionParameters).build();
    final TestExecutionRequest testExecutionRequest =
        new TestExecutionRequest(
            operationDescriptors,
            ImmutableList.copyOf(testClassNames),
            ImmutableMultimap.copyOf(testMethods));
    connection.run(
        new ConsumerAction<Void>() {
          public ConsumerOperationParameters getParameters() {
            return operationParameters;
          }

          public Void run(ConsumerConnection connection) {
            connection.runTests(testExecutionRequest, getParameters());
            return null;
          }
        },
        new ResultHandlerAdapter(handler));
  }

  private class ResultHandlerAdapter
      extends org.gradle.tooling.internal.consumer.ResultHandlerAdapter<Void> {
    public ResultHandlerAdapter(ResultHandler<? super Void> handler) {
      super(handler);
    }

    @Override
    protected String connectionFailureMessage(Throwable failure) {
      return String.format("Could not execute tests using %s.", connection.getDisplayName());
    }
  }
}
Esempio n. 28
0
 public Collection<Dependency> getDependencies() {
   return dependencies.values();
 }
Esempio n. 29
0
 public Service add(Dependency dep) {
   dependencies.put(dep.initiator, dep);
   return this;
 }
Esempio n. 30
0
 public Service(String name) {
   super(name);
   components = new LinkedHashMap<String, Component>();
   dependencies = LinkedListMultimap.create();
 }