private SecurityGroup getSecurityGroup(
     final String nodeId, final SecurityGroupExtension securityApi, final String locationId) {
   // Expect to have two security groups on the node: one shared between all nodes in the location,
   // that is cached in sharedGroupCache, and one created by Jclouds that is unique to the node.
   // Relies on customize having been called before. This should be safe because the arguments
   // needed to call this method are not available until post-instance creation.
   SecurityGroup machineUniqueSecurityGroup;
   Tasks.setBlockingDetails("Loading unique security group for node: " + nodeId);
   try {
     machineUniqueSecurityGroup =
         uniqueGroupCache.get(
             nodeId,
             new Callable<SecurityGroup>() {
               @Override
               public SecurityGroup call() throws Exception {
                 SecurityGroup sg =
                     getUniqueSecurityGroupForNodeCachingSharedGroupIfPreviouslyUnknown(
                         nodeId, locationId, securityApi);
                 if (sg == null) {
                   throw new IllegalStateException(
                       "Failed to find machine-unique group on node: " + nodeId);
                 }
                 return sg;
               }
             });
   } catch (UncheckedExecutionException e) {
     throw Throwables.propagate(new Exception(e.getCause()));
   } catch (ExecutionException e) {
     throw Throwables.propagate(new Exception(e.getCause()));
   } finally {
     Tasks.resetBlockingDetails();
   }
   return machineUniqueSecurityGroup;
 }
Ejemplo n.º 2
0
 /**
  * Loads the cache result, computing it if needed by executing the query phase and otherwise
  * deserializing the cached value into the {@link SearchContext#queryResult() context's query
  * result}. The combination of load + compute allows to have a single load operation that will
  * cause other requests with the same key to wait till its loaded an reuse the same cache.
  */
 public void loadIntoContext(
     final ShardSearchRequest request, final SearchContext context, final QueryPhase queryPhase)
     throws Exception {
   assert canCache(request, context);
   Key key = buildKey(request, context);
   Loader loader = new Loader(queryPhase, context, key);
   Value value = cache.get(key, loader);
   if (loader.isLoaded()) {
     key.shard.requestCache().onMiss();
     // see if its the first time we see this reader, and make sure to register a cleanup key
     CleanupKey cleanupKey =
         new CleanupKey(
             context.indexShard(),
             ((DirectoryReader) context.searcher().getIndexReader()).getVersion());
     if (!registeredClosedListeners.containsKey(cleanupKey)) {
       Boolean previous = registeredClosedListeners.putIfAbsent(cleanupKey, Boolean.TRUE);
       if (previous == null) {
         context.searcher().getIndexReader().addReaderClosedListener(cleanupKey);
       }
     }
   } else {
     key.shard.requestCache().onHit();
     // restore the cached query result into the context
     final QuerySearchResult result = context.queryResult();
     result.readFromWithId(context.id(), value.reference.streamInput());
     result.shardTarget(context.shardTarget());
   }
 }
  /**
   * Creates a valid Period based on the given date. E.g. the given date is February 10. 2007, a
   * monthly PeriodType should return February 2007.
   *
   * @param date the date which is contained by the created period.
   * @return the valid Period based on the given date
   */
  public Period createPeriod(final Date date) {
    try {
      return PERIOD_CACHE.get(getCacheKey(date), () -> createPeriod(createCalendarInstance(date)));
    } catch (ExecutionException ignored) {
    }

    return null;
  }
Ejemplo n.º 4
0
 /**
  * 获取缓存
  *
  * @param key
  * @param callable
  * @return
  */
 public static Object get(String key, Callable callable) {
   Object object = null;
   try {
     object = cache.get(key, callable);
   } catch (ExecutionException e) {
     logger.error("cache get error:{}", ExceptionUtils.getMessage(e));
   }
   return object;
 }
Ejemplo n.º 5
0
 public User getUser(final UUID uuid) {
   try {
     return users.get(uuid.toString());
   } catch (ExecutionException ex) {
     return null;
   } catch (UncheckedExecutionException ex) {
     return null;
   }
 }
  @GET
  @Timed
  @ApiOperation(
      value =
          "Get a list of all sources (not more than 5000) that have messages in the current indices. "
              + "The result is cached for 10 seconds.",
      notes =
          "Range: The parameter is in seconds relative to the current time. 86400 means 'in the last day',"
              + "0 is special and means 'across all indices'")
  @ApiResponses(value = {@ApiResponse(code = 400, message = "Invalid range parameter provided.")})
  @Produces(MediaType.APPLICATION_JSON)
  public SourcesList list(
      @ApiParam(
              name = "range",
              value = "Relative timeframe to search in. See method description.",
              required = true)
          @QueryParam("range")
          @Min(0)
          final int range,
      @ApiParam(
              name = "size",
              value = "Maximum size of the result set.",
              required = false,
              defaultValue = "5000")
          @QueryParam("size")
          @DefaultValue("5000")
          @Min(0)
          final int size) {
    final TermsResult sources;
    try {
      sources =
          CACHE.get(
              range,
              new Callable<TermsResult>() {
                @Override
                public TermsResult call() throws Exception {
                  try {
                    return searches.terms("source", size, "*", RelativeRange.create(range));
                  } catch (InvalidRangeParametersException | InvalidRangeFormatException e) {
                    throw new ExecutionException(e);
                  }
                }
              });
    } catch (ExecutionException e) {
      if (e.getCause() instanceof InvalidRangeParametersException) {
        LOG.error("Invalid relative time range: " + range, e);
        throw new BadRequestException("Invalid time range: " + range, e);
      } else {
        LOG.error("Could not calculate list of sources.", e);
        throw new InternalServerErrorException(e);
      }
    }

    return SourcesList.create(
        sources.getTerms().size(), sources.getTerms(), sources.took().millis(), range);
  }
  /**
   * Creates a valid Period based on the given date. E.g. the given date is February 10. 2007, a
   * monthly PeriodType should return February 2007. This method is intended for use in situations
   * where a huge number of of periods will be generated and its desirable to re-use the calendar.
   *
   * @param date the date which is contained by the created period.
   * @param calendar the calendar implementation to use.
   * @return the valid Period based on the given date
   */
  public Period createPeriod(final Date date, final org.hisp.dhis.calendar.Calendar calendar) {
    try {
      return PERIOD_CACHE.get(
          getCacheKey(calendar, date),
          () -> createPeriod(calendar.fromIso(DateTimeUnit.fromJdkDate(date)), calendar));
    } catch (ExecutionException ignored) {
    }

    return null;
  }
Ejemplo n.º 8
0
    @Override
    public String simplify(final String input) {
      try {
        return cache.get(
            input,
            new Callable<String>() {

              @Override
              public String call() throws Exception {
                return simplifier.simplify(input);
              }
            });
      } catch (ExecutionException e) {
        // Can't happen. Simplifier may not throw checked exceptions
        throw new IllegalStateException(e);
      }
    }
Ejemplo n.º 9
0
  public static Object get(String key) {

    Object value = null;
    try {
      value =
          cache.get(
              key,
              new Callable<Object>() {
                @Override
                public Object call() throws Exception {
                  return "from cache :" + key;
                }
              });
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
    return value;
  }
Ejemplo n.º 10
0
 @SuppressWarnings("unchecked")
 @Override
 public T get() {
   Cache<EventDAO, Object> cache = CACHE_MAP.get(getClass());
   assert cache != null;
   try {
     return (T)
         cache.get(
             eventDAO,
             new Callable<Object>() {
               @Override
               public Object call() {
                 return create(eventDAO);
               }
             });
   } catch (ExecutionException e) {
     throw Throwables.propagate(e.getCause());
   }
 }
  @Override
  protected Object doInvoke(Object proxy, final Method method, Object[] args) throws Throwable {
    M methodResolver = null;
    if (methodCaches == null) {
      methodResolver = createMethodResolver(method);
    } else {
      methodResolver =
          methodCaches.get(
              method,
              new Callable<M>() {

                @Override
                public M call() throws Exception {
                  return createMethodResolver(method);
                }
              });
    }
    return invokeMethod(proxy, methodResolver, args);
  }
Ejemplo n.º 12
0
  public SyncProduct createSyncProduct(final I_PMM_Product pmmProduct) {
    final String product_uuid = SyncUUIDs.toUUIDString(pmmProduct);
    try {
      final SyncProduct syncProduct =
          syncProductsCache.get(
              product_uuid,
              new Callable<SyncProduct>() {

                @Override
                public SyncProduct call() throws Exception {
                  return createSyncProductNoCache(pmmProduct);
                }
              });
      return syncProduct.copy();
    } catch (final ExecutionException ex) {
      throw new RuntimeException(
          "Failed creating " + SyncProduct.class + " for " + pmmProduct, ex.getCause());
    }
  }
Ejemplo n.º 13
0
  @Override
  public Channel queryUniqueByName(final String name) {

    try {

      return cacheOnName.get(
          name,
          new Callable<Channel>() {

            @Override
            public Channel call() throws Exception {
              return (Channel)
                  getSqlSession().selectOne(getNamespace().concat(".queryUniqueByName"), name);
            }
          });
    } catch (Exception ignore) {
      getLogger().error("some error occur when access to the cache on name", ignore);
      return null;
    }
  }
Ejemplo n.º 14
0
  /**
   * @param clazz
   * @param methodName
   * @param parameterTypes
   * @return
   * @throws NoSuchMethodException
   */
  public static Method findMethod(
      final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes)
      throws NoSuchMethodException {
    String key = makeFindMethodCacheKey(clazz, methodName, parameterTypes);
    Method method = null;
    try {
      method =
          findMethodCache.get(
              key,
              new Callable<Method>() {

                public Method call() throws Exception {
                  return _findMethod(clazz, methodName, parameterTypes);
                }
              });
    } catch (ExecutionException e) {
      throw new Siren4JRuntimeException(e);
    }
    return method;
  }
 /**
  * Builds a cache for each URL that determines how it should be processed.
  *
  * @return
  */
 private URLProcessor lookupProcessorFromCache(String requestURIWithoutContextPath)
     throws ExecutionException {
   if (urlCache == null) {
     urlCache =
         CacheBuilder.newBuilder()
             .maximumSize(maxCacheElements)
             .concurrencyLevel(maxCacheConcurrency)
             .expireAfterWrite(cacheExpirationSeconds, TimeUnit.SECONDS)
             .build(
                 new CacheLoader<String, URLProcessor>() {
                   public URLProcessor load(String key) throws IOException, ServletException {
                     if (LOG.isDebugEnabled()) {
                       LOG.debug("Loading URL processor into Cache");
                     }
                     return determineURLProcessor(key);
                   }
                 });
   }
   return urlCache.get(requestURIWithoutContextPath);
 }
Ejemplo n.º 16
0
  private ConfigDataHandler getConfigDataHandler(final String app, final String dataId)
      throws ExecutionException {
    return cdhs.get(
        dataId,
        new Callable<ConfigDataHandler>() {

          @Override
          public ConfigDataHandler call() throws Exception {
            return cdhf.getConfigDataHandler(
                dataId,
                new ConfigDataListener() {

                  @Override
                  public void onDataRecieved(String dataId, String data) {
                    parseConfig(dataId, app, data);
                  }
                });
          }
        });
  }
  protected CookieManager getPersonalCookieManager() {
    try {
      if (!ThreadContext.exists()) return defaultManager;

      OrientDbWebSession session = OrientDbWebSession.get();
      session.bind();
      String id = session.getId();
      if (session.isSignedIn()) id = session.getUsername() + '-' + id;
      return cache.get(
          id,
          new Callable<CookieManager>() {

            @Override
            public CookieManager call() throws Exception {
              return new CookieManager();
            }
          });
    } catch (ExecutionException e) {
      throw new IllegalStateException("Cookie Manager should be always calculated");
    }
  }
  private void setSecurityGroupOnTemplate(
      final JcloudsLocation location,
      final Template template,
      final SecurityGroupExtension securityApi) {
    SecurityGroup shared;
    Tasks.setBlockingDetails(
        "Loading security group shared by instances in "
            + template.getLocation()
            + " in app "
            + applicationId);
    try {
      shared =
          sharedGroupCache.get(
              template.getLocation(),
              new Callable<SecurityGroup>() {
                @Override
                public SecurityGroup call() throws Exception {
                  return getOrCreateSharedSecurityGroup(template.getLocation(), securityApi);
                }
              });
    } catch (ExecutionException e) {
      throw Throwables.propagate(new Exception(e.getCause()));
    } finally {
      Tasks.resetBlockingDetails();
    }

    Set<String> originalGroups = template.getOptions().getGroups();
    template.getOptions().securityGroups(shared.getName());
    if (!originalGroups.isEmpty()) {
      LOG.info(
          "Replaced configured security groups: configured={}, replaced with={}",
          originalGroups,
          template.getOptions().getGroups());
    } else {
      LOG.debug(
          "Configured security groups at {} to: {}", location, template.getOptions().getGroups());
    }
  }
 public Object get(final String key, Callable<?> valueLoader) throws ExecutionException {
   shouldNotBeWhiteSpace(key, "key");
   return cache.get(key, valueLoader);
 }