com.google.common.base.Strings Java Examples

The following examples show how to use com.google.common.base.Strings. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: WebPickerField.java    From cuba with Apache License 2.0 6 votes vote down vote up
@Override
public void setDebugId(String id) {
    super.setDebugId(id);
    if (id != null) {
        String debugId = getDebugId();

        TestIdManager testIdManager = AppUI.getCurrent().getTestIdManager();

        for (Action action : actions) {
            CubaButton button = actionButtons.get(action);
            if (button != null && Strings.isNullOrEmpty(button.getId())) {
                button.setId(testIdManager.getTestId(debugId + "_" + action.getId()));
            }
        }
    }
}
 
Example #2
Source File: JdbcUtils.java    From platform with Apache License 2.0 6 votes vote down vote up
/**
 * 移除临时表
 *
 * @param temporaryTableName 临时表名
 */
public static void dropTemporaryTable(Connection con, String temporaryTableName) throws SQLException {
    if (!Strings.isNullOrEmpty(temporaryTableName)) {
        Statement dropTemporaryStatement = null;
        try {
            dropTemporaryStatement = con.createStatement();
            dropTemporaryStatement.execute(String.format("truncate table %s", temporaryTableName));
            dropTemporaryStatement.execute(String.format("drop table %s", temporaryTableName));
        } catch (Exception e) {
            log.error("Drop temporary table {} failure.", temporaryTableName, e);
            throw new SQLException(String.format("Drop temporary table %s failure.", temporaryTableName));
        } finally {
            close(dropTemporaryStatement);
        }
    }
}
 
Example #3
Source File: CurseFile.java    From ModPackDownloader with MIT License 6 votes vote down vote up
@Override
public void init() {
	setProjectUrl(buildProjectUrl());

	try {
		if (Strings.isNullOrEmpty(getProjectName()) || Strings.isNullOrEmpty(getName())) {
			val conn = (HttpURLConnection) new URL(getProjectUrl()).openConnection();
			conn.setInstanceFollowRedirects(false);
			conn.connect();

			val newProjectName = conn.getHeaderField("Location").split("/")[5];

			if (Strings.isNullOrEmpty(getProjectName())) {
				setProjectName(newProjectName);
			}

			if (Strings.isNullOrEmpty(getName())) {
				setName(newProjectName);
			}
		}
	} catch (final IOException e) {
		log.error(e);
	}
	setDownloadUrl(getDownloadUrl());

}
 
Example #4
Source File: PlainTextScenarioWriter.java    From JGiven with Apache License 2.0 6 votes vote down vote up
private String getIntroString( List<Word> words, int depth ) {
    String intro;
    if( depth > 0 ) {
        intro = INDENT + String.format( "%" + maxFillWordLength + "s ", " " ) +
                Strings.repeat( NESTED_INDENT, depth - 1 ) + NESTED_HEADING;

        if( words.get( 0 ).isIntroWord() ) {
            intro = intro + WordUtil.capitalize( words.get( 0 ).getValue() ) + " ";
        }
    } else {
        if( words.get( 0 ).isIntroWord() ) {
            intro = INDENT + String.format( "%" + maxFillWordLength + "s ", WordUtil.capitalize( words.get( 0 ).getValue() ) );
        } else {
            intro = INDENT + String.format( "%" + maxFillWordLength + "s ", " " );
        }
    }
    return intro;
}
 
Example #5
Source File: MessageServiceImpl.java    From qmq with Apache License 2.0 6 votes vote down vote up
private byte[] getMessageBytesWithMeta(String brokerGroup, String subject, List<BackupMessageMeta> metas) {
    final String backupAddress = metaSupplier.resolveServerAddress(brokerGroup);
    if (Strings.isNullOrEmpty(backupAddress)) return new byte[]{};
    String url = MESSAGE_QUERY_PROTOCOL + backupAddress + MESSAGE_QUERY_URL;

    try {
        BoundRequestBuilder boundRequestBuilder = ASYNC_HTTP_CLIENT.prepareGet(url);
        boundRequestBuilder.addQueryParam("backupQuery", serializer.serialize(getQuery(subject, metas)));

        final Response response = boundRequestBuilder.execute().get();
        if (response.getStatusCode() != HttpResponseStatus.OK.code()) {
            return new byte[]{};
        }

        final ByteBuffer buffer = response.getResponseBodyAsByteBuffer();


        return buffer.array();
    } catch (InterruptedException | ExecutionException e) {
        LOG.error("get message byte with meta failed.", e);
        throw new RuntimeException("get message byte failed.");
    }
}
 
Example #6
Source File: ListCursorsCommand.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
  Map<Registry, Key<Cursor>> registries =
      Registries.getTlds()
          .stream()
          .map(Registry::get)
          .filter(r -> r.getTldType() == filterTldType)
          .filter(r -> !filterEscrowEnabled || r.getEscrowEnabled())
          .collect(toImmutableMap(r -> r, r -> Cursor.createKey(cursorType, r)));
  Map<Key<Cursor>, Cursor> cursors = ofy().load().keys(registries.values());
  if (!registries.isEmpty()) {
    String header = String.format(OUTPUT_FMT, "TLD", "Cursor Time", "Last Update Time");
    System.out.printf("%s\n%s\n", header, Strings.repeat("-", header.length()));
    registries
        .entrySet()
        .stream()
        .map(
            e ->
                renderLine(
                    e.getKey().getTldStr(), Optional.ofNullable(cursors.get(e.getValue()))))
        .sorted()
        .forEach(System.out::println);
  }
}
 
Example #7
Source File: AgentParsingTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
@Test
public void declarationWithoutGuard() throws Exception {
	SarlScript mas = file(getParseHelper(), getValidationHelper(), multilineString(
			"event E {}",
			"agent A1 {",
			"on E {}",
			"}"
			));
	assertEquals(2, mas.getXtendTypes().size());
	//
	assertTrue(Strings.isNullOrEmpty(mas.getPackage()));
	//
	SarlEvent event = (SarlEvent) mas.getXtendTypes().get(0);
	assertEquals("E", event.getName());
	assertNull(event.getExtends());
	assertTrue(event.getMembers().isEmpty());
	//
	SarlAgent agent = (SarlAgent) mas.getXtendTypes().get(1);
	assertEquals("A1", agent.getName());
	assertNull(agent.getExtends());
	assertEquals(1, agent.getMembers().size());
	//
	SarlBehaviorUnit eventHandler = (SarlBehaviorUnit) agent.getMembers().get(0);
	assertTypeReferenceIdentifier(eventHandler.getName(), "E");
	assertNull(eventHandler.getGuard());
}
 
Example #8
Source File: TestMaxHttpUrlLength.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void testUrlNotLongerThan4096() {
  RestTemplate restTemplate = RestTemplateBuilder.create();

  String q = Strings.repeat("q", 4096 - "GET /springmvc/controller/sayhi?name=".length() - " HTTP/1.1\r".length());
  TestMgr.check("hi " + q + " [" + q + "]",
      restTemplate.getForObject("cse://springmvc/springmvc/controller/sayhi?name=" + q,
          String.class));

  q = Strings.repeat("q", 4096 + 1 - "GET /springmvc/controller/sayhi?name=".length() - " HTTP/1.1\r".length());
  try {
    restTemplate.getForObject("cse://springmvc/springmvc/controller/sayhi?name=" + q,
        String.class);
    TestMgr.check(true, false);
  } catch (InvocationException e) {
    TestMgr.check(414, e.getStatusCode());
  }
}
 
Example #9
Source File: SummaryResource.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
/**
 * Returns if the given metric is a simple ratio metric such as "A/B" where A and B is a metric.
 *
 * @param metricConfigDTO the config of a metric.
 *
 * @return true if the given metric is a simple ratio metric.
 */
static boolean isSimpleRatioMetric(MetricConfigDTO metricConfigDTO) {
  if (metricConfigDTO != null) {
    String metricExpression = metricConfigDTO.getDerivedMetricExpression();
    if (!Strings.isNullOrEmpty(metricExpression)) {
      Pattern pattern = Pattern.compile(SIMPLE_RATIO_METRIC_EXPRESSION_ID_PARSER);
      Matcher matcher = pattern.matcher(metricExpression);
      return matcher.matches();
    }
  }
  return false;
}
 
Example #10
Source File: TransactionInfoServiceImpl.java    From galaxy with Apache License 2.0 5 votes vote down vote up
private List<TransactionInfoDto> fromProtocol(DataSourceInfoDto dataSourceInfoDto) throws Exception{
    List<TransactionInfoDto> resultList = null;
    // Http
    String result = null;
    if (dataSourceInfoDto.getStatus() == DataSourceStatusEnum.HTTP.getCode()) {
        Map<String, String> params = new HashMap<String, String>();
        if (transactionInfo.getTxId() > 0) {
            params.put("txId", String.valueOf(transactionInfo.getTxId()));
        }
        if (transactionInfo.getParentId() > 0) {
            params.put("parentId", String.valueOf(transactionInfo.getParentId()));
        }
        if (!Strings.isNullOrEmpty(transactionInfo.getModuleId())) {
            params.put("moduleId", transactionInfo.getModuleId());
        }
        if (!Strings.isNullOrEmpty(transactionInfo.getBusinessId())) {
            params.put("businessId", transactionInfo.getBusinessId());
        }
        if (!Strings.isNullOrEmpty(transactionInfo.getBusinessType())) {
            params.put("businessType", transactionInfo.getBusinessType());
        }
        if (transactionInfo.getTxType() > -1) {
            params.put("txType", String.valueOf(transactionInfo.getTxType()));
        }
        if (transactionInfo.getTxStatus() > -1) {
            params.put("txStatus", String.valueOf(transactionInfo.getTxStatus()));
        }
        if (transactionInfo.getGmtCreated() != null) {
            params.put("gmtCreated", String.valueOf(transactionInfo.getGmtCreated()));
        }
        result = httpClientService.doGet(dataSourceInfoDto.getUrl(), params);
    }
    resultList = JSON.parseObject(result, List.class);
    return resultList;
}
 
Example #11
Source File: DynamoDbDelegate.java    From dynamodb-janusgraph-storage-backend with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static AwsClientBuilder.EndpointConfiguration getEndpointConfiguration(final Optional<String> endpoint, final String signingRegion) {
    Preconditions.checkArgument(endpoint != null, "must provide an optional endpoint and not null");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(signingRegion), "must provide a signing region");
    final String expectedServiceEndpoint = "https://" + Region.getRegion(Regions.fromName(signingRegion)).getServiceEndpoint(AmazonDynamoDB.ENDPOINT_PREFIX);
    if (endpoint.isPresent() && !Strings.isNullOrEmpty(endpoint.get())) {
        final String regionParsedFromEndpoint = AwsHostNameUtils.parseRegion(endpoint.get(), AmazonDynamoDB.ENDPOINT_PREFIX);
        Preconditions.checkArgument(regionParsedFromEndpoint == null || signingRegion.equals(regionParsedFromEndpoint));
        return new AwsClientBuilder.EndpointConfiguration(endpoint.get(), signingRegion);
    } else {
        //Regions.fromName will throw IllegalArgumentException if signingRegion is not valid.
        return new AwsClientBuilder.EndpointConfiguration(expectedServiceEndpoint, signingRegion);
    }
}
 
Example #12
Source File: HostAndPort.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * Split a freeform string into a host and port, without strict validation.
 *
 * Note that the host-only formats will leave the port field undefined. You can use
 * {@link #withDefaultPort(int)} to patch in a default value.
 *
 * @param hostPortString the input string to parse.
 * @return if parsing was successful, a populated HostAndPort object.
 * @throws IllegalArgumentException if nothing meaningful could be parsed.
 */


public static HostAndPort fromString(String hostPortString) {
  checkNotNull(hostPortString);
  String host;
  String portString = null;
  boolean hasBracketlessColons = false;
  if (hostPortString.startsWith("[")) {
    String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString);
    host = hostAndPort[0];
    portString = hostAndPort[1];
  } else {
    int colonPos = hostPortString.indexOf(':');
    if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
      // Exactly 1 colon. Split into host:port.
      host = hostPortString.substring(0, colonPos);
      portString = hostPortString.substring(colonPos + 1);
    } else {
      // 0 or 2+ colons. Bare hostname or IPv6 literal.
      host = hostPortString;
      hasBracketlessColons = (colonPos >= 0);
    }
  }
  int port = NO_PORT;
  if (!Strings.isNullOrEmpty(portString)) {
    // Try to parse the whole port string as a number.
    // JDK7 accepts leading plus signs. We don't want to.
    checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString);
    try {
      port = Integer.parseInt(portString);
    } catch (NumberFormatException e) {
      throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
    }
    checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString);
  }
  return new HostAndPort(host, port, hasBracketlessColons);
}
 
Example #13
Source File: SkillParsingTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
@Test
@Tag("sarlParsing")
public void completeFinalFieldInitialization() throws Exception {
	SarlScript mas = file(getParseHelper(), getValidationHelper(), multilineString(
			"capacity C1 { }",
			"skill S1 implements C1 {",
			"	val field1 : int = 5",
			"	val field2 : String = \"\"",
			"}"
			));
	assertEquals(2, mas.getXtendTypes().size());
	//
	assertTrue(Strings.isNullOrEmpty(mas.getPackage()));
	//
	SarlCapacity capacity = (SarlCapacity) mas.getXtendTypes().get(0);
	assertEquals("C1", capacity.getName());
	assertTypeReferenceIdentifiers(capacity.getExtends());
	assertEquals(0, capacity.getMembers().size());
	//
	SarlSkill skill = (SarlSkill) mas.getXtendTypes().get(1);
	assertEquals("S1", skill.getName());
	assertNull(skill.getExtends());
	assertTypeReferenceIdentifiers(skill.getImplements(), "C1");
	assertEquals(2, skill.getMembers().size());
	//
	SarlField attr1 = (SarlField) skill.getMembers().get(0);
	assertEquals("field1", attr1.getName());
	assertTypeReferenceIdentifier(attr1.getType(), "int");
	assertXExpression(attr1.getInitialValue(), XNumberLiteral.class, "5");
	//
	SarlField attr2 = (SarlField) skill.getMembers().get(1);
	assertEquals("field2", attr2.getName());
	assertTypeReferenceIdentifier(attr2.getType(), "java.lang.String");
	assertXExpression(attr2.getInitialValue(), XStringLiteral.class, "");
}
 
Example #14
Source File: DetailPrinter.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
void printDetail(PrintStream stream) {
    Ansi ansi = Ansi.ansi();

    String title = "Details of " + propertyInfo.getName();
    ansi
            .a(title)
            .newline()
            .a(Strings.repeat("-", title.length()))
            .newline().newline();

    printSummary(propertyInfo, ansi);
    printDeclaration(propertyInfo, ansi);
    printLongDescription(propertyInfo, ansi);
    printAdditionalInfo(propertyInfo, ansi);
    ansi.newline();

    stream.print(ansi.toString());
}
 
Example #15
Source File: RelationConstraint.java    From baleen with Apache License 2.0 5 votes vote down vote up
/**
 * Returns true if any of the strings in args are null or empty
 *
 * @param args
 * @return
 */
private boolean isNullOrEmpty(String... args) {
  for (String a : args) {
    if (Strings.isNullOrEmpty(a)) return true;
  }

  return false;
}
 
Example #16
Source File: LogView.java    From helloiot with GNU General Public License v3.0 5 votes vote down vote up
public void setDevice(DeviceSubscribe device) {
    this.device = device;
    if (Strings.isNullOrEmpty(getLabel())) {
        setLabel(device.getProperties().getProperty("label"));
    }
    if (device.getFormat().alignment().getHpos() == HPos.RIGHT) {
        statusview.getStyleClass().add("textinput-right");
    } else {
        statusview.getStyleClass().remove("textinput-right");
    }
}
 
Example #17
Source File: TemplateMessageServiceImpl.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
protected List<EmailAddress> getEmailAddresses(String recipients) {

    List<EmailAddress> emailAddressList = Lists.newArrayList();
    if (Strings.isNullOrEmpty(recipients)) {
      return emailAddressList;
    }

    for (String recipient :
        Splitter.onPattern(RECIPIENT_SEPARATOR)
            .trimResults()
            .omitEmptyStrings()
            .splitToList(recipients)) {
      emailAddressList.add(getEmailAddress(recipient));
    }
    return emailAddressList;
  }
 
Example #18
Source File: DirectSqlDatabase.java    From metacat with Apache License 2.0 5 votes vote down vote up
/**
 * Updates the database object.
 * @param databaseInfo database object
 */
public void update(final DatabaseInfo databaseInfo) {
    log.debug("Start: Database update using direct sql for {}", databaseInfo.getName());
    final long start = registry.clock().wallTime();
    try {
        final Long databaseId = getDatabaseId(databaseInfo.getName());
        final DatabaseInfo existingDatabaseInfo = getDatabaseById(databaseId, databaseInfo.getName());
        final Map<String, String> newMetadata = databaseInfo.getMetadata() == null ? Maps.newHashMap()
            : databaseInfo.getMetadata();
        final MapDifference<String, String> diff = Maps.difference(existingDatabaseInfo.getMetadata(), newMetadata);
        insertDatabaseParams(databaseId, diff.entriesOnlyOnRight());
        final Map<String, String> updateParams = diff.entriesDiffering().entrySet().stream()
            .collect(Collectors.toMap(Map.Entry::getKey, s -> s.getValue().rightValue()));
        updateDatabaseParams(databaseId, updateParams);
        final String uri =
            Strings.isNullOrEmpty(databaseInfo.getUri()) ? existingDatabaseInfo.getUri() : databaseInfo.getUri();
        final String newOwner = getOwner(databaseInfo.getAudit());
        final String owner =
            Strings.isNullOrEmpty(newOwner) ? newOwner : existingDatabaseInfo.getAudit().getCreatedBy();
        jdbcTemplate.update(SQL.UPDATE_DATABASE, new SqlParameterValue(Types.VARCHAR, uri),
            new SqlParameterValue(Types.VARCHAR, owner),
            new SqlParameterValue(Types.BIGINT, databaseId));
    } finally {
        this.fastServiceMetric.recordTimer(
            HiveMetrics.TagAlterDatabase.getMetricName(), registry.clock().wallTime() - start);
        log.debug("End: Database update using direct sql for {}", databaseInfo.getName());
    }
}
 
Example #19
Source File: IntegrationQueryServiceImpl.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
@Override
public List<IdNamePairDto> findAll(int ciTypeId, String name, Integer attrId) {
    List<AdmIntegrateTemplate> templs = null;
    if (attrId != null) {
        templs = intTempRepository.findAllByCiTypeIdAndTailAttrId(ciTypeId, attrId);
    } else if (Strings.isNullOrEmpty(name)) {
        templs = intTempRepository.findAllByCiTypeId(ciTypeId);
    } else {
        templs = intTempRepository.findAllByCiTypeIdAndNameContaining(ciTypeId, name);
    }

    return Lists.transform(templs, (x) -> {
        return new IdNamePairDto(x.getIdAdmIntegrateTemplate(), x.getName());
    });
}
 
Example #20
Source File: UserUpdater.java    From osiam with MIT License 5 votes vote down vote up
private void updateTitle(User user, UserEntity userEntity, Set<String> attributes) {
    if (attributes.contains("title")) {
        userEntity.setTitle(null);
    }

    if (!Strings.isNullOrEmpty(user.getTitle())) {
        userEntity.setTitle(user.getTitle());
    }
}
 
Example #21
Source File: EmulatorHelper.java    From firebase-admin-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
@Nullable
static boolean isEmulatorUrl(String databaseUrl) {
  if (Strings.isNullOrEmpty(databaseUrl)) {
    return false;
  }
  RepoInfo repoInfo = Utilities.parseUrl(databaseUrl).repoInfo;
  return !repoInfo.host.endsWith(".firebaseio.com") && databaseUrl.contains("ns=");
}
 
Example #22
Source File: BatchProfilerCLI.java    From metron with Apache License 2.0 5 votes vote down vote up
/**
 * Extracts profile information from a file or from zookeeper
 * @param commandLine Command line information.
 * @return Profile information
 * @throws MissingOptionException if command line options are missing
 * @throws IOException If there are disk or network issues retrieving profiles
 */
private static ProfilerConfig handleProfileDefinitions(CommandLine commandLine) throws MissingOptionException, IOException {
  final String PROFILE_LOCATION_ERROR =
          "A single profile location (--profiles or --zookeeper) must be specified";
  ProfilerConfig profiles;

  if ((!PROFILE_ZK.has(commandLine)) && (!PROFILE_DEFN_FILE.has(commandLine))) {
    throw new MissingOptionException(PROFILE_LOCATION_ERROR);
  }
  if (PROFILE_ZK.has(commandLine) && PROFILE_DEFN_FILE.has(commandLine)) {
    throw new IllegalArgumentException(PROFILE_LOCATION_ERROR);
  }

  if (PROFILE_ZK.has(commandLine)) {
    profiles = handleProfileDefinitionsZK(commandLine);
  } else {
    profiles = handleProfileDefinitionsFile(commandLine);
  }

  // event time can specified via command line override
  if (PROFILE_TIMESTAMP_FLD.has(commandLine)) {
    final String timestampField = PROFILE_TIMESTAMP_FLD.get(commandLine);
    Preconditions.checkArgument(!Strings.isNullOrEmpty(timestampField), "timestampField must be not be empty if specified");
    profiles.setTimestampField(timestampField);
  }
  LOG.info("Utilising profile: {}", profiles.toString());
  return profiles;
}
 
Example #23
Source File: EntityRelationConverter.java    From baleen with Apache License 2.0 5 votes vote down vote up
private void convertFeatures(Map<String, Object> map, Base base) {
  for (Feature f : base.getType().getFeatures()) {
    processFeature(map, base, f);
  }
  map.put(fields.getType(), base.getType().getShortName());
  if (map.get(FIELD_VALUE) == null || Strings.isNullOrEmpty(map.get(FIELD_VALUE).toString())) {
    map.put(FIELD_VALUE, base.getCoveredText());
  }
}
 
Example #24
Source File: DefaultServerStore.java    From qconfig with MIT License 5 votes vote down vote up
public DefaultServerStore(final ServerDao serverDao, String currentRoom, int freshServerInfoIntervalMs) {
    logger.info("init qconfig server store");
    this.serverDao = serverDao;
    this.defaultRoom = currentRoom;

    AppServerConfig appServer = ServerManager.getInstance().getAppServerConfig();
    this.self = new QConfigServer(appServer.getIp(), appServer.getPort(), currentRoom);
    Preconditions.checkArgument(!"127.0.0.1".equals(self.getIp()), "self ip can not be 127.0.0.1");
    Preconditions.checkArgument(self.getPort() != 0, "self port can not be 0");
    serverDao.insert(self);
    logger.info("init qconfig server store successOf, self {}", self);

    this.ipRoomMapping = CacheBuilder.newBuilder().build(new CacheLoader<String, String>() {
        @Override
        public String load(String ip) throws Exception {
            String room = serverDao.selectRoom(ip);
            if (Strings.isNullOrEmpty(room)) {
                Monitor.serverIpRoomGetError.inc();
                logger.error("can not find room for ip [{}]", ip);
                throw new IllegalArgumentException("can not find room for ip [" + ip + "]");
            }
            return room;
        }
    });

    freshServerInfos();
    Executors.newSingleThreadScheduledExecutor(new NamedThreadFactory("fresh-qconfig-server-info")).scheduleWithFixedDelay(new Runnable() {
        @Override
        public void run() {
            try {
                freshServerInfos();
            } catch (Exception e) {
                Monitor.serverInfoFreshError.inc();
                logger.error("fresh qconfig server info error", e);
            }
        }
    }, freshServerInfoIntervalMs, freshServerInfoIntervalMs, TimeUnit.MILLISECONDS);
}
 
Example #25
Source File: StreamMetadataStoreTest.java    From pravega with Apache License 2.0 5 votes vote down vote up
@Test
public void listStreamsInScopePaginated() throws Exception {
    // list stream in scope
    String scope = "scopeList";
    store.createScope(scope).get();
    String stream1 = "stream1";
    String stream2 = "stream2";
    String stream3 = "stream3";

    store.createStream(scope, stream1, configuration1, System.currentTimeMillis(), null, executor).get();
    store.setState(scope, stream1, State.ACTIVE, null, executor).get();
    store.createStream(scope, stream2, configuration2, System.currentTimeMillis(), null, executor).get();
    store.setState(scope, stream2, State.ACTIVE, null, executor).get();
    store.createStream(scope, stream3, configuration2, System.currentTimeMillis(), null, executor).get();
    store.setState(scope, stream3, State.ACTIVE, null, executor).get();
    
    Pair<List<String>, String> streamInScope = store.listStream(scope, "", 2, executor).get();
    assertEquals("List streams in scope", 2, streamInScope.getKey().size());
    assertFalse(Strings.isNullOrEmpty(streamInScope.getValue()));

    streamInScope = store.listStream(scope, streamInScope.getValue(), 2, executor).get();
    assertEquals("List streams in scope", 1, streamInScope.getKey().size());
    assertFalse(Strings.isNullOrEmpty(streamInScope.getValue()));

    streamInScope = store.listStream(scope, streamInScope.getValue(), 2, executor).get();
    assertEquals("List streams in scope", 0, streamInScope.getKey().size());
    assertFalse(Strings.isNullOrEmpty(streamInScope.getValue()));
    
    store.deleteStream(scope, stream1, null, executor).join();
    
    streamInScope = store.listStream(scope, "", 2, executor).get();
    assertEquals("List streams in scope", 2, streamInScope.getKey().size());
    assertFalse(Strings.isNullOrEmpty(streamInScope.getValue()));

    streamInScope = store.listStream(scope, streamInScope.getValue(), 2, executor).get();
    assertEquals("List streams in scope", 0, streamInScope.getKey().size());
    assertFalse(Strings.isNullOrEmpty(streamInScope.getValue()));
}
 
Example #26
Source File: ConfigUtil.java    From eagle with Apache License 2.0 5 votes vote down vote up
public static void collectConfigParams(MergeConfig data, AbstractConfig config, String prefix) throws Exception {
    try {
        if (config == null) {
            return;
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(config.getClass());
        PropertyDescriptor[] pros = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pro : pros) {
            Method rdM = pro.getReadMethod();
            if (rdM != null && isPrimitive(rdM.getReturnType())) {
                ConfigDesc configDesc = rdM.getAnnotation(ConfigDesc.class);
                if (configDesc != null && configDesc.excluded()) {
                    continue;
                }
                String key = pro.getName();
                if (configDesc != null && !Strings.isNullOrEmpty(configDesc.key())) {
                    key = configDesc.key();
                }
                Object value = rdM.invoke(config);
                if (value == null || Strings.isNullOrEmpty(String.valueOf(value))) {
                    if (configDesc != null && configDesc.required()) {
                        throw new EagleFrameException("parameter:%s is not allow null or empty", key);
                    }
                    continue;
                }
                data.addExt(Strings.isNullOrEmpty(prefix) ? key : String.format("%s.%s", prefix, key), String.valueOf(value));
            }
        }
    } catch (Exception e) {
        logger.error("ConfigUtil.collectConfigParams", e);
        throw e;
    }
}
 
Example #27
Source File: IndexingServiceImpl.java    From connector-sdk with Apache License 2.0 5 votes vote down vote up
@Override
public Operation getOperation(String name) throws IOException {
  validateRunning();
  checkArgument(!Strings.isNullOrEmpty(name), "Operation name cannot be null.");

  CloudSearch.Operations.Get request = this.service.operations().get(name);
  acquireToken(Operations.DEFAULT);
  return executeRequest(request, indexingServiceStats, true /* intializeDefaults */);
}
 
Example #28
Source File: DatasourceInfoServiceImpl.java    From tcc-transaction with Apache License 2.0 5 votes vote down vote up
private boolean validate(DataSourceInfo info){
    if (info.getStatus() == 1 && Strings.isNullOrEmpty(info.getUrl())) return false;
    if (info.getStatus()== 0) {
        if (Strings.isNullOrEmpty(info.getDriverClass()) || Strings.isNullOrEmpty(info.getDbUrl())
                || Strings.isNullOrEmpty(info.getUsername())) {
            return false;
        }
        if (Strings.isNullOrEmpty(info.getPassword()) || Strings.isNullOrEmpty(info.getJndi())) {
            return false;
        }
    }
    return true;
}
 
Example #29
Source File: PartitionedDataWriter.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Get the partition info of a work unit from the {@code state}. Then partition info will be removed from the
 * {@code state} to avoid persisting useless information
 *
 * <p>
 *   In Gobblin, only the {@link PartitionedDataWriter} knows all partitions written for a work unit. Each partition
 *   {@link DataWriter} decides the actual form of a dataset partition
 * </p>
 */
public static List<PartitionDescriptor> getPartitionInfoAndClean(State state, int branchId) {
  String partitionsKey = getPartitionsKey(branchId);
  String json = state.getProp(partitionsKey);
  if (Strings.isNullOrEmpty(json)) {
    return Lists.newArrayList();
  }
  state.removeProp(partitionsKey);
  return PartitionDescriptor.fromPartitionJsonList(json);
}
 
Example #30
Source File: ForkedTaskVariablesManager.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * @return craeted RMNodeClient if possible (there should be decrypter and url), otherwise null
 */
public RMNodeClient createRMNodeClient(TaskContext container) {
    if (container.getDecrypter() != null && !Strings.isNullOrEmpty(container.getSchedulerRestUrl())) {
        try {
            return new RMNodeClient(container.getDecrypter().decrypt(), container.getSchedulerRestUrl());
        } catch (Exception e) {
            return null;
        }
    }
    return null;
}