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: 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 #8
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 #9
Source File: JanusEclipsePlugin.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Create a status.
 *
 * @param severity the severity level, see {@link IStatus}.
 * @param code the code of the error.
 * @param cause the cause of the problem.
 * @return the status.
 */
public IStatus createStatus(int severity, int code, Throwable cause) {
	String message = cause.getLocalizedMessage();
	if (Strings.isNullOrEmpty(message)) {
		message = cause.getMessage();
	}
	if (Strings.isNullOrEmpty(message)) {
		message = cause.getClass().getSimpleName();
	}
	return createStatus(severity, code, message, cause);
}
 
Example #10
Source File: MockUserManagementService.java    From cloudbreak with Apache License 2.0 5 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 #11
Source File: UiControllerDependencyInjector.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected MethodHandle getInstallTargetSetterMethod(Install annotation, Frame frame, Class<?> instanceClass,
                                                    Method provideMethod) {
    String subjectProperty;
    if (Strings.isNullOrEmpty(annotation.subject()) && annotation.type() == Object.class) {
        InstallSubject installSubjectAnnotation = findMergedAnnotation(instanceClass, InstallSubject.class);
        if (installSubjectAnnotation != null) {
            subjectProperty = installSubjectAnnotation.value();
        } else {
            throw new DevelopmentException(
                    String.format("Unable to determine @Install subject of %s in %s", provideMethod, frame.getId())
            );
        }
    } else if (annotation.type() != Object.class) {
        subjectProperty = StringUtils.uncapitalize(annotation.type().getSimpleName());
    } else {
        subjectProperty = annotation.subject();
    }

    String subjectSetterName = "set" + StringUtils.capitalize(subjectProperty);
    // Check if addSubject is supported, e.g: addValidator(), addStyleProvider()
    String subjectAddName = "add" + StringUtils.capitalize(subjectProperty);

    MethodHandle targetSetterMethod = reflectionInspector.getInstallTargetMethod(instanceClass, subjectAddName);
    if (targetSetterMethod == null) {
        targetSetterMethod = reflectionInspector.getInstallTargetMethod(instanceClass, subjectSetterName);
    }

    if (targetSetterMethod == null) {
        throw new DevelopmentException(
                String.format("Unable to find @Install target method %s in %s", subjectProperty, instanceClass)
        );
    }

    return targetSetterMethod;
}
 
Example #12
Source File: ImportDateTime.java    From axelor-open-suite with GNU Affero General Public License v3.0 5 votes vote down vote up
public LocalDateTime updateYear(LocalDateTime datetime, String year) {
  if (!Strings.isNullOrEmpty(year)) {
    Matcher matcher = patternYear.matcher(year);
    if (matcher.find()) {
      Long years = Long.parseLong(matcher.group());
      if (year.startsWith("+")) datetime = datetime.plusYears(years);
      else if (year.startsWith("-")) datetime = datetime.minusYears(years);
      else datetime = datetime.withYear(years.intValue());
    }
  }
  return datetime;
}
 
Example #13
Source File: Oneof.java    From api-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the name of the oneof.
 */
public String getName() {
  if (Strings.isNullOrEmpty(proto.getName())) {
    return "oneof";
  }
  return proto.getName();
}
 
Example #14
Source File: Tag.java    From intercom-java with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static TaggableCollection createTagTypedCollection(Tag tag, UserCollection users) {
    TaggableCollection taggableCollection = new TaggableCollection();
    taggableCollection.setName(tag.getName());
    taggableCollection.setId(tag.getId());
    final List<Map<String, Object>> usersLite = Lists.newArrayList();
    final List<User> pageItems = users.getPage();
    for (User user : pageItems) {
        Map<String, Object> userMap = Maps.newHashMap();
        final String id = user.getId();
        final String email = user.getEmail();
        final String userId = user.getUserId();

        if (user.isUntag()) {
            userMap.put("untag", true);
        }

        if (!Strings.isNullOrEmpty(id)) {
            userMap.put("id", id);
            usersLite.add(userMap);
        } else if (!Strings.isNullOrEmpty(userId)) {
            userMap.put("user_id", userId);
            usersLite.add(userMap);
        } else if (!Strings.isNullOrEmpty(email)) {
            userMap.put("email", email);
            usersLite.add(userMap);
        } else {
            logger.warn("no identifiers found for user tag target, skipping [" + tag + "] [" + user.toString() + "]");
        }
    }
    taggableCollection.setUsers(usersLite);
    return taggableCollection;
}
 
Example #15
Source File: JsHintProcessor.java    From sputnik with Apache License 2.0 5 votes vote down vote up
private String readConfiguration() {
    String configurationFileName = getConfigurationFileName();
    if (Strings.isNullOrEmpty(configurationFileName)) {
        return null;
    }
    try (FileReader configurationFileReader = new FileReader(configurationFileName)) {
        return CharStreams.toString(configurationFileReader);
    } catch (IOException e) {
        throw new ReviewException("IO exception when reading JSHint configuration.", e);
    }
}
 
Example #16
Source File: DynamicDataSource.java    From galaxy with Apache License 2.0 5 votes vote down vote up
private String getPassword(String username, String password) {
    if (Strings.isNullOrEmpty(password)) {
        // TODO Cyber
    } else {
        return password;
    }
    return "";
}
 
Example #17
Source File: FilterController.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the list of rule id and display name.
 *
 * @param assetGroup the asset group
 * @param domain the domain
 * @return ResponseEntity<Object>
 */

@RequestMapping(path = "/v1/filters/rules", method = RequestMethod.GET)
public ResponseEntity<Object> getRules(@RequestParam("ag") String assetGroup, @RequestParam("domain") String domain) {
    if (Strings.isNullOrEmpty(assetGroup)) {
        return ResponseUtils.buildFailureResponse(new ServiceException(ASSET_MANDATORY));
    }
    ResponseData response = null;
    try {
        response = new ResponseData(filterService.getRules(assetGroup, domain));
    } catch (ServiceException e) {
        return complianceService.formatException(e);
    }
    return ResponseUtils.buildSucessResponse(response);
}
 
Example #18
Source File: AddForeignKey.java    From quantumdb with Apache License 2.0 5 votes vote down vote up
AddForeignKey(String table, String... columns) {
	checkArgument(!Strings.isNullOrEmpty(table), "You must specify a 'table'.");
	checkArgument(columns != null && columns.length > 0, "You must specify at least one 'column'.");

	this.name = "fk_" + RandomHasher.generateHash();
	this.onDelete = Action.NO_ACTION;
	this.onUpdate= Action.NO_ACTION;
	this.referringTableName = table;
	this.referringColumnNames = columns;
}
 
Example #19
Source File: SarlDocumentationParser.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Change the pattern of the tag.
 *
 * @param tag the tag.
 * @param regex the regular expression.
 */
public void setPattern(Tag tag, String regex) {
	if (Strings.isNullOrEmpty(regex)) {
		this.rawPatterns.remove(tag);
		this.compiledPatterns.remove(tag);
	} else {
		this.rawPatterns.put(tag, regex);
		this.compiledPatterns.put(tag, Pattern.compile("^\\s*" + regex, PATTERN_COMPILE_OPTIONS)); //$NON-NLS-1$
	}
}
 
Example #20
Source File: Settings.java    From Slide with GNU General Public License v3.0 5 votes vote down vote up
private void BuildLayout(String text) {
    LinearLayout parent = (LinearLayout) findViewById(R.id.settings_parent);

    /* Clear the settings out, then re-add the default top-level settings */
    parent.removeAllViews();
    parent.addView(getLayoutInflater().inflate(R.layout.activity_settings_child, null));
    Bind();

    /* The EditView contains text that we can use to search for matching settings */
    if (!Strings.isNullOrEmpty(text)){
        LayoutInflater inflater = getLayoutInflater();

        for (Integer activity: settings_activities) {
            parent.addView(inflater.inflate(activity, null));
        }

        mSettingsGeneralFragment.Bind();
        mManageOfflineContentFragment.Bind();
        mSettingsThemeFragment.Bind();
        mSettingsFontFragment.Bind();
        mSettingsCommentsFragment.Bind();
        mSettingsHandlingFragment.Bind();
        mSettingsHistoryFragment.Bind();
        mSettingsDataFragment.Bind();
        mSettingsRedditFragment.Bind();

        /* Go through each subview and scan it for matching text, non-matches */
        loopViews(parent, text.toLowerCase(), true, "");
    }

    /* Try to clean up the mess we've made */
    System.gc();
}
 
Example #21
Source File: CustomDifferenceListener.java    From googleads-java-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Finds the namespace URI of the node, navigating up the node tree if necessary.
 *
 * @return the namespace URI of the node, which may be null.
 */
private String getNamespaceURI(Node node) {
  while (node != null && Strings.isNullOrEmpty(node.getNamespaceURI())) {
    node = node.getParentNode();
  }
  return node == null ? null : node.getNamespaceURI();
}
 
Example #22
Source File: AbstractLegacyTestOCCKVStore.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Test
public void testConcurrentUpdate() {
  final K key = gen.newKey();
  final V value = gen.newVal();

  //Initial put.
  kvStore.put(key, value);
  final String initialTag = versionExtractor.getTag(value);

  //First update.
  kvStore.put(key, value);
  final String firstUpdateTag = versionExtractor.getTag(value);
  assertFalse(Strings.isNullOrEmpty(firstUpdateTag));
  assertNotEquals(initialTag, firstUpdateTag);

  //Attempt to update with value containing stale tag.
  boolean threw = false;
  try {
    versionExtractor.setTag(value, initialTag);
    kvStore.put(key, value);
  } catch (ConcurrentModificationException ex) {
    threw = true;
  }
  assertTrue(threw);

  //Ensure that value doesn't get mutated after a failed update attempt.
  assertEquals(firstUpdateTag, versionExtractor.getTag(kvStore.get(key)));
}
 
Example #23
Source File: X509CertificateTypeConverter.java    From osiam with MIT License 5 votes vote down vote up
@Override
public X509Certificate.Type convertToEntityAttribute(String dbData) {
    if (Strings.isNullOrEmpty(dbData)) {
        return null;
    }

    return new X509Certificate.Type(dbData);
}
 
Example #24
Source File: WindowsPerformanceCounterFeed.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Override
public void onSuccess(WinRmToolResponse val) {
    for (String pollResponse : val.getStdOut().split("\r\n")) {
        if (Strings.isNullOrEmpty(pollResponse)) {
            continue;
        }
        String path = pollResponse.substring(0, OUTPUT_COLUMN_WIDTH - 1);
        // The performance counter output prepends the sensor name with "\\<machinename>" so we need to remove it
        Matcher machineNameLookbackMatcher = MACHINE_NAME_LOOKBACK_PATTERN.matcher(path);
        if (!machineNameLookbackMatcher.find()) {
            continue;
        }
        String name = machineNameLookbackMatcher.group(0).trim();
        String rawValue = pollResponse.substring(OUTPUT_COLUMN_WIDTH).replaceAll("^\\s+", "");
        WindowsPerformanceCounterPollConfig<?> config = getPollConfig(name);
        Class<?> clazz = config.getSensor().getType();
        AttributeSensor<Object> attribute = (AttributeSensor<Object>) Sensors.newSensor(clazz, config.getSensor().getName(), config.getDescription());
        try {
            Object value = TypeCoercions.coerce(rawValue, TypeToken.of(clazz));
            entity.sensors().set(attribute, value);
        } catch (Exception e) {
            Exceptions.propagateIfFatal(e);
            if (failedAttributes.add(attribute)) {
                log.warn("Failed to coerce value '{}' to {} for {} -> {}", new Object[] {rawValue, clazz, entity, attribute});
            } else {
                if (log.isTraceEnabled()) log.trace("Failed (repeatedly) to coerce value '{}' to {} for {} -> {}", new Object[] {rawValue, clazz, entity, attribute});
            }
        }
    }
}
 
Example #25
Source File: DhcpManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Modified
protected void modified(ComponentContext context) {
    Dictionary<?, ?> properties = context.getProperties();

    String updatedConfig = Tools.get(properties, ALLOW_HOST_DISCOVERY);
    if (!Strings.isNullOrEmpty(updatedConfig)) {
        allowHostDiscovery = Boolean.valueOf(updatedConfig);
        log.info("Host discovery is set to {}", updatedConfig);
    }

    log.info("Modified");
}
 
Example #26
Source File: ProcessorFactory.java    From qconfig with MIT License 5 votes vote down vote up
private void checkQMapConfig(QMapConfig annotation, Action action) {
    boolean keyExist = !Strings.isNullOrEmpty(annotation.key());
    boolean defaultValueExist = !Strings.isNullOrEmpty(annotation.defaultValue());
    boolean translatorExist = !TrivialMapTranslator.class.equals(annotation.translator());
    if (translatorExist) {
        Preconditions.checkState(!keyExist && !defaultValueExist, "qconfig annotation conflict, translator can not exist with key or default value, class %s, %s %s", action.getClazz().getName(), action.getType(), action.getName());
    } else if (defaultValueExist) {
        Preconditions.checkState(keyExist, "qconfig annotation illegal, default value must exist with key, class %s, %s %s", action.getClazz().getName(), action.getType(), action.getName());
    }

}
 
Example #27
Source File: SREsPreferencePage.java    From sarl with Apache License 2.0 5 votes vote down vote up
private boolean isDuplicateName(String name) {
	final String sreName = Strings.nullToEmpty(name);
	for (final ISREInstall sre : this.sreArray) {
		if (sreName.equals(sre.getName())) {
			return true;
		}
	}
	return false;
}
 
Example #28
Source File: SessionManagerImpl.java    From swellrt with Apache License 2.0 5 votes vote down vote up
@Override
public String getLoginUrl(String redirect) {
  if (Strings.isNullOrEmpty(redirect)) {
    return SIGN_IN_URL;
  } else {
    PercentEscaper escaper =
        new PercentEscaper(PercentEscaper.SAFEQUERYSTRINGCHARS_URLENCODER, false);
    String queryStr = "?r=" + escaper.escape(redirect);
    return SIGN_IN_URL + queryStr;
  }
}
 
Example #29
Source File: GitRevisionHistory.java    From MOE with Apache License 2.0 5 votes vote down vote up
/**
 * Parse the output of Git into RevisionMetadata.
 *
 * @param log  the output of getMetadata to parse
 */
@VisibleForTesting
RevisionMetadata parseMetadata(String log) {
  if (Strings.isNullOrEmpty(log.trim())) {
    return null;
  }
  // Split on the log delimiter. Limit to 5 so that it will act correctly
  // even if the log delimiter happens to be in the commit message.
  List<String> split = Splitter.on(LOG_DELIMITER).limit(5).splitToList(log);

  // The fourth item contains all of the parents, each separated by a space.
  ImmutableList.Builder<Revision> parentBuilder = ImmutableList.<Revision>builder();
  for (String parent : Splitter.on(' ').omitEmptyStrings().split(split.get(3))) {
    parentBuilder.add(Revision.create(parent, headCloneSupplier.get().getRepositoryName()));
  }

  DateTime date = GIT_DATE_FMT.parseDateTime(split.get(2));

  // TODO(cgruber): scan for fields from git metadata rather than description?
  return RevisionMetadata.builder()
      .id(split.get(0))
      .author(split.get(1))
      .date(date)
      .description(split.get(4))
      .withParents(parentBuilder.build())
      .build();
}
 
Example #30
Source File: H2TraceQueryDAO.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Override
public List<SegmentRecord> queryByTraceId(String traceId) throws IOException {
    List<SegmentRecord> segmentRecords = new ArrayList<>();
    try (Connection connection = h2Client.getConnection()) {

        try (ResultSet resultSet = h2Client.executeQuery(
            connection, "select * from " + SegmentRecord.INDEX_NAME + " where " + SegmentRecord.TRACE_ID + " = ?",
            traceId
        )) {
            while (resultSet.next()) {
                SegmentRecord segmentRecord = new SegmentRecord();
                segmentRecord.setSegmentId(resultSet.getString(SegmentRecord.SEGMENT_ID));
                segmentRecord.setTraceId(resultSet.getString(SegmentRecord.TRACE_ID));
                segmentRecord.setServiceId(resultSet.getString(SegmentRecord.SERVICE_ID));
                segmentRecord.setServiceInstanceId(resultSet.getString(SegmentRecord.SERVICE_INSTANCE_ID));
                segmentRecord.setEndpointName(resultSet.getString(SegmentRecord.ENDPOINT_NAME));
                segmentRecord.setStartTime(resultSet.getLong(SegmentRecord.START_TIME));
                segmentRecord.setEndTime(resultSet.getLong(SegmentRecord.END_TIME));
                segmentRecord.setLatency(resultSet.getInt(SegmentRecord.LATENCY));
                segmentRecord.setIsError(resultSet.getInt(SegmentRecord.IS_ERROR));
                String dataBinaryBase64 = resultSet.getString(SegmentRecord.DATA_BINARY);
                if (!Strings.isNullOrEmpty(dataBinaryBase64)) {
                    segmentRecord.setDataBinary(Base64.getDecoder().decode(dataBinaryBase64));
                }
                segmentRecord.setVersion(resultSet.getInt(SegmentRecord.VERSION));
                segmentRecords.add(segmentRecord);
            }
        }
    } catch (SQLException e) {
        throw new IOException(e);
    }
    return segmentRecords;
}