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;
 }
  @Override
  public void write(E entity) {
    Preconditions.checkState(
        state.equals(ReaderWriterState.OPEN), "Attempt to write to a writer in state:%s", state);

    reusedKey.reuseFor(entity);

    DatasetWriter<E> writer = cachedWriters.getIfPresent(reusedKey);
    if (writer == null) {
      // avoid checking in every whether the entity belongs in the view by only
      // checking when a new writer is created
      Preconditions.checkArgument(
          view.includes(entity), "View %s does not include entity %s", view, entity);
      // get a new key because it is stored in the cache
      StorageKey key = StorageKey.copy(reusedKey);
      try {
        writer = cachedWriters.getUnchecked(key);
      } catch (UncheckedExecutionException ex) {
        throw new IllegalArgumentException(
            "Problem creating view for entity: " + entity, ex.getCause());
      }
    }

    writer.write(entity);
  }
 /**
  * Flattens a class's type hierarchy into a set of {@code Class} objects including all
  * superclasses (transitively) and all interfaces implemented by these superclasses.
  */
 @VisibleForTesting
 static ImmutableSet<Class<?>> flattenHierarchy(Class<?> concreteClass) {
   try {
     return flattenHierarchyCache.getUnchecked(concreteClass);
   } catch (UncheckedExecutionException e) {
     throw Throwables.propagate(e.getCause());
   }
 }
 @Override
 public NodeInitializer getNodeInitializer(NodeInitializerContext<?> nodeInitializerContext) {
   try {
     return cache.get(nodeInitializerContext);
   } catch (ExecutionException e) {
     throw UncheckedException.throwAsUncheckedException(e);
   } catch (UncheckedExecutionException e) {
     throw UncheckedException.throwAsUncheckedException(e.getCause());
   }
 }
 /**
  * Creates a new rule source instance to be applied to a model element.
  *
  * @throws InvalidModelRuleDeclarationException On badly formed rule source class.
  */
 public <T> ExtractedRuleSource<T> extract(Class<T> source)
     throws InvalidModelRuleDeclarationException {
   try {
     return cache.get(source).newInstance(source);
   } catch (ExecutionException e) {
     throw UncheckedException.throwAsUncheckedException(e);
   } catch (UncheckedExecutionException e) {
     throw UncheckedException.throwAsUncheckedException(e.getCause());
   }
 }
 @Override
 public T get() {
   try {
     return cache.get("FOO").orNull();
   } catch (UncheckedExecutionException e) {
     throw propagate(e.getCause());
   } catch (ExecutionException e) {
     throw propagate(e.getCause());
   }
 }
 @Override
 public <T extends Project> Job<T> get(String id) throws Exception {
   logger.debug("CACHED_JS: get " + id);
   try {
     return cache.get(id).get();
   } catch (ExecutionException ex) {
     if (ex.getCause() instanceof NotInCachedException) {
       return null;
     } else {
       throw ex;
     }
   } catch (UncheckedExecutionException ex) {
     logger.fatal("CachedJobStorage", ex.getCause());
     throw ex;
   }
 }
 public BugzillaRestConfiguration getRepositoryConfiguration(TaskRepository repository)
     throws CoreException {
   if (clientCache.getIfPresent(new RepositoryKey(repository)) == null) {
     getClient(repository);
   }
   try {
     Optional<BugzillaRestConfiguration> configurationOptional =
         configurationCache.get(new RepositoryKey(repository));
     return configurationOptional.isPresent() ? configurationOptional.get() : null;
   } catch (UncheckedExecutionException e) {
     throw new CoreException(
         new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
   } catch (ExecutionException e) {
     throw new CoreException(
         new Status(IStatus.ERROR, BugzillaRestCore.ID_PLUGIN, e.getMessage(), e));
   }
 }
示例#9
0
 @SuppressWarnings("unchecked")
 @Override
 public <T> T get(Object key, final Callable<T> valueLoader) {
   try {
     return (T)
         fromStoreValue(
             this.cache.get(
                 key,
                 new Callable<Object>() {
                   @Override
                   public Object call() throws Exception {
                     return toStoreValue(valueLoader.call());
                   }
                 }));
   } catch (ExecutionException ex) {
     throw new ValueRetrievalException(key, valueLoader, ex.getCause());
   } catch (UncheckedExecutionException ex) {
     throw new ValueRetrievalException(key, valueLoader, ex.getCause());
   }
 }
  @Override
  public NodeMetadata apply(VirtualMachine from) {
    // convert the result object to a jclouds NodeMetadata
    NodeMetadataBuilder builder = new NodeMetadataBuilder();
    builder.ids(from.getId() + "");
    builder.name(from.getName());
    // TODO: in cloudstack 2.2.12, when "name" was set fine on the backend,
    // but wrong API response was returned to the user
    // http://bugs.cloud.com/show_bug.cgi?id=11664
    //
    // we set displayName to the same value as name, but this could be wrong
    // on hosts not started with jclouds
    builder.hostname(from.getDisplayName());
    builder.location(findLocationForVirtualMachine.apply(from));
    builder.group(parseGroupFromName(from.getDisplayName()));
    Image image = findImageForVirtualMachine.apply(from);
    if (image != null) {
      builder.imageId(image.getId());
      builder.operatingSystem(image.getOperatingSystem());
    }

    builder.hardware(
        new HardwareBuilder()
            .ids(from.getServiceOfferingId() + "")
            .name(from.getServiceOfferingName() + "")
            // .tags() TODO
            .processors(ImmutableList.of(new Processor(from.getCpuCount(), from.getCpuSpeed())))
            .ram((int) from.getMemory()) //
            .hypervisor(from.getHypervisor()) //
            .build());

    builder.state(vmStateToNodeState.get(from.getState()));

    Set<String> publicAddresses = newHashSet(), privateAddresses = newHashSet();
    if (from.getIPAddress() != null) {
      boolean isPrivate = isPrivateIPAddress(from.getIPAddress());
      if (isPrivate) {
        privateAddresses.add(from.getIPAddress());
      } else {
        publicAddresses.add(from.getIPAddress());
      }
    }
    for (NIC nic : from.getNICs()) {
      if (nic.getIPAddress() != null) {
        if (isPrivateIPAddress(nic.getIPAddress())) {
          privateAddresses.add(nic.getIPAddress());
        } else {
          publicAddresses.add(nic.getIPAddress());
        }
      }
    }
    try {
      /* Also add to the list of public IPs any public IP address that has a
      forwarding rule that links to this machine */
      Iterables.addAll(
          publicAddresses,
          transform(
              filter(
                  getIPForwardingRulesByVirtualMachine.getUnchecked(from.getId()),
                  new Predicate<IPForwardingRule>() {
                    @Override
                    public boolean apply(@Nullable IPForwardingRule rule) {
                      return !"Deleting".equals(rule.getState());
                    }
                  }),
              new Function<IPForwardingRule, String>() {
                @Override
                public String apply(@Nullable IPForwardingRule rule) {
                  return rule.getIPAddress();
                }
              }));
    } catch (UncheckedExecutionException e) {
      if (Throwables2.getFirstThrowableOfType(e, ResourceNotFoundException.class) == null) {
        Throwables.propagateIfPossible(e.getCause());
        throw e;
      }
    }
    return builder.privateAddresses(privateAddresses).publicAddresses(publicAddresses).build();
  }
示例#11
0
  /** {@inheritDoc} */
  public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
      throws IOException, ServletException {
    // According to CORS spec OPTIONS method does not pass auth info
    if (((HttpServletRequest) req).getMethod().equals("OPTIONS")) {
      chain.doFilter(req, resp);
      return;
    }
    Object auth = null;
    int numberOfTries = 0;
    if (!appConfig.isInitialized()) {
      appConfig.initialize(filterConfig, req);
    }
    int retries = appConfig.getRetries();
    long pauseTime = appConfig.getPauseTime();

    // Extract credential
    String token = ((HttpServletRequest) req).getHeader(TOKEN);

    if (token == null) {
      if (!appConfig.isDelayAuthDecision()) {
        logger.error(HttpServletResponse.SC_UNAUTHORIZED + " No token found.");
        ((HttpServletResponse) resp).sendError(HttpServletResponse.SC_UNAUTHORIZED, TOKEN_NOTFOUND);
        return;
      } else {
        logger.info("No token found...Skipping");
      }
    } else {
      do {
        try {
          auth = FilterUtils.getCachedToken(token);
        } catch (ServiceUnavailableException e) {
          if (numberOfTries < retries) {
            FilterUtils.pause(pauseTime);
            logger.debug("Retrying connection after " + pauseTime + " seconds.");
            numberOfTries++;
            continue;
          } else {
            logger.debug("Exhausted retries..");
            TokenExceptionHandler handler =
                TokenExceptionHandler.valueOf("ServiceUnavailableException");
            handler.onException(e, resp, token);
          }
          return;
        } catch (ClientProtocolException e) {
          if (numberOfTries < retries) {
            FilterUtils.pause(pauseTime);
            logger.debug("Retrying connection after " + pauseTime + " seconds.");
            numberOfTries++;
            continue;
          } else {
            logger.debug("Exhausted retries..");
            TokenExceptionHandler handler =
                TokenExceptionHandler.valueOf("ClientProtocolException");
            handler.onException(e, resp, token);
          }
          return;
        } catch (UncheckedExecutionException e) {
          final TokenExceptionHandler handler;
          final Exception toHandle;
          if ((e.getCause() != null) && e.getCause() instanceof AdminAuthException) {
            toHandle = (AdminAuthException) e.getCause();
            handler = TokenExceptionHandler.valueOf("AdminAuthException");
          } else if ((e.getCause() != null) && e.getCause() instanceof AuthException) {
            toHandle = (AuthException) e.getCause();
            handler = TokenExceptionHandler.valueOf("AuthException");
          } else {
            toHandle = e;
            handler = TokenExceptionHandler.valueOf("UncheckedExecutionException");
          }
          handler.onException(toHandle, resp, token);
          return;
        }

      } while (auth == null && numberOfTries <= retries);
    }
    req = FilterUtils.wrapRequest(req, auth);
    logger.debug("TokenAuth: Forwarding down stream to next filter/servlet");
    // Forward downstream...
    chain.doFilter(req, resp);
  }