auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { CompletableFuture<Boolean> result = new CompletableFuture<>(); List<String> originalLabels = issue.getLabels(); logger.info("Changing labels for " + issue + " on UI"); CompletableFuture<Optional<TurboIssue>> localLabelsReplaceFuture = repoOpControl.replaceIssueLabelsLocally(issue, newLabels); localLabelsReplaceFuture.thenRun(this::refreshUI); updateIssueLabelsOnServer(issue, newLabels) .exceptionally((e) -> { result.completeExceptionally(e); return false; }) .thenCombine(localLabelsReplaceFuture, (isUpdateSuccessful, locallyModifiedIssue) -> handleIssueLabelsUpdateResult(isUpdateSuccessful, locallyModifiedIssue, originalLabels)) .thenAccept((isReplacementSuccessful) -> { <START> if (!result.isCompletedExceptionally()) { <END> result.complete(isReplacementSuccessful); } }); return result; }</code><technical_language>This part is a bit confusing -- propagate failure completeExceptionally a boolean value. clear difference is reading this part. Is a simplify it, completeExceptionally end if isReplacementSuccessful is false</technical_language>

Target:
public CompletableFuture<Boolean> replaceIssueLabels(TurboIssue issue, List<String> newLabels) { CompletableFuture<Boolean> result = new CompletableFuture<>(); List<String> originalLabels = issue.getLabels(); logger.info("Changing labels for " + issue + " on UI"); CompletableFuture<Optional<TurboIssue>> localLabelsReplaceFuture = repoOpControl.replaceIssueLabelsLocally(issue, newLabels); localLabelsReplaceFuture.thenRun(this::refreshUI); updateIssueLabelsOnServer(issue, newLabels) .exceptionally((e) -> { result.completeExceptionally(e); return false; }) .thenCombine(localLabelsReplaceFuture, (isUpdateSuccessful, locallyModifiedIssue) -> handleIssueLabelsUpdateResult(isUpdateSuccessful, locallyModifiedIssue, originalLabels)) .thenAccept(result::complete); return result; }
Source:
<code>public void createPullRequest() throws Exception { String projectUrl = testAuxiliaryRepo.getHtmlUrl() + ".git"; projectExplorer.waitProjectExplorer(); menu.runCommand(WORKSPACE, IMPORT_PROJECT); <START> importWidget.waitAndTypeImporterAsGitInfo(projectUrl, PROJECT_NAME); <END> configureTypeOfProject(); projectExplorer.waitItem(PROJECT_NAME); projectExplorer.openItemByPath(PROJECT_NAME); openFileAndChangeContent(PATH_TO_README_FILE, generate("", 12)); pullRequestPanel.clickPullRequestBtn(); pullRequestPanel.enterComment(COMMENT); pullRequestPanel.enterTitle(TITLE); pullRequestPanel.clickCreatePRBtn(); pullRequestPanel.clickOkCommitBtn(); pullRequestPanel.waitStatusOk(FORK_CREATED); pullRequestPanel.waitStatusOk(BRANCH_PUSHED_ON_YOUR_FORK); pullRequestPanel.waitMessage(PULL_REQUEST_CREATED); }</code><technical_language>I think, replace importWidget.waitAndTypeImporterAsGitInfo() git.importJavaApp()</technical_language>

Target:
public void createPullRequest() throws Exception { projectExplorer.waitProjectExplorer(); git.importJavaApp(testGitHubRepository.getHtmlUrl(), PROJECT_NAME, MAVEN); projectExplorer.openItemByPath(PROJECT_NAME); openFileAndChangeContent(PATH_TO_README_FILE, generate("", 12)); pullRequestPanel.clickPullRequestBtn(); pullRequestPanel.enterComment(COMMENT); pullRequestPanel.enterTitle(TITLE); pullRequestPanel.clickCreatePRBtn(); pullRequestPanel.clickOkCommitBtn(); pullRequestPanel.waitStatusOk(FORK_CREATED); pullRequestPanel.waitStatusOk(BRANCH_PUSHED_ON_YOUR_FORK); pullRequestPanel.waitMessage(PULL_REQUEST_CREATED); }
Source:
<code>private void sendIfEnabled(MetricAttribute type, String name, double value, long timestamp) throws IOException { <START> if (isMetricAttributeDisabled(type)){ <END> return; } graphite.send(prefix(name, type.getCode()), format(value), timestamp); }</code><technical_language>avoid changes in classes targeted this pull request</technical_language>

Target:
private void sendIfEnabled(MetricAttribute type, String name, double value, long timestamp) throws IOException { if (getDisabledMetricAttributes().contains(type)){ return; } graphite.send(prefix(name, type.getCode()), format(value), timestamp); }
Source:
<code>private void makeAttributesModifiable() { if (!attributesCanBeModified) { this.attributesCanBeModified = true; final Map<String, Object> tempAttributes = attributes; this.attributes = new HashMap<>(); <START> if (tempAttributes != null) { <END> this.attributes = new HashMap<>(tempAttributes); } } }</code><technical_language>do this check earlier avoid allocating a map used, e.g. if (tempAttributes != null) { this.attributes = new HashMap<>(tempAttributes); } else { this.attributes = new HashMap<>(); }</technical_language>

Target:
private void makeAttributesModifiable() { if (!attributesCanBeModified) { this.attributesCanBeModified = true; final Map<String, Object> tempAttributes = attributes; if (tempAttributes != null) { this.attributes = new HashMap<>(tempAttributes); } else { this.attributes = new HashMap<>(); } } }
Source:
<code>public TransportDataMessage(byte[] data) { try { this.version = data[0]; this.messageType = data[1]; this.channelName = new String(data, 4, 16, "UTF-8"); if (messageType == 5) { byte[] logicalTimestampMsBytes = Arrays.copyOfRange(data, 20, 28); <START> this.logicalTimestampMs = ByteBuffer.wrap(logicalTimestampMsBytes).getLong(); <END> byte[] payload = Arrays.copyOfRange(data, 32, data.length); for (int element = 0; element < (payload.length / 17); element++) { int index = element * 17; byte[] tsIdBytes = Arrays.copyOfRange(payload, index + 1, index + 9); String encodedTsId = StringUtils .remove(DatatypeConverter.printBase64Binary(tsIdBytes), "="); Map<String, Object> elementMap = new HashMap<String, Object>(4); elementMap.put("tsId", encodedTsId); byte[] valueBytes = Arrays.copyOfRange(payload, index + 9, index + 17); switch (payload[index]) { case 1: elementMap.put("value", ByteBuffer.wrap(valueBytes).getLong()); break; case 2: elementMap.put("value", ByteBuffer.wrap(valueBytes).getDouble()); break; default: log.warn("ignoring data message with unknown value type {}", payload[index]); continue; } this.data.add(elementMap); } } else { log.warn("Unsupported binary message type {}", messageType); } } catch (Exception ex) { log.error("failed to construct transport data message", ex); } }</code><technical_language>wrap individual sections of data byte array ByteBuffers decode them. Wrap thing, navigate ByteBuffer read sections of it</technical_language>

Target:
public TransportDataMessage(byte[] data) { try { ByteBuffer buffer = ByteBuffer.wrap(data); this.version = buffer.get(0); this.kind = Kind.fromBinaryType(buffer.get(1)); this.channelName = new String(data, 4, 16, "UTF-8"); if (this.kind == Kind.DATA) { this.logicalTimestampMs = buffer.getLong(20); byte[] payload = Arrays.copyOfRange(data, 32, data.length); for (int element = 0; element < (payload.length / 17); element++) { int index = element * 17; byte[] tsIdBytes = Arrays.copyOfRange(payload, index + 1, index + 9); String encodedTsId = StringUtils .remove(DatatypeConverter.printBase64Binary(tsIdBytes), "="); Map<String, Object> elementMap = new HashMap<String, Object>(4); elementMap.put("tsId", encodedTsId); switch (payload[index]) { case 1: elementMap.put("value", buffer.getLong(index + 41)); break; case 2: elementMap.put("value", buffer.getDouble(index + 41)); break; default: log.warn("ignoring data message with unknown value type {}", payload[index]); continue; } this.data.add(elementMap); } } else { log.warn("Unsupported binary message type {}", this.kind); } } catch (Exception ex) { log.error("failed to construct transport data message", ex); } }
Source:
<code>public VoltCSVFormatter create(String formatName, Properties props) { <START> VoltCSVFormatter formatter = new VoltCSVFormatter(formatName, props); <END> return formatter; }</code><technical_language>VoltCSVFormatter name</technical_language>

Target:
public Formatter<String> create(String formatName, Properties props) { if(useSuperCsv(props)){ return new VoltSuperCSVFormatter(formatName, props); } return new VoltCSVFormatter(formatName, props); }
Source:
<code>private String computeRelativePathToRoot(){ if (this.root.equals(this.f)) { return ""; } LinkedList<String> relativePath = new LinkedList<>(); FilePath current = this.f; while (current != null && !current.equals(this.root)) { relativePath.addFirst(current.getName()); current = current.getParent(); } <START> return String.join("/", relativePath) + "/"; <END> }</code><technical_language>this code is duplicated, encapsulate for maintainability's sake</technical_language>

Target:
private String computeRelativePathToRoot(){ if (this.root.equals(this.f)) { return ""; } LinkedList<String> relativePath = new LinkedList<>(); FilePath current = this.f; while (current != null && !current.equals(this.root)) { relativePath.addFirst(current.getName()); current = current.getParent(); } return joinWithForwardSlashes(relativePath); }
Source:
<code>public dClass(String s) { path=s; dclass_index=0; <START> isDClassInitialized = ( init() >= 0); <END> }</code><technical_language>I inlined parameterless init spare rise in complexity</technical_language>

Target:
public dClass(String s) { path=s; dclass_index=0; isDClassInitialized = ( init(s) >= 0); }
Source:
<code>public void syncPostBatch(final String topicId, final List<BatchItem> batch) throws EventPublishingException { final CountDownLatch done = new CountDownLatch(batch.size()); for (final BatchItem item : batch) { final ProducerRecord<String, String> record = new ProducerRecord<>(topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); item.setStep(EventPublishingStep.PUBLISHING); try { kafkaProducer.send(record, kafkaSendCallback(item, done)); } catch (InterruptException | SerializationException | BufferExhaustedException e) { item.safeFail("internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } } try { final boolean isSuccessful = done.await(settings.getKafkaSendTimeoutMs(), TimeUnit.MILLISECONDS); if (!isSuccessful) { for (final BatchItem item : batch) { <START> item.safeFail("timed out"); <END> } throw new EventPublishingException("Timeout publishing events"); } } catch (InterruptedException e) { for (final BatchItem item : batch) { item.safeFail("internal error"); } throw new EventPublishingException("Error publishing message to kafka", e); } }</code><technical_language>do set for item? posible scenario events submitted timed out in case isSuccessful false</technical_language>

Target:
public void syncPostBatch(final String topicId, final List<BatchItem> batch) throws EventPublishingException { final CountDownLatch done = new CountDownLatch(batch.size()); for (final BatchItem item : batch) { final ProducerRecord<String, String> record = new ProducerRecord<>(topicId, toKafkaPartition(item.getPartition()), item.getPartition(), item.getEvent().toString()); item.setStep(EventPublishingStep.PUBLISHING); try { kafkaProducer.send(record, kafkaSendCallback(item, done)); } catch (InterruptException | SerializationException | BufferExhaustedException e) { item.updateStatusAndDetail(EventPublishingStatus.FAILED, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } } try { final boolean isSuccessful = done.await(settings.getKafkaSendTimeoutMs(), TimeUnit.MILLISECONDS); if (!isSuccessful) { failBatch(batch, "timed out"); throw new EventPublishingException("Timeout publishing events"); } } catch (InterruptedException e) { failBatch(batch, "internal error"); throw new EventPublishingException("Error publishing message to kafka", e); } }
Source:
<code>private Geometry standardizeGeometry(Geometry geometry) { <START> if (geometry instanceof GeometryCollection && !(geometry instanceof MultiPolygon)) { <END> return standardizeGeometryCollection((GeometryCollection) geometry); } if (geometry instanceof LinearRing) { return linearRingToLineString(geometry); } return geometry; }</code><technical_language>a MultiPolygon LineStrings</technical_language>

Target:
private Geometry standardizeGeometry(Geometry geometry) { if (geometry instanceof GeometryCollection) { return standardizeGeometryCollection((GeometryCollection) geometry); } if (geometry instanceof LinearRing) { return linearRingToLineString((LinearRing) geometry); } return geometry; }
Source:
<code>default boolean acquirePatiently(Duration timeout) { long timeWaited = 0L; while (timeWaited < timeout.toMillis()) { final OptionalLong waitTime = getWaitTimeForPermit(); if (!waitTime.isPresent()) { return true; } else { <START> final long timeToSleep = Math.max(100, waitTime.getAsLong()); <END> try { Thread.sleep(timeToSleep); timeWaited += timeToSleep; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } } return false; }</code><technical_language>If this method is called timeout = 5 seconds, getWaitTimeForPermit() returns 30 seconds, I this implementation incorrectly sleep for 30 seconds 5 seconds</technical_language>

Target:
default boolean acquirePatiently(Duration timeout) { long timeWaited = 0L; while (timeWaited < timeout.toMillis()) { final OptionalLong waitTime = getWaitTimeForPermit(); if (!waitTime.isPresent()) { return true; } else { final long timeAvailableToWait = timeout.toMillis() - timeWaited; final long timeToSleep = Math.min(timeAvailableToWait, waitTime.getAsLong()); try { Thread.sleep(timeToSleep); timeWaited += timeToSleep; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw Throwables.propagate(e); } } } return false; }
Source:
<code>private List<? extends ResourceTag> getResourceTags(final List<String> resourceIds, ResourceObjectType resourceType) { List<String> uuids = new ArrayList<String>(); List<String> internalIds = new ArrayList<String>(); for(String resourceId : resourceIds){ if(resourceId.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")){ uuids.add(resourceId); }else{ Long internalId = null; try { internalId = Long.parseLong(resourceId); } catch (final NumberFormatException e) { <START> internalId = null; <END> } if (internalId != null) { internalIds.add(resourceId); }else{ throw new InvalidParameterValueException("Invalid resourceId"); } } } SearchBuilder<ResourceTagVO> sb = _resourceTagDao.createSearchBuilder(); if(!uuids.isEmpty() && !internalIds.isEmpty()){ throw new InvalidParameterValueException("Expecting only uuids or Ids"); }else if (!uuids.isEmpty()){ sb.and("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.IN); }else if (!internalIds.isEmpty()){ sb.and("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.IN); } sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); SearchCriteria<ResourceTagVO> sc = sb.create(); if (!uuids.isEmpty()){ sc.setParameters("resourceUuid", resourceIds.toArray()); }else if (!internalIds.isEmpty()){ sc.setParameters("resourceId", resourceIds.toArray()); } sc.setParameters("resourceType", resourceType); return _resourceTagDao.search(sc, null); }</code><technical_language>throwing InvalidParameterValueException here</technical_language>

Target:
private List<? extends ResourceTag> getResourceTags(final List<String> resourceIds, ResourceObjectType resourceType) { List<String> uuids = new ArrayList<String>(); List<String> internalIds = new ArrayList<String>(); for(String resourceId : resourceIds){ if(resourceId.matches("^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")){ uuids.add(resourceId); }else{ try { Long.parseLong(resourceId); } catch (final NumberFormatException e) { throw new InvalidParameterValueException("Invalid resourceId"); } internalIds.add(resourceId); } } SearchBuilder<ResourceTagVO> sb = _resourceTagDao.createSearchBuilder(); if(!uuids.isEmpty() && !internalIds.isEmpty()){ throw new InvalidParameterValueException("Expecting only uuids or Ids"); }else if (!uuids.isEmpty()){ sb.and("resourceUuid", sb.entity().getResourceUuid(), SearchCriteria.Op.IN); }else if (!internalIds.isEmpty()){ sb.and("resourceId", sb.entity().getResourceId(), SearchCriteria.Op.IN); } sb.and("resourceType", sb.entity().getResourceType(), SearchCriteria.Op.EQ); SearchCriteria<ResourceTagVO> sc = sb.create(); if (!uuids.isEmpty()){ sc.setParameters("resourceUuid", resourceIds.toArray()); }else if (!internalIds.isEmpty()){ sc.setParameters("resourceId", resourceIds.toArray()); } sc.setParameters("resourceType", resourceType); return _resourceTagDao.search(sc, null); }
Source:
<code><START> public void setMaxSize( int maxSize ) { <END> this.maxSize = maxSize; }</code><technical_language>this method, setPurgeTimeout, package-private? testable, reduces risk of misuse</technical_language>

Target:
void setMaxSize( int maxSize ) { this.maxSize = maxSize; }
Source:
<code>public <START> CommandProvider() <END> { }</code><technical_language>is a good place for init work :-)</technical_language>

Target:
public CommandProvider() { idToCommand = new HashMap<>(); }
Source:
<code>public static Certificate map(CertificateInfo entity, Certificate template) { Certificate model = template != null ? template : new Certificate(); model.setContent(entity.getPayload()); <START> model.setSubject(entity.getDescription()); <END> return model; }</code><technical_language>need add subject well, description else. I if subject is a subject generate certificate out of payload extract subject hold subject in CertificateInfo. I planning add fingerprint issuer description</technical_language>

Target:
public static Certificate map(CertificateInfo entity, Certificate template) { Certificate model = template != null ? template : new Certificate(); model.setContent(entity.getPayload()); model.setSubject(entity.getSubject()); model.setDescription(entity.getDescription()); return model; }
Source:
<code>public Set<Type> getImportTypes() { <START> Set<Type> imported = new HashSet(super.getImportTypes()); <END> imported.addAll( importTypes ); if ( assignment != null ) { imported.addAll( assignment.getImportTypes() ); } return imported; }</code><technical_language>extend Collections.asSet(...) var-arg variant for collection, i.e. asSet(Collection<T> ... collections)</technical_language>

Target:
public Set<Type> getImportTypes() { Set<Type> imported = org.mapstruct.ap.util.Collections.asSet( importTypes, super.getImportTypes() ); if ( assignment != null ) { imported.addAll( assignment.getImportTypes() ); } return imported; }
Source:
<code>public void onTextSelected(ActionMode mode) { MenuItem shareItem = null; webViewActionMode = mode; Menu menu = mode.getMenu(); for (int i = 0; i < menu.size(); i++) { MenuItem item = menu.getItem(i); try { String resourceName = activity.getResources().getResourceName(item.getItemId()); if (resourceName.contains("share")) { shareItem = item; } if (!ApiUtil.hasLollipop()) { fixMenuItemTheme(item); } <START> } catch (Resources.NotFoundException e) { <END> } } if (shareItem == null) { shareItem = mode.getMenu().add(Menu.NONE, Menu.NONE, Menu.NONE, activity.getString(R.string.menu_share_page)); shareItem.setIcon(R.drawable.ic_share_dark); MenuItemCompat.setShowAsAction(shareItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT); } shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { requestTextSelection(); if (webViewActionMode != null) { webViewActionMode.finish(); webViewActionMode = null; } return true; } }); createFunnel(); funnel.logHighlight(); }</code><technical_language>II this code inherited clearer if scope of this block reduced activity.getResources().getResourceName(item.getItemId()) do a null check resourceName</technical_language>

Target:
public void onTextSelected(ActionMode mode) { webViewActionMode = mode; Menu menu = mode.getMenu(); MenuItem shareItem = getSystemMenuItemByName(menu, "share"); if (shareItem == null) { shareItem = mode.getMenu().add(Menu.NONE, Menu.NONE, Menu.NONE, activity.getString(R.string.menu_share_page)); shareItem.setIcon(R.drawable.ic_share_dark); MenuItemCompat.setShowAsAction(shareItem, MenuItemCompat.SHOW_AS_ACTION_ALWAYS | MenuItemCompat.SHOW_AS_ACTION_WITH_TEXT); } shareItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { requestTextSelection(); if (webViewActionMode != null) { webViewActionMode.finish(); webViewActionMode = null; } return true; } }); createFunnel(); funnel.logHighlight(); }
Source:
<code>private BoundedContext selectBoundedContext(Target target) { TypeUrl type = TypeUrl.parse(target.getType()); BoundedContext result = typeToContextMap.get(type); if (result == null) { <START> throw newIllegalArgumentException("Trying to subscribe to an unknown type: %s", type); <END> } return result; }</code><technical_language>This method is called cancel selectBoundedContext(Subscription subscription). text is misleading. Also, I a good idea throw exception. return Optional.empty(). if called subscribe I throw exception (and return a respective error gRPC observer's onError). if called cancel I emit a warning, a case a show-stopper</technical_language>

Target:
private Optional<BoundedContext> selectBoundedContext(Target target) { TypeUrl type = TypeUrl.parse(target.getType()); BoundedContext selected = typeToContextMap.get(type); Optional<BoundedContext> result = Optional.ofNullable(selected); return result; }
Source:
<code>public Object perform(InvocationContext ctx) throws Throwable { if (mutations == null || mutations.isEmpty()) { return super.perform(ctx); } MVCCEntry<K, V> entry = (MVCCEntry<K, V>) ctx.lookupEntry(key); EntryView.ReadWriteEntryView<K, V> rw = EntryViews.readWrite(entry); Object ret = null; for (Mutation<K, V, ?> mutation : mutations) { ret = mutation.apply(rw); entry.updatePreviousValue(); } if (f != null) { ret = f.apply(rw); } <START> return snapshot(ret, new CacheEncoders()); <END> }</code><technical_language>is this missing encoder classes purpose</technical_language>

Target:
public Object perform(InvocationContext ctx) throws Throwable { if (mutations == null || mutations.isEmpty()) { return super.perform(ctx); } MVCCEntry<K, V> entry = (MVCCEntry<K, V>) ctx.lookupEntry(key); EntryView.ReadWriteEntryView<K, V> rw = EntryViews.readWrite(entry, cacheEncoders); Object ret = null; for (Mutation<K, V, ?> mutation : mutations) { ret = mutation.apply(rw); entry.updatePreviousValue(); } if (f != null) { ret = f.apply(rw); } return snapshot(ret); }
Source:
<code>public void testMultipleHandles() throws CRException, IOException { GenericConfiguration config = new GenericConfiguration(); GenericConfigurationFileLoader.load(config, "${" + CRUtil.PORTALNODE_CONFPATH + "}/multipleDatasourceHandle.properties"); CRConfigUtil crConfig = new CRConfigUtil(config,"crConfig"); assertNotNull(crConfig); crConfig.initDS(); <START> assertNotNull(crConfig.getRequestProcessorConfig(1)); <END> assertNotNull(crConfig.getRequestProcessorConfig(1).getDatasource()); assertNotNull(crConfig.getRequestProcessorConfig(1).getDatasource().getHandlePool()); Datasource ds = crConfig.getRequestProcessorConfig(1).getDatasource(); assertNotEquals(ds.getHandlePool().getHandle(), ds.getHandlePool().getHandle()); }</code><technical_language>Add Messages assert Methods</technical_language>

Target:
public void testMultipleHandles() throws CRException, IOException { GenericConfiguration config = new GenericConfiguration(); GenericConfigurationFileLoader.load(config, "${" + CRUtil.PORTALNODE_CONFPATH + "}/multipleDatasourceHandle.properties"); CRConfigUtil crConfig = new CRConfigUtil(config, "crConfig"); assertNotNull("crConfig is null", crConfig); crConfig.initDS(); assertNotNull("first request processor is null", crConfig.getRequestProcessorConfig(1)); assertNotNull("datasource is null", crConfig.getRequestProcessorConfig(1).getDatasource()); Datasource ds = crConfig.getRequestProcessorConfig(1).getDatasource(); assertNotNull("datasource handlePool is null", ds.getHandlePool()); assertNotEquals("both fetched datasource handles are the same", ds .getHandlePool().getHandle(), ds.getHandlePool().getHandle()); }
Source:
<code>public void actionPerformed(ActionEvent e) { final Object source = e.getSource(); if (source == cancelButton) { resetJDialog(); this.dispose(); } else if (source == applyTemplateButton) { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if(template.getParameters() != null && !template.getParameters().isEmpty()) { this.setContentPane(configureParametersPanel(template.getParameters())); this.revalidate(); }else { checkDirtyAndLoad(e); } } else if (source == reloadTemplateButton || source == previous) { resetJDialog(); <START> } else if(source == validateButton) { <END> checkDirtyAndLoad(e); resetJDialog(); } }</code><technical_language>for. Spacepolice is calling :)</technical_language>

Target:
public void actionPerformed(ActionEvent e) { final Object source = e.getSource(); if (source == cancelButton) { resetJDialog(); this.dispose(); } else if (source == applyTemplateButton) { String selectedTemplate = templateList.getText(); Template template = TemplateManager.getInstance().getTemplateByName(selectedTemplate); if (hasParameters(template)) { this.setContentPane(configureParametersPanel(template.getParameters())); this.revalidate(); } else { checkDirtyAndLoad(e); } } else if (source == reloadTemplateButton || source == previous) { resetJDialog(); } else if (source == validateButton) { checkDirtyAndLoad(e); resetJDialog(); } }
Source:
<code>void handleDomainObjectSelectedEvent(final @Observes DomainObjectSelectionEvent event) { checkNotNull("event", event); if (Objects.equals(getCanvasHandler(), event.getCanvasHandler())) { <START> selectedDomainObject = Optional.of(event.getDomainObject()); <END> } }</code><technical_language>getCanvasHandler() event.getCanvasHandler() null values? Otherwise, I Optional.ofNullable(..)</technical_language>

Target:
void handleDomainObjectSelectedEvent(final @Observes DomainObjectSelectionEvent event) { checkNotNull("event", event); if (Objects.equals(getCanvasHandler(), event.getCanvasHandler())) { selectedDomainObject = Optional.ofNullable(event.getDomainObject()); } }
Source:
<code>private VirtualMachine cloneMaster(VirtualMachine master, String tag, String name, VirtualMachineCloneSpec cloneSpec, String folderName) { VirtualMachine cloned = null; try { FolderNameToFolderManagedEntity toFolderManagedEntity = new FolderNameToFolderManagedEntity(serviceInstance, master); Folder folder = toFolderManagedEntity.apply(folderName); Task task = master.cloneVM_Task(folder, name, cloneSpec); String result = task.waitForTask(); if (result.equals(Task.SUCCESS)) { while (cloned == null) { logger.trace("<< after clone search for VM with name: " + name); cloned = getVM(name, folder); if (cloned == null) folder = serviceInstance.get().getInstance().getRootFolder(); else break; <START> sleep(500); <END> } } else { String errorMessage = task.getTaskInfo().getError().getLocalizedMessage(); logger.error(errorMessage); } } catch (Exception e) { logger.error("Can't clone vm: " + e.toString(), e); propagate(e); } return checkNotNull(cloned, "cloned"); }</code><technical_language>Remove this established mechanisms wait for things</technical_language>

Target:
private VirtualMachine cloneMaster(VirtualMachine master, String tag, String name, VirtualMachineCloneSpec cloneSpec, String folderName) { VirtualMachine cloned = null; try { FolderNameToFolderManagedEntity toFolderManagedEntity = new FolderNameToFolderManagedEntity(serviceInstance, master); Folder folder = toFolderManagedEntity.apply(folderName); Task task = master.cloneVM_Task(folder, name, cloneSpec); String result = task.waitForTask(); if (result.equals(Task.SUCCESS)) { logger.trace("<< after clone search for VM with name: " + name); Retryer<VirtualMachine> retryer = RetryerBuilder.<VirtualMachine>newBuilder() .retryIfResult(Predicates.<VirtualMachine>isNull()) .withStopStrategy(StopStrategies.stopAfterAttempt(5)) .retryIfException().withWaitStrategy(WaitStrategies.fixedWait(1, TimeUnit.SECONDS)) .build(); cloned = retryer.call(new GetVirtualMachineCallable(name, folder, serviceInstance.get().getInstance().getRootFolder())); } else { String errorMessage = task.getTaskInfo().getError().getLocalizedMessage(); logger.error(errorMessage); } } catch (Exception e) { if (e instanceof NoPermission){ NoPermission noPermission = (NoPermission)e; logger.error("NoPermission: " + noPermission.getPrivilegeId()); } logger.error("Can't clone vm: " + e.toString(), e); propagate(e); } if (cloned == null) logger.error("<< Failed to get cloned VM. " + name); return checkNotNull(cloned, "cloned"); }
Source:
<code>private CookieSpec getCookieSpec(final HttpState state) { if (this.cookiespec == null) { int i = state.getCookiePolicy(); if (i == -1) { this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy()); } else { this.cookiespec = CookiePolicy.getSpecByPolicy(i); } this.cookiespec.setValidDateFormats( <START> (Collection<?>)this.params.getParameter(HttpMethodParams.DATE_PATTERNS)); <END> } return this.cookiespec; }</code><technical_language>This forked classes, ideally do essential changes</technical_language>

Target:
private CookieSpec getCookieSpec(final HttpState state) { if (this.cookiespec == null) { int i = state.getCookiePolicy(); if (i == -1) { this.cookiespec = CookiePolicy.getCookieSpec(this.params.getCookiePolicy()); } else { this.cookiespec = CookiePolicy.getSpecByPolicy(i); } this.cookiespec.setValidDateFormats( (Collection)this.params.getParameter(HttpMethodParams.DATE_PATTERNS)); } return this.cookiespec; }
Source:
<code>public List<ProgramState> constrain(ProgramState state, Constraint constraint) { if (constraint.isStricterOrEqualTo(Constraint.TRUTHY)) { return firstOperandValue.constrain(state, secondOperandConstraint); } else if (constraint.isStricterOrEqualTo(Constraint.FALSY)) { return firstOperandValue.constrain(state, secondOperandConstraint.not()); } <START> return ImmutableList.of(state); <END> }</code><technical_language>@vilchik-elena Good question: here? reach code</technical_language>

Target:
public List<ProgramState> constrain(ProgramState state, Constraint constraint) { if (constraint.equals(Constraint.TRUTHY)) { return firstOperandValue.constrain(state, secondOperandConstraint); } else if (constraint.equals(Constraint.FALSY)) { return firstOperandValue.constrain(state, secondOperandConstraint.not()); } return ImmutableList.of(); }
Source:
<code>public void line(CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession) throws WorldEditException { Pattern pattern = we.getBlockPattern(player, args.getString(0)); Region region = session.getSelection(session.getSelectionWorld()); <START> Vector pos1 = ((CuboidRegion) region).getPos1(); <END> Vector pos2 = ((CuboidRegion) region).getPos2(); int blocksChanged = editSession.drawLine(region, pattern, pos1, pos2); player.print(blocksChanged + " block(s) have been changed."); }</code><technical_language>letting ClassCastExceptions happen</technical_language>

Target:
public void line(CommandContext args, LocalSession session, LocalPlayer player, EditSession editSession) throws WorldEditException { Region region = session.getSelection(session.getSelectionWorld()); if (!(region instanceof CuboidRegion)) { player.printError("Invalid region type"); return; } if (args.argsLength() < 2 ? false : args.getDouble(1) < 0) { player.printError("Invalid thickness. Must not be negative"); return; } Pattern pattern = we.getBlockPattern(player, args.getString(0)); CuboidRegion cuboidregion = (CuboidRegion) region; Vector pos1 = cuboidregion.getPos1(); Vector pos2 = cuboidregion.getPos2(); int blocksChanged = editSession.drawLine(pattern, pos1, pos2, args.argsLength() < 2 ? 0 : args.getDouble(1), !args.hasFlag('h')); player.print(blocksChanged + " block(s) have been changed."); }
Source:
<code>public ListenerResource( final @Json ObjectMapper jsonMapper, final @Smile ObjectMapper smileMapper, final ListenerHandler handler ) { <START> this.jsonMapper = Preconditions.checkNotNull(jsonMapper); <END> this.smileMapper = smileMapper; this.handler = handler; }</code><technical_language>add a message</technical_language>

Target:
public ListenerResource( final @Json ObjectMapper jsonMapper, final @Smile ObjectMapper smileMapper, final ListenerHandler handler ) { this.jsonMapper = Preconditions.checkNotNull(jsonMapper, "jsonMapper"); this.smileMapper = Preconditions.checkNotNull(smileMapper, "smileMapper"); this.handler = Preconditions.checkNotNull(handler, "listener handler"); }
Source:
<code>public void execute(ExecuteCommandParams params) { if (CLIENT_UPDATE_PROJECTS_CLASSPATH.equals(params.getCommand())) { for (Object project : params.getArguments()) { eventBus.fireEvent( <START> new ExternalLibrariesUpdateEvent(removePrefixUri(String.valueOf(project)))); <END> } } }</code><technical_language>I generally name events happened, in this case sth. "ProjectClasspathChangedEvent"</technical_language>

Target:
public void execute(ExecuteCommandParams params) { if (CLIENT_UPDATE_PROJECTS_CLASSPATH.equals(params.getCommand())) { for (Object project : params.getArguments()) { eventBus.fireEvent(new ProjectClasspathChangedEvent(stringValue(project))); } } }
Source:
<code>public void handleEvent(){ String message = "Edit the port to be exposed by the service"; final IServicePort port = model.getSelectedServicePort(); final ServicePortAdapter target = new ServicePortAdapter(port); final boolean previousRoutePort = model.getRoutingPort() == port; ServicePortDialog dialog = new ServicePortDialog(target, message, model.getServicePorts(), previousRoutePort); if(Window.OK == dialog.open()) { target.setName(NLS.bind("{0}-tcp", target.getPort())); model.updateServicePort(port, target); model.setSelectedServicePort(target); boolean routePort = dialog.isRoutePort(); if (routePort != previousRoutePort) { model.setRoutingPort(routePort?target:null); <START> portsViewer.refresh(); <END> } } }</code><technical_language>apparently binding list of ports, do refresh? if refreshing is more of a workaround for a bug required code</technical_language>

Target:
public void handleEvent(){ String message = "Edit the port to be exposed by the service"; final IServicePort port = model.getSelectedServicePort(); final ServicePortAdapter target = new ServicePortAdapter((ServicePortAdapter)port); ServicePortDialog dialog = new ServicePortDialog(target, message, model.getServicePorts()); if(Window.OK == dialog.open()) { target.setName(NLS.bind("{0}-tcp", target.getPort())); model.updateServicePort(port, target); model.setSelectedServicePort(target); } }
Source:
<code>public PartitionIterator resolve() { int count = responses.size(); List<UnfilteredPartitionIterator> iters = new ArrayList<>(count); Replica[] sources = new Replica[count]; for (int i = 0; i < count; i++) { MessageIn<ReadResponse> msg = responses.get(i); iters.add(msg.payload.makeIterator(command)); Replica replica = replicaMap.get(msg.from); <START> if (replica == null) <END> replica = command.decorateEndpoint(msg.from); if (replica == null) replica = Replica.fullStandin(msg.from); sources[i] = replica != null ? replica : Replica.fullStandin(msg.from); } DataLimits.Counter mergedResultCounter = command.limits().newCounter(command.nowInSec(), true, command.selectsFullPartition(), enforceStrictLiveness); UnfilteredPartitionIterator merged = mergeWithShortReadProtection(iters, sources, mergedResultCounter); FilteredPartitions filtered = FilteredPartitions.filter(merged, new Filter(command.nowInSec(), command.metadata().enforceStrictLiveness())); PartitionIterator counted = Transformation.apply(filtered, mergedResultCounter); return Transformation.apply(counted, new EmptyPartitionsDiscarder()); }</code><technical_language>knew kind of Replica message. kind of Replica get response different? pending states work. I get fail decorate it. right. If message eliciting this response time</technical_language>

Target:
public PartitionIterator resolve() { int count = responses.size(); List<UnfilteredPartitionIterator> iters = new ArrayList<>(count); Replica[] sources = new Replica[count]; for (int i = 0; i < count; i++) { MessageIn<ReadResponse> msg = responses.get(i); iters.add(msg.payload.makeIterator(command)); Replica replica = replicaMap.get(msg.from); if (replica == null) replica = command.decorateEndpoint(msg.from); assert replica != null; sources[i] = replica; } DataLimits.Counter mergedResultCounter = command.limits().newCounter(command.nowInSec(), true, command.selectsFullPartition(), enforceStrictLiveness); UnfilteredPartitionIterator merged = mergeWithShortReadProtection(iters, sources, mergedResultCounter); FilteredPartitions filtered = FilteredPartitions.filter(merged, new Filter(command.nowInSec(), command.metadata().enforceStrictLiveness())); PartitionIterator counted = Transformation.apply(filtered, mergedResultCounter); return Transformation.apply(counted, new EmptyPartitionsDiscarder()); }
Source:
<code>public void testAllRestPropertiesEnabled() throws Exception { Config config = new Config(); config.getNetworkConfig().getMemcacheProtocolConfig().setEnabled(true); <START> config.getNetworkConfig().getRestApiConfig().setEnabled(true); <END> HazelcastInstance hz = factory.newHazelcastInstance(config); hz.getMap("test").put("testKey", "testValue"); assertTextProtocolResponse(hz, TEST_URL_DATA); }</code><technical_language>This test needs DATA endpoint group enabled. This is remaining test failure; great if squash commits PR builder passes merge this PR</technical_language>

Target:
public void testAllRestPropertiesEnabled() throws Exception { Config config = new Config(); config.getNetworkConfig().getMemcacheProtocolConfig().setEnabled(true); RestApiConfig restApiConfig = config.getNetworkConfig().getRestApiConfig(); restApiConfig.setEnabled(true); restApiConfig.enableGroups(DATA); HazelcastInstance hz = factory.newHazelcastInstance(config); hz.getMap("test").put("testKey", "testValue"); assertTextProtocolResponse(hz, TEST_URL_DATA); }
Source:
<code>public boolean clearStream(StreamSpec streamSpec) { LOG.info("Creating Kafka topic: on system: {}", streamSpec.getPhysicalName(), streamSpec.getSystemName()); String topicName = streamSpec.getPhysicalName(); try { DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(ImmutableSet.of(topicName)); deleteTopicsResult.all().get(KAFKA_ADMIN_OPS_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (Exception e) { <START> LOG.error("Failed to delete topic with exception " + topicName + "\n" + e + "\n" + e.getCause()); <END> return false; } return true; }</code><technical_language>This work expected slf4j messageformatter string concatenation(+). suggestion LOG.error("Deleting topic: exception ", topicName, e);</technical_language>

Target:
public boolean clearStream(StreamSpec streamSpec) { LOG.info("Creating Kafka topic: on system: {}", streamSpec.getPhysicalName(), streamSpec.getSystemName()); String topicName = streamSpec.getPhysicalName(); try { DeleteTopicsResult deleteTopicsResult = adminClient.deleteTopics(ImmutableSet.of(topicName)); deleteTopicsResult.all().get(KAFKA_ADMIN_OPS_TIMEOUT_MS, TimeUnit.MILLISECONDS); } catch (Exception e) { LOG.error("Failed to delete topic with exception {}.", topicName, e); return false; } return true; }
Source:
<code>protected void schedulePublish(long delay) { if (isRunning() && executorQueued.compareAndSet(false, true)) { long now = System.currentTimeMillis(); delay = Math.max(0, Math.max(delay, (executorTime + 100) - now)); if (LOG.isTraceEnabled()) LOG.trace("{} scheduling publish in {}ms", this, delay); Runnable job = new Runnable() { @Override public void run() { try { executorTime = System.currentTimeMillis(); executorQueued.set(false); publishNow(); } catch (Exception e) { if (isRunning()) { LOG.error("Error resizing: "+e, e); } else { if (LOG.isDebugEnabled()) LOG.debug("Error resizing, but no longer running: "+e, e); } } catch (Throwable t) { LOG.error("Error in service-failure-detector: "+t, t); throw Exceptions.propagate(t); <START> } <END> } }; ScheduledTask task = new ScheduledTask(MutableMap.of("delay", Duration.of(delay, TimeUnit.MILLISECONDS)), new BasicTask(job)); ((EntityInternal)entity).getExecutionContext().submit(task); } }</code><technical_language>"problem" instead of "error" in log messages, imply not-an-Exception java class. Throwable? Error types do need log</technical_language>

Target:
protected void schedulePublish(long delay) { if (isRunning() && executorQueued.compareAndSet(false, true)) { long now = System.currentTimeMillis(); delay = Math.max(0, Math.max(delay, (executorTime + MIN_PERIOD_BETWEEN_EXECS_MILLIS) - now)); if (LOG.isTraceEnabled()) LOG.trace("{} scheduling publish in {}ms", this, delay); Runnable job = new Runnable() { @Override public void run() { try { executorTime = System.currentTimeMillis(); executorQueued.set(false); publishNow(); } catch (Exception e) { if (isRunning()) { LOG.error("Problem resizing: "+e, e); } else { if (LOG.isDebugEnabled()) LOG.debug("Problem resizing, but no longer running: "+e, e); } } catch (Throwable t) { LOG.error("Problem in service-failure-detector: "+t, t); throw Exceptions.propagate(t); } } }; ScheduledTask task = new ScheduledTask(MutableMap.of("delay", Duration.of(delay, TimeUnit.MILLISECONDS)), new BasicTask(job)); ((EntityInternal)entity).getExecutionContext().submit(task); } }
Source:
<code>protected VDS getEntity(int index) { <START> VDS vds = setUpEntityExpectations(control.createMock(VDS.class), control.createMock(RpmVersion.class), index); <END> VdsStatic vdsStatic = control.createMock(VdsStatic.class); expect(vdsStatic.getId()).andReturn(GUIDS[2]).anyTimes(); expect(vds.getStaticData()).andReturn(vdsStatic).anyTimes(); return vds; }</code><technical_language>create rpmversion in dedicated test forcing other tests defining (!NULL check in mapper do trick for you)</technical_language>

Target:
protected VDS getEntity(int index) { VDS vds = setUpEntityExpectations(control.createMock(VDS.class), index); VdsStatic vdsStatic = control.createMock(VdsStatic.class); expect(vdsStatic.getId()).andReturn(GUIDS[2]).anyTimes(); expect(vds.getStaticData()).andReturn(vdsStatic).anyTimes(); return vds; }
Source:
<code>public MessageChannel getOutputChannel() { if (this.handler instanceof MessageProducer) { return ((MessageProducer) this.handler).getOutputChannel(); } else if (this.handler instanceof AbstractMessageRouter) { <START> return ((AbstractMessageRouter) this.handler).getDefaultOutputChannel(); <END> } else { return null; } }</code><technical_language>I if proxy need more special interface... WDYT</technical_language>

Target:
public MessageChannel getOutputChannel() { if (this.handler instanceof MessageProducer) { return ((MessageProducer) this.handler).getOutputChannel(); } else if (this.handler instanceof MessageRouter) { return ((MessageRouter) this.handler).getDefaultOutputChannel(); } else { return null; } }
Source:
<code>private MediaLayout createHelpLayout() { TextView text = new TextView(getContext()); String markdownText = mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_MARKDOWN); if (markdownText != null) { text.setText(forceMarkdown(markdownText)); text.setMovementMethod(LinkMovementMethod.getInstance()); } else { try { text.setText(mPrompt.getHelpText()); } catch (XPathException exception) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), exception.getLocalizedMessage(), true); <START> } catch (Exception e) { <END> Logger.exception(TAG + ".createHelpLayout", e); e.printStackTrace(); } } text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize); int padding = (int)getResources().getDimension(R.dimen.help_text_padding); text.setPadding(0, 0, 0, 7); text.setId(38475483); MediaLayout helpLayout = MediaLayout.buildAudioImageVisualLayout(getContext(), text, mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_AUDIO), mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_IMAGE), mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_VIDEO), null); helpLayout.setPadding(padding, padding, padding, padding); return helpLayout; }</code><technical_language>remove</technical_language>

Target:
private MediaLayout createHelpLayout() { TextView text = new TextView(getContext()); String markdownText = mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_MARKDOWN); if (markdownText != null) { text.setText(forceMarkdown(markdownText)); text.setMovementMethod(LinkMovementMethod.getInstance()); } else { try { text.setText(mPrompt.getHelpText()); } catch (XPathException exception) { UserfacingErrorHandling.createErrorDialog((CommCareActivity)getContext(), exception.getLocalizedMessage(), true); } } text.setTextSize(TypedValue.COMPLEX_UNIT_DIP, mQuestionFontSize); int padding = (int)getResources().getDimension(R.dimen.help_text_padding); text.setPadding(0, 0, 0, 7); text.setId(38475483); MediaLayout helpLayout = MediaLayout.buildAudioImageVisualLayout(getContext(), text, mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_AUDIO), mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_IMAGE), mPrompt.getHelpMultimedia(FormEntryCaption.TEXT_FORM_VIDEO), null); helpLayout.setPadding(padding, padding, padding, padding); return helpLayout; }
Source:
<code>public Context getContext(String context_type) { GstContextPtr gstContextPtr = GSTELEMENT_API.gst_element_get_context(this, context_type); <START> return gstContextPtr != null ? new Context(Natives.initializer(gstContextPtr.getPointer())) : null; <END> }</code><technical_language>this Natives.callerOwnsReturn(..)</technical_language>

Target:
public Context getContext(String context_type) { GstContextPtr gstContextPtr = GSTELEMENT_API.gst_element_get_context(this, context_type); return gstContextPtr != null ? Natives.callerOwnsReturn(gstContextPtr, Context.class) : null; }
Source:
<code>protected Collection<MessageChannel> determineTargetChannels(Message<?> message) { List<MessageChannel> channels = new ArrayList<MessageChannel>(); <START> ConcurrentLinkedQueue<Recipient> recipientList = this.recipients; <END> for (Recipient recipient : recipientList) { if (recipient.accept(message)) { channels.add(recipient.getChannel()); } } return channels; }</code><technical_language>sure, if this scope variable is needed anymore. Concurrent... stuff ConcurrentModificationException</technical_language>

Target:
protected Collection<MessageChannel> determineTargetChannels(Message<?> message) { List<MessageChannel> channels = new ArrayList<MessageChannel>(); for (Recipient recipient : this.recipients) { if (recipient.accept(message)) { channels.add(recipient.getChannel()); } } return channels; }
Source:
<code>private static String getVersion() { <START> final String defaultVersion = "dev-" + System.currentTimeMillis(); <END> final String fileName = "bigtable-version.properties"; final String versionProperty = "bigtable.version"; try (InputStream stream = BigtableVersionInfo.class.getResourceAsStream(fileName)) { if (stream == null) { LOG.error("Could not load properties file bigtable-version.properties"); return defaultVersion; } Properties properties = new Properties(); properties.load(stream); String value = properties.getProperty(versionProperty); if (value == null) { LOG.error("$1 not found in $2.", versionProperty, fileName); } else if (value.startsWith("$")){ LOG.info("$1 property is not replaced.", versionProperty); } else { return value; } } catch (IOException e) { LOG.error("Error while trying to get user agent name from $1", e, fileName); } return defaultVersion; }</code><technical_language>do in a follow-up change strongly recommend ident gitattributes facility embed git commit hash in user agent: <LINK_0> straightforward do</technical_language>

Target:
private static String getVersion() { final String defaultVersion = "dev-" + System.currentTimeMillis(); final String fileName = "bigtable-version.properties"; final String versionProperty = "bigtable.version"; try (InputStream stream = BigtableVersionInfo.class.getResourceAsStream(fileName)) { if (stream == null) { LOG.error("Could not load properties file bigtable-version.properties"); return defaultVersion; } Properties properties = new Properties(); properties.load(stream); String value = properties.getProperty(versionProperty); if (value == null) { LOG.error("%s not found in %s.", versionProperty, fileName); } else if (value.startsWith("$")){ LOG.info("%s property is not replaced.", versionProperty); } else { return value; } } catch (IOException e) { LOG.error("Error while trying to get user agent name from %s", e, fileName); } return defaultVersion; }