@Provides
 @Singleton
 @ImageQuery
 protected Map<String, String> imageQuery(ValueOfConfigurationKeyOrNull config) {
   String amiQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_AMI_QUERY));
   String owners = config.apply(PROPERTY_EC2_AMI_OWNERS);
   if ("".equals(owners)) {
     amiQuery = null;
   } else if (owners != null) {
     StringBuilder query = new StringBuilder();
     if ("*".equals(owners)) query.append("state=available;image-type=machine");
     else query.append("owner-id=").append(owners).append(";state=available;image-type=machine");
     Logger.getAnonymousLogger()
         .warning(
             String.format(
                 "Property %s is deprecated, please use new syntax: %s=%s",
                 PROPERTY_EC2_AMI_OWNERS, PROPERTY_EC2_AMI_QUERY, query.toString()));
     amiQuery = query.toString();
   }
   Builder<String, String> builder = ImmutableMap.<String, String>builder();
   if (amiQuery != null) builder.put(PROPERTY_EC2_AMI_QUERY, amiQuery);
   String ccQuery = Strings.emptyToNull(config.apply(PROPERTY_EC2_CC_AMI_QUERY));
   if (ccQuery != null) builder.put(PROPERTY_EC2_CC_AMI_QUERY, ccQuery);
   return builder.build();
 }
예제 #2
0
  /** Used in SQALE */
  public PagedResult<RuleDto> find(Map<String, Object> params) {
    RuleQuery query = new RuleQuery();
    query.setQueryText(Strings.emptyToNull((String) params.get("searchQuery")));
    query.setKey(Strings.emptyToNull((String) params.get("key")));
    query.setLanguages(RubyUtils.toStrings(params.get("languages")));
    query.setRepositories(RubyUtils.toStrings(params.get("repositories")));
    query.setSeverities(RubyUtils.toStrings(params.get("severities")));
    query.setStatuses(RubyUtils.toEnums(params.get("statuses"), RuleStatus.class));
    query.setTags(RubyUtils.toStrings(params.get("tags")));
    query.setSortField(RuleIndexDefinition.FIELD_RULE_NAME);
    String profile = Strings.emptyToNull((String) params.get("profile"));
    if (profile != null) {
      query.setQProfileKey(profile);
      query.setActivation(true);
    }

    SearchOptions options = new SearchOptions();
    Integer pageSize = RubyUtils.toInteger(params.get("pageSize"));
    int size = pageSize != null ? pageSize : 50;
    Integer page = RubyUtils.toInteger(params.get("p"));
    int pageIndex = page != null ? page : 1;
    options.setPage(pageIndex, size);
    SearchIdResult<RuleKey> result = service.search(query, options);
    List<RuleDto> ruleDtos = loadDtos(result.getIds());
    return new PagedResult<>(
        ruleDtos, PagingResult.create(options.getLimit(), pageIndex, result.getTotal()));
  }
예제 #3
0
파일: PlMerge.java 프로젝트: wgapl/bazel
  public static void main(String[] args) throws OptionsParsingException, IOException {
    FileSystem fileSystem = FileSystems.getDefault();
    OptionsParser parser = OptionsParser.newOptionsParser(PlMergeOptions.class);
    parser.parse(args);
    PlMergeOptions options = parser.getOptions(PlMergeOptions.class);

    if (options.controlPath == null) {
      missingArg("control");
    }

    InputStream in = Files.newInputStream(fileSystem.getPath(options.controlPath));
    Control control = Control.parseFrom(in);
    validateControl(control);

    PlistMerging merging =
        PlistMerging.from(
            control, new KeysToRemoveIfEmptyString("CFBundleIconFile", "NSPrincipalClass"));

    String primaryBundleId = Strings.emptyToNull(control.getPrimaryBundleId());
    String fallbackBundleId = Strings.emptyToNull(control.getFallbackBundleId());

    if (primaryBundleId != null || fallbackBundleId != null) {
      // Only set the bundle identifier if we were passed arguments to do so.
      // This prevents CFBundleIdentifiers being put into strings files.
      merging.setBundleIdentifier(primaryBundleId, fallbackBundleId);
    }
    merging.writePlist(fileSystem.getPath(control.getOutFile()));
  }
예제 #4
0
 // sqale
 public void updateRule(Map<String, Object> params) {
   RuleUpdate update =
       RuleUpdate.createForPluginRule(RuleKey.parse((String) params.get("ruleKey")));
   String fn = (String) params.get("debtRemediationFunction");
   if (fn == null) {
     update.setDebtRemediationFunction(null);
   } else {
     update.setDebtRemediationFunction(
         new DefaultDebtRemediationFunction(
             DebtRemediationFunction.Type.valueOf(fn),
             Strings.emptyToNull((String) params.get("debtRemediationCoefficient")),
             Strings.emptyToNull((String) params.get("debtRemediationOffset"))));
   }
   updater.update(update, userSession);
 }
예제 #5
0
  private static boolean isValueEquals(
      final AbstractField<?> field, final Object orginalValue, final Object currentValue) {
    if (Set.class.equals(field.getType())) {
      return CollectionUtils.isEqualCollection(
          CollectionUtils.emptyIfNull((Collection<?>) orginalValue),
          CollectionUtils.emptyIfNull((Collection<?>) currentValue));
    }

    if (String.class.equals(field.getType())) {
      return Objects.equals(
          Strings.emptyToNull((String) orginalValue), Strings.emptyToNull((String) currentValue));
    }

    return Objects.equals(orginalValue, currentValue);
  }
예제 #6
0
  private Optional<Brand> getBrandWithoutChannel(ProgData progData, Timestamp updatedAt) {

    String brandId = progData.getSeriesId();
    if (Strings.isNullOrEmpty(brandId) || Strings.isNullOrEmpty(brandId.trim())) {
      return Optional.absent();
    }

    String brandUri = PaHelper.getBrandUri(brandId);
    Alias brandAlias = PaHelper.getBrandAlias(brandId);

    Maybe<Identified> possiblePrevious =
        contentResolver.findByCanonicalUris(ImmutableList.of(brandUri)).getFirstValue();

    Brand brand =
        possiblePrevious.hasValue()
            ? (Brand) possiblePrevious.requireValue()
            : new Brand(brandUri, "pa:b-" + brandId, Publisher.PA);

    brand.addAlias(brandAlias);
    brand.setTitle(progData.getTitle());
    brand.setDescription(Strings.emptyToNull(progData.getSeriesSynopsis()));
    setCertificate(progData, brand);
    setGenres(progData, brand);
    setTopicRefs(brand);

    if (isClosedBrand(Optional.of(brand))) {
      brand.setScheduleOnly(true);
    }

    brand.setLastUpdated(updatedAt.toDateTimeUTC());

    return Optional.of(brand);
  }
예제 #7
0
  private RuleKey createCustomRule(
      RuleKey ruleKey, NewRule newRule, RuleDto templateRuleDto, DbSession dbSession) {
    RuleDto ruleDto =
        RuleDto.createFor(ruleKey)
            .setTemplateId(templateRuleDto.getId())
            .setConfigKey(templateRuleDto.getConfigKey())
            .setName(newRule.name())
            .setDescription(newRule.markdownDescription())
            .setDescriptionFormat(Format.MARKDOWN)
            .setSeverity(newRule.severity())
            .setStatus(newRule.status())
            .setLanguage(templateRuleDto.getLanguage())
            .setDefaultSubCharacteristicId(templateRuleDto.getDefaultSubCharacteristicId())
            .setDefaultRemediationFunction(templateRuleDto.getDefaultRemediationFunction())
            .setDefaultRemediationCoefficient(templateRuleDto.getDefaultRemediationCoefficient())
            .setDefaultRemediationOffset(templateRuleDto.getDefaultRemediationOffset())
            .setEffortToFixDescription(templateRuleDto.getEffortToFixDescription())
            .setTags(templateRuleDto.getTags())
            .setSystemTags(templateRuleDto.getSystemTags());
    dbClient.ruleDao().insert(dbSession, ruleDto);

    for (RuleParamDto templateRuleParamDto :
        dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, templateRuleDto.getKey())) {
      String customRuleParamValue =
          Strings.emptyToNull(newRule.parameter(templateRuleParamDto.getName()));
      createCustomRuleParams(customRuleParamValue, ruleDto, templateRuleParamDto, dbSession);
    }
    return ruleKey;
  }
예제 #8
0
  @Override
  public Response<String> apply(AccountResource rsrc, Input input)
      throws AuthException, ResourceNotFoundException, ResourceConflictException, OrmException {
    if (input == null) {
      input = new Input();
    }
    input.httpPassword = Strings.emptyToNull(input.httpPassword);

    String newPassword;
    if (input.generate) {
      if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canGenerateHttpPassword()) {
        throw new AuthException("not allowed to generate HTTP password");
      }
      newPassword = generate();

    } else if (input.httpPassword == null) {
      if (self.get() != rsrc.getUser() && !self.get().getCapabilities().canAdministrateServer()) {
        throw new AuthException("not allowed to clear HTTP password");
      }
      newPassword = null;
    } else {
      if (!self.get().getCapabilities().canAdministrateServer()) {
        throw new AuthException(
            "not allowed to set HTTP password directly, " + "need to be Gerrit administrator");
      }
      newPassword = input.httpPassword;
    }
    return apply(rsrc.getUser(), newPassword);
  }
 @Override
 public void performApply(ILaunchConfigurationWorkingCopy config) {
   config.setAttribute(
       IJavaLaunchConfigurationConstants.ATTR_PROJECT_NAME,
       Strings.emptyToNull(this.fProjText.getText().trim()));
   config.setAttribute(
       SARLEclipseConfig.ATTR_AGENT_NAME,
       Strings.emptyToNull(this.agentNameTextField.getText().trim()));
   config.setAttribute(
       SARLEclipseConfig.ATTR_ROOT_CONTEXT_ID_TYPE, getSelectedContextIdentifierType().name());
   config.setAttribute(
       SARLEclipseConfig.ATTR_SHOW_LOGO_OPTION, this.showLogoOptionButton.getSelection());
   config.setAttribute(
       SARLEclipseConfig.ATTR_SHOW_LOG_INFO, this.showLogInfoButton.getSelection());
   config.setAttribute(SARLEclipseConfig.ATTR_SRE_OFFLINE, this.offlineButton.getSelection());
   mapResources(config);
 }
  protected NodeMetadataBuilder buildInstance(
      final RunningInstance instance, NodeMetadataBuilder builder) {
    builder.providerId(instance.getId());
    builder.id(instance.getRegion() + "/" + instance.getId());
    String group = getGroupForInstance(instance);
    builder.group(group);
    // standard convention from aws-ec2, which might not be re-used outside.
    if (instance.getPrivateDnsName() != null)
      builder.hostname(instance.getPrivateDnsName().replaceAll("\\..*", ""));
    addCredentialsForInstance(builder, instance);
    builder.status(instanceToNodeStatus.get(instance.getInstanceState()));
    builder.backendStatus(instance.getRawState());

    // collect all ip addresses into one bundle in case the api mistakenly put a private address
    // into the public address field
    Builder<String> addressesBuilder = ImmutableSet.builder();
    if (Strings.emptyToNull(instance.getIpAddress()) != null)
      addressesBuilder.add(instance.getIpAddress());
    // Add dnsName (if available) to addresses, when the IPAddress is null
    // happens on Eucalyptus sometimes.
    else if (Strings.emptyToNull(instance.getDnsName()) != null)
      addressesBuilder.add(instance.getDnsName());
    if (Strings.emptyToNull(instance.getPrivateIpAddress()) != null)
      addressesBuilder.add(instance.getPrivateIpAddress());

    Set<String> addresses = addressesBuilder.build();

    builder.publicAddresses(filter(addresses, not(IsPrivateIPAddress.INSTANCE)));
    builder.privateAddresses(filter(addresses, IsPrivateIPAddress.INSTANCE));
    builder.hardware(parseHardware(instance));
    Location location = getLocationForAvailabilityZoneOrRegion(instance);
    builder.location(location);
    builder.imageId(instance.getRegion() + "/" + instance.getImageId());

    // extract the operating system from the image
    RegionAndName regionAndName = new RegionAndName(instance.getRegion(), instance.getImageId());
    try {
      Image image = imageMap.get().getUnchecked(regionAndName);
      if (image != null) builder.operatingSystem(image.getOperatingSystem());
    } catch (CacheLoader.InvalidCacheLoadException e) {
      logger.debug("image not found for %s: %s", regionAndName, e);
    } catch (UncheckedExecutionException e) {
      logger.debug("error getting image for %s: %s", regionAndName, e);
    }
    return builder;
  }
 @Override
 protected String normalize(String value) {
   if (value != null) {
     String stateProvince = LETTER_MATCHER.retainFrom(value);
     stateProvince = WHITESPACE_MATCHER.trimAndCollapseFrom(stateProvince, ' ');
     stateProvince = StringUtils.stripAccents(stateProvince);
     stateProvince = Strings.emptyToNull(stateProvince);
     return super.normalize(stateProvince);
   }
   return null;
 }
예제 #12
0
  /** Build MergingArguments from a plmerge protobuf. */
  public MergingArguments(Control control) {
    ImmutableList.Builder<Path> sourceFilePathsBuilder = new Builder<>();
    for (String pathString : control.getSourceFileList()) {
      sourceFilePathsBuilder.add(fileSystem.getPath(pathString));
    }
    sourceFilePaths = sourceFilePathsBuilder.build();

    ImmutableList.Builder<Path> immutableSourceFilePathsBuilder = new Builder<>();
    for (String pathString : control.getImmutableSourceFileList()) {
      immutableSourceFilePathsBuilder.add(fileSystem.getPath(pathString));
    }
    immutableSourceFilePaths = immutableSourceFilePathsBuilder.build();

    outFile = control.getOutFile();
    variableSubstitutions = control.getVariableSubstitutionMap();

    primaryBundleId = Strings.emptyToNull(control.getPrimaryBundleId());
    fallbackBundleId = Strings.emptyToNull(control.getFallbackBundleId());
    executableName = Strings.emptyToNull(control.getExecutableName());
  }
 @Override
 public void processParameters(
     final CommandMethodDescriptor descriptor,
     final CommandParamsContext context,
     final List<ParamInfo<Param>> paramsInfo) {
   for (ParamInfo<Param> paramInfo : paramsInfo) {
     final String name = Strings.emptyToNull(paramInfo.annotation.value());
     check(name != null, "Named parameter requires not empty name");
     context.addNamedParam(name, paramInfo);
   }
 }
예제 #14
0
  private void copyTo() {
    config.setName(nameText.getText().trim());
    config.setTitle(Strings.emptyToNull(titleText.getText().trim()));
    config.setGameVersion(gameVersionText.getText().trim());

    LaunchModifier launchModifier = config.getLaunchModifier();
    FnPatternList userFiles = config.getUserFiles();

    launchModifier.setFlags(SwingHelper.linesToList(launchFlagsArea.getText()));
    userFiles.setInclude(SwingHelper.linesToList(userFilesIncludeArea.getText()));
    userFiles.setExclude(SwingHelper.linesToList(userFilesExcludeArea.getText()));
  }
 public static CssClassFaFacet create(
     final ViewModelLayout viewModelLayout, final FacetHolder holder) {
   if (viewModelLayout == null) {
     return null;
   }
   final String cssClassFa = Strings.emptyToNull(viewModelLayout.cssClassFa());
   final CssClassFaPosition position =
       CssClassFaPosition.from(viewModelLayout.cssClassFaPosition());
   return cssClassFa != null
       ? new CssClassFaFacetForViewModelLayoutAnnotation(cssClassFa, position, holder)
       : null;
 }
예제 #16
0
  private GroupInfo init(GroupDescription.Basic group) {
    GroupInfo info = new GroupInfo();
    info.id = Url.encode(group.getGroupUUID().get());
    info.name = Strings.emptyToNull(group.getName());
    info.url = Strings.emptyToNull(group.getUrl());
    info.options = new GroupOptionsInfo(group);

    AccountGroup g = GroupDescriptions.toAccountGroup(group);
    if (g != null) {
      info.description = Strings.emptyToNull(g.getDescription());
      info.groupId = g.getId().get();
      if (g.getOwnerGroupUUID() != null) {
        info.ownerId = Url.encode(g.getOwnerGroupUUID().get());
        GroupDescription.Basic o = groupBackend.get(g.getOwnerGroupUUID());
        if (o != null) {
          info.owner = o.getName();
        }
      }
    }

    return info;
  }
예제 #17
0
 @Override
 public String apply(final String key) {
   if (key == null) {
     return null;
   }
   final String presentVal;
   try {
     presentVal = loadingCache.get(key, new applyCallable(key));
     return Strings.emptyToNull(presentVal);
   } catch (ExecutionException e) {
     LOGGER.debug("value not found for key [%s]", key);
     return null;
   }
 }
예제 #18
0
 @Override
 public Filter toFilter() {
   if (extractionFn == null) {
     return new SelectorFilter(dimension, value);
   } else {
     final String valueOrNull = Strings.emptyToNull(value);
     final Predicate<String> predicate =
         new Predicate<String>() {
           @Override
           public boolean apply(String input) {
             return Objects.equals(valueOrNull, input);
           }
         };
     return new DimensionPredicateFilter(dimension, predicate, extractionFn);
   }
 }
예제 #19
0
 private void kbInvoiceItemsIdsFromString(
     @Nullable final String kbInvoiceItemsIdsAsString,
     final Map<UUID, Set<UUID>> kbInvoiceItemsIds)
     throws IOException {
   if (Strings.emptyToNull(kbInvoiceItemsIdsAsString) != null) {
     final Map<UUID, Set<UUID>> kbInvoiceItemsIdsAsMap =
         objectMapper.readValue(
             kbInvoiceItemsIdsAsString, new TypeReference<Map<UUID, Set<UUID>>>() {});
     for (final UUID kbInvoiceItemId : kbInvoiceItemsIdsAsMap.keySet()) {
       if (kbInvoiceItemsIds.get(kbInvoiceItemId) == null) {
         kbInvoiceItemsIds.put(kbInvoiceItemId, new HashSet<UUID>());
       }
       kbInvoiceItemsIds.get(kbInvoiceItemId).addAll(kbInvoiceItemsIdsAsMap.get(kbInvoiceItemId));
     }
   }
 }
 public BusinessFactoryBase(
     final CurrencyConversionDao currencyConversionDao,
     final OSGIKillbillLogService logService,
     final OSGIKillbillAPI osgiKillbillAPI,
     final OSGIConfigPropertiesService osgiConfigPropertiesService,
     final Clock clock) {
   this.logService = logService;
   this.osgiKillbillAPI = osgiKillbillAPI;
   this.clock = clock;
   this.referenceCurrency =
       Objects.firstNonNull(
           Strings.emptyToNull(
               osgiConfigPropertiesService.getString(ANALYTICS_REFERENCE_CURRENCY_PROPERTY)),
           "USD");
   this.currencyConversionDao = currencyConversionDao;
 }
  @Override
  public void afterRegistration(
      final OObjectDatabaseTx db,
      final SchemeDescriptor descriptor,
      final Field field,
      final LuceneIndex annotation) {
    db.getMetadata().getIndexManager().reload();
    final String property = field.getName();
    final String model = descriptor.schemeClass;
    final String name =
        Objects.firstNonNull(Strings.emptyToNull(annotation.name().trim()), model + '.' + property);
    final OClass clazz = db.getMetadata().getSchema().getClass(model);
    final OIndex<?> classIndex = clazz.getClassIndex(name);
    final OClass.INDEX_TYPE type = OClass.INDEX_TYPE.FULLTEXT;
    if (!descriptor.initialRegistration && classIndex != null) {
      final IndexValidationSupport support = new IndexValidationSupport(classIndex, logger);
      support.checkTypeCompatible(type);
      support.checkFieldsCompatible(property);

      final boolean correct =
          support
              .isIndexSigns(
                  classIndex.getConfiguration().field("algorithm"), getAnalyzer(classIndex))
              .matchRequiredSigns(
                  type, OLuceneIndexFactory.LUCENE_ALGORITHM, annotation.value().getName());
      if (!correct) {
        support.dropIndex(db);
      } else {
        // index ok
        return;
      }
    }
    final ODocument metadata = createMetadata(annotation);
    SchemeUtils.command(
        db,
        "create index %s on %s (%s) %s engine %s metadata %s",
        name,
        model,
        property,
        type.name(),
        OLuceneIndexFactory.LUCENE_ALGORITHM,
        metadata.toJSON());
    logger.info("Lucene fulltext index '{}' ({} [{}]) created", name, model, property);
  }
예제 #22
0
  @Override
  public DimFilter optimize() {
    if (this.getExtractionFn() instanceof LookupExtractionFn
        && ((LookupExtractionFn) this.getExtractionFn()).isOptimize()) {
      LookupExtractionFn exFn = (LookupExtractionFn) this.getExtractionFn();
      LookupExtractor lookup = exFn.getLookup();

      final String convertedValue = Strings.emptyToNull(value);

      // We cannot do an unapply()-based optimization if the selector value
      // and the replaceMissingValuesWith value are the same, since we have to match on
      // all values that are not present in the lookup.
      if (!exFn.isRetainMissingValue()
          && Objects.equals(convertedValue, exFn.getReplaceMissingValueWith())) {
        return this;
      }

      final String mappingForValue = lookup.apply(convertedValue);
      final List<String> keys = new ArrayList<>();
      keys.addAll(lookup.unapply(convertedValue));

      // If retainMissingValues is true and the selector value is not in the lookup map,
      // there may be row values that match the selector value but are not included
      // in the lookup map. Match on the selector value as well.
      // If the selector value is overwritten in the lookup map, don't add selector value to keys.
      if (exFn.isRetainMissingValue() && mappingForValue == null) {
        keys.add(convertedValue);
      }

      if (keys.isEmpty()) {
        return this;
      } else if (keys.size() == 1) {
        return new SelectorDimFilter(dimension, keys.get(0), null);
      } else {
        return new InDimFilter(dimension, keys, null);
      }
    }
    return this;
  }
예제 #23
0
  private Optional<Brand> getBrand(ProgData progData, Channel channel, Timestamp updatedAt) {
    String brandId = progData.getSeriesId();
    if (Strings.isNullOrEmpty(brandId) || Strings.isNullOrEmpty(brandId.trim())) {
      return Optional.absent();
    }

    String brandUri = PaHelper.getBrandUri(brandId);
    Alias brandAlias = PaHelper.getBrandAlias(brandId);

    Maybe<Identified> possiblePrevious =
        contentResolver.findByCanonicalUris(ImmutableList.of(brandUri)).getFirstValue();

    Brand brand =
        possiblePrevious.hasValue()
            ? (Brand) possiblePrevious.requireValue()
            : new Brand(brandUri, "pa:b-" + brandId, Publisher.PA);

    brand.addAlias(brandAlias);
    brand.setTitle(progData.getTitle());
    brand.setDescription(Strings.emptyToNull(progData.getSeriesSynopsis()));
    brand.setSpecialization(specialization(progData, channel));
    brand.setMediaType(channel.getMediaType());
    setCertificate(progData, brand);
    setGenres(progData, brand);

    selectImages(
        progData.getPictures(),
        brand,
        PA_PICTURE_TYPE_BRAND,
        PA_PICTURE_TYPE_SERIES,
        Maybe.<String>nothing());

    if (isClosedBrand(Optional.of(brand))) {
      brand.setScheduleOnly(true);
    }
    brand.setLastUpdated(updatedAt.toDateTimeUTC());

    return Optional.of(brand);
  }
예제 #24
0
 private GitilesView.Builder parseArchiveCommand(
     HttpServletRequest req, String repoName, String path) throws IOException {
   String ext = null;
   for (String e : ArchiveFormat.allExtensions()) {
     if (path.endsWith(e)) {
       path = path.substring(0, path.length() - e.length());
       ext = e;
       break;
     }
   }
   if (ext == null || path.endsWith("/")) {
     return null;
   }
   RevisionParser.Result result = parseRevision(req, path);
   if (result == null || result.getOldRevision() != null) {
     return null;
   }
   return GitilesView.archive()
       .setRepositoryName(repoName)
       .setRevision(result.getRevision())
       .setPathPart(Strings.emptyToNull(result.getPath()))
       .setExtension(ext);
 }
예제 #25
0
  private boolean isMandatoryFieldNotEmptyAndValid(
      final Component currentChangedComponent, final Object newValue) {

    boolean valid = true;
    final List<AbstractField<?>> requiredComponents =
        allComponents.stream().filter(field -> field.isRequired()).collect(Collectors.toList());

    requiredComponents.addAll(
        allComponents.stream().filter(this::hasNullValidator).collect(Collectors.toList()));

    for (final AbstractField field : requiredComponents) {
      Object value = getCurrentVaue(currentChangedComponent, newValue, field);

      if (String.class.equals(field.getType())) {
        value = Strings.emptyToNull((String) value);
      }

      if (Set.class.equals(field.getType())) {
        value = emptyToNull((Collection<?>) value);
      }

      if (value == null) {
        return false;
      }

      // We need to loop through the entire loop for validity testing.
      // Otherwise the UI will only mark the
      // first field with errors and then stop. If there are several
      // fields with errors, this is bad.
      field.setValue(value);
      if (!field.isValid()) {
        valid = false;
      }
    }

    return valid;
  }
예제 #26
0
    private Allocation(final RunInstancesType request) {
      this.context = Contexts.lookup();
      this.instanceIds = Maps.newHashMap();
      this.instanceUuids = Maps.newHashMap();
      this.request = request;
      this.minCount = request.getMinCount();
      this.maxCount = request.getMaxCount();
      this.usePrivateAddressing = "private".equals(request.getAddressingType());
      this.disableApiTermination =
          Optional.fromNullable(request.getDisableTerminate()).or(Boolean.FALSE);
      this.monitoring = request.getMonitoring() == null ? Boolean.FALSE : request.getMonitoring();
      this.clientToken = Strings.emptyToNull(request.getClientToken());

      this.ownerFullName = this.context.getUserFullName();
      if ((this.request.getInstanceType() == null) || "".equals(this.request.getInstanceType())) {
        this.request.setInstanceType(VmTypes.defaultTypeName());
      }

      this.reservationIndex = UniqueIds.nextIndex(VmInstance.class, (long) request.getMaxCount());
      this.reservationId = IdentityIdFormats.generate(getAuthenticatedArn(), "r");
      this.request.setMonitoring(this.monitoring);
      // GRZE:FIXME: moved all this encode/decode junk into util.UserDatas
      if (this.request.getUserData() != null) {
        try {
          this.userData = Base64.decode(this.request.getUserData());
          this.request.setUserData(new String(Base64.encode(this.userData)));
        } catch (Exception e) {
        }
      } else {
        try {
          this.request.setUserData(new String(Base64.encode(new byte[0])));
        } catch (Exception ex) {
          LOG.error(ex, ex);
        }
      }
      this.credential = null;
    }
예제 #27
0
  public Map<String, Object> toSoyData(ObjectId treeId, TreeWalk tw)
      throws MissingObjectException, IOException {
    ReadmeHelper readme =
        new ReadmeHelper(reader, view, MarkdownConfig.get(cfg), rootTree, requestUri);
    List<Object> entries = Lists.newArrayList();
    GitilesView.Builder urlBuilder = GitilesView.path().copyFrom(view);
    while (tw.next()) {
      FileType type = FileType.forEntry(tw);
      String name = tw.getNameString();

      GitilesView.Type viewType = view.getType();
      if (viewType == GitilesView.Type.PATH) {
        urlBuilder.setPathPart(view.getPathPart() + "/" + name);
      } else if (viewType == GitilesView.Type.REVISION) {
        // Got here from a tag pointing at a tree.
        urlBuilder.setPathPart(name);
      } else {
        throw new IllegalStateException(
            String.format("Cannot render TreeSoyData from %s view", viewType));
      }

      String url = urlBuilder.toUrl();
      if (type == FileType.TREE) {
        name += "/";
        url += "/";
      }
      Map<String, String> entry = Maps.newHashMapWithExpectedSize(4);
      entry.put("type", type.toString());
      entry.put("name", name);
      entry.put("url", url);
      if (type == FileType.SYMLINK) {
        String target = new String(reader.open(tw.getObjectId(0)).getCachedBytes(), UTF_8);
        entry.put("targetName", getTargetDisplayName(target));
        String targetUrl = resolveTargetUrl(view, target);
        if (targetUrl != null) {
          entry.put("targetUrl", targetUrl);
        }
      } else {
        readme.considerEntry(tw);
      }
      entries.add(entry);
    }

    Map<String, Object> data = Maps.newHashMapWithExpectedSize(3);
    data.put("sha", treeId.name());
    data.put("entries", entries);

    if (view.getType() == GitilesView.Type.PATH
        && view.getRevision().getPeeledType() == OBJ_COMMIT) {
      data.put("logUrl", GitilesView.log().copyFrom(view).toUrl());
      data.put(
          "archiveUrl",
          GitilesView.archive()
              .copyFrom(view)
              .setPathPart(Strings.emptyToNull(view.getPathPart()))
              .setExtension(archiveFormat.getDefaultSuffix())
              .toUrl());
      data.put("archiveType", archiveFormat.getShortName());
    }

    if (readme.isPresent()) {
      data.put("readmePath", readme.getPath());
      data.put("readmeHtml", readme.render());
    }

    return data;
  }
예제 #28
0
 private String asStringOrNull(Object obj) {
   return Strings.emptyToNull(Optional.fromNullable(obj).or("").toString());
 }
 @Override
 public String apply(Object value) {
   return Strings.emptyToNull(fn.apply(value));
 }
예제 #30
0
 protected Optional<String> rtFilmIdentifierFor(ProgData progData) {
   return Optional.fromNullable(Strings.emptyToNull(progData.getRtFilmnumber()));
 }