auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Timeline> listTimelines(final String eventType) { return jdbcTemplate.query( BASE_TIMELINE_QUERY + " WHERE t.et_name=? order by t.t_order", new Object[]{eventType}, <START> timelineRowMapper); <END> }</code><technical_language>a small impovement, method notation mapper is place params vararg is 3rd place. allow pass eventType creation of array</technical_language>

Target:
public List<Timeline> listTimelines(final String eventType) { return jdbcTemplate.query( BASE_TIMELINE_QUERY + " WHERE t.et_name=? order by t.tl_order", timelineRowMapper, eventType); }
Source:
<code>public static List<BlockMetaData> filterRowGroups(List<FilterLevel> levels, Filter filter, List<BlockMetaData> blocks, ParquetFileReader reader) { <START> Objects.requireNonNull(filter, "filter"); <END> return filter.accept(new RowGroupFilter(levels, blocks, reader)); }</code><technical_language>suggestion Objects.requireNonNull(filter, "filter null");</technical_language>

Target:
public static List<BlockMetaData> filterRowGroups(List<FilterLevel> levels, Filter filter, List<BlockMetaData> blocks, ParquetFileReader reader) { Objects.requireNonNull(filter, "filter cannot be null"); return filter.accept(new RowGroupFilter(levels, blocks, reader)); }
Source:
<code>private void write(Object msg, boolean flush, ChannelPromise promise) { final AbstractChannelHandlerContext next; if (flush) { AbstractChannelHandlerContext ctx = this; do { ctx = ctx.prev; <START> } while ((ctx.executionMask & MASK_WRITE) == 0 && (ctx.executionMask & MASK_FLUSH) == 0); <END> next = ctx; } else { next = findContextOutbound(MASK_WRITE); } final Object m = pipeline.touch(msg, next); EventExecutor executor = next.executor(); if (executor.inEventLoop()) { if (flush) { next.invokeWriteAndFlush(m, promise); } else { next.invokeWrite(m, promise); } } else { final AbstractWriteTask task; if (flush) { task = WriteAndFlushTask.newInstance(next, m, promise); } else { task = WriteTask.newInstance(next, m, promise); } if (!safeExecute(executor, task, promise, m)) { task.cancel(); } } }</code><technical_language>(ctx.executionMask & MASK_WRITE) == 0 && (ctx.executionMask & MASK_FLUSH) == 0 as: (ctx.executionMask & (MASK_WRITE|MASK_FLUSH)) == 0</technical_language>

Target:
private void write(Object msg, boolean flush, ChannelPromise promise) { final AbstractChannelHandlerContext next = findContextOutbound(flush ? (MASK_WRITE | MASK_FLUSH) : MASK_WRITE); final Object m = pipeline.touch(msg, next); EventExecutor executor = next.executor(); if (executor.inEventLoop()) { if (flush) { next.invokeWriteAndFlush(m, promise); } else { next.invokeWrite(m, promise); } } else { final AbstractWriteTask task; if (flush) { task = WriteAndFlushTask.newInstance(next, m, promise); } else { task = WriteTask.newInstance(next, m, promise); } if (!safeExecute(executor, task, promise, m)) { task.cancel(); } } }
Source:
<code>public void serialize_test() { Note note = new Note() .setAuthor(HARDCODED_AUTHOR) .setDate(HARDCODED_DATE) .setUserIdsToNotify(Arrays.asList(HARDCODED_USER_IDS)) .setId(HARDCODED_ID) .setContactId(HARDCODED_CONTACT_ID) .setLinkedDealId(HARDCODED_LINKED_ID) .setModifiedAt(HARDCODED_MODIFY_DATE) .setCreatedAt(HARDCODED_CREATE_DATE); String json = NoteSerializer.toJsonObject(note); try { Note parsedNote = NoteSerializer.fromString(json); assertEquals(HARDCODED_AUTHOR, parsedNote.getAuthor()); assertEquals(HARDCODED_CONTACT_ID, parsedNote.getContactId()); assertEquals(HARDCODED_DATE, parsedNote.getDate()); assertEquals(HARDCODED_MODIFY_DATE, parsedNote.getModifiedAt()); assertEquals(HARDCODED_CREATE_DATE, parsedNote.getCreatedAt()); assertEquals(HARDCODED_ID, parsedNote.getId()); List<String> parsedUserIds = parsedNote.getUserIdsToNotify(); List<String> originalUserIds = Arrays.asList(HARDCODED_USER_IDS); assertTrue( parsedUserIds.containsAll(originalUserIds) && originalUserIds.containsAll(parsedUserIds)); } catch (OnePageException e) { e.printStackTrace(); <START> } <END> }</code><technical_language>@fraggjkee recommend put test fail if catch block. right test pass if parsing completely fails (line 43). a quick I method do trick: junit.framework.Assert#fail()</technical_language>

Target:
public void serialize_test() { Note note = new Note() .setAuthor(HARDCODED_AUTHOR) .setDate(HARDCODED_DATE) .setUserIdsToNotify(Arrays.asList(HARDCODED_USER_IDS)) .setId(HARDCODED_ID) .setContactId(HARDCODED_CONTACT_ID) .setLinkedDealId(HARDCODED_LINKED_ID) .setModifiedAt(HARDCODED_MODIFY_DATE) .setCreatedAt(HARDCODED_CREATE_DATE); String string = NoteSerializer.toJsonObject(note); try { JSONObject json = new JSONObject(string); Note parsedNote = NoteSerializer.fromJsonObject(json); assertEquals(HARDCODED_AUTHOR, parsedNote.getAuthor()); assertEquals(HARDCODED_CONTACT_ID, parsedNote.getContactId()); assertEquals(HARDCODED_DATE, parsedNote.getDate()); assertEquals(HARDCODED_MODIFY_DATE, parsedNote.getModifiedAt()); assertEquals(HARDCODED_CREATE_DATE, parsedNote.getCreatedAt()); assertEquals(HARDCODED_ID, parsedNote.getId()); List<String> parsedUserIds = parsedNote.getUserIdsToNotify(); List<String> originalUserIds = Arrays.asList(HARDCODED_USER_IDS); assertTrue(parsedUserIds.containsAll(originalUserIds) && originalUserIds.containsAll(parsedUserIds)); } catch (Exception e) { e.printStackTrace(); Assert.fail(); } }
Source:
<code>public void testAcquireLockWithLockNotAvailableException() { JedisOps ops = mock(JedisOps.class); when(ops.setnx(eq("key"), anyString())).thenReturn(0L); when(ops.ttl("key")).thenReturn(30L); RedisLock lock = new RedisLock(ops); try { lock.acquireLock("key", 10); } catch (LockNotAvailableException e) { assertTrue("LockNotAvailableException expected", true); <START> } <END> InOrder inOrder = inOrder(ops); inOrder.verify(ops, times(1)).setnx(eq("key"), anyString()); inOrder.verify(ops, times(1)).expire("key", 10); }</code><technical_language>This is effective test exception is thrown. If exception is thrown, catch block is executed, assertTrue() fire. instead a pattern try { lock.acquireLock("key", 10); fail("expected exception"); } catch (LockNotAvailableException e) { // stuff } I frequently extend this Exception thrownEx = null; try { lock.acquireLock("key", 10); fail("expected exception"); } catch (LockNotAvailableException e) { thrownEx = e; } assertNotNull(thrownEx) a double-check throw exception</technical_language>

Target:
public void testAcquireLockWithLockNotAvailableException() { JedisOps ops = mock(JedisOps.class); when(ops.setnx(eq("key"), anyString())).thenReturn(0L); when(ops.ttl("key")).thenReturn(-1L); when(ops.expire("key", 10)).thenReturn(1L); RedisLock lock = new RedisLock(ops); LockNotAvailableException expected = null; try { lock.acquireLock("key", 10); fail("LockNotAvailableException expected."); } catch (LockNotAvailableException e) { expected = e; } assertNotNull(expected); InOrder inOrder = inOrder(ops); inOrder.verify(ops, times(1)).setnx(eq("key"), anyString()); inOrder.verify(ops, times(1)).expire("key", 10); }
Source:
<code>public List<DataType> all() { <START> return new ArrayList<>(dataTypes.values()); <END> }</code><technical_language>all() is internally I rewrite as: java public Collection<DataType> all() { return dataTypes.values(); }</technical_language>

Target:
private Collection<DataType> all() { return dataTypes.values(); }
Source:
<code>private void startSequencesAtBeginning(TopicPartition topicPartition, ProducerIdAndEpoch newProducerIdAndEpoch) { final PrimitiveRef.IntRef sequence = PrimitiveRef.ofInt(0); <START> getPartition(topicPartition).resetSequenceNumbers(inFlightBatch -> { <END> inFlightBatch.resetProducerState(newProducerIdAndEpoch, sequence.value, inFlightBatch.isTransactional()); sequence.value += inFlightBatch.recordCount; }); getPartition(topicPartition).nextSequence = sequence.value; getPartition(topicPartition).lastAckedSequence = NO_LAST_ACKED_SEQUENCE_NUMBER; }</code><technical_language>nit: save result of getPartition(topicPartition)</technical_language>

Target:
private void startSequencesAtBeginning(TopicPartition topicPartition, ProducerIdAndEpoch newProducerIdAndEpoch) { final PrimitiveRef.IntRef sequence = PrimitiveRef.ofInt(0); TopicPartitionEntry topicPartitionEntry = getPartition(topicPartition); topicPartitionEntry.resetSequenceNumbers(inFlightBatch -> { inFlightBatch.resetProducerState(newProducerIdAndEpoch, sequence.value, inFlightBatch.isTransactional()); sequence.value += inFlightBatch.recordCount; }); topicPartitionEntry.nextSequence = sequence.value; topicPartitionEntry.lastAckedSequence = NO_LAST_ACKED_SEQUENCE_NUMBER; }
Source:
<code>private String getDataSourceName(DataSource dataSource) { <START> Preconditions.checkArgument( <END> dataSource instanceof TableDataSource, "Subqueries and Unions are only supported in the broker" ); return Iterables.getOnlyElement(dataSource.getNames()); }</code><technical_language>I instance of inheritance in place. throw UOE in other table data source data sources</technical_language>

Target:
private String getDataSourceName(DataSource dataSource) { return Iterables.getOnlyElement(dataSource.getNames()); }
Source:
<code>private void canTerminate(IProcessDMContext[] procDmcs, DataRequestMonitor<Boolean> rm) { if (procDmcs.length == 0) { IGDBControl gdbControl = fTracker.getService(IGDBControl.class); if (gdbControl != null) { rm.setData(true); } else { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Service is not available.")); } rm.done(); return; } IMultiTerminate multiTerminate = fTracker.getService(IMultiTerminate.class); if (multiTerminate != null) { multiTerminate.canTerminateSome(procDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null && procDmcs.length == 1) { procService.canTerminate(procDmcs[0], rm); } else { <START> rm.setData(false);; <END> rm.done(); } } }</code><technical_language>;;</technical_language>

Target:
private void canTerminate(IProcessDMContext[] procDmcs, DataRequestMonitor<Boolean> rm) { if (procDmcs.length == 0) { IGDBControl gdbControl = fTracker.getService(IGDBControl.class); if (gdbControl != null) { rm.setData(true); } else { rm.setStatus(new Status(IStatus.ERROR, GdbUIPlugin.PLUGIN_ID, "Service is not available.")); } rm.done(); return; } IMultiTerminate multiTerminate = fTracker.getService(IMultiTerminate.class); if (multiTerminate != null) { multiTerminate.canTerminateSome(procDmcs, rm); } else { IProcesses procService = fTracker.getService(IProcesses.class); if (procService != null && procDmcs.length == 1) { procService.canTerminate(procDmcs[0], rm); } else { rm.setData(false); rm.done(); } } }
Source:
<code>public AbfsRestOperation createPath(final String path, final boolean isFile, final boolean overwrite, final String permission, final String umask, final boolean appendBlob) throws AzureBlobFileSystemException { final List<AbfsHttpHeader> requestHeaders = createDefaultHeaders(); if (!overwrite) { requestHeaders.add(new AbfsHttpHeader(IF_NONE_MATCH, AbfsHttpConstants.STAR)); } if (permission != null && !permission.isEmpty()) { requestHeaders.add(new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_PERMISSIONS, permission)); } if (umask != null && !umask.isEmpty()) { requestHeaders.add(new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_UMASK, umask)); } final AbfsUriQueryBuilder abfsUriQueryBuilder = createDefaultUriQueryBuilder(); abfsUriQueryBuilder.addQuery(QUERY_PARAM_RESOURCE, isFile ? FILE : DIRECTORY); if (appendBlob) { abfsUriQueryBuilder.addQuery(QUERY_PARAM_BLOBTYPE, APPEND_BLOB_TYPE); } <START> final URL url = createRequestUrl(path, abfsUriQueryBuilder.toString()); <END> final AbfsRestOperation op = new AbfsRestOperation( AbfsRestOperationType.CreatePath, this, HTTP_METHOD_PUT, url, requestHeaders); op.execute(); return op; }</code><technical_language>Test change account in prod tenant doesnt Dec-12 bits</technical_language>

Target:
public AbfsRestOperation createPath(final String path, final boolean isFile, final boolean overwrite, final String permission, final String umask, final boolean appendBlob) throws AzureBlobFileSystemException { final List<AbfsHttpHeader> requestHeaders = createDefaultHeaders(); if (!overwrite) { requestHeaders.add(new AbfsHttpHeader(IF_NONE_MATCH, AbfsHttpConstants.STAR)); } if (permission != null && !permission.isEmpty()) { requestHeaders.add(new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_PERMISSIONS, permission)); } if (umask != null && !umask.isEmpty()) { requestHeaders.add(new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_UMASK, umask)); } final AbfsUriQueryBuilder abfsUriQueryBuilder = createDefaultUriQueryBuilder(); abfsUriQueryBuilder.addQuery(QUERY_PARAM_RESOURCE, isFile ? FILE : DIRECTORY); if (appendBlob) { abfsUriQueryBuilder.addQuery(QUERY_PARAM_BLOBTYPE, APPEND_BLOB_TYPE); } String operation = isFile ? SASTokenProvider.CREATEFILE_OPERATION : SASTokenProvider.MKDIR_OPERATION; appendSASTokenToQuery(path, operation, abfsUriQueryBuilder); final URL url = createRequestUrl(path, abfsUriQueryBuilder.toString()); final AbfsRestOperation op = new AbfsRestOperation( AbfsRestOperationType.CreatePath, this, HTTP_METHOD_PUT, url, requestHeaders); op.execute(); return op; }
Source:
<code>private static SecretKeyEncryptionStrategy instantiateSecreteKeyEncryptionStrategy(String className) { log.debug("About to instantiate secret key encryption strategy {}", className); SecretKeyEncryptionStrategy strategy = null; Class keyEncryptionStrategyClazz = null; try { keyEncryptionStrategyClazz = AccumuloVFSClassLoader.loadClass(className); } catch (ClassNotFoundException e1) { throw new RuntimeException("Could not find configured secret key encryption strategy: " + className); } Class[] interfaces = keyEncryptionStrategyClazz.getInterfaces(); boolean implementsSecretKeyStrategy = false; for (Class clazz : interfaces) { if (clazz.equals(SecretKeyEncryptionStrategy.class)) { implementsSecretKeyStrategy = true; break; } } if (!implementsSecretKeyStrategy) { throw new RuntimeException("Configured Accumulo secret key encryption strategy \"%s\" does not implement the SecretKeyEncryptionStrategy interface."); } else { try { strategy = (SecretKeyEncryptionStrategy) keyEncryptionStrategyClazz.newInstance(); log.debug("Successfully instantiated secret key encryption strategy {}", className); } catch (InstantiationException e) { <START> throw new RuntimeException("Got instantiation exception when instantiating secret key encryption strategy " + className); <END> } catch (IllegalAccessException e) { throw new RuntimeException("Got illegal access exception when trying to instantiate secret key encryption strategy " + className); } } return strategy; }</code><technical_language>a lot of catch blocks essentially error, multi-catch syntax, clean a bit. original exception passed a parameter, lose portions of stack trace</technical_language>

Target:
private static SecretKeyEncryptionStrategy instantiateSecreteKeyEncryptionStrategy(String className) { log.debug("About to instantiate secret key encryption strategy {}", className); SecretKeyEncryptionStrategy strategy = null; Class<?> keyEncryptionStrategyClazz = null; try { keyEncryptionStrategyClazz = AccumuloVFSClassLoader.loadClass(className); } catch (ClassNotFoundException e1) { throw new IllegalArgumentException("Could not find configured secret key encryption strategy: " + className); } Class<?>[] interfaces = keyEncryptionStrategyClazz.getInterfaces(); boolean implementsSecretKeyStrategy = false; for (Class<?> clazz : interfaces) { if (clazz.equals(SecretKeyEncryptionStrategy.class)) { implementsSecretKeyStrategy = true; break; } } if (!implementsSecretKeyStrategy) { throw new IllegalArgumentException( "Configured Accumulo secret key encryption strategy \"%s\" does not implement the SecretKeyEncryptionStrategy interface."); } else { try { strategy = (SecretKeyEncryptionStrategy) keyEncryptionStrategyClazz.newInstance(); log.debug("Successfully instantiated secret key encryption strategy {}", className); } catch (InstantiationException | IllegalAccessException e) { throw new IllegalArgumentException("Unable to instantiate the secret key encryption strategy: " + className, e); } } return strategy; }
Source:
<code>public void removeAllChangeListeners() { <START> realm.checkIfValid(); <END> realm.sharedRealm.capabilities.checkCanDeliverNotification(BaseRealm.LISTENER_NOT_ALLOWED_MESSAGE); collection.removeAllListeners(); }</code><technical_language>nice if this incorporated checkForAddRemoveListener method? checkForAddRemoveListener(listener, checkForNull)</technical_language>

Target:
public void removeAllChangeListeners() { checkForAddRemoveListener(null, false); collection.removeAllListeners(); }
Source:
<code>public void testUploadPart() throws InterruptedException { MockResponse mr = buildBaseResponse(204); mr.addHeader(GlacierHeaders.TREE_HASH, TREEHASH); server.enqueue(mr); assertThat(client.uploadPart(VAULT_NAME, MULTIPART_UPLOAD_ID, ContentRange.fromPartNumber(0, 4), <START> buildPayload(4 * MiB))).isEqualTo(HashCode.fromString(TREEHASH)); <END> RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /-/vaults/" + VAULT_NAME + "/multipart-uploads/" + MULTIPART_UPLOAD_ID + " " + HTTP); assertEquals(request.getHeader(HttpHeaders.CONTENT_RANGE), "bytes 0-4194303/*"); assertEquals(request.getHeader(HttpHeaders.CONTENT_LENGTH), "4194304"); }</code><technical_language>TREEHASH a HashCode</technical_language>

Target:
public void testUploadPart() throws InterruptedException { MockResponse mr = buildBaseResponse(204); mr.addHeader(GlacierHeaders.TREE_HASH, TREEHASH); server.enqueue(mr); assertThat(client.uploadPart(VAULT_NAME, MULTIPART_UPLOAD_ID, ContentRange.fromPartNumber(0, 4), buildPayload(4 * MiB))).isEqualTo(TREEHASH); RecordedRequest request = server.takeRequest(); assertEquals(request.getRequestLine(), "PUT /-/vaults/" + VAULT_NAME + "/multipart-uploads/" + MULTIPART_UPLOAD_ID + " " + HTTP); assertEquals(request.getHeader(HttpHeaders.CONTENT_RANGE), "bytes 0-4194303/*"); assertEquals(request.getHeader(HttpHeaders.CONTENT_LENGTH), "4194304"); }
Source:
<code>public String render(final ListAllMyBucketsResult obj) throws JsonProcessingException { if (obj == null) { return "You do not have any buckets"; } <START> ObjectMapper mapper = new ObjectMapper(); <END> return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); }</code><technical_language>final</technical_language>

Target:
public String render(final ListAllMyBucketsResult obj) throws JsonProcessingException { final ObjectMapper mapper = new ObjectMapper(); if( (obj == null) || (null == obj.getBuckets()) ){ return mapper.writerWithDefaultPrettyPrinter().writeValueAsString("You do not have any buckets"); } return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj); }
Source:
<code>protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); var mw = ((KeywordFieldMapper) mergeWith); this.ignoreAbove = ((KeywordFieldMapper) mergeWith).ignoreAbove; if (!Objects.equals(this.lengthLimit, mw.lengthLimit)) { throw new IllegalArgumentException( "mapper [" + name() + "] has different length_limit settings, current [" <START> + this.fieldType().lengthLimit + "], merged [" + mw.fieldType().lengthLimit + "]"); <END> } }</code><technical_language>suggestion this.ignoreAbove = mw.ignoreAbove;</technical_language>

Target:
protected void doMerge(Mapper mergeWith, boolean updateAllTypes) { super.doMerge(mergeWith, updateAllTypes); var mw = ((KeywordFieldMapper) mergeWith); this.ignoreAbove = mw.ignoreAbove; if (!Objects.equals(this.lengthLimit, mw.lengthLimit)) { throw new IllegalArgumentException( "mapper [" + name() + "] has different length_limit settings, current [" + this.lengthLimit + "], merged [" + mw.lengthLimit + "]"); } }
Source:
<code>private void storeReleasedTime(AndroidCommCarePlatform platform, Reference ref) { long releasedOnTime = -1; if (ref instanceof JavaHttpReference) { Headers responseHeaders = ((JavaHttpReference)ref).getResponseHeaders(); if (responseHeaders != null) { String releasedOnStr = responseHeaders.get(HEADER_APP_RELEASED_ON); try { if (releasedOnStr != null) { releasedOnTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm'Z'").parse(releasedOnStr).getTime(); } } catch (ParseException e) { <START> e.printStackTrace(); <END> } } } if (releasedOnTime == -1) { releasedOnTime = new Date().getTime(); } HiddenPreferences.setReleasedOnTimeForOngoingAppDownload(platform, releasedOnTime); }</code><technical_language>want eat this error silently. A parse error means HQ is setting header, in wrong format, means phones silently fail properly feature correctly, anyone's knowledge</technical_language>

Target:
private void storeReleasedTime(AndroidCommCarePlatform platform, Reference ref) throws ParseException { long releasedOnTime = -1; if (ref instanceof ReleasedOnTimeSupportedReference) { releasedOnTime = ((ReleasedOnTimeSupportedReference)ref).getReleasedOnTime(); } if (releasedOnTime == -1) { releasedOnTime = new Date().getTime(); } HiddenPreferences.setReleasedOnTimeForOngoingAppDownload(platform, releasedOnTime); }
Source:
<code>public void centerOnNode(DataNode node) throws NodeNotFoundException { double x = -1; for (WrapperClone wrapperClone : graphData) { if (wrapperClone.getDataNodes().contains(node)) { <START> x = wrapperClone.getX(); <END> break; } } if (x != -1) { setZoomCenter(x); } else { throw new NodeNotFoundException(); } }</code><technical_language>Wrapper#getX() : float float instead of double</technical_language>

Target:
public void centerOnNode(DataNode node) throws NodeNotFoundException { float x = -1; for (WrapperClone wrapperClone : graphData) { if (wrapperClone.getDataNodes().contains(node)) { x = wrapperClone.getX(); break; } } if (x != -1) { setZoomCenter(x); } else { throw new NodeNotFoundException(); } }
Source:
<code>public SourceRecord extractRecord() throws SQLException { Struct record = new Struct(schemaMapping.schema()); for (FieldSetter setter : schemaMapping.fieldSetters()) { try { setter.setField(record, resultSet); } catch (IOException e) { log.warn("Ignoring record because processing failed:", e); } catch (SQLException e) { log.warn("Ignoring record due to SQL error:", e); } } offset = criteria.extractValues(schemaMapping.schema(), record, offset); final String topic; final Map<String, String> partition; switch (mode) { case TABLE: if (useFqn) { String fqn = ExpressionBuilder.create().append(tableId, false).toString(); partition = new HashMap<>(); partition.put(JdbcSourceConnectorConstants.TABLE_NAME_KEY, fqn); partition.put(JdbcSourceConnectorConstants.OFFSET_PROTOCOL_VERSION, "1"); topic = topicPrefix + fqn; } else { String name = tableId.tableName(); partition = Collections.singletonMap(JdbcSourceConnectorConstants.TABLE_NAME_KEY, name); topic = topicPrefix + name; <START> } <END> break; case QUERY: partition = Collections.singletonMap(JdbcSourceConnectorConstants.QUERY_NAME_KEY, JdbcSourceConnectorConstants.QUERY_NAME_VALUE); topic = topicPrefix; break; default: throw new ConnectException("Unexpected query mode: " + mode); } return new SourceRecord(partition, offset.toMap(), topic, record.schema(), record); }</code><technical_language>of this extracted a strategy function compute topic table ID (e.g., topicName(TableId)), a method compute partitions for a table ID (e.g., sourcePartitions(TableId)). separate strategy implementations for protocol version, a strategy implementation passed this class</technical_language>

Target:
public SourceRecord extractRecord() throws SQLException { Struct record = new Struct(schemaMapping.schema()); for (FieldSetter setter : schemaMapping.fieldSetters()) { try { setter.setField(record, resultSet); } catch (IOException e) { log.warn("Ignoring record because processing failed:", e); } catch (SQLException e) { log.warn("Ignoring record due to SQL error:", e); } } offset = criteria.extractValues(schemaMapping.schema(), record, offset); return new SourceRecord(partition, offset.toMap(), topic, record.schema(), record); }
Source:
<code>protected void decodeValue(Klv klv) { byte[] bytes = klv.getValue(); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(bytes); CharsetMatch charsetMatch = charsetDetector.detect(); <START> Charset charset = Charset.defaultCharset(); <END> if (charsetMatch != null) { try { charset = Charset.forName(charsetMatch.getName()); } catch (IllegalArgumentException e) { LOGGER.trace( "Unsupported encoding of %s, falling back to default encoding", charsetMatch.getName()); } } value = new String(bytes, charset); }</code><technical_language>question: is safe Charset.defaultCharset() here? Some systems default charsets. For example, Windows Linux</technical_language>

Target:
protected void decodeValue(Klv klv) { byte[] bytes = klv.getValue(); CharsetDetector charsetDetector = new CharsetDetector(); charsetDetector.setText(bytes); CharsetMatch charsetMatch = charsetDetector.detect(); Charset charset = Charset.defaultCharset(); if (charsetMatch != null) { try { charset = Charset.forName(charsetMatch.getName()); } catch (IllegalArgumentException e) { LOGGER.trace( "Unsupported encoding of {}, falling back to default encoding", charsetMatch.getName()); } } value = new String(bytes, charset); }
Source:
<code>private AzureBlobStorageImpl constructImpl() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); <START> if (Objects.isNull(containerName) || containerName.isEmpty()) { <END> containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } checkValidEncryptionParameters(); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = buildPipeline(); } return new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(); }</code><technical_language>ImplUtils a isNullOrEmpty method handle checks</technical_language>

Target:
private AzureBlobStorageImpl constructImpl() { Objects.requireNonNull(blobName, "'blobName' cannot be null."); if (ImplUtils.isNullOrEmpty(containerName)) { containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } checkValidEncryptionParameters(); HttpPipeline pipeline = super.getPipeline(); if (pipeline == null) { pipeline = buildPipeline(); } return new AzureBlobStorageBuilder() .url(String.format("%s/%s/%s", endpoint, containerName, blobName)) .pipeline(pipeline) .build(); }
Source:
<code>public void testLongFileNameThatDoesNotRequireEncoding() { String str = StringUtils.repeat("1", 256); assertEquals( <START> "11111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111.71634944", <END> fileManager.getFileName(TaskTestUtil.createMockTask(str), true)); }</code><technical_language>Strings.repeat something</technical_language>

Target:
public void testLongFileNameThatDoesNotRequireEncoding() { String str = StringUtils.repeat("1", 256); assertEquals(StringUtils.repeat("1", 242) + ".71634944", fileManager.getFileName(TaskTestUtil.createMockTask(str), false)); assertEquals(str, fileManager.getFileName(TaskTestUtil.createMockTask(str), true)); }
Source:
<code>public boolean applyCSSProperty(Object element, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (!(element instanceof ISelectionBackgroundCustomizationElement && element instanceof ElementAdapter) || !(((ElementAdapter) element).getNativeWidget() instanceof Widget) || property == null || value.getCssValueType() != CSSValue.CSS_PRIMITIVE_VALUE) { return false; } Widget widget = (Widget) ((ElementAdapter) element).getNativeWidget(); ISelectionBackgroundCustomizationElement treeElement = (ISelectionBackgroundCustomizationElement) element; Color newColor = (Color) engine.convert(value, Color.class, widget.getDisplay()); switch <START> (property.toLowerCase()) { <END> case SWT_SELECTION_FOREGROUND_COLOR: treeElement.setSelectionForegroundColor(newColor); break; case SWT_SELECTION_BACKGROUND_COLOR: treeElement.setSelectionBackgroundColor(newColor); break; case SWT_SELECTION_BORDER_COLOR: treeElement.setSelectionBorderColor(newColor); break; case SWT_HOT_BACKGROUND_COLOR: treeElement.setHotBackgroundColor(newColor); break; case SWT_HOT_BORDER_COLOR: treeElement.setHotBorderColor(newColor); break; } return true; }</code><technical_language>original code toLowerCase(). add it</technical_language>

Target:
public boolean applyCSSProperty(Object element, String property, CSSValue value, String pseudo, CSSEngine engine) throws Exception { if (!(element instanceof ISelectionBackgroundCustomizationElement && element instanceof ElementAdapter) || !(((ElementAdapter) element).getNativeWidget() instanceof Widget) || property == null || value.getCssValueType() != CSSValue.CSS_PRIMITIVE_VALUE) { return false; } Widget widget = (Widget) ((ElementAdapter) element).getNativeWidget(); ISelectionBackgroundCustomizationElement treeElement = (ISelectionBackgroundCustomizationElement) element; Color newColor = (Color) engine.convert(value, Color.class, widget.getDisplay()); switch (property) { case SWT_SELECTION_FOREGROUND_COLOR: treeElement.setSelectionForegroundColor(newColor); break; case SWT_SELECTION_BACKGROUND_COLOR: treeElement.setSelectionBackgroundColor(newColor); break; case SWT_SELECTION_BORDER_COLOR: treeElement.setSelectionBorderColor(newColor); break; case SWT_HOT_BACKGROUND_COLOR: treeElement.setHotBackgroundColor(newColor); break; case SWT_HOT_BORDER_COLOR: treeElement.setHotBorderColor(newColor); break; } return false; }
Source:
<code><START> public Optional<Guid> <END> getUserIdIfExternal() { return isInternalExecution() ? Optional.empty() : Optional.ofNullable(getUserId()); }</code><technical_language>this reduced protected</technical_language>

Target:
protected Optional<Guid> getUserIdIfExternal() { return isInternalExecution() ? Optional.empty() : Optional.ofNullable(getUserId()); }
Source:
<code>protected DatabaseName unmarshal0( ReadableChannel channel ) throws IOException { byte nullMarker = channel.get(); if ( nullMarker == 0 ) { return null; } else { int nameLength = (int) channel.get(); byte[] nameBytes = new byte[nameLength]; channel.get( nameBytes, nameLength ); <START> return new DatabaseName( UTF8.decode( nameBytes ) ); <END> } }</code><technical_language>a StringMarshal helper class of this UTF8 logic for a string</technical_language>

Target:
protected DatabaseName unmarshal0( ReadableChannel channel ) throws IOException { return new DatabaseName( StringMarshal.unmarshal( channel ) ); }
Source:
<code>protected <C, R> void doDispatch(CommandMessage<C> command, CommandCallback<? super C, R> callback) { MessageMonitor.MonitorCallback monitorCallback = messageMonitor.onMessageIngested(command); MessageHandler<? super CommandMessage<?>> handler = findCommandHandlerFor(command).orElseThrow(() -> { NoHandlerForCommandException exception = new NoHandlerForCommandException( <START> format("No handler was subscribed to command [%s]", command.getCommandName())); <END> monitorCallback.reportFailure(exception); return exception; }); try { Object result = doDispatch(command, handler); monitorCallback.reportSuccess(); callback.onSuccess(command, (R) result); } catch (Exception throwable) { monitorCallback.reportFailure(throwable); callback.onFailure(command, throwable); } }</code><technical_language>handler subscribed **for** command</technical_language>

Target:
protected <C, R> void doDispatch(CommandMessage<C> command, CommandCallback<? super C, R> callback) { MessageMonitor.MonitorCallback monitorCallback = messageMonitor.onMessageIngested(command); MessageHandler<? super CommandMessage<?>> handler = findCommandHandlerFor(command).orElseThrow(() -> { NoHandlerForCommandException exception = new NoHandlerForCommandException( format("No handler was subscribed to command [%s]", command.getCommandName())); monitorCallback.reportFailure(exception); return exception; }); handle(command, handler, new MonitorAwareCallback<>(callback, monitorCallback)); }
Source:
<code>private void processNewResponses() throws InterruptedException, IOException { SocketServerResponse curr = (SocketServerResponse) channel.receiveResponse(id); while (curr != null) { curr.onDequeueFromResponseQueue(); SocketServerRequest request = (SocketServerRequest) curr.getRequest(); String connectionId = request.getConnectionId(); try { if (curr.getPayload() == null) { logger.trace("Socket server received no response and hence closing the connection"); selector.close(connectionId); } else { logger.trace("Socket server received response to send, registering for write: {}", curr); NetworkSend networkSend = new NetworkSend(connectionId, curr.getPayload(), curr.getMetrics(), time); selector.send(networkSend); } } catch (IllegalStateException e) { logger <START> .error("Attempt to write to socket for which there is no open connection. Connection id {}", connectionId); <END> } finally { curr = (SocketServerResponse) channel.receiveResponse(id); } } }</code><technical_language>This is assumption. in try block throw IllegalStateException right? I suggest logging exception message here</technical_language>

Target:
private void processNewResponses() throws InterruptedException, IOException { SocketServerResponse curr = (SocketServerResponse) channel.receiveResponse(id); while (curr != null) { curr.onDequeueFromResponseQueue(); SocketServerRequest request = (SocketServerRequest) curr.getRequest(); String connectionId = request.getConnectionId(); try { if (curr.getPayload() == null) { logger.trace("Socket server received no response and hence closing the connection"); selector.close(connectionId); } else { logger.trace("Socket server received response to send, registering for write: {}", curr); NetworkSend networkSend = new NetworkSend(connectionId, curr.getPayload(), curr.getMetrics(), time); selector.send(networkSend); } } catch (IllegalStateException e) { metrics.processNewResponseErrorCount.inc(); logger.debug("Error in processing new responses", e); } finally { curr = (SocketServerResponse) channel.receiveResponse(id); } } }
Source:
<code>public static boolean postHasEdits(@Nullable PostImmutableModel oldPost, PostImmutableModel newPost) { if (oldPost == null) { return newPost != null; } return newPost == null || !(StringUtils.equals(oldPost.getTitle(), newPost.getTitle()) && StringUtils.equals(oldPost.getContent(), newPost.getContent()) && StringUtils.equals(oldPost.getExcerpt(), newPost.getExcerpt()) && StringUtils.equals(oldPost.getStatus(), newPost.getStatus()) && StringUtils.equals(oldPost.getPassword(), newPost.getPassword()) && StringUtils.equals(oldPost.getPostFormat(), newPost.getPostFormat()) && StringUtils.equals(oldPost.getDateCreated(), newPost.getDateCreated()) && StringUtils.equals(oldPost.getSlug(), newPost.getSlug()) && oldPost.getFeaturedImageId() == newPost.getFeaturedImageId() && oldPost.getTagNameList().containsAll(newPost.getTagNameList()) && newPost.getTagNameList().containsAll(oldPost.getTagNameList()) && oldPost.getCategoryIdList().containsAll(newPost.getCategoryIdList()) <START> && newPost.getCategoryIdList().containsAll(oldPost.getCategoryIdList()) <END> && oldPost.getLocation().equals(newPost.getLocation()) && oldPost.getChangesConfirmedContentHashcode() == newPost .getChangesConfirmedContentHashcode() ); }</code><technical_language>call PostLocation.companion.equals here</technical_language>

Target:
public static boolean postHasEdits(@Nullable PostImmutableModel oldPost, PostImmutableModel newPost) { if (oldPost == null) { return newPost != null; } return newPost == null || !(StringUtils.equals(oldPost.getTitle(), newPost.getTitle()) && StringUtils.equals(oldPost.getContent(), newPost.getContent()) && StringUtils.equals(oldPost.getExcerpt(), newPost.getExcerpt()) && StringUtils.equals(oldPost.getStatus(), newPost.getStatus()) && StringUtils.equals(oldPost.getPassword(), newPost.getPassword()) && StringUtils.equals(oldPost.getPostFormat(), newPost.getPostFormat()) && StringUtils.equals(oldPost.getDateCreated(), newPost.getDateCreated()) && StringUtils.equals(oldPost.getSlug(), newPost.getSlug()) && oldPost.getFeaturedImageId() == newPost.getFeaturedImageId() && oldPost.getTagNameList().containsAll(newPost.getTagNameList()) && newPost.getTagNameList().containsAll(oldPost.getTagNameList()) && oldPost.getCategoryIdList().containsAll(newPost.getCategoryIdList()) && newPost.getCategoryIdList().containsAll(oldPost.getCategoryIdList()) && PostLocation.Companion.equals(oldPost.getLocation(), newPost.getLocation()) && oldPost.getChangesConfirmedContentHashcode() == newPost .getChangesConfirmedContentHashcode() ); }
Source:
<code>public void noConflictTable() throws Exception, UpdateException { long baseline = System.currentTimeMillis(); final DataBuilderProvider.DataBuilder builder = DataBuilderProvider .row(-1, true); for (int i = 0; i < 1000; i++) { builder .row(i, true); } final Object[][] end = builder.end(); long now = System.currentTimeMillis(); System.out.println("Loading of model took.. " + (now - baseline) + " ms"); baseline = now; final GuidedDecisionTable52 table52 = analyzerProvider.makeAnalyser() .withPersonAgeColumn("==") .withPersonApprovedActionSetField() .withData(end) .buildTable(); now = System.currentTimeMillis(); System.out.println("Made table.. " + (now - baseline) + " ms"); baseline = now; final Analyzer analyzer = analyzerProvider.makeAnalyser(table52); now = System.currentTimeMillis(); <START> System.out.println("Indexing.. " + (now - baseline) + " ms"); <END> baseline = now; analyzer.analyze(); now = System.currentTimeMillis(); System.out.println("Validated.. " + (now - baseline) + " ms"); baseline = now; table52.getData() .get(1) .get(2) .setNumericValue(3); List<Coordinate> updates = new ArrayList<>(); updates.add(new Coordinate(1, 2)); analyzerProvider.getUpdateManager(table52, analyzer) .update(table52, updates); now = System.currentTimeMillis(); System.out.println("Update.. " + (now - baseline) + " ms"); assertContains(REDUNDANT_ROWS, analyzerProvider.getAnalysisReport()); }</code><technical_language>Please sysout. Logging is friend</technical_language>

Target:
public void noConflictTable() throws Exception, UpdateException { long baseline = System.currentTimeMillis(); final DataBuilderProvider.DataBuilder builder = DataBuilderProvider .row(-1, true); for (int i = 0; i < 1000; i++) { builder .row(i, true); } final Object[][] data = builder.end(); table52 = new ExtendedGuidedDecisionTableBuilder("org.test", new ArrayList<Import>(), "mytable") .withConditionIntegerColumn("$p", "Person", "age", "==") .withActionSetField("$p", "approved", DataType.TYPE_BOOLEAN) .withData(data) .buildTable(); long now = System.currentTimeMillis(); logger.debug("Loading of model took.. " + (now - baseline) + " ms"); baseline = now; fireUpAnalyzer(); now = System.currentTimeMillis(); logger.debug("Analyzing took.. " + (now - baseline) + " ms"); baseline = now; setValue(1, 2, 3); now = System.currentTimeMillis(); logger.debug("Update.. " + (now - baseline) + " ms"); assertContains(REDUNDANT_ROWS, analyzerProvider.getAnalysisReport()); }
Source:
<code>private void makeDependences(Job job, Map<String, ArrayList<String>> dependencies) throws JobCreationException { if (dependencies != null && dependencies.size() > 0 && job.getType() == JobType.TASKSFLOW) { TaskFlowJob tfj = (TaskFlowJob) job; for (Task t : tfj.getTasks()) { ArrayList<String> names = dependencies.get(t.getName()); if (names != null) { for (String name : names) { if (tfj.getTask(name) == null) { throw new JobCreationException("Unknown dependence: " + name); } else { <START> t.addDependence(tfj.getTask(name)); <END> } } } } } }</code><technical_language>replace java if (tfj.getTask(name) == null) { throw new JobCreationException("Unknown dependence: " + name); } else { t.addDependence(tfj.getTask(name)); } java t.addDependence(Optional.ofNullable(tfj.getTask(name)).orThrow( () -> new JobCreationException("Unknown dependence: " + name));</technical_language>

Target:
private void makeDependences(Job job, Map<String, ArrayList<String>> dependencies) throws JobCreationException { if (dependencies != null && !dependencies.isEmpty() && job.getType() == JobType.TASKSFLOW) { TaskFlowJob tfj = (TaskFlowJob) job; for (Task t : tfj.getTasks()) { ArrayList<String> names = dependencies.get(t.getName()); createTaskDependencies(tfj, t, names); } } }
Source:
<code>public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RebootVmCommand<P> command = getCommand(cmdId); boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandEntity entity = CommandCoordinatorUtil.getCommandEntity(childCmdId); switch (entity.getCommandStatus()) { case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; break; default: break; } } if (anyFailed) { command.setCommandStatus(CommandStatus.FAILED); } else { VM vm = DbFacade.getInstance().getVmDao().get(command.getParameters().getVmId()); if (isVmDownForColdReboot(vm)) { command.proceedWithColdRun(); } <START> } <END> }</code><technical_language>if VM is highly-available (so automatically restarted) user managed run VM coco it? I this command lock VM is tricky.</technical_language>

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RebootVmCommand<P> command = getCommand(cmdId); boolean anyFailed = false; for (Guid childCmdId : childCmdIds) { CommandEntity entity = CommandCoordinatorUtil.getCommandEntity(childCmdId); switch (entity.getCommandStatus()) { case FAILED: case FAILED_RESTARTED: case UNKNOWN: anyFailed = true; break; default: break; } } if (anyFailed) { command.setCommandStatus(CommandStatus.FAILED); } else { VM vm = DbFacade.getInstance().getVmDao().get(command.getParameters().getVmId()); if (isVmDownForColdReboot(vm)) { command.endSuccessfully(); } } }
Source:
<code>public void run() { <START> if (!mServiceConnection.isBound()) { <END> mServiceConnection.unBindService(mContext); mCallback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED)); } }</code><technical_language>unclear here. This appears check service *isn't* bound calling unbindService(Context)</technical_language>

Target:
public void run() { if (!mServiceConnection.isBound()) { mServiceConnection.unBindService(mContext); mCallback.onError(new AuthenticationException(ADALError.BROKER_BIND_SERVICE_FAILED, "'bindService' timeout.")); } }
Source:
<code>public int hashCode() { <START> return Objects.hash(machine, content); <END> }</code><technical_language>1 for Objects.hash(...) for hashcodes, create array i is important thin places cheaper possible. If define hashcode for LogMessage, is useful this message in collections smth, based log message nature deal tons of messages. Checkout [this](<LINK_0> for generating cheaper hashcode</technical_language>

Target:
public int hashCode() { return Objects.hash(machineName, content); }
Source:
<code>private Stream<Map<Address, InternalCacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); try { <START> return StreamSupport <END> .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); } finally { streamInProgress.compareAndSet(true, false); } }</code><technical_language>topology a LocalizedCacheTopology</technical_language>

Target:
private Stream<Map<Address, CacheEntry<K, V>>> getConflicts(LocalizedCacheTopology topology) { if (stateConsumer.isStateTransferInProgress()) throw log.getConflictsStateTransferInProgress(cacheName); if (!streamInProgress.compareAndSet(false, true)) throw log.getConflictsAlreadyInProgress(); return StreamSupport .stream(new ReplicaSpliterator(topology), false) .filter(filterConsistentEntries()); }
Source:
<code>public WTextAreaUI() { panel.add(messages); WFieldLayout fieldLayout = new WFieldLayout(LAYOUT_FLAT); fieldLayout.setTitle("this is a bunch of fields"); <START> WTextArea wTextField = new WTextArea(); <END> fieldLayout.addField("this is a textarea", wTextField); wTextField.setMandatory(true); panel.add(fieldLayout); add(createWButton()); add(panel); }</code><technical_language>Copy-paste changed member name. Is wise a WTextArea called wTextField</technical_language>

Target:
public WTextAreaUI() { panel.add(messages); WFieldLayout fieldLayout = new WFieldLayout(LAYOUT_FLAT); fieldLayout.setTitle("this is a bunch of fields"); fieldLayout.addField("this is a textarea", wTextArea); wTextArea.setMandatory(true); panel.add(fieldLayout); add(createWButton()); add(panel); }
Source:
<code>public String toString() { <START> StringBuilder result = new StringBuilder("[Test: \"" + m_name + \").append( verbose:").append(m_verbose); <END> result.append("[parameters:"); for (Map.Entry<String, String> entry : m_parameters.entrySet()) { result.append(entry.getKey()).append("=>").append(entry.getValue()); } result.append("]"); result.append("[metagroups:"); for (Map.Entry<String, List<String>> entry : m_metaGroups.entrySet()) { result.append(entry.getKey()).append("="); for (String n : entry.getValue()) { result.append(n).append(","); } } result.append("] "); result.append("[included: "); for (String g : m_includedGroups) { result.append(g).append(" "); } result.append("]"); result.append("[excluded: "); for (String g : m_excludedGroups) { result.append(g).append(""); } result.append("] "); result.append(" classes:"); for (XmlClass cl : m_xmlClasses) { result.append(cl).append(" "); } result.append(" packages:"); for (XmlPackage p : m_xmlPackages) { result.append(p).append(" "); } result.append("] "); return result.toString(); }</code><technical_language>missed new StringBuilder().append("[Test: \"").append(m_name).append("\"")</technical_language>

Target:
public String toString() { StringBuilder result = new StringBuilder("[Test: \"") .append(m_name) .append("\"") .append(" verbose:") .append(m_verbose); result.append("[parameters:"); for (Map.Entry<String, String> entry : m_parameters.entrySet()) { result.append(entry.getKey()).append("=>").append(entry.getValue()); } result.append("]"); result.append("[metagroups:"); for (Map.Entry<String, List<String>> entry : m_metaGroups.entrySet()) { result.append(entry.getKey()).append("="); for (String n : entry.getValue()) { result.append(n).append(","); } } result.append("] "); result.append("[included: "); for (String g : m_includedGroups) { result.append(g).append(" "); } result.append("]"); result.append("[excluded: "); for (String g : m_excludedGroups) { result.append(g).append(" "); } result.append("] "); result.append(" classes:"); for (XmlClass cl : m_xmlClasses) { result.append(cl).append(" "); } result.append(" packages:"); for (XmlPackage p : m_xmlPackages) { result.append(p).append(" "); } result.append("] "); return result.toString(); }
Source:
<code>public void testRename() throws Exception { typeContext = new LabelClientTypeContext(store, LabelType.METRIC, metrics, eventBus, MAX_CACHE_SIZE); final LabelId labelId = typeContext.createId("oldName").get(); ListenableFuture<Void> response = typeContext.rename("oldName", "newName"); <START> Futures.addCallback(response, new FutureCallback<Void>() { <END> @Override public void onSuccess(final Void result) { Futures.addCallback(typeContext.getName(labelId), new FutureCallback<Optional<String>>() { @Override public void onSuccess(final Optional<String> result) { if (!result.isPresent()) { fail(); } assertEquals("newName", result.get()); } @Override public void onFailure(final Throwable throwable) { fail(); } }); } @Override public void onFailure(final Throwable throwable) { fail(); } }); }</code><technical_language>blocking calls for futures. In case is verbose block work result directly. Also, contract for Store#renameLabel is if checks current name exists new name exist a call it, if #renameLabel call returns successfully future exception, label renamed. This means is strictly necessary test label is renamed here, enough call #rename block exception</technical_language>

Target:
public void testRename() throws Exception { typeContext = new LabelClientTypeContext(store, LabelType.METRIC, metrics, eventBus, MAX_CACHE_SIZE); final LabelId labelId = typeContext.createId("oldName").get(); typeContext.rename("oldName", "newName").get(); Optional<String> optional = typeContext.getName(labelId).get(); assertEquals("newName", optional.get()); }