private void resetImagePendingAvailable(final String imageId, final String reason) {
    String taskMessage = "";
    /// tag image and instances with proper message
    try {
      final ImageInfo image = Images.lookupImage(imageId);
      final String taskId = ((MachineImageInfo) image).getImageConversionId();
      if (taskId != null) {
        conversionTaskCache.invalidate(taskId);
        Optional<DiskImageConversionTask> task = conversionTaskCache.get(taskId);
        if (task.isPresent()) taskMessage = task.get().getStatusMessage();
      }
      final String tagMessage = reason != null ? reason : taskMessage;
      this.tagResources(imageId, "failed", tagMessage);
    } catch (final Exception ex) {;
    } finally {
      taggedImages.remove(imageId);
    }

    try (final TransactionResource db = Entities.transactionFor(ImageInfo.class)) {
      try {
        final ImageInfo entity = Entities.uniqueResult(Images.exampleWithImageId(imageId));
        entity.setState(ImageMetadata.State.pending_available);
        entity.setImageFormat(ImageMetadata.ImageFormat.partitioned.name());
        ((MachineImageInfo) entity).setImageConversionId(null);
        Entities.persist(entity);
        db.commit();
      } catch (final Exception ex) {
        LOG.error("Failed to mark the image state available for conversion: " + imageId, ex);
      }
    }
  }
示例#2
0
  @Test
  public void testHttp() throws Exception {
    // Verify that http_proxy and HTTP_PROXY are used for http requests
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "http_proxy", PROXY_URL,
                    "HTTP_PROXY", "http://ignore",
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());
    assertExpectedProxyConfig(
        proxyConfigFromEnv(
                "http",
                ImmutableMap.of(
                    "HTTP_PROXY", PROXY_URL,
                    "https_proxy", "http://ignore",
                    "HTTPS_PROXY", "http://ignore"))
            .get());

    // Verify that https_proxy and HTTPS_PROXY are not used for http requests
    assertThat(
        proxyConfigFromEnv(
            "http", ImmutableMap.of("https_proxy", PROXY_URL, "HTTPS_PROXY", "http://ignore")),
        is(Optional.absent()));

    assertThat(
        proxyConfigFromEnv("http", ImmutableMap.of("HTTPS_PROXY", PROXY_URL)),
        is(Optional.absent()));
  }
  /**
   * Creates instances of CloudSim's VM class from a list of virtual machine registers.
   *
   * @param vmList a list of virtual machine registers.
   * @param brokerId the id of the broker that owns the virtual machines.
   * @return a list of VM instances.
   * @since 1.0
   */
  static List<Vm> createVms(List<VirtualMachineRegistry> vmList, int brokerId) {
    List<Vm> list = new ArrayList<Vm>();

    int vmId = 0;
    for (VirtualMachineRegistry vmr : vmList) {
      for (int n = 0; n < vmr.getAmount(); n++) {
        Optional<CloudletScheduler> cs =
            CLOUDLET_SCHEDULER.getExtensionInstanceByName(
                vmr.getSchedulingPolicyAlias(), vmr.getMips(), vmr.getPesNumber());

        if (!cs.isPresent()) {
          Dialog.showErrorMessage(
              null,
              format(
                  "Error on loading the cloudlet scheduler [%s]", vmr.getSchedulingPolicyAlias()));
          return null;
        }

        list.add(
            new Vm(
                vmId,
                brokerId,
                vmr.getMips(),
                vmr.getPesNumber(),
                vmr.getRam(),
                vmr.getBw(),
                vmr.getSize(),
                vmr.getVmm(),
                cs.get()));
        vmId++;
      }
    }
    return list;
  }
  public Router createRouter(String routerName, String externalNetworkId)
      throws RegionException, NeutronException {
    if (!checkRouterNameExist(routerName)) {
      Optional<? extends RouterApi> routerApiExtension = neutronApi.getRouterApi(getRegionOne());

      if (routerApiExtension.isPresent()) {
        RouterApi routerApi = routerApiExtension.get();
        ExternalGatewayInfo externalGateway =
            ExternalGatewayInfo.builder()
                .networkId(externalNetworkId)
                //                  .enableSnat(true)
                .build();
        return routerApi.create(
            CreateRouter.createBuilder()
                .name(routerName)
                .adminStateUp(true)
                .externalGatewayInfo(externalGateway)
                .build());

      } else {
        throw new NeutronException("RouterApi is not present");
      }

    } else {

      throw new NeutronException("Router name exists on this tenant!");
    }
  }
 private void findMachinesBasedOnLocalIp() {
   Optional<InetAddress> localhost = getLocalAddress();
   if (localhost.isPresent()) {
     InetAddress inetAddress = localhost.get();
     myIp = inetAddress.getAddress();
     scanningThreadPool.submit(
         new Runnable() {
           @Override
           public void run() {
             if (!isCancelled()) {
               searchForIp(myIp);
             }
           }
         });
     for (int i = 1; i <= MAX_IPS; i++) {
       final int finalI = i;
       scanningThreadPool.submit(
           new Runnable() {
             @Override
             public void run() {
               if (!isCancelled()) {
                 searchForIp(createSubnetAddress(myIp, (byte) finalI));
               }
             }
           });
     }
   }
 }
示例#6
0
 /**
  * Retrieves a custom biome
  *
  * @param targetBiome The string name of the targertBiome. See {@link GetBiomeIDEvent#targetBiome}
  *     for valid values.
  * @return The requested biome. If the biome does not exist, the <code>Optional</code> value will
  *     not be present.
  */
 public static Optional<BiomeGenBase> getBiome(String targetBiome) {
   final GetBiomeIDEvent event = new GetBiomeIDEvent(targetBiome);
   Api.getExtrabiomesXLEventBus().post(event);
   if (event.biomeID <= 0 || BiomeGenBase.getBiomeGenArray()[event.biomeID] == null)
     return Optional.absent();
   return Optional.of(BiomeGenBase.getBiomeGenArray()[event.biomeID]);
 }
 private Optional<Double> getFreeYslot(
     long starttime,
     long endtime,
     double slotHeight,
     boolean useEndPos,
     List<Class<? extends AnimationPartBase>> types) {
   final List<AnimationPartBase> foundAnimations = new ArrayList<AnimationPartBase>();
   for (Class<? extends AnimationPartBase> type : types) {
     foundAnimations.addAll(searchAnimationWithType(type, starttime, endtime));
   }
   for (int i = 0; i < 20; i++) {
     double ypos = 65 + (slotHeight) * i;
     boolean posInlist = false;
     for (AnimationPartBase animation : foundAnimations) {
       if (useEndPos) {
         if (Math.abs(animation.endy - ypos) < 0.0001) {
           posInlist = true;
         }
       } else {
         if (Math.abs(animation.starty - ypos) < 0.0001) {
           posInlist = true;
         }
       }
     }
     if (!posInlist) {
       return Optional.of(ypos);
     }
   }
   return Optional.absent();
 }
示例#8
0
 private String getGoEnvFromTool(ProcessExecutor processExecutor, String env) {
   Path goTool = getGoToolPath();
   Optional<Map<String, String>> goRootEnv =
       delegate
           .getPath("go", "root")
           .transform(
               new Function<Path, Map<String, String>>() {
                 @Override
                 public Map<String, String> apply(Path input) {
                   return ImmutableMap.of("GOROOT", input.toString());
                 }
               });
   try {
     ProcessExecutor.Result goToolResult =
         processExecutor.launchAndExecute(
             ProcessExecutorParams.builder()
                 .addCommand(goTool.toString(), "env", env)
                 .setEnvironment(goRootEnv)
                 .build(),
             EnumSet.of(ProcessExecutor.Option.EXPECTING_STD_ERR),
             /* stdin */ Optional.<String>absent(),
             /* timeOutMs */ Optional.<Long>absent(),
             /* timeoutHandler */ Optional.<Function<Process, Void>>absent());
     if (goToolResult.getExitCode() == 0) {
       return CharMatcher.WHITESPACE.trimFrom(goToolResult.getStdout().get());
     } else {
       throw new HumanReadableException(goToolResult.getStderr().get());
     }
   } catch (InterruptedException e) {
     throw Throwables.propagate(e);
   } catch (IOException e) {
     throw new HumanReadableException(e, "Could not run \"%s env %s\": %s", env, goTool);
   }
 }
  public static class Builder {
    private Optional<Calendar> startDate = Optional.absent();
    private Optional<Calendar> endDate = Optional.absent();
    private Optional<String> Vendor = Optional.absent();
    private Optional<Integer> poId = Optional.absent();

    private Builder() {}

    public Builder startDate(Calendar startDate) {
      this.startDate = Optional.of(startDate);
      return this;
    }

    public Builder endDate(Calendar endDate) {
      this.endDate = Optional.of(endDate);
      return this;
    }

    public Builder Vendor(String Vendor) {
      this.Vendor = Optional.of(Vendor);
      return this;
    }

    public Builder poId(Integer poId2) {
      this.poId = Optional.of(poId2);
      return this;
    }

    public VarianceReportFilter create() {
      return new VarianceReportFilter(startDate, endDate, Vendor, poId);
    }
  }
  @SuppressWarnings("unchecked")
  @Test
  public void validateIovisorModuleInstanceTest() {
    DataBroker dataBroker = Mockito.mock(DataBroker.class);
    when(dataBroker.newReadOnlyTransaction()).thenReturn(mock(ReadOnlyTransaction.class));

    PowerMockito.mockStatic(DataStoreHelper.class);
    Optional<IovisorModuleInstances> result = mock(Optional.class);
    PowerMockito.when(
            DataStoreHelper.readFromDs(
                any(LogicalDatastoreType.class),
                any(InstanceIdentifier.class),
                any(ReadOnlyTransaction.class)))
        .thenReturn(result);

    Uri goodUri = mock(Uri.class);

    when(result.isPresent()).thenReturn(false);
    Assert.assertFalse(IovisorModuleUtils.validateIovisorModuleInstance(dataBroker, goodUri));

    when(result.isPresent()).thenReturn(true);
    IovisorModuleInstance iovisorModuleInstance = mock(IovisorModuleInstance.class);
    when(iovisorModuleInstance.getUri()).thenReturn(goodUri);
    List<IovisorModuleInstance> iovisorModuleInstanceList = new ArrayList<>();
    iovisorModuleInstanceList.add(iovisorModuleInstance);
    IovisorModuleInstances iovisorModuleInstances = mock(IovisorModuleInstances.class);
    when(iovisorModuleInstances.getIovisorModuleInstance()).thenReturn(iovisorModuleInstanceList);
    when(result.get()).thenReturn(iovisorModuleInstances);
    Assert.assertTrue(IovisorModuleUtils.validateIovisorModuleInstance(dataBroker, goodUri));

    Uri wrongUri = mock(Uri.class);
    Assert.assertFalse(IovisorModuleUtils.validateIovisorModuleInstance(dataBroker, wrongUri));
  }
 /**
  * Gets the project for this tab.
  *
  * @return The {@link Project}. Not {@code null}.
  */
 public Project getProject() {
   Optional<Project> project = ProjectManager.get().getProject(projectId);
   if (!project.isPresent()) {
     throw new IllegalStateException("Unknown project: " + project);
   }
   return project.get();
 }
示例#12
0
  private static void runScanExercise(Map<String, Path> paths) {
    // Exercise name, should it be something else than directory name?
    String exerciseName = paths.get(EXERCISE_PATH).toFile().getName();
    Optional<ExerciseDesc> exerciseDesc = Optional.absent();
    try {
      exerciseDesc = executor.scanExercise(paths.get(EXERCISE_PATH), exerciseName);

      if (!exerciseDesc.isPresent()) {
        log.error("Absent exercise description after running scanExercise");
        printErrAndExit("ERROR: Could not scan the exercises.");
      }
    } catch (NoLanguagePluginFoundException e) {
      log.error("No suitable language plugin for project at {}", paths.get(EXERCISE_PATH), e);
      printErrAndExit(
          "ERROR: Could not find suitable language plugin for the given " + "exercise path.");
    }

    try {
      JsonWriter.writeObjectIntoJsonFormat(exerciseDesc.get(), paths.get(OUTPUT_PATH));
      System.out.println(
          "Exercises scanned successfully, results can be found in "
              + paths.get(OUTPUT_PATH).toString());
    } catch (IOException e) {
      log.error("Could not write output to {}", paths.get(OUTPUT_PATH), e);
      printErrAndExit("ERROR: Could not write the results to the given file.");
    }
  }
 private Optional<WebDriverFacade> webDriverFacade() {
   if (driver instanceof WebElementFacade) {
     return Optional.of((WebDriverFacade) driver);
   } else {
     return Optional.absent();
   }
 }
  private void testCorrectnessOfErrorFunction(List<Number> inputList) throws Exception {
    int inRange = 0;
    int numberOfRuns = 1000;
    double sampleRatio = 1 / (double) WEIGHT;
    double actual = getExpectedValue(inputList);
    Random rand = new Random(1);

    for (int i = 0; i < numberOfRuns; i++) {
      // Compute Sampled Value using sampledList (numberOfRuns times)
      ImmutableList.Builder<Number> sampledList = ImmutableList.builder();
      for (Number x : inputList) {
        if (rand.nextDouble() < sampleRatio) {
          sampledList.add(x);
        }
      }

      BlockBuilder builder = getType().createBlockBuilder(new BlockBuilderStatus());
      for (Number sample : sampledList.build()) {
        if (getType() == BIGINT) {
          BIGINT.writeLong(builder, sample.longValue());
        } else if (getType() == DOUBLE) {
          DOUBLE.writeDouble(builder, sample.doubleValue());
        } else {
          throw new AssertionError("Can only handle longs and doubles");
        }
      }
      Page page = new Page(builder.build());
      page = OperatorAssertion.appendSampleWeight(ImmutableList.of(page), WEIGHT).get(0);
      Accumulator accumulator =
          getFunction()
              .bind(
                  ImmutableList.of(0),
                  Optional.<Integer>absent(),
                  Optional.of(page.getChannelCount() - 1),
                  getConfidence())
              .createAccumulator();

      accumulator.addInput(page);
      Block result = accumulator.evaluateFinal();

      String approxValue =
          BlockAssertions.toValues(accumulator.getFinalType(), result).get(0).toString();
      double approx = Double.parseDouble(approxValue.split(" ")[0]);
      double error = Double.parseDouble(approxValue.split(" ")[2]);

      // Check if actual answer lies within [approxAnswer - error, approxAnswer + error]
      if (Math.abs(approx - actual) <= error) {
        inRange++;
      }
    }

    BinomialDistribution binomial = new BinomialDistribution(numberOfRuns, getConfidence());
    int lowerBound = binomial.inverseCumulativeProbability(0.01);
    int upperBound = binomial.inverseCumulativeProbability(0.99);
    assertTrue(
        lowerBound < inRange && inRange < upperBound,
        String.format(
            "%d out of %d passed. Expected [%d, %d]",
            inRange, numberOfRuns, lowerBound, upperBound));
  }
 public AndroidBinaryBuilder setIntraDexReorderResources(
     boolean enableReorder, SourcePath reorderTool, SourcePath reorderData) {
   arg.reorderClassesIntraDex = Optional.of(enableReorder);
   arg.dexReorderToolFile = Optional.of(reorderTool);
   arg.dexReorderDataDumpFile = Optional.of(reorderData);
   return this;
 }
 @Override
 /* @Nullable */
 protected Map<JvmIdentifiableElement, LightweightTypeReference> getFlattenedReassignedTypes() {
   if (flattenedReassignedTypes != null) {
     // already computed
     return flattenedReassignedTypes.orNull();
   }
   Map<JvmIdentifiableElement, LightweightTypeReference> result =
       parent.getFlattenedReassignedTypes();
   if (result == null) {
     // parent doesn't have reassigned types
     // use only locally reassigned types
     return (flattenedReassignedTypes = Optional.fromNullable(super.getFlattenedReassignedTypes()))
         .orNull();
   }
   Map<JvmIdentifiableElement, LightweightTypeReference> myReassignedTypes =
       basicGetReassignedTypes();
   if (myReassignedTypes.isEmpty()) {
     // no locally reassigned types, use result from parent which was already checked for null
     return (flattenedReassignedTypes = Optional.of(result)).orNull();
   }
   // merge parent's reassigned types and locally reassigned types
   result = Maps.newHashMap(result);
   result.putAll(myReassignedTypes);
   return (flattenedReassignedTypes = Optional.of(result)).orNull();
 }
示例#17
0
  @Test
  public void testItemDeserialize() throws JsonSyntaxException, IOException {
    String json =
        on("\n")
            .join(
                readLines(this.getClass().getClassLoader().getResourceAsStream("article.example")));
    Items items = GsonFactory.getGsonBuilder().fromJson(json, Items.class);

    assertThat(items).isNotNull();
    assertThat(items.size()).isEqualTo(1);

    Optional<Article> first = items.first();
    assertThat(first.isPresent()).isTrue();

    assertThat(first.get().getId()).isEqualTo(229279689L);
    assertThat(first.get().getTitle())
        .isEqualTo("The Massive Ryder Cup Preview - The Triangle Blog - Grantland");
    assertThat(first.get().getResolvedTitle()).isEqualTo("The Massive Ryder Cup Preview");
    assertThat(first.get().getExcerpt())
        .isEqualTo(
            "The list of things I love about the Ryder Cup is so long that it could fill a (tedious) novel, and golf fans can probably guess most of them.");

    assertThat(first.get().getImages().size()).isEqualTo(1);
    assertThat(first.get().getVideos().size()).isEqualTo(1);
  }
  private ApiElement(Optional<ApiElement> parent, String name, ApiElementType type) {
    this.parent = parent;
    this.name = name;
    this.type = type;
    this.hashCode = Objects.hashCode(parent, name, type);

    Preconditions.checkArgument(
        (name.length() == 0) == (type == ApiElementType.PACKAGE && !parent.isPresent()));
    Preconditions.checkArgument(!name.contains("."), name);
    Preconditions.checkArgument(parent.isPresent() || name.length() == 0);
    switch (type) {
      case CLASS:
        Preconditions.checkArgument(
            parent.get().type == ApiElementType.PACKAGE
                || parent.get().type == ApiElementType.CLASS);
        return;
      case CONSTRUCTOR:
        Preconditions.checkArgument(name.equals(CONSTRUCTOR_SPECIAL_METHOD_NAME));
        Preconditions.checkArgument(
            parent.isPresent() && parent.get().type == ApiElementType.CLASS);
        return;
      case FIELD:
      case METHOD:
        Preconditions.checkArgument(
            parent.isPresent() && parent.get().type == ApiElementType.CLASS);
        return;
      case PACKAGE:
        Preconditions.checkArgument(
            !parent.isPresent() || parent.get().type == ApiElementType.PACKAGE);
        return;
    }
    throw new AssertionError(type);
  }
 public static Optional<TrackerFilterEnum> getByValue(String filterAction) {
   if (valuesSet.contains(filterAction)) {
     return Optional.of(TrackerFilterEnum.valueOf(filterAction.toUpperCase()));
   } else {
     return Optional.absent();
   }
 }
  /**
   * Push all new objects from the specified {@link Ref} to the remote.
   *
   * @param ref the local ref that points to new commit data
   * @param refspec the remote branch to push to
   */
  @Override
  public void pushNewData(Ref ref, String refspec, ProgressListener progress)
      throws SynchronizationException {
    Optional<Ref> remoteRef = HttpUtils.getRemoteRef(repositoryURL, refspec);
    checkPush(ref, remoteRef);
    beginPush();

    progress.setDescription("Uploading objects to " + refspec);
    progress.setProgress(0);

    CommitTraverser traverser = getPushTraverser(remoteRef);

    traverser.traverse(ref.getObjectId());

    List<ObjectId> toSend = new LinkedList<ObjectId>(traverser.commits);
    Collections.reverse(toSend);
    Set<ObjectId> have = new HashSet<ObjectId>(traverser.have);

    Deduplicator deduplicator = deduplicationService.createDeduplicator();
    try {
      sendPackedObjects(toSend, have, deduplicator, progress);
    } finally {
      deduplicator.release();
    }

    ObjectId originalRemoteRefValue = ObjectId.NULL;
    if (remoteRef.isPresent()) {
      originalRemoteRefValue = remoteRef.get().getObjectId();
    }

    String nameToSet =
        remoteRef.isPresent() ? remoteRef.get().getName() : Ref.HEADS_PREFIX + refspec;

    endPush(nameToSet, ref.getObjectId(), originalRemoteRefValue.toString());
  }
示例#21
0
 @Override
 public Optional<Favicon> load(FaviconSource source) throws Exception {
   // Try loading the favicon
   BufferedImage image = FaviconHelper.loadSafely(core, source);
   if (image == null) return Optional.absent(); // Favicon loading failed
   else return Optional.of(Favicon.create(image)); // Success!
 }
 private int parsePushLimit() {
   final String confKey = "push.chunk.limit";
   Optional<String> configLimit = localRepository.command(ConfigGet.class).setName(confKey).call();
   int limit = DEFAULT_PUSH_BATCH_LIMIT;
   if (configLimit.isPresent()) {
     String climit = configLimit.get();
     LOGGER.debug("Setting push batch limit to {} bytes as configured by {}", climit, confKey);
     try {
       int tmpLimit = Integer.parseInt(climit);
       if (tmpLimit < 1024) {
         LOGGER.warn(
             "Value for push batch limit '{}' is set too low ({}). "
                 + "A minimum of 1024 bytes is needed. Using the default value of {} bytes",
             confKey,
             tmpLimit,
             limit);
       } else {
         limit = tmpLimit;
       }
     } catch (NumberFormatException e) {
       LOGGER.warn("Invalid config value for {}, using the default of {} bytes", confKey, limit);
     }
   } else {
     LOGGER.info(
         "No push batch limit set through {}, using the default of {} bytes", confKey, limit);
   }
   return limit;
 }
示例#23
0
  private static boolean canMerge(
      IjFolder parent, IjFolder child, PackagePathCache packagePathCache) {
    Preconditions.checkArgument(child.getPath().startsWith(parent.getPath()));

    if (!child.canMergeWith(parent)) {
      return false;
    }

    if (parent.getWantsPackagePrefix() != child.getWantsPackagePrefix()) {
      return false;
    }

    if (parent.getWantsPackagePrefix()) {
      Optional<Path> parentPackage = packagePathCache.lookup(parent);
      if (!parentPackage.isPresent()) {
        return false;
      }
      Path childPackage = packagePathCache.lookup(child).get();

      int pathDifference = child.getPath().getNameCount() - parent.getPath().getNameCount();
      Preconditions.checkState(pathDifference == 1);
      if (childPackage.getNameCount() == 0) {
        return false;
      }
      if (!MorePaths.getParentOrEmpty(childPackage).equals(parentPackage.get())) {
        return false;
      }
    }
    return true;
  }
  private void executeForProject(Component project) {
    String projectKey = project.getKey();
    Settings settings = settingsRepository.getSettings(project);
    String qualityGateSetting = settings.getString(PROPERTY_QUALITY_GATE);

    if (qualityGateSetting == null || StringUtils.isBlank(qualityGateSetting)) {
      LOGGER.debug("No quality gate is configured for project " + projectKey);
      qualityGateHolder.setNoQualityGate();
      return;
    }

    try {
      long qualityGateId = Long.parseLong(qualityGateSetting);
      Optional<QualityGate> qualityGate = qualityGateService.findById(qualityGateId);
      if (qualityGate.isPresent()) {
        qualityGateHolder.setQualityGate(qualityGate.get());
      } else {
        qualityGateHolder.setNoQualityGate();
      }
    } catch (NumberFormatException e) {
      throw new IllegalStateException(
          String.format(
              "Unsupported value (%s) in property %s", qualityGateSetting, PROPERTY_QUALITY_GATE),
          e);
    }
  }
 private Optional<InetAddress> getRemoteAddress(byte[] addressAsBytes) {
   try {
     return Optional.fromNullable(InetAddress.getByAddress(addressAsBytes));
   } catch (Exception ex) {
     return Optional.absent();
   }
 }
示例#26
0
 public Optional<BoardTileModel> placeTileModel(
     GridModel.GridPosition gridPosition, ConveyorTileModel conveyorTileModel) {
   if (cannotPlaceTileAtPosition(gridPosition)) return Optional.absent();
   BoardTileModel boardTileModel = boardTileModelFactory.createTileModel(conveyorTileModel);
   gridModel.set(gridPosition, boardTileModel);
   return Optional.of(boardTileModel);
 }
示例#27
0
  @Test
  public void testNullValue() {
    config.put("section.null", null);

    Optional<String> str = config.get("section.null");
    assertFalse(str.isPresent());
  }
示例#28
0
  public void testUpdateQuotasOfCurrentTenantThenReset() {
    if (apiOption.isPresent()) {
      QuotaApi api = apiOption.get();
      Quota before = api.getByTenant(tenant);
      assertQuotasIsValid(before);

      Quota modified =
          before
              .toBuilder()
              .cores(before.getCores() - 1)
              .instances(before.getInstances() - 1)
              .metadataItems(before.getMetadatas() - 1)
              .ram(before.getRam() - 1)
              .volumes(before.getVolumes() - 1)
              .build();

      assertTrue(api.updateQuotaOfTenant(modified, tenant));

      assertEquals(api.getByTenant(tenant), modified);

      assertTrue(api.updateQuotaOfTenant(before, tenant));

      assertEquals(api.getByTenant(tenant), before);
    }
  }
示例#29
0
 public static final Optional<String> httpPost(
     Entity framework, String subUrl, String dataUrl, Map<String, Object> substitutions) {
   String targetUrl =
       Urls.mergePaths(framework.sensors().get(MesosFramework.FRAMEWORK_URL), subUrl);
   String templateContents = ResourceUtils.create().getResourceAsString(dataUrl);
   String processedJson =
       TemplateProcessor.processTemplateContents(templateContents, substitutions);
   LOG.debug("Posting JSON to {}: {}", targetUrl, processedJson);
   URI postUri = URI.create(targetUrl);
   HttpToolResponse response =
       HttpTool.httpPost(
           MesosUtils.buildClient(framework),
           postUri,
           MutableMap.of(
               HttpHeaders.CONTENT_TYPE, "application/json",
               HttpHeaders.ACCEPT, "application/json"),
           processedJson.getBytes());
   LOG.debug("Response: " + response.getContentAsString());
   if (!HttpTool.isStatusCodeHealthy(response.getResponseCode())) {
     LOG.warn(
         "Invalid response code {}: {}", response.getResponseCode(), response.getReasonPhrase());
     return Optional.absent();
   } else {
     LOG.debug("Successfull call to {}: {}", targetUrl);
     return Optional.of(response.getContentAsString());
   }
 }
 private void updateTags(final List<String> images) throws Exception {
   for (final String imageId : images) {
     try {
       final ImageInfo image = Images.lookupImage(imageId);
       final ImageMetadata.State imgState = image.getState();
       final String taskId = ((MachineImageInfo) image).getImageConversionId();
       if (ImageMetadata.State.pending_available.equals(
           imgState)) {; // do nothing for images not yet in conversion
       } else if (ImageMetadata.State.pending_conversion.equals(imgState)) {
         String message = "";
         try {
           Optional<DiskImageConversionTask> task = conversionTaskCache.get(taskId);
           if (task.isPresent()) {
             message = task.get().getStatusMessage();
           }
         } catch (final Exception ex) {;
         }
         // if needed, we can add messages as well; not sure yet if the messages are clear
         this.tagResources(imageId, "active", message);
         taggedImages.add(imageId);
       } else if (ImageMetadata.State.available.equals(imgState)
           && taggedImages.contains(imageId)) {
         try {
           this.removeTags(imageId);
         } catch (final Exception ex) {;
         } finally {
           taggedImages.remove(imageId);
         }
       }
     } catch (final Exception ex) {
       LOG.error("Failed to update tags for resources in conversion", ex);
     }
   }
 }