コード例 #1
0
  @Test
  public void tooLongSender() throws Exception {
    Mailbox mbox =
        MailboxManager.getInstance().getMailboxByAccountId(MockProvisioning.DEFAULT_ACCOUNT_ID);
    Map<String, Object> fields = new HashMap<String, Object>();
    fields.put(ContactConstants.A_firstName, Strings.repeat("F", 129));
    Contact contact =
        mbox.createContact(null, new ParsedContact(fields), Mailbox.ID_FOLDER_CONTACTS, null);

    DbConnection conn = DbPool.getConnection(mbox);

    Assert.assertEquals(
        Strings.repeat("F", 128),
        DbUtil.executeQuery(
                conn,
                "SELECT sender FROM mboxgroup1.mail_item WHERE mailbox_id = ? AND id = ?",
                mbox.getId(),
                contact.getId())
            .getString(1));

    fields.put(ContactConstants.A_firstName, null);
    fields.put(ContactConstants.A_lastName, Strings.repeat("L", 129));
    mbox.modifyContact(null, contact.getId(), new ParsedContact(fields));

    Assert.assertEquals(
        Strings.repeat("L", 128),
        DbUtil.executeQuery(
                conn,
                "SELECT sender FROM mboxgroup1.mail_item WHERE mailbox_id = ? AND id = ?",
                mbox.getId(),
                contact.getId())
            .getString(1));

    conn.closeQuietly();
  }
コード例 #2
0
ファイル: ClientBuilder.java プロジェクト: freddiezhao/hedwig
  public T build() {
    Preconditions.checkArgument(null != serviceType, "ServiceType cannot be null.");
    Preconditions.checkArgument(null != clazz, "Service interface cannot be null.");
    Preconditions.checkArgument(clazz.isInterface(), "Service interface must be an interface.");
    if (null == factory) {
      if (null == strategy) {
        strategy = Strategy.RANDOM;
      }
      factory = LoadBalancerSupport.newFactory(strategy);
    }
    ServiceProxyFactory proxyFactory;
    switch (serviceType) {
      case THRIFT:
        proxyFactory = ThriftServiceProxyFactory.getInstance();
        break;
      default:
        throw new IllegalArgumentException("Not supported ServiceType: " + serviceType);
    }
    if (StringUtils.isEmpty(serviceName)) {
      serviceName = ServiceConfigHelper.buildDefaultServiceName(serviceType, clazz);
    }
    if (Strings.isNullOrEmpty(serviceGroup)) {
      serviceGroup = ZookeeperConfig.getServiceGroup(serviceName);
    }
    if (!Strings.isNullOrEmpty(user)) {}

    return proxyFactory.getService(serviceGroup, serviceName, factory, clazz);
  }
コード例 #3
0
 @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();
 }
コード例 #4
0
 public static final By elementWithAttribute(
     String element, String attributeName, String attributeValue) {
   Preconditions.checkArgument(!Strings.isNullOrEmpty(element));
   Preconditions.checkArgument(!Strings.isNullOrEmpty(attributeName));
   Preconditions.checkArgument(!Strings.isNullOrEmpty(attributeValue));
   return By.xpath(String.format(".//%s[@%s='%s']", element, attributeName, attributeValue));
 }
コード例 #5
0
ファイル: Main.java プロジェクト: dandujaipalreddy/mockserver
  private static boolean validateArguments(Map<String, String> parsedArguments) {
    List<String> errorMessages = new ArrayList<String>();
    validatePortListArgument(parsedArguments, SERVER_PORT_KEY, errorMessages);
    validatePortArgument(parsedArguments, PROXY_PORT_KEY, errorMessages);
    validatePortArgument(parsedArguments, PROXY_REMOTE_PORT_KEY, errorMessages);
    validateHostnameArgument(parsedArguments, PROXY_REMOTE_HOST_KEY, errorMessages);

    if (!errorMessages.isEmpty()) {
      int maxLengthMessage = 0;
      for (String errorMessage : errorMessages) {
        if (errorMessage.length() > maxLengthMessage) {
          maxLengthMessage = errorMessage.length();
        }
      }
      outputPrintStream.println(
          System.getProperty("line.separator") + "   " + Strings.padEnd("", maxLengthMessage, '='));
      for (String errorMessage : errorMessages) {
        outputPrintStream.println("   " + errorMessage);
      }
      outputPrintStream.println(
          "   " + Strings.padEnd("", maxLengthMessage, '=') + System.getProperty("line.separator"));
      return false;
    }
    return true;
  }
コード例 #6
0
  private SafeHtml createArgumentLabel(ArgumentEditor argEditor) {
    SafeHtmlBuilder labelText = new SafeHtmlBuilder();
    Boolean isRequired = argEditor.requiredEditor().getValue();
    if ((isRequired != null) && isRequired) {
      // If the field is required, it needs to be marked as such.
      labelText.append(appearance.getRequiredFieldLabel());
    }
    // JDS Remove the trailing colon. The FieldLabels will apply it automatically.
    String label = Strings.nullToEmpty(argEditor.labelEditor().getValue());
    SafeHtml safeHtmlLabel = SafeHtmlUtils.fromString(label.replaceFirst(":$", ""));
    ArgumentType argumentType = argEditor.typeEditor().getValue();
    if (Info.equals(argumentType)) {
      labelText.append(appearance.sanitizeHtml(label));
    } else {
      if (Flag.equals(argumentType)) {
        labelText.append(new SafeHtmlBuilder().appendHtmlConstant("&nbsp;").toSafeHtml());
      }
      String id = argEditor.idEditor().getValue();
      String description = argEditor.descriptionEditor().getValue();

      if (Strings.isNullOrEmpty(description) || EMPTY_GROUP_ARG_ID.equals(id)) {
        labelText.append(safeHtmlLabel);
      } else {
        labelText.append(appearance.getContextualHelpLabel(safeHtmlLabel, description));
      }
    }
    return labelText.toSafeHtml();
  }
コード例 #7
0
  @Test
  public void singleValueField_WithMaxSize() throws Exception {
    SearchResponse response =
        client()
            .prepareSearch("idx")
            .setTypes("high_card_type")
            .addAggregation(
                terms("terms")
                    .executionHint(randomExecutionHint())
                    .field(SINGLE_VALUED_FIELD_NAME)
                    .size(20)
                    .order(
                        Terms.Order.term(
                            true))) // we need to sort by terms cause we're checking the first 20
                                    // values
            .execute()
            .actionGet();

    assertSearchResponse(response);

    Terms terms = response.getAggregations().get("terms");
    assertThat(terms, notNullValue());
    assertThat(terms.getName(), equalTo("terms"));
    assertThat(terms.getBuckets().size(), equalTo(20));

    for (int i = 0; i < 20; i++) {
      Terms.Bucket bucket = terms.getBucketByKey("val" + Strings.padStart(i + "", 3, '0'));
      assertThat(bucket, notNullValue());
      assertThat(key(bucket), equalTo("val" + Strings.padStart(i + "", 3, '0')));
      assertThat(bucket.getDocCount(), equalTo(1l));
    }
  }
コード例 #8
0
 private void getTLSParameters() {
   String tempString = System.getProperty("enableNettyTLS");
   enableNettyTLS =
       Strings.isNullOrEmpty(tempString) ? TLS_DISABLED : Boolean.parseBoolean(tempString);
   log.info("enableNettyTLS = {}", enableNettyTLS);
   if (enableNettyTLS) {
     ksLocation = System.getProperty("javax.net.ssl.keyStore");
     if (Strings.isNullOrEmpty(ksLocation)) {
       enableNettyTLS = TLS_DISABLED;
       return;
     }
     tsLocation = System.getProperty("javax.net.ssl.trustStore");
     if (Strings.isNullOrEmpty(tsLocation)) {
       enableNettyTLS = TLS_DISABLED;
       return;
     }
     ksPwd = System.getProperty("javax.net.ssl.keyStorePassword").toCharArray();
     if (MIN_KS_LENGTH > ksPwd.length) {
       enableNettyTLS = TLS_DISABLED;
       return;
     }
     tsPwd = System.getProperty("javax.net.ssl.trustStorePassword").toCharArray();
     if (MIN_KS_LENGTH > tsPwd.length) {
       enableNettyTLS = TLS_DISABLED;
       return;
     }
   }
 }
コード例 #9
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()));
  }
コード例 #10
0
ファイル: DDF.java プロジェクト: ranjeet-floyd/DDF
  /**
   * Initialization to be done after constructor assignments, such as setting of the all-important
   * DDFManager.
   */
  protected void initialize(
      DDFManager manager,
      Object data,
      Class<?>[] typeSpecs,
      String namespace,
      String name,
      Schema schema)
      throws DDFException {
    this.validateSchema(schema);
    this.setManager(manager); // this must be done first in case later stuff needs a manager

    if (typeSpecs != null) {
      this.getRepresentationHandler().set(data, typeSpecs);
    }

    this.getSchemaHandler().setSchema(schema);
    if (schema != null && schema.getTableName() == null) {
      String tableName = this.getSchemaHandler().newTableName();
      schema.setTableName(tableName);
    }

    if (Strings.isNullOrEmpty(namespace)) namespace = this.getManager().getNamespace();
    this.setNamespace(namespace);

    manager.setDDFUUID(this, UUID.randomUUID());

    if (!Strings.isNullOrEmpty(name)) manager.setDDFName(this, name);

    // Facades
    this.ML = new MLFacade(this, this.getMLSupporter());
    this.VIEWS = new ViewsFacade(this, this.getViewHandler());
    this.Transform = new TransformFacade(this, this.getTransformationHandler());
    this.R = new RFacade(this, this.getAggregationHandler());
    this.mCreatedTime = new Date();
  }
コード例 #11
0
  @LargeTest
  public void testTTSAudioLocale() throws Exception {
    solo.pressSpinnerItem(6 /* Question audio spinner */, 3 /* German */);
    // solo.sleep(300);

    solo.pressSpinnerItem(7 /* Answer audio spinner */, 2 /* Italian */);
    // solo.sleep(300);

    solo.clickOnActionBarItem(R.id.save);
    // solo.sleep(2000);

    AnyMemoDBOpenHelper helper =
        AnyMemoDBOpenHelperManager.getHelper(mActivity, TestHelper.SAMPLE_DB_PATH);
    try {
      SettingDao settingDao = helper.getSettingDao();
      Setting setting = settingDao.queryForId(1);
      assertEquals("DE", setting.getQuestionAudio());
      assertEquals("IT", setting.getAnswerAudio());
      assertTrue(Strings.isNullOrEmpty(setting.getQuestionAudioLocation()));
      assertTrue(Strings.isNullOrEmpty(setting.getAnswerAudioLocation()));

    } finally {
      AnyMemoDBOpenHelperManager.releaseHelper(helper);
    }
  }
コード例 #12
0
  @Override
  public BasicDocumentRevision updateLocalDocument(
      String docId, String prevRevId, final DocumentBody body) {
    Preconditions.checkState(this.isOpen(), "Database is closed");
    Preconditions.checkArgument(
        !Strings.isNullOrEmpty(docId), "Input document id can not be empty");
    Preconditions.checkArgument(
        !Strings.isNullOrEmpty(prevRevId), "Input previous revision id can not be empty");
    Preconditions.checkNotNull(body, "Input document body can not be null");

    CouchUtils.validateRevisionId(prevRevId);

    DocumentRevision preRevision = this.getLocalDocument(docId, prevRevId);
    this.sqlDb.beginTransaction();
    try {
      String newRevId = CouchUtils.generateNextLocalRevisionId(prevRevId);
      ContentValues values = new ContentValues();
      values.put("revid", newRevId);
      values.put("json", body.asBytes());
      String[] whereArgs = new String[] {docId, prevRevId};
      int rowsUpdated = this.sqlDb.update("localdocs", values, "docid=? AND revid=?", whereArgs);
      if (rowsUpdated == 1) {
        this.sqlDb.setTransactionSuccessful();
        return this.getLocalDocument(docId, newRevId);
      } else {
        throw new IllegalStateException("Error updating local docs: " + preRevision);
      }
    } finally {
      this.sqlDb.endTransaction();
    }
  }
コード例 #13
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()));
  }
  private ClientDetailsEntity validateAuth(ClientDetailsEntity newClient)
      throws ValidationException {
    if (newClient.getTokenEndpointAuthMethod() == null) {
      newClient.setTokenEndpointAuthMethod(AuthMethod.SECRET_BASIC);
    }

    if (newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_BASIC
        || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_JWT
        || newClient.getTokenEndpointAuthMethod() == AuthMethod.SECRET_POST) {

      if (Strings.isNullOrEmpty(newClient.getClientSecret())) {
        // no secret yet, we need to generate a secret
        newClient = clientService.generateClientSecret(newClient);
      }
    } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.PRIVATE_KEY) {
      if (Strings.isNullOrEmpty(newClient.getJwksUri()) && newClient.getJwks() == null) {
        throw new ValidationException(
            "invalid_client_metadata",
            "JWK Set URI required when using private key authentication",
            HttpStatus.BAD_REQUEST);
      }

      newClient.setClientSecret(null);
    } else if (newClient.getTokenEndpointAuthMethod() == AuthMethod.NONE) {
      newClient.setClientSecret(null);
    } else {
      throw new ValidationException(
          "invalid_client_metadata", "Unknown authentication method", HttpStatus.BAD_REQUEST);
    }
    return newClient;
  }
コード例 #15
0
ファイル: CoreFilter.java プロジェクト: colin-lee/core-filter
 /* 避免中文乱码 */
 private void setContentType(HttpServletResponse res) {
   String contentType = res.getContentType();
   if (Strings.isNullOrEmpty(contentType)) {
     contentType = "text/html; charset=UTF-8";
   }
   final String iso = "iso-8859-1";
   if (!contentType.toLowerCase().contains("charset")) {
     String encoding = res.getCharacterEncoding();
     if (Strings.isNullOrEmpty(encoding) || encoding.toLowerCase().equals(iso)) {
       encoding = "UTF-8";
     }
     contentType += "; charset=" + encoding;
     res.setContentType(contentType);
   } else {
     int pos = contentType.toLowerCase().lastIndexOf(iso);
     if (pos > 0) {
       String mime = contentType.substring(0, pos) + "UTF-8";
       int start = pos + iso.length() + 1;
       if (start < contentType.length()) {
         mime += contentType.substring(start);
       }
       res.setContentType(mime);
     }
   }
 }
コード例 #16
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);
  }
  @Override
  public void downloadPositions(String city, String csvFileLocation) {

    if (Strings.isNullOrEmpty(city)) {
      throw new IllegalArgumentException(String.format("Invalid value of city '%s'", city));
    }

    // If destination dir is not provided as second argument in command line, then get it from
    // application.properties file.
    if (Strings.isNullOrEmpty(csvFileLocation)) {
      csvFileLocation = csvOutputDir;
      logger.info("Used destination directory from 'application.properties'.");
    } else {
      logger.info("Used destination directory provided in command line argument.");
    }

    logger.info(String.format("Retrieve date from JSON API. City: '%s'", city));
    String url = jsonAPI + city;
    String response = httpURLConnectionService.sendGet(url);

    JsonLocationInfo[] jsonLocationInfoArr =
        new Gson().fromJson(response, JsonLocationInfo[].class);

    logger.info("Export date to .csv file.");
    csvGeneratorService.generateCsv(city, csvFileLocation, jsonLocationInfoArr);
  }
コード例 #18
0
ファイル: Config.java プロジェクト: OpenNMS/opennms
 public Long getCacheReloadTime() throws NumberFormatException {
   String value = getTrimmedProperty("jira.cache.reloadTime");
   if (!Strings.isNullOrEmpty(value) && !Strings.isNullOrEmpty(value.trim())) {
     return Long.valueOf(value.trim());
   }
   return null;
 }
コード例 #19
0
ファイル: WidgetAction.java プロジェクト: DaisyCQ/NADEEF
 private static String getSubquery(String filter) {
   String sql = "VIOLATION";
   if (!Strings.isNullOrEmpty(filter)) {
     if (filter.startsWith(":=")) {
       String vid = filter.substring(2).trim();
       if (!Strings.isNullOrEmpty(vid)) {
         String[] tokens = vid.split(",");
         for (String token : tokens)
           if (!SQLUtil.isValidInteger(token))
             throw new IllegalArgumentException("Input is not valid.");
         sql = "(select * from VIOLATION where vid = any(array[" + vid + "])) a";
       }
     } else if (filter.startsWith("?=")) {
       String tid = filter.substring(2).trim();
       if (!Strings.isNullOrEmpty(tid)) {
         String[] tokens = tid.split(",");
         for (String token : tokens)
           if (!SQLUtil.isValidInteger(token))
             throw new IllegalArgumentException("Input is not valid.");
         sql = "(select * from VIOLATION where tid = any(array[" + tid + "])) a";
       }
     } else {
       sql = "(select * from VIOLATION where value like '%" + filter + "%') a";
     }
   }
   return sql;
 }
コード例 #20
0
  protected void encodeIcon(FacesContext context, UIComponent component) throws IOException {
    TreeNodeState nodeState = getNodeState(context);

    AbstractTreeNode treeNode = (AbstractTreeNode) component;

    AbstractTree tree = treeNode.findTreeComponent();

    if (nodeState.isLeaf()) {
      String iconLeaf = (String) getFirstNonEmptyAttribute("iconLeaf", treeNode, tree);
      encodeIconForNodeState(context, tree, treeNode, nodeState, iconLeaf);
    } else {
      String iconExpanded = (String) getFirstNonEmptyAttribute("iconExpanded", treeNode, tree);
      String iconCollapsed = (String) getFirstNonEmptyAttribute("iconCollapsed", treeNode, tree);

      if (Strings.isNullOrEmpty(iconCollapsed) && Strings.isNullOrEmpty(iconExpanded)) {
        encodeIconForNodeState(context, tree, treeNode, nodeState, null);
      } else {
        SwitchType toggleType =
            TreeRendererBase.getToggleTypeOrDefault(treeNode.findTreeComponent());

        if (toggleType == SwitchType.client || nodeState == TreeNodeState.collapsed) {
          encodeIconForNodeState(context, tree, treeNode, TreeNodeState.collapsed, iconCollapsed);
        }

        if (toggleType == SwitchType.client
            || nodeState == TreeNodeState.expanded
            || nodeState == TreeNodeState.expandedNoChildren) {
          encodeIconForNodeState(context, tree, treeNode, TreeNodeState.expanded, iconExpanded);
        }
      }
    }
  }
コード例 #21
0
ファイル: ModMetadata.java プロジェクト: richardg867/FML
 public ModMetadata(JsonNode node) {
   Map<JsonStringNode, Object> processedFields =
       Maps.transformValues(node.getFields(), new JsonStringConverter());
   modId = (String) processedFields.get(aStringBuilder("modid"));
   if (Strings.isNullOrEmpty(modId)) {
     FMLLog.log(Level.SEVERE, "Found an invalid mod metadata file - missing modid");
     throw new LoaderException();
   }
   name = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("name")));
   description = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("description")));
   url = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("url")));
   updateUrl = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("updateUrl")));
   logoFile = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("logoFile")));
   version = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("version")));
   credits = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("credits")));
   parent = Strings.nullToEmpty((String) processedFields.get(aStringBuilder("parent")));
   authorList =
       Objects.firstNonNull(
           ((List<String>) processedFields.get(aStringBuilder("authors"))),
           Objects.firstNonNull(
               ((List<String>) processedFields.get(aStringBuilder("authorList"))), authorList));
   requiredMods =
       processReferences(processedFields.get(aStringBuilder("requiredMods")), HashSet.class);
   dependencies =
       processReferences(processedFields.get(aStringBuilder("dependencies")), ArrayList.class);
   dependants =
       processReferences(processedFields.get(aStringBuilder("dependants")), ArrayList.class);
   useDependencyInformation =
       Boolean.parseBoolean(
           Strings.nullToEmpty(
               (String) processedFields.get(aStringBuilder("useDependencyInformation"))));
 }
コード例 #22
0
  private List<String> getNonBinaryColumns() {
    List<String> columns =
        Lists.newArrayList(
            Iterables.filter(
                Iterables.transform(
                    getValueTable().getVariables(),
                    new Function<Variable, String>() {
                      @Nullable
                      @Override
                      public String apply(@Nullable Variable input) {
                        if (input.getValueType().isBinary()) return null;

                        return getValueTable().getVariableSqlName(input.getName());
                      }
                    }),
                Predicates.notNull()));

    String created = getValueTable().getCreatedTimestampColumnName();

    if (!Strings.isNullOrEmpty(created)) columns.add(created);

    String updated = getValueTable().getUpdatedTimestampColumnName();

    if (!Strings.isNullOrEmpty(updated)) columns.add(updated);

    return columns;
  }
コード例 #23
0
 public void load() throws BackingStoreException {
   options.clear();
   for (final CompilerOption option : CompilerOption.ALL_OPTIONS) {
     final String value = helper.getString(option.getName(), null);
     if (option instanceof BooleanOption) {
       options.put(
           option,
           value != null
               ? Boolean.parseBoolean(value)
               : ((BooleanOption) option).getDefaultValue());
     } else if (option instanceof PathsOption) {
       if (!Strings.isNullOrEmpty(value)) {
         options.put(option, PathsOption.fromString(value));
       }
     } else if (option instanceof ModuleOption) {
       if (!Strings.isNullOrEmpty(value)) {
         options.put(option, value);
       }
     } else {
       if (value != null) {
         // final String[] str = value.split(SEPARATOR);
         // options.put(option, new Tuple<String, String>(str[0],
         // str[1]));
       }
     }
   }
   options.put(CompilerOption.DEBUG_INFO, true);
 }
コード例 #24
0
  private Person ingestPerson(org.atlasapi.remotesite.pa.profiles.bindings.Person paPerson) {
    Person person = new Person();
    person.setCanonicalUri(PERSON_URI_PREFIX + paPerson.getId());

    Name name = paPerson.getName();
    // First and Last name are optional in the dtd so check both are
    // non-null to avoid strange names.
    if (!Strings.isNullOrEmpty(name.getFirstname()) && !Strings.isNullOrEmpty(name.getLastname())) {
      person.withName(name.getFirstname() + " " + name.getLastname());
    }
    person.setGivenName(name.getFirstname());
    person.setFamilyName(name.getLastname());

    person.setGender(paPerson.getGender());
    if (paPerson.getBorn() != null) {
      person.setBirthDate(dateTimeFormatter.parseDateTime(paPerson.getBorn()));
    }
    person.setBirthPlace(paPerson.getBornIn());
    person.setDescription(paPerson.getEarlyLife() + "\n\n" + paPerson.getCareer());
    person.addQuote(paPerson.getQuote());
    person.setPublisher(Publisher.PA_PEOPLE);
    person.setImages(extractImages(paPerson.getPictures()));
    person.setImage(getPrimary(person.getImages()));
    setDirectEquivalentToPAPerson(person, paPerson.getId());
    return person;
  }
コード例 #25
0
  private List<CrewMember> people(ProgData progData) {
    List<CrewMember> people = Lists.newArrayList();

    for (CastMember cast : progData.getCastMember()) {
      if (!Strings.isNullOrEmpty(cast.getActor().getPersonId())) {
        Actor actor =
            Actor.actor(
                cast.getActor().getPersonId(),
                cast.getActor().getvalue(),
                cast.getCharacter(),
                Publisher.PA);
        if (!people.contains(actor)) {
          people.add(actor);
        }
      }
    }

    for (StaffMember staffMember : progData.getStaffMember()) {
      if (!Strings.isNullOrEmpty(staffMember.getPerson().getPersonId())) {
        String roleKey = staffMember.getRole().toLowerCase().replace(' ', '_');
        CrewMember crewMember =
            CrewMember.crewMember(
                staffMember.getPerson().getPersonId(),
                staffMember.getPerson().getvalue(),
                roleKey,
                Publisher.PA);
        if (!people.contains(crewMember)) {
          people.add(crewMember);
        }
      }
    }

    return people;
  }
コード例 #26
0
ファイル: TestRunning.java プロジェクト: LittlePeng/buck
  /**
   * A helper method that adds extra XML.
   *
   * <p>This includes a test name, time (in ms), message, and stack trace, when present. Example:
   *
   * <pre>
   * &lt;testresult name="failed_test" time="200">
   *   &lt;message>Reason for test failure&lt;/message>
   *   &lt;stacktrace>Stacktrace here&lt;/stacktrace>
   * &lt;/testresult>
   * </pre>
   *
   * @param testCase The test case summary containing one or more tests.
   * @param testEl The XML element object for the <test> tag, in which extra information tags will
   *     be added.
   */
  @VisibleForTesting
  static void addExtraXmlInfo(TestCaseSummary testCase, Element testEl) {
    Document doc = testEl.getOwnerDocument();
    // Loop through the test case and extract test data.
    for (TestResultSummary testResult : testCase.getTestResults()) {
      // Extract the test name and time.
      String name = Strings.nullToEmpty(testResult.getTestName());
      String time = Long.toString(testResult.getTime());

      // Create the tag: <testresult name="..." time="...">
      Element testResultEl = doc.createElement("testresult");
      testResultEl.setAttribute("name", name);
      testResultEl.setAttribute("time", time);
      testEl.appendChild(testResultEl);

      // Create the tag: <message>(Error message here)</message>
      Element messageEl = doc.createElement("message");
      String message = Strings.nullToEmpty(testResult.getMessage());
      messageEl.appendChild(doc.createTextNode(message));
      testResultEl.appendChild(messageEl);

      // Create the tag: <stacktrace>(Stacktrace here)</stacktrace>
      Element stacktraceEl = doc.createElement("stacktrace");
      String stacktrace = Strings.nullToEmpty(testResult.getStacktrace());
      stacktraceEl.appendChild(doc.createTextNode(stacktrace));
      testResultEl.appendChild(stacktraceEl);
    }
  }
コード例 #27
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      String asyncTaskClass = getParameter(request, TaskQueueAsyncTaskScheduler.TASK_QUEUE);

      // event details
      String eventClassAsString = getParameter(request, TaskQueueAsyncTaskScheduler.EVENT);
      String eventAsJson = getParameter(request, TaskQueueAsyncTaskScheduler.EVENT_AS_JSON);

      // if event is passed then it should be dispatched to it's handler
      if (!Strings.isNullOrEmpty(eventClassAsString) && !Strings.isNullOrEmpty(eventAsJson)) {

        eventDispatcher.dispatchAsyncEvent(eventClassAsString, eventAsJson);

        // if asyncTask is provided it should be executed
      } else if (!Strings.isNullOrEmpty(asyncTaskClass)) {

        Map<String, String[]> params = Maps.newHashMap(request.getParameterMap());

        // todo do not pass map here;
        taskDispatcher.dispatchAsyncTask(params, asyncTaskClass);
      }

    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }
コード例 #28
0
  /** Handles POST request for the register page. */
  private void doRegisterPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String username = req.getParameter("username");
    String location = req.getParameter("location");

    if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(location)) {
      doRegisterGet(req, resp, "Please complete all fields.");
      return;
    }

    ParticipantId id;
    try {
      id = ParticipantId.of(username + "@" + domain);
    } catch (InvalidParticipantAddress e) {
      doRegisterGet(req, resp, "Invalid username specified, use alphanumeric characters only.");
      return;
    }

    RobotAccountData robotAccount;
    try {
      robotAccount = robotRegistrar.registerNew(id, location);
    } catch (RobotRegistrationException e) {
      doRegisterGet(req, resp, e.getMessage());
      return;
    } catch (PersistenceException e) {
      LOG.severe("Failed to retrieve account data for " + id, e);
      doRegisterGet(req, resp, "Failed to retrieve account data for " + id.getAddress());
      return;
    }
    onRegisterSuccess(req, resp, robotAccount);
  }
  /*
   * This is the main entry point for the filter.
   *
   * (non-Javadoc)
   *
   * @see org.springframework.security.web.authentication.
   * AbstractAuthenticationProcessingFilter
   * #attemptAuthentication(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse)
   */
  @Override
  public Authentication attemptAuthentication(
      HttpServletRequest request, HttpServletResponse response)
      throws AuthenticationException, IOException, ServletException {

    if (!Strings.isNullOrEmpty(request.getParameter("error"))) {

      // there's an error coming back from the server, need to handle this
      handleError(request, response);
      return null; // no auth, response is sent to display page or something

    } else if (!Strings.isNullOrEmpty(request.getParameter("code"))) {

      // we got back the code, need to process this to get our tokens
      Authentication auth = handleAuthorizationCodeResponse(request, response);
      return auth;

    } else {

      // not an error, not a code, must be an initial login of some type
      handleAuthorizationRequest(request, response);

      return null; // no auth, response redirected to the server's Auth Endpoint (or possibly to the
                   // account chooser)
    }
  }
コード例 #30
0
ファイル: PTestClient.java プロジェクト: lirui-intel/hive
 public PTestClient(String logsEndpoint, String apiEndPoint, String password, String testOutputDir)
     throws MalformedURLException {
   this.testOutputDir = testOutputDir;
   if (!Strings.isNullOrEmpty(testOutputDir)) {
     Preconditions.checkArgument(
         !Strings.isNullOrEmpty(logsEndpoint),
         "logsEndPoint must be specified if " + OUTPUT_DIR + " is specified");
     if (logsEndpoint.endsWith("/")) {
       this.mLogsEndpoint = logsEndpoint;
     } else {
       this.mLogsEndpoint = logsEndpoint + "/";
     }
   } else {
     this.mLogsEndpoint = null;
   }
   if (apiEndPoint.endsWith("/")) {
     this.mApiEndPoint = apiEndPoint + "api/v1";
   } else {
     this.mApiEndPoint = apiEndPoint + "/api/v1";
   }
   URL apiURL = new URL(mApiEndPoint);
   mMapper = new ObjectMapper();
   mHttpClient = new DefaultHttpClient();
   mHttpClient
       .getCredentialsProvider()
       .setCredentials(
           new AuthScope(apiURL.getHost(), apiURL.getPort(), AuthScope.ANY_REALM),
           new UsernamePasswordCredentials("hive", password));
 }