Ejemplo n.º 1
1
  public void turlRetrievalFailed(
      String surl, String reason, String remoteRequestId, String remoteFileId) {
    synchronized (remoteSurlToFileReqIds) {
      Collection<Long> fileRequestSet = remoteSurlToFileReqIds.get(surl);
      if (fileRequestSet == null || fileRequestSet.isEmpty()) {
        LOG.error("turlArrived for unknown SURL = " + surl);
        return;
      }
      for (long id : fileRequestSet) {
        CopyFileRequest cfr = getFileRequest(id);

        try {
          String type = isSourceSrm() && !isSourceLocal() ? "source" : "destination";
          String error = "retrieval of " + type + " TURL failed with error " + reason;
          LOG.error(error);
          cfr.setState(State.FAILED, error);
        } catch (IllegalStateTransition ist) {
          LOG.error("Illegal State Transition : " + ist.getMessage());
        }
        cfr.saveJob();

        remoteSurlToFileReqIds.remove(surl, id);
      }
    }
    remoteFileRequestDone(surl, remoteRequestId, remoteFileId);
  }
  boolean areAbstractSuccessors(
      AbstractState pElement,
      CFAEdge pCfaEdge,
      Collection<? extends AbstractState> pSuccessors,
      ProofChecker wrappedProofChecker)
      throws CPATransferException, InterruptedException {
    ARGState element = (ARGState) pElement;

    assert Iterables.elementsEqual(element.getChildren(), pSuccessors);

    AbstractState wrappedState = element.getWrappedState();
    Multimap<CFAEdge, AbstractState> wrappedSuccessors = HashMultimap.create();
    for (AbstractState absElement : pSuccessors) {
      ARGState successorElem = (ARGState) absElement;
      wrappedSuccessors.put(element.getEdgeToChild(successorElem), successorElem.getWrappedState());
    }

    if (pCfaEdge != null) {
      return wrappedProofChecker.areAbstractSuccessors(
          wrappedState, pCfaEdge, wrappedSuccessors.get(pCfaEdge));
    }

    CFANode loc = AbstractStates.extractLocation(element);
    for (CFAEdge edge : leavingEdges(loc)) {
      if (!wrappedProofChecker.areAbstractSuccessors(
          wrappedState, edge, wrappedSuccessors.get(edge))) {
        return false;
      }
    }
    return true;
  }
  /**
   * Connects cfgNode to the proper CATCH block if target subtree might throw an exception. If there
   * are FINALLY blocks reached before a CATCH, it will make the corresponding entry in finallyMap.
   */
  private void connectToPossibleExceptionHandler(Node cfgNode, Node target) {
    if (mayThrowException(target) && !exceptionHandler.isEmpty()) {
      Node lastJump = cfgNode;
      for (Node handler : exceptionHandler) {
        if (NodeUtil.isFunction(handler)) {
          return;
        }
        Preconditions.checkState(handler.getType() == Token.TRY);
        Node catchBlock = NodeUtil.getCatchBlock(handler);

        if (!NodeUtil.hasCatchHandler(catchBlock)) { // No catch but a FINALLY.
          if (lastJump == cfgNode) {
            createEdge(cfgNode, Branch.ON_EX, handler.getLastChild());
          } else {
            finallyMap.put(lastJump, handler.getLastChild());
          }
        } else { // Has a catch.
          if (lastJump == cfgNode) {
            createEdge(cfgNode, Branch.ON_EX, catchBlock);
            return;
          } else {
            finallyMap.put(lastJump, catchBlock);
          }
        }
        lastJump = handler;
      }
    }
  }
  private void handleContinue(Node node) {
    String label = null;
    if (node.hasChildren()) {
      label = node.getFirstChild().getString();
    }
    Node cur;
    Node lastJump;
    // Similar to handBreak's logic with a few minor variation.
    Node parent = node.getParent();
    for (cur = node, lastJump = node;
        !isContinueTarget(cur, parent, label);
        cur = parent, parent = parent.getParent()) {
      if (cur.getType() == Token.TRY && NodeUtil.hasFinally(cur)) {
        if (lastJump == node) {
          createEdge(lastJump, Branch.UNCOND, cur.getLastChild());
        } else {
          finallyMap.put(lastJump, computeFallThrough(cur.getLastChild()));
        }
        lastJump = cur;
      }
      Preconditions.checkState(parent != null, "Cannot find continue target.");
    }
    Node iter = cur;
    if (cur.getChildCount() == 4) {
      iter = cur.getFirstChild().getNext().getNext();
    }

    if (lastJump == node) {
      createEdge(node, Branch.UNCOND, iter);
    } else {
      finallyMap.put(lastJump, iter);
    }
  }
Ejemplo n.º 5
0
  public GraphIndex(Graph graph) {
    LOG.info("Indexing graph...");

    for (String feedId : graph.getFeedIds()) {
      for (Agency agency : graph.getAgencies(feedId)) {
        Map<String, Agency> agencyForId = agenciesForFeedId.getOrDefault(feedId, new HashMap<>());
        agencyForId.put(agency.getId(), agency);
        this.agenciesForFeedId.put(feedId, agencyForId);
      }
    }

    Collection<Edge> edges = graph.getEdges();
    /* We will keep a separate set of all vertices in case some have the same label.
     * Maybe we should just guarantee unique labels. */
    Set<Vertex> vertices = Sets.newHashSet();
    for (Edge edge : edges) {
      vertices.add(edge.getFromVertex());
      vertices.add(edge.getToVertex());
      if (edge instanceof TablePatternEdge) {
        TablePatternEdge patternEdge = (TablePatternEdge) edge;
        TripPattern pattern = patternEdge.getPattern();
        patternForId.put(pattern.code, pattern);
      }
    }
    for (Vertex vertex : vertices) {
      vertexForId.put(vertex.getLabel(), vertex);
      if (vertex instanceof TransitStop) {
        TransitStop transitStop = (TransitStop) vertex;
        Stop stop = transitStop.getStop();
        stopForId.put(stop.getId(), stop);
        stopVertexForStop.put(stop, transitStop);
        stopsForParentStation.put(stop.getParentStation(), stop);
      }
    }
    for (TransitStop stopVertex : stopVertexForStop.values()) {
      Envelope envelope = new Envelope(stopVertex.getCoordinate());
      stopSpatialIndex.insert(envelope, stopVertex);
    }
    for (TripPattern pattern : patternForId.values()) {
      patternsForFeedId.put(pattern.getFeedId(), pattern);
      patternsForRoute.put(pattern.route, pattern);

      for (Trip trip : pattern.getTrips()) {
        patternForTrip.put(trip, pattern);
        tripForId.put(trip.getId(), trip);
      }
      for (Stop stop : pattern.getStops()) {
        patternsForStop.put(stop, pattern);
      }
    }
    for (Route route : patternsForRoute.asMap().keySet()) {
      routeForId.put(route.getId(), route);
    }

    // Copy these two service indexes from the graph until we have better ones.
    calendarService = graph.getCalendarService();
    serviceCodes = graph.serviceCodes;
    this.graph = graph;
    LOG.info("Done indexing graph.");
  }
Ejemplo n.º 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();
 }
  /**
   * Gets the feed mapping for a feed.
   *
   * @return a multimap from feed attribute ID to the set of field IDs mapped to the attribute
   */
  private static Multimap<Long, Integer> getFeedMapping(
      AdWordsServices adWordsServices, AdWordsSession session, Feed feed, long placeholderType)
      throws Exception {
    // Get the FeedMappingService.
    FeedMappingServiceInterface feedMappingService =
        adWordsServices.get(session, FeedMappingServiceInterface.class);
    String query =
        String.format(
            "SELECT FeedMappingId, AttributeFieldMappings WHERE FeedId = %d and PlaceholderType = %d "
                + "AND Status = 'ENABLED'",
            feed.getId(), placeholderType);

    Multimap<Long, Integer> attributeMappings = HashMultimap.create();
    int offset = 0;
    FeedMappingPage feedMappingPage;

    do {
      String pageQuery = String.format(query + " LIMIT %d, %d", offset, PAGE_SIZE);
      feedMappingPage = feedMappingService.query(pageQuery);
      if (feedMappingPage.getEntries() != null) {
        // Normally, a feed attribute is mapped only to one field. However, you may map it to more
        // than one field if needed.
        for (FeedMapping feedMapping : feedMappingPage.getEntries()) {
          for (AttributeFieldMapping attributeMapping : feedMapping.getAttributeFieldMappings()) {
            attributeMappings.put(
                attributeMapping.getFeedAttributeId(), attributeMapping.getFieldId());
          }
        }
      }
      offset += PAGE_SIZE;
    } while (offset < feedMappingPage.getTotalNumEntries());

    return attributeMappings;
  }
Ejemplo n.º 8
0
  protected void updateSuperProjects(ReviewDb db, Set<Branch.NameKey> updatedBranches)
      throws SubmoduleException {
    try {
      // These (repo/branch) will be updated later with all the given
      // individual submodule subscriptions
      Multimap<Branch.NameKey, SubmoduleSubscription> targets = HashMultimap.create();

      for (Branch.NameKey updatedBranch : updatedBranches) {
        for (SubmoduleSubscription sub : db.submoduleSubscriptions().bySubmodule(updatedBranch)) {
          targets.put(sub.getSuperProject(), sub);
        }
      }
      updatedSubscribers.addAll(updatedBranches);
      // Update subscribers.
      for (Branch.NameKey dest : targets.keySet()) {
        try {
          if (!updatedSubscribers.add(dest)) {
            log.error("Possible circular subscription involving " + dest);
          } else {
            updateGitlinks(db, dest, targets.get(dest));
          }
        } catch (SubmoduleException e) {
          log.warn("Cannot update gitlinks for " + dest, e);
        }
      }
    } catch (OrmException e) {
      logAndThrowSubmoduleException("Cannot read subscription records", e);
    }
  }
  private Multimap<String, String> computeUserParameters() {
    Multimap<String, String> result = LinkedHashMultimap.create();
    for (String key : suite.parameterNames()) {

      // first check if the user has specified values
      Collection<String> userValues = userParameterArguments.get(key);
      if (!userValues.isEmpty()) {
        result.putAll(key, userValues);
        // TODO: type convert 'em to validate?

      } else { // otherwise use the default values from the suite
        Set<String> values = suite.parameterValues(key);
        if (values.isEmpty()) {
          throw new ConfigurationException(
              key
                  + " has no values. "
                  + "Did you forget a -D"
                  + key
                  + "=<value> command line argument?");
        }
        result.putAll(key, values);
      }
    }
    return result;
  }
 private void checkForIssue(Symbol symbol, Multimap<String, Symbol> membersByName) {
   String name = symbol.name();
   for (String knownMemberName : membersByName.keySet()) {
     if (name.equalsIgnoreCase(knownMemberName)) {
       for (Symbol knownMemberSymbol : membersByName.get(knownMemberName)) {
         if (!symbol.equals(knownMemberSymbol)
             && isValidIssueLocation(symbol, knownMemberSymbol)
             && isInvalidMember(symbol, knownMemberSymbol)) {
           addIssue(
               symbol.declaration(),
               "Rename "
                   + getSymbolTypeName(symbol)
                   + " \""
                   + name
                   + "\" "
                   + "to prevent any misunderstanding/clash with "
                   + getSymbolTypeName(knownMemberSymbol)
                   + " \""
                   + knownMemberName
                   + "\" "
                   + "defined "
                   + getDefinitionPlace(symbol, knownMemberSymbol)
                   + ".");
           break;
         }
       }
     }
   }
 }
 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;
 }
Ejemplo n.º 12
0
  private Multimap<Cell, Long> getCellTsPairsToSweep(
      Multimap<Cell, Long> cellTsMappings,
      PeekingIterator<RowResult<Value>> values,
      long sweepTimestamp,
      SweepStrategy sweepStrategy,
      @Output Set<Cell> sentinelsToAdd) {
    Multimap<Cell, Long> cellTsMappingsToSweep = HashMultimap.create();

    Map<Long, Long> startTsToCommitTs = transactionService.get(cellTsMappings.values());
    for (Map.Entry<Cell, Collection<Long>> entry : cellTsMappings.asMap().entrySet()) {
      Cell cell = entry.getKey();
      Collection<Long> timestamps = entry.getValue();
      boolean sweepLastCommitted = isLatestValueEmpty(cell, values);
      Iterable<? extends Long> timestampsToSweep =
          getTimestampsToSweep(
              cell,
              timestamps,
              startTsToCommitTs,
              sentinelsToAdd,
              sweepTimestamp,
              sweepLastCommitted,
              sweepStrategy);
      cellTsMappingsToSweep.putAll(entry.getKey(), timestampsToSweep);
    }
    return cellTsMappingsToSweep;
  }
Ejemplo n.º 13
0
  @Override
  public Collection<SourcedDeviceUpnp> getDeviceList() {
    // horribly unoptimal impl!
    Map<String, SourcedDeviceUpnp> baseXmpp =
        convertToSourcedDimmableLightMap(mXmppConnector.getDeviceList(), Source.XMPP);
    Map<String, SourcedDeviceUpnp> baseLocal =
        convertToSourcedDimmableLightMap(mLocalConnector.getDeviceList(), Source.LOCAL);

    Multimap<String, SourcedDeviceUpnp> multiMap = ArrayListMultimap.create();
    multiMap.putAll(Multimaps.forMap(baseXmpp));
    multiMap.putAll(Multimaps.forMap(baseLocal));

    Iterable<SourcedDeviceUpnp> lights =
        Iterables.transform(
            multiMap.asMap().values(),
            new Function<Collection<SourcedDeviceUpnp>, SourcedDeviceUpnp>() {
              @Override
              public SourcedDeviceUpnp apply(Collection<SourcedDeviceUpnp> lightsCollection) {
                EnumSet<Source> sources = EnumSet.noneOf(Source.class);
                for (SourcedDeviceUpnp light : lightsCollection) {
                  sources.addAll(light.getSources());
                }
                // we make srong assumption here that all sources on list have same state
                // (name/switch state/brightness)
                SourcedDeviceUpnp first = Iterables.getFirst(lightsCollection, null);
                first.setSources(sources);
                return first;
              }
            });

    return Lists.newArrayList(lights);
  }
  public static String paramsListToString(Multimap<String, String> params) {
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (String key : params.keySet()) {
      if (key != null) {
        Collection<String> values = params.get(key);
        for (String value : values) {
          if (value != null) {
            if (first) {
              first = false;
            } else {
              result.append("&");
            }
            try {
              result.append(URLEncoder.encode(key, "UTF-8"));
              result.append("=");
              result.append(URLEncoder.encode(value, "UTF-8"));
            } catch (UnsupportedEncodingException e) {
              Log.e(TAG, "paramsListToString: " + e.getClass() + ": " + e.getLocalizedMessage());
            }
          }
        }
      }
    }

    return result.toString();
  }
 public static String paramsListToString(Map<String, String> params) {
   Multimap<String, String> multimap = HashMultimap.create(params.size(), 1);
   for (String key : params.keySet()) {
     multimap.put(key, params.get(key));
   }
   return paramsListToString(multimap);
 }
Ejemplo n.º 16
0
 private void markAsFragment(final Multimap<TerminalRule, AbstractRule> calledFrom) {
   Set<TerminalRule> _keySet = calledFrom.keySet();
   final Function1<TerminalRule, Boolean> _function =
       (TerminalRule it) -> {
         boolean _isFragment = it.isFragment();
         return Boolean.valueOf((!_isFragment));
       };
   Iterable<TerminalRule> _filter = IterableExtensions.<TerminalRule>filter(_keySet, _function);
   final Function1<TerminalRule, Boolean> _function_1 =
       (TerminalRule it) -> {
         Collection<AbstractRule> _get = calledFrom.get(it);
         return Boolean.valueOf(this.allAreTerminalRules(_get));
       };
   Iterable<TerminalRule> _filter_1 =
       IterableExtensions.<TerminalRule>filter(_filter, _function_1);
   final Function1<TerminalRule, Boolean> _function_2 =
       (TerminalRule it) -> {
         EObject _eContainer = it.eContainer();
         EList<AbstractRule> _hiddenTokens = ((Grammar) _eContainer).getHiddenTokens();
         boolean _contains = _hiddenTokens.contains(it);
         return Boolean.valueOf((!_contains));
       };
   Iterable<TerminalRule> _filter_2 =
       IterableExtensions.<TerminalRule>filter(_filter_1, _function_2);
   final Consumer<TerminalRule> _function_3 =
       (TerminalRule it) -> {
         it.setFragment(true);
       };
   _filter_2.forEach(_function_3);
 }
Ejemplo n.º 17
0
  public String configFile() {
    // Check template URL exists
    String templateUrl = driver.getEntity().getConfig(NginxController.SERVER_CONF_TEMPLATE_URL);
    ResourceUtils.create(this).checkUrlExists(templateUrl);

    // Check SSL configuration
    ProxySslConfig ssl = driver.getEntity().getConfig(NginxController.SSL_CONFIG);
    if (ssl != null
        && Strings.isEmpty(ssl.getCertificateDestination())
        && Strings.isEmpty(ssl.getCertificateSourceUrl())) {
      throw new IllegalStateException(
          "ProxySslConfig can't have a null certificateDestination and null certificateSourceUrl. One or both need to be set");
    }

    // For mapping by URL
    Iterable<UrlMapping> mappings = ((NginxController) driver.getEntity()).getUrlMappings();
    Multimap<String, UrlMapping> mappingsByDomain = LinkedHashMultimap.create();
    for (UrlMapping mapping : mappings) {
      Collection<String> addrs = mapping.getAttribute(UrlMapping.TARGET_ADDRESSES);
      if (addrs != null && addrs.size() > 0) {
        mappingsByDomain.put(mapping.getDomain(), mapping);
      }
    }
    Map<String, Object> substitutions =
        MutableMap.<String, Object>builder()
            .putIfNotNull("ssl", ssl)
            .put("urlMappings", mappings)
            .put("domainMappings", mappingsByDomain)
            .build();

    // Get template contents and process
    String contents = ResourceUtils.create(driver.getEntity()).getResourceAsString(templateUrl);
    return TemplateProcessor.processTemplateContents(contents, driver, substitutions);
  }
Ejemplo n.º 18
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);
   }
 }
Ejemplo n.º 19
0
 private Multimap<String, TaggedRegion> makeTags(Collection<TaggedRegion> tags) {
   Multimap<String, TaggedRegion> ret = ArrayListMultimap.create();
   for (TaggedRegion r : tags) {
     ret.put(r.getName(), r);
   }
   return ret;
 }
Ejemplo n.º 20
0
    public Multimap<Node, Split> computeAssignments(Set<Split> splits) {
      Multimap<Node, Split> assignment = HashMultimap.create();

      for (Split split : splits) {
        List<Node> candidateNodes;
        if (locationAwareScheduling) {
          candidateNodes = selectCandidateNodes(nodeMap.get().get(), split);
        } else {
          candidateNodes = selectRandomNodes(minCandidates);
        }
        checkCondition(
            !candidateNodes.isEmpty(), NO_NODES_AVAILABLE, "No nodes available to run query");

        Node chosen = null;
        int min = Integer.MAX_VALUE;
        for (Node node : candidateNodes) {
          RemoteTask task = taskMap.get(node);
          int currentSplits = (task == null) ? 0 : task.getQueuedSplits();
          int assignedSplits = currentSplits + assignment.get(node).size();
          if (assignedSplits < min && assignedSplits < maxPendingSplitsPerTask) {
            chosen = node;
            min = assignedSplits;
          }
        }
        if (chosen != null) {
          assignment.put(chosen, split);
        }
      }
      return assignment;
    }
Ejemplo n.º 21
0
 @Override
 protected void prepare() {
   super.prepare();
   try {
     classMap = infoService.getMarkClassMap(currentUser);
     root = new DefaultTreeNode("Root", null);
     log.info("Start-------------------------Create Tree------------------------------Start");
     for (String key : classMap.keySet()) {
       TreeNode node = new DefaultTreeNode(key, root);
       Collection<Tclass> entry = classMap.get(key);
       Tclass[] tclasses = new Tclass[entry.size()];
       entry.toArray(tclasses);
       Set<ClassType> typeSet = new HashSet<>();
       for (int i = 0; i < tclasses.length; i++) {
         if (!typeSet.contains(tclasses[i].getType())) {
           typeSet.add(tclasses[i].getType());
           TreeNode childNode = new DefaultTreeNode(tclasses[i].getType().getLabel(), node);
         }
       }
     }
     log.info("End-------------------------Create Tree------------------------------End");
   } catch (Exception ex) {
     log.error("教师的授课班级加载出错", ex);
   }
   items = new ArrayList<>();
   classesForChoose = new ArrayList<>();
 }
Ejemplo n.º 22
0
 private List<Cluster> doPrivilegedLookup(String partitionName, String vmTypeName)
     throws NotEnoughResourcesException {
   if (Partition.DEFAULT_NAME.equals(partitionName)) {
     Iterable<Cluster> authorizedClusters =
         Iterables.filter(
             Clusters.getInstance().listValues(),
             RestrictedTypes.filterPrivilegedWithoutOwner());
     Multimap<VmTypeAvailability, Cluster> sorted = TreeMultimap.create();
     for (Cluster c : authorizedClusters) {
       sorted.put(c.getNodeState().getAvailability(vmTypeName), c);
     }
     if (sorted.isEmpty()) {
       throw new NotEnoughResourcesException(
           "Not enough resources: no availability zone is available in which you have permissions to run instances.");
     } else {
       return Lists.newArrayList(sorted.values());
     }
   } else {
     ServiceConfiguration ccConfig =
         Topology.lookup(ClusterController.class, Partitions.lookupByName(partitionName));
     Cluster cluster = Clusters.lookup(ccConfig);
     if (cluster == null) {
       throw new NotEnoughResourcesException("Can't find cluster " + partitionName);
     }
     if (!RestrictedTypes.filterPrivilegedWithoutOwner().apply(cluster)) {
       throw new NotEnoughResourcesException("Not authorized to use cluster " + partitionName);
     }
     return Lists.newArrayList(cluster);
   }
 }
Ejemplo n.º 23
0
 /** Gets a map of item attribute modifiers, used by ItemSword to increase hit damage. */
 public Multimap getItemAttributeModifiers() {
   Multimap multimap = super.getItemAttributeModifiers();
   multimap.put(
       SharedMonsterAttributes.attackDamage.getAttributeUnlocalizedName(),
       new AttributeModifier(field_111210_e, "Tool modifier", (double) this.damageVsEntity, 0));
   return multimap;
 }
Ejemplo n.º 24
0
  private void applyStart(GridJob job) {

    String fullJobId = job.getFullJobId();
    Collection<JobActor> actors = jobActorMap.get(fullJobId);
    if (actors.isEmpty()) {
      JobActor jobActor = createJobActor(job);
      addJobActor(fullJobId, jobActor);
      actors = jobActorMap.get(fullJobId);
    }

    if (job.getNode() == null) {
      log.warn("No node for job being started: {}", fullJobId);
      return;
    }

    log.debug("Starting job {} on {}", fullJobId, job.getNode().getShortName());

    String nodeName = job.getNode().getShortName();
    if (actors.size() > 1) {
      log.warn("More than one actor for job being started: " + fullJobId);
    }

    JobActor jobActor = actors.iterator().next();

    int i = 0;
    GridJob[] nodeJobs = job.getNode().getSlots();
    for (int s = 0; s < nodeJobs.length; s++) {
      GridJob nodeJob = nodeJobs[s];
      if (nodeJob == null) continue;
      if (!nodeJob.getFullJobId().equals(fullJobId)) continue;

      if (i > 0) {
        jobActor = cloneJobActor(fullJobId);
      }

      PVector endPos = getLatticePos(nodeName, s + "");
      // TODO: random outside location in direction of vector from 0,0,0
      PVector startPos = new PVector(1000, 1000, 1000);
      jobActor.pos = startPos;

      if (tweenChanges) {
        // scale duration to the distance that needs to be traveled
        float distance = jobActor.pos.dist(endPos);
        float duration = (DURATION_JOB_START * distance / DISTANCE_JOB_START) * 0.6f;

        Tween tween =
            new Tween("start_job_" + fullJobId + "#" + i, getTweenDuration(duration))
                .addPVector(jobActor.pos, endPos)
                .call(jobActor, "jobStarted")
                .setEasing(Tween.SINE_OUT)
                .noAutoUpdate();

        jobActor.tweens.add(tween);
      } else {
        jobActor.pos.set(endPos);
      }

      i++;
    }
  }
Ejemplo n.º 25
0
 public Multimap func_111205_h() {
   Multimap var1 = super.func_111205_h();
   var1.put(
       SharedMonsterAttributes.field_111264_e.func_111108_a(),
       new AttributeModifier(field_111210_e, "Tool modifier", (double) this.field_77865_bY, 0));
   return var1;
 }
  // Entry format "revision;member;renamedMethod"
  public void executeOptimizedRenamings(String csvFile) {
    // revision;member;renamed method
    try {
      // grouping entries that share same revision
      Multimap<String, String> groups = ArrayListMultimap.create();
      File revFile = new File(csvFile);
      BufferedReader bufferedReader =
          new BufferedReader(new InputStreamReader(new FileInputStream(revFile.getAbsolutePath())));
      String line;
      while ((line = bufferedReader.readLine()) != null) {
        String entry = line;
        String[] columns = entry.split(";");
        String revDir = columns[0];
        groups.put(revDir, entry);
      }
      bufferedReader.close();

      // executing entries that share same revision
      ArrayList<String> sharedRevisionEntryList = new ArrayList<String>();
      for (String keyRevDir : groups.keySet()) {
        for (String currentEntry : groups.get(keyRevDir)) {
          sharedRevisionEntryList.add(currentEntry);
        }
        executeGroupedEntries(sharedRevisionEntryList);
        sharedRevisionEntryList.clear();
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }
  }
Ejemplo n.º 27
0
  private void handleReturn(Node node) {
    Node lastJump = null;
    for (Iterator<Node> iter = exceptionHandler.iterator(); iter.hasNext(); ) {
      Node curHandler = iter.next();
      if (NodeUtil.isFunction(curHandler)) {
        break;
      }
      if (NodeUtil.hasFinally(curHandler)) {
        if (lastJump == null) {
          createEdge(node, Branch.UNCOND, curHandler.getLastChild());
        } else {
          finallyMap.put(lastJump, computeFallThrough(curHandler.getLastChild()));
        }
        lastJump = curHandler;
      }
    }

    if (node.hasChildren()) {
      connectToPossibleExceptionHandler(node, node.getFirstChild());
    }

    if (lastJump == null) {
      createEdge(node, Branch.UNCOND, null);
    } else {
      finallyMap.put(lastJump, null);
    }
  }
 private void printReferencesReportByRevision(
     ArrayList<String> sharedRevisionEntryList, Multimap<String, String> invokers) {
   try {
     // int references = getNumberOfReferencesByRevision(invokers);
     String header = "";
     String revision = (sharedRevisionEntryList.get(0).split(";"))[0];
     File file = new File("results/parser_references_by_revision_numbers.csv");
     if (!file.exists()) {
       file.createNewFile();
       header = "revision;referencesToRenamedMethods";
     }
     FileWriter fw = new FileWriter(file, true);
     BufferedWriter bw = new BufferedWriter(fw);
     // bw.write(revision+";"+references);
     if (!header.isEmpty()) {
       bw.write(header + "\n");
     }
     bw.write(revision + ";" + invokers.keySet().size());
     if (null != currentMergeResult)
       currentMergeResult.refToRenamedMethodsFromParser = invokers.keySet().size();
     bw.newLine();
     bw.close();
     fw.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
 private int getNumberOfReferencesByRevision(Multimap<String, String> invokers) {
   int references = 0;
   for (String key : invokers.keySet()) {
     references += invokers.get(key).size();
   }
   return references;
 }
  private void processInputs() {
    // Index.
    for (INPUT userOrderedInput : userOrderedInputs) {
      if (userOrderedInput.getProvides().isEmpty()) {
        nonExportingInputs.add(userOrderedInput);
      }
      for (String providedSymbolName : userOrderedInput.getProvides()) {
        exportingInputBySymbolName.put(providedSymbolName, userOrderedInput);
      }
    }
    for (INPUT userOrderedInput : userOrderedInputs) {
      for (String symbolName : userOrderedInput.getRequires()) {
        INPUT importedInput = exportingInputBySymbolName.get(symbolName);
        if (importedInput != null) {
          importedInputByImportingInput.put(userOrderedInput, importedInput);
        }
      }
    }

    // Order.
    // For each input, traverse in user-provided order.
    for (INPUT userOrderedInput : userOrderedInputs) {
      // Traverse the graph starting from this input and record any
      // newly-reached inputs.
      orderInput(userOrderedInput);
    }

    // Free temporary indexes.
    completedInputs.clear();
    importedInputByImportingInput.clear();
  }