Java Code Examples for com.google.common.base.Strings

The following examples show how to use com.google.common.base.Strings. These examples are extracted from open source projects. 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 Project: seed   Source File: DetailPrinter.java    License: Mozilla Public License 2.0 6 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 2
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 3
Source Project: cuba   Source File: WebPickerField.java    License: 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 4
Source Project: platform   Source File: JdbcUtils.java    License: 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 5
private Set<ObjectPoint> loadPoints(final int id)
{
	final String json = configManager.getConfiguration(CONFIG_GROUP, "region_" + id);

	if (Strings.isNullOrEmpty(json))
	{
		return null;
	}

	Set<ObjectPoint> points = GSON.fromJson(json, new TypeToken<Set<ObjectPoint>>()
	{
	}.getType());
	// Prior to multiloc support the plugin would mark objects named "null", which breaks
	// in most cases due to the specific object being identified being ambiguous, so remove
	// them
	return points.stream()
		.filter(point -> !point.getName().equals("null"))
		.collect(Collectors.toSet());
}
 
Example 6
Source Project: cloudbreak   Source File: MockUserManagementService.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void getIdPMetadataForWorkloadSSO(
        GetIdPMetadataForWorkloadSSORequest request,
        StreamObserver<GetIdPMetadataForWorkloadSSOResponse> responseObserver) {
    checkArgument(!Strings.isNullOrEmpty(request.getAccountId()));
    try {
        String metadata = Resources.toString(
                Resources.getResource("sso/cdp-idp-metadata.xml"),
                Charsets.UTF_8).trim();
        metadata = metadata.replace("accountId_REPLACE_ME", request.getAccountId());
        metadata = metadata.replace("hostname_REPLACE_ME", "localhost");
        responseObserver.onNext(
                GetIdPMetadataForWorkloadSSOResponse.newBuilder()
                        .setMetadata(metadata)
                        .build());
        responseObserver.onCompleted();
    } catch (IOException e) {
        throw Status.INTERNAL
                .withDescription("Could not find IdP metadata resource")
                .withCause(e)
                .asRuntimeException();
    }
}
 
Example 7
Source Project: ModPackDownloader   Source File: CurseFile.java    License: 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 8
Source Project: JGiven   Source File: PlainTextScenarioWriter.java    License: 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 9
Source Project: qmq   Source File: MessageServiceImpl.java    License: 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 10
Source Project: nomulus   Source File: ListCursorsCommand.java    License: 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 11
Source Project: sarl   Source File: AgentParsingTest.java    License: 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 12
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 13
Source Project: incubator-pinot   Source File: SummaryResource.java    License: 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 14
Source Project: galaxy   Source File: TransactionInfoServiceImpl.java    License: 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 15
@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 16
Source Project: codebuff   Source File: HostAndPort.java    License: 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 17
Source Project: sarl   Source File: SkillParsingTest.java    License: 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 18
Source Project: baleen   Source File: RelationConstraint.java    License: 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 19
Source Project: helloiot   Source File: LogView.java    License: 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 20
Source Project: metacat   Source File: DirectSqlDatabase.java    License: 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 21
Source Project: we-cmdb   Source File: IntegrationQueryServiceImpl.java    License: 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 22
Source Project: osiam   Source File: UserUpdater.java    License: 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 23
Source Project: firebase-admin-java   Source File: EmulatorHelper.java    License: 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 24
Source Project: metron   Source File: BatchProfilerCLI.java    License: 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 25
Source Project: baleen   Source File: EntityRelationConverter.java    License: 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 26
Source Project: qconfig   Source File: DefaultServerStore.java    License: 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 27
Source Project: pravega   Source File: StreamMetadataStoreTest.java    License: 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 28
Source Project: eagle   Source File: ConfigUtil.java    License: 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 29
Source Project: connector-sdk   Source File: IndexingServiceImpl.java    License: 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 30
Source Project: tcc-transaction   Source File: DatasourceInfoServiceImpl.java    License: 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;
}