public PullRequestData addPullRequestData(GHPullRequest pullRequest, AbstractProject project)
      throws IOException {

    ConcurrentHashMap<String, PullRequestData> pullRequestDataMap =
        projectPullRequestDataLookup.get(project);

    if (pullRequestDataMap == null) {
      projectPullRequestDataLookup.putIfAbsent(
          project, new ConcurrentHashMap<String, PullRequestData>());
      pullRequestDataMap = projectPullRequestDataLookup.get(project);
    }

    PullRequestData data = pullRequestDataMap.get(pullRequest.getHtmlUrl().toString());
    if (data == null) {

      String pullRequestUrl = pullRequest.getHtmlUrl().toString();

      PullRequestData newPullRequestData =
          new PullRequestData(pullRequest, ProjectData.getInstance(project, true));

      pullRequestDataMap.putIfAbsent(pullRequestUrl, newPullRequestData);

      data = pullRequestDataMap.get(pullRequestUrl);

      if (data == newPullRequestData) {
        data.save();
      }
    }

    return data;
  }
示例#2
0
 public static void revertBlock(Block block) {
   for (int ID : instances.keySet()) {
     if (instances.get(ID).blockInAffectedBlocks(block)) {
       instances.get(ID).affectedblocks.remove(block);
     }
   }
 }
示例#3
0
        @Override
        public boolean receivedPacket(BinaryXMPPExtension object) {

          JID jid = object.getTransferDescription().getSender();
          LOG.trace("intercepting incoming packet from: " + jid);

          discardIncomingSessionPackets.putIfAbsent(jid, false);

          boolean discard = discardIncomingSessionPackets.get(jid);

          if (discard) {
            LOG.trace("discarding incoming packet: " + object);
            return false;
          }

          blockIncomingSessionPackets.putIfAbsent(jid, false);

          boolean blockIncomingPackets = blockIncomingSessionPackets.get(jid);

          if (blockIncomingPackets || blockAllIncomingSessionPackets) {

            blockedIncomingSessionPackets.putIfAbsent(
                jid, new ConcurrentLinkedQueue<BinaryXMPPExtension>());

            LOG.trace("queuing incoming packet: " + object);
            blockedIncomingSessionPackets.get(jid).add(object);
            return false;
          }

          return true;
        }
  public void processDiscoInfoResponse(JID from, String id, List<Element> identities)
      throws ComponentException {
    String originatingServer = remoteServerInfoRequestIds.get(id);
    if (originatingServer == null) {
      return;
    }
    remoteServerInfoRequestIds.remove(id);
    remoteServerItemsToProcess.put(
        originatingServer, remoteServerItemsToProcess.get(originatingServer) - 1);

    String identityType;
    for (Element identity : identities) {
      identityType = identity.attributeValue("type");
      if (identityType != null && identityType.equals(IDENTITY_TYPE_CHANNELS)) {
        setDiscoveredServer(originatingServer, from.toString());
        sendFederatedRequests(originatingServer);
      }
    }

    if (remoteServerItemsToProcess.get(originatingServer) < 1) {
      if (!discoveredServers.containsKey(originatingServer)) {
        sendRemoteChannelServerNotFoundErrorResponses(originatingServer);
        remoteChannelDiscoveryStatus.put(originatingServer, NO_CHANNEL_SERVER);
        waitingStanzas.remove(originatingServer);
      } else {
        remoteChannelDiscoveryStatus.put(originatingServer, DISCOVERED);
      }
    }
  }
示例#5
0
        @Override
        public boolean sendPacket(TransferDescription description, byte[] payload) {

          JID jid = description.getRecipient();
          LOG.trace("intercepting outgoing packet to: " + jid);

          discardOutgoingSessionPackets.putIfAbsent(jid, false);

          boolean discard = discardOutgoingSessionPackets.get(jid);

          if (discard) {
            LOG.trace("discarding outgoing packet: " + description);
            return false;
          }

          blockOutgoingSessionPackets.putIfAbsent(jid, false);

          boolean blockOutgoingPackets = blockOutgoingSessionPackets.get(jid);

          if (blockOutgoingPackets || blockAllOutgoingSessionPackets) {

            blockedOutgoingSessionPackets.putIfAbsent(
                jid, new ConcurrentLinkedQueue<OutgoingPacketHolder>());

            OutgoingPacketHolder holder = new OutgoingPacketHolder();
            holder.description = description;
            holder.payload = payload;

            LOG.trace("queuing outgoing packet: " + description);
            blockedOutgoingSessionPackets.get(jid).add(holder);
            return false;
          }

          return true;
        }
示例#6
0
 /**
  * Starts the Match from a non tournament table
  *
  * @param userId table owner
  * @param roomId
  * @param tableId
  */
 public void startMatch(UUID userId, UUID roomId, UUID tableId) {
   if (controllers.containsKey(tableId)) {
     controllers.get(tableId).startMatch(userId);
     // chat of start dialog can be killed
     ChatManager.getInstance().destroyChatSession(controllers.get(tableId).getChatId());
   }
 }
 @Override
 public <T> T getService(Class<T> serviceClass) {
   //noinspection unchecked
   T service = (T) myServices.get(serviceClass);
   if (service == null) {
     final Iterator<T> iterator =
         ServiceLoader.load(serviceClass, serviceClass.getClassLoader()).iterator();
     if (!iterator.hasNext()) {
       throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found");
     }
     service = iterator.next();
     if (iterator.hasNext()) {
       throw new ServiceConfigurationError(
           "More than one implementation for "
               + serviceClass
               + " found: "
               + service.getClass()
               + " and "
               + iterator.next().getClass());
     }
     myServices.putIfAbsent(serviceClass, service);
     //noinspection unchecked
     service = (T) myServices.get(serviceClass);
   }
   return service;
 }
  @Override
  public Theme getTheme(String name, Theme.Type type) throws IOException {
    if (name == null) {
      name = defaultTheme;
    }

    if (themeCache != null) {
      ExtendingThemeManagerFactory.ThemeKey key =
          ExtendingThemeManagerFactory.ThemeKey.get(name, type);
      Theme theme = themeCache.get(key);
      if (theme == null) {
        theme = loadTheme(name, type);
        if (theme == null) {
          theme = loadTheme("keycloak", type);
          if (theme == null) {
            theme = loadTheme("base", type);
          }
          log.errorv("Failed to find {0} theme {1}, using built-in themes", type, name);
        } else if (themeCache.putIfAbsent(key, theme) != null) {
          theme = themeCache.get(key);
        }
      }
      return theme;
    } else {
      return loadTheme(name, type);
    }
  }
示例#9
0
  /**
   * 画像を取得し、imageSetterを呼び出す。
   *
   * <p>フェッチに失敗したときは{@link ImageSetter#onException(Exception, ConnectionInfo)}が呼び出される
   *
   * @param imageSetter 画像セッター
   * @param url URL
   * @return キャッシュヒットしたかどうか
   * @throws InterruptedException 割り込まれた。
   */
  public boolean setImageIcon(ImageSetter imageSetter, URL url) throws InterruptedException {
    String urlString = url.toString();
    ImageEntry imageEntry = cachedImages.get(urlString);
    if (imageEntry == null) {
      FetchEntry fetchEntry = fetchEntryMap.get(urlString);
      FetchEntry newEntry = null;
      if (fetchEntry == null) {
        newEntry = getFetchEntry(urlString, url);
        fetchEntry = fetchEntryMap.putIfAbsent(urlString, newEntry);
      }
      if (fetchEntry == null) {
        newEntry.addSetter(imageSetter);
        configuration.addJob(JobQueue.PRIORITY_UI, new ImageFetcher(newEntry));
        return false;
      } else {
        synchronized (fetchEntry) {
          if (fetchEntry.isFinished()) {
            imageEntry = fetchEntry.imageEntry;
          } else {
            fetchEntry.addSetter(imageSetter);
            return false;
          }
        }
      }
    }

    if (imageEntry instanceof ErrorImageEntry) {
      return false;
    } else {
      imageSetter.setImageRecursively(imageEntry.image);
      return true;
    }
  }
示例#10
0
  public static ZKPool getZkPool(String zkAddr) throws PlatformException {
    if (pools.get(zkAddr) == null) {
      synchronized (LOCK) {
        if (pools.get(zkAddr) == null) {
          GenericObjectPoolConfig config = new GenericObjectPoolConfig();
          config.setMaxTotal(total);
          config.setTestOnBorrow(false);
          config.setMinIdle(10);
          int timeOut = 2000;
          if (StringUtils.isBlank(zkAddr)) {
            throw new PlatformException(
                ZkErrorCodeConstants.NO_PARSE_ZK_INFO,
                "zkAddr can not be null,and its format is ip:port");
          }

          if (!StringUtils.isBlank(zkTimeout)) {
            timeOut = Integer.parseInt(zkTimeout);
          }

          ZKPool zkPool = new ZKPool(config, zkAddr, timeOut);
          pools.put(zkAddr, zkPool);
        }
      }
    }

    return pools.get(zkAddr);
  }
 public void _controllerShowSwitches(CommandInterpreter ci) {
   Set<Long> sids = switches.keySet();
   StringBuffer s = new StringBuffer();
   int size = sids.size();
   if (size == 0) {
     ci.print("switches: empty");
     return;
   }
   Iterator<Long> iter = sids.iterator();
   s.append("Total: " + size + " switches\n");
   while (iter.hasNext()) {
     Long sid = iter.next();
     Date date = switches.get(sid).getConnectedDate();
     String switchInstanceName = ((SwitchHandler) switches.get(sid)).getInstanceName();
     s.append(
         switchInstanceName
             + "/"
             + HexString.toHexString(sid)
             + " connected since "
             + date.toString()
             + "\n");
   }
   ci.print(s.toString());
   return;
 }
示例#12
0
 public void run() {
   for (String name : lastLoc.keySet()) {
     Player player = plugin.getServer().getPlayer(name);
     if (player == null) {
       removePlayer(name);
     } else {
       // workaround for bukkit issue
       String prevWorld = lastLoc.get(name).getWorld().getName();
       String curWorld = player.getLocation().getWorld().getName();
       if (prevWorld.equals(curWorld)) {
         if (player.getLocation().distance(lastLoc.get(name)) < 1) {
           continue;
         }
       }
       // if distance between player's current location and stored
       // location is less than 1, this move is not active; if active
       // and ignore vehicle movement is set and player in vehicle,
       // then update location, but don't count this move as active
       addPlayer(player);
       if (!isIgnoreVehicleMovement || !player.isInsideVehicle()) {
         afkBooter.getPlayerActivity().recordActivity(name);
       }
     }
   }
 }
 // TODO
 @GET
 @Path("/jobQueue/{jobID}")
 // @Produces(MediaType.TEXT_XML)
 public Response checkJobQueue(@PathParam("jobID") String jobID) {
   // does job exist?
   System.out.println("[checkJobQueue] queue length = " + jobqueue.size());
   System.out.println("[checkJobQueue] jobID = " + jobID);
   if (jobqueue.containsKey(UUID.fromString(jobID))) {
     System.out.println("Found job ID");
     // if job is not finished yet return 200
     if (jobqueue.get(UUID.fromString(jobID)).getStatus() == SFPGenJob.PROCESSING)
       return Response.status(Status.OK)
           .entity("Still processing - please check back later.")
           .build();
     // if job is finished and SFP has been created
     else {
       // return path to SFP resource
       URI sfp_uri;
       try {
         sfp_uri = new URI("SFP/sfplist/" + jobID);
         // update jobQueue
         SFPGenJob currjob = jobqueue.get(UUID.fromString(jobID));
         currjob.updateStatus(SFPGenJob.GONE);
         jobqueue.put(UUID.fromString(jobID), currjob);
         return Response.status(Status.SEE_OTHER).location(sfp_uri).build();
       } catch (URISyntaxException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       }
       return Response.serverError().build();
     }
   } else return Response.serverError().entity("No such job ID").build();
 }
  /** {@inheritDoc} */
  @Override
  public Broadcaster lookup(Class<? extends Broadcaster> c, Object id, boolean createIfNull) {
    Broadcaster b = store.get(id);
    if (b != null && !c.isAssignableFrom(b.getClass())) {
      String msg =
          "Invalid lookup class " + c.getName() + ". Cached class is: " + b.getClass().getName();
      logger.debug(msg);
      throw new IllegalStateException(msg);
    }

    if ((b == null && createIfNull) || (b != null && b.isDestroyed())) {
      if (b != null) {
        logger.debug("Removing destroyed Broadcaster {}", b.getID());
        store.remove(b.getID(), b);
      }

      Broadcaster nb = store.get(id);
      if (nb == null) {
        nb = createBroadcaster(c, id);
        store.put(id, nb);
      }

      if (nb == null) {
        logger.debug("Added Broadcaster {} . Factory size: {}", id, store.size());
      }

      b = nb;
    }

    return b;
  }
  /**
   * update the distance vectors from the message and refresh the routing table
   *
   * @param msg
   */
  public void updateRouteFromMsg(PA2TCP msg) {
    // payload: 192.168.0.8:1111=323;192.168.0.8:2323 223

    String sourceAddress = msg.sourceAddress;
    if (!neighbors.containsKey(sourceAddress)) {
      return;
    }
    lastHeardTimeTable.put(sourceAddress, new Date().getTime());

    // if the source neighbor is set to close(INFINITE_COST), recover the link
    if (neighbors.get(sourceAddress) == PA2Util.INFINTE_COST) {
      neighbors.put(sourceAddress, neighborsBackup.get(sourceAddress));
    }

    String[] tmp = new String(msg.payloadData).split(";");
    ConcurrentHashMap<String, Double> neighborCostTable = new ConcurrentHashMap<String, Double>();
    for (int i = 0; i < tmp.length; i++) {
      String[] item = tmp[i].split("=");
      if (item[1].startsWith(PA2Util.INFINITY_TAG)) {
        neighborCostTable.put(item[0], PA2Util.INFINTE_COST);
      } else {
        neighborCostTable.put(item[0], Double.valueOf(item[1]));
      }
    }

    bfCostTable.replace(sourceAddress, neighborCostTable);

    if (refreshBFCostTable(sourceAddress)) {
      sendVectorsToNeighbors();
    }
  }
  @Override
  protected void onComplete(Request request, Response response) {
    activeRequestsCounter.dec();
    Long duration =
        computeDurationMillis(START_TIMES_BY_CORRELATION_ID.remove(request.getCorrelationId()));

    if (duration != null && duration.longValue() > 0) {
      allTimesTimer.update(duration, TimeUnit.MILLISECONDS);

      String name = getRouteName(request);
      if (name == null || name.isEmpty()) return;

      ROUTE_TIMERS.get(name).update(duration, TimeUnit.MILLISECONDS);
    }

    Counter responseCounter = COUNTERS_BY_RESPONSE.get(response.getResponseStatus().getCode());

    if (responseCounter == null) {
      responseCounter = metrics.counter(getResponseCounterName(response.getResponseStatus()));
      COUNTERS_BY_RESPONSE.putIfAbsent(response.getResponseStatus().getCode(), responseCounter);
    }

    responseCounter.inc();
    publish(request, response, duration);
  }
示例#17
0
 @Override
 public boolean registerBid(double value, int uniqueUserId, int auctionId) throws RemoteException {
   RMIClientIntf clientIntf = registeredUsers.get(uniqueUserId);
   Bid bid = new Bid(value, uniqueUserId);
   if (!liveAuctionItems.containsKey(auctionId)) {
     clientIntf.callBack("Auction item id does not exist\n");
     return false;
   }
   if (uniqueUserId == liveAuctionItems.get(auctionId).getCreator_id()) {
     clientIntf.callBack("Not able to register bid - bidder is the creator of this auction\n");
     return false;
   } else {
     if (liveAuctionItems.get(auctionId).addBidder(bid)) {
       clientIntf.callBack(
           "Bid registered to auction with id "
               + auctionId
               + " and amount "
               + bid.getBid()
               + "\n");
       return true;
     } else {
       clientIntf.callBack(
           "Bid rejected, user has already placed a bid for this auction, can only place higher bids\n");
       return false;
     }
   }
 }
示例#18
0
 /**
  * update the count of bytes of this stat datanode
  *
  * @param lastPrefix the path of the node that is quotaed
  * @param diff the diff to added to number of bytes
  */
 public void updateBytes(String lastPrefix, long diff) {
   String statNode = Quotas.statPath(lastPrefix);
   DataNode node = nodes.get(statNode);
   StatsTrack updatedStat = null;
   synchronized (node) {
     updatedStat = new StatsTrack(new String(node.data));
     updatedStat.setBytes(updatedStat.getBytes() + diff);
     node.data = updatedStat.toString().getBytes();
   }
   // now check if the bytes match the quota
   String quotaNode = Quotas.quotaPath(lastPrefix);
   node = nodes.get(quotaNode);
   StatsTrack thisStats = null;
   synchronized (node) {
     thisStats = new StatsTrack(new String(node.data));
   }
   if (thisStats.getBytes() < updatedStat.getBytes()) {
     LOG.warn(
         "Quota exceeded: "
             + lastPrefix
             + " bytes="
             + updatedStat.getBytes()
             + " limit="
             + thisStats.getBytes());
   }
 }
示例#19
0
  @Override
  public void notifyResult(AuctionItem item) {
    if (registeredUsers.containsKey(item.getCreator_id())) {
      RMIClientIntf creator = registeredUsers.get(item.getCreator_id());
      try {
        creator.callBack("Your Auction has produced the following results :\n ");
        creator.callBack(item.getResult());
      } catch (RemoteException e) {
        System.out.println("Creator no longer online\n");
      }
    } else {
      System.out.println("Creator id does not exist\n");
    } // Normally an auction with no creator registered should not exist but since this is a
    // simplified implementation
    // We allow bids on auctions with no creator (usually the initialised ones) for testing
    // purposes.
    if (item.numberOfBids() != 0) {
      System.out.println("Notifying bidders");
      Iterator<Bid> it = item.getBidders();
      while (it.hasNext()) {
        Bid bidder = it.next();
        if (registeredUsers.containsKey(bidder.getUserId())) {
          RMIClientIntf client = registeredUsers.get(bidder.getUserId());
          try {
            client.callBack(item.getResult());
          } catch (RemoteException e) {
            System.out.println("Bidder with id " + bidder.getUserId() + " no longer online\n");
          }

        } else {
          System.out.println("User id does not exist\n");
        }
      }
    }
  }
 private void caughtException(Invoker<?> invoker, Invocation invocation, Exception e) {
   String interfaceName = invoker.getUrl().getParameter(Constants.INTERFACE_KEY);
   String method = invocation.getMethodName();
   StringBuffer interfaceConfig = new StringBuffer(Config.DUBBO_REFERENCE_PREFIX);
   interfaceConfig.append(interfaceName);
   StringBuffer methodConfig = new StringBuffer(interfaceConfig.toString());
   methodConfig.append(".").append(method);
   String methodKey = methodConfig.toString();
   int timeout =
       invoker
           .getUrl()
           .getMethodParameter(
               invocation.getMethodName(), Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
   int limit = Config.getBreakLimit(invoker, invocation);
   // 一个异常的有效期,是通过连续出现异常数量乘以每个调用的超时时间,比如你配置连续出现10次异常之后进行服务降级,并且每次服务调用的超时时间是2000ms的话,同时
   // 每个服务重试次数是为2次,那么就是在(2+1)*2000*10
   ExceptionMarker breakMarker =
       new ExceptionMarker(System.currentTimeMillis(), limit * timeout, e);
   if (!breakCounterMap.containsKey(methodKey)) {
     BreakCounter oldValue = breakCounterMap.putIfAbsent(methodKey, new BreakCounter(methodKey));
     // 返回的oldValue为空,表示之前没有创建了赌赢的异常计数器,则需要对它分配一个loop
     if (oldValue == null) {
       nextLoop().register(breakCounterMap.get(methodKey));
     }
   }
   BreakCounter counter = breakCounterMap.get(methodKey);
   counter.addExceptionMarker(breakMarker);
   logger.info(
       "[{}] caught exception for rpc invoke [{}.{}],current exception count [{}]",
       localHost,
       interfaceName,
       method,
       counter.getCurrentExceptionCount());
 }
示例#21
0
  public static ZKPool getZkPool(String zkAddr, Properties poolConfig) throws PlatformException {
    synchronized (LOCK) {
      if (pools.get(zkAddr) == null) {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        try {
          // ConfigUtil.propertiesToProperty(poolConfig, config);
        } catch (Exception e) {
          throw new PlatformException(ZkErrorCodeConstants.CONFIG_ZK_ERROR, "传入的配置错误", e);
        }
        int timeOut = 2000;
        if (StringUtils.isBlank(zkAddr)) {
          throw new PlatformException(
              ZkErrorCodeConstants.NO_PARSE_ZK_INFO,
              "zkAddr can not be null,and its format is ip:port");
        }

        if (!StringUtils.isBlank(zkTimeout)) {
          timeOut = Integer.parseInt(zkTimeout);
        }

        ZKPool zkPool = new ZKPool(config, zkAddr, timeOut);
        pools.put(zkAddr, zkPool);
      }
    }

    return pools.get(zkAddr);
  }
 /**
  * get the next hop to send the data towards the destination.
  *
  * <p>the method first acquire the next hop neighbor from the routing table, then check if the
  * neighbor is in the proxy table, if yes, the next hop is the proxy, otherwise is the neighbor
  *
  * @param dst destinationAddress
  * @return address of next hop
  */
 public String getNextHop(String dst) {
   String neighbor = routingTable.get(dst);
   if (proxyMap.containsKey(neighbor)) {
     return proxyMap.get(neighbor);
   } else {
     return neighbor;
   }
 }
 public void addErrorMsg(int ruleid, String errorMsg) {
   CodeGenMain code = ruleToCodeMap.get(ruleid);
   String prevMsg = errorLog.get(code);
   if (prevMsg != null) {
     errorMsg = prevMsg + "\n" + errorMsg;
   }
   errorLog.put(code, errorMsg);
 }
示例#24
0
 @Override
 public Object get(String key) {
   Object tim = cacheMap.get(makeTimKey(key));
   if (tim != null && System.currentTimeMillis() < Long.parseLong(tim.toString())) {
     return cacheMap.get(makeDataKey(key));
   }
   return null;
 }
 @Override
 public Optional<FundsMutationSubject> findByName(String name) {
   final Integer id = nameUniqueIndex.get(name);
   if (id == null) {
     return Optional.empty();
   }
   return Optional.ofNullable(table.get(id));
 }
示例#26
0
 public EventDefinition getEventDefintion(String name) {
   EventDefinition def = inputEvents.get(name);
   if (def != null) {
     return def;
   } else {
     return outputEvents.get(name);
   }
 }
 private UsersConnectionPool connectByKey(UsersConnectionPool.UserConnectionId key) {
   UsersConnectionPool connectionPool = connectionsPerUser.get(key);
   if (null == connectionPool) {
     connectionsPerUser.putIfAbsent(
         key, new UsersConnectionPool(connectionManager, timeOutTimer, key, properties, config));
     connectionPool = connectionsPerUser.get(key);
   }
   return connectionPool;
 }
示例#28
0
 private static String getNextDefaultIndex(String cacheName) {
   AtomicInteger curInd = defaultIndices.get(cacheName);
   if (curInd == null) {
     defaultIndices.putIfAbsent(cacheName, new AtomicInteger(0));
     curInd = defaultIndices.get(cacheName);
   }
   int i = curInd.getAndIncrement();
   return i == 0 ? "" : Integer.toString(i);
 }
 @Override
 public Promise<Integer, Throwable, Void> getAlbumTrackCount(final Album album) {
   Deferred<Integer, Throwable, Void> deferred = new ADeferredObject<>();
   if (mAlbumTracks.get(album) != null) {
     return deferred.resolve(mAlbumTracks.get(album).size());
   }
   return deferred.reject(
       new Throwable("Couldn't find album " + album.getName() + " in collection"));
 }
 @Override
 public void lock(String name) throws Exception {
   InterProcessMutex lock = locks.get(name);
   if (lock == null) {
     locks.putIfAbsent(name, new InterProcessMutex(curatorFramework, zooKeeperPath + "/" + name));
     lock = locks.get(name);
   }
   lock.acquire();
 }