auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void updateBookmarkButtons() { if (playlistBookmarkButton == null || activity == null) { return; } final int iconAttr = playlistEntity == null ? R.drawable.ic_playlist_add_white_24dp : R.drawable.ic_playlist_add_check_white_24dp; final int titleRes = playlistEntity == null ? R.string.bookmark_playlist : R.string.unbookmark_playlist; <START> playlistBookmarkButton.setIcon(iconAttr); playlistBookmarkButton.setTitle(titleRes); <END> }</code><technical_language>While it, move variables here: suggestion playlistBookmarkButton.setIcon(playlistEntity == null ? R.drawable.ic_playlist_add_white_24dp : R.drawable.ic_playlist_add_check_white_24dp); playlistBookmarkButton.setTitle(playlistEntity == null ? R.string.bookmark_playlist : R.string.unbookmark_playlist);</technical_language>

Target:
private void updateBookmarkButtons() { if (playlistBookmarkButton == null || activity == null) { return; } playlistBookmarkButton.setIcon(playlistEntity == null ? R.drawable.ic_playlist_add_white_24dp : R.drawable.ic_playlist_add_check_white_24dp); playlistBookmarkButton.setTitle(playlistEntity == null ? R.string.bookmark_playlist : R.string.unbookmark_playlist); }
Source:
<code>public void validate(Object obj, Errors errors) { RelationshipType relationshipType = (RelationshipType) obj; if (relationshipType == null) { <START> errors.rejectValue("relationshipType", "error.general"); <END> } else { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aIsToB", "RelationshipType.aIsToB.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bIsToA", "RelationshipType.bIsToA.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "Description", "error.description"); } }</code><technical_language>Typically, in this case throw IllegalArgumentException obj null</technical_language>

Target:
public void validate(Object obj, Errors errors) { RelationshipType relationshipType = (RelationshipType) obj; if (relationshipType == null) { errors.rejectValue("relationshipType", "error.general"); } else { ValidationUtils.rejectIfEmptyOrWhitespace(errors, "aIsToB", "RelationshipType.aIsToB.required"); ValidationUtils.rejectIfEmptyOrWhitespace(errors, "bIsToA", "RelationshipType.bIsToA.required"); } }
Source:
<code>public void testSerializingUsesISO8601() throws ParseException { Date baseDate = new Date(); <START> Gson gson = new Gson(); <END> String dateString = gson.toJson(baseDate); SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.ISO_8601_DATE_TIME_FORMAT); Date date = formatter.parse(dateString); assertEquals(date, baseDate); }</code><technical_language>newGson(), exercise ServerJsonDateAdapterFactory</technical_language>

Target:
public void testSerializingUsesISO8601() throws ParseException { Date baseDate = new Date(); Gson gson = newGson(); String dateString = gson.toJson(baseDate).replace("\"", ""); SimpleDateFormat formatter = new SimpleDateFormat(DateUtil.ISO_8601_DATE_TIME_FORMAT); Date date = formatter.parse(dateString); baseDate = DateUtils.truncate(baseDate, Calendar.SECOND); assertEquals(baseDate.getTime(), date.getTime()); }
Source:
<code>public void setup() { mockSession = mock(Session.class); mockSessionFactory = mock(SessionFactory.class); <START> helper = spy(new HibernateHelper(mockSessionFactory, new AccountPersistentExceptionConverter())); <END> doAnswer(invocation -> { Function<Session, ?> function = invocation.getArgumentAt(0, Function.class); return function.apply(mockSession); }).when(helper).execute(any()); }</code><technical_language>create a test converter (or a mock converter) instead of a hard dependency AccountPersistentExceptionConverter</technical_language>

Target:
public void setup() { mockSession = mock(Session.class); mockSessionFactory = mock(SessionFactory.class); mockExceptionConverter = mock(PersistenceExceptionConverter.class); helper = spy(new HibernateHelper(mockSessionFactory, mockExceptionConverter)); doAnswer(invocation -> { Function<Session, ?> function = invocation.getArgumentAt(0, Function.class); return function.apply(mockSession); }).when(helper).execute(any()); }
Source:
<code>public CommitStatus setState(final String state) { <START> if (state.equals(STATE_ERROR) || state.equals(STATE_FAILURE) || state.equals(STATE_PENDING) <END> || state.equals(STATE_SUCCESS)) { this.state = state; return this; } throw new IllegalArgumentException(MessageFormat.format("Invalid state {0}", state)); }</code><technical_language>This throw a NullPointerException state is null. Reverse equals checks prevent this. if (STATE_ERROR.equals(state) || STATE_FAILURE.equals(state) || STATE_PENDING.equals(state) || STATE_SUCCESS(state))</technical_language>

Target:
public CommitStatus setState(final String state) { if (STATE_ERROR.equals(state) || STATE_FAILURE.equals(state) || STATE_PENDING.equals(state) || STATE_SUCCESS.equals(state)) { this.state = state; return this; } throw new IllegalArgumentException(MessageFormat.format("Invalid state {0}", state)); }
Source:
<code>public void testAnErrorMessageIsDisplayedWhenAResourceIsUpdatedWithANameAlreadyRegistered() throws InterruptedException { ResourcesPage resourcesPage = new ResourcesPage(); ResourceInfoPage resourceInfoPage = resourcesPage.openResourceInfoPage(resourceUpdateName); resourceInfoPage.setResourceName(resourceName) .setResourceDisplayName(resourceDisplayName) <START> .clickSaveResourceWithErrorBtn(); <END> Assert.assertTrue(RoomBaseAbstractPage.isErrorMessageCorrect(RESOURCE_NAME_DUPLICATED)); resourcesPage = resourceInfoPage.clickCancelResourceBtn(); }</code><technical_language>be: resourceInfoPage .setResourceName(resourceName) .setResourceDisplayName(resourceDisplayName) .clickSaveResourceWithErrorBtn();</technical_language>

Target:
public void testAnErrorMessageIsDisplayedWhenAResourceIsUpdatedWithANameAlreadyRegistered() throws InterruptedException { ResourcesPage resourcesPage = new ResourcesPage(); ResourceInfoPage resourceInfoPage = resourcesPage.openResourceInfoPage(resourceUpdateName); resourceInfoPage.setResourceName(resourceName) .setResourceDisplayName(resourceDisplayName) .clickSaveResourceWithErrorBtn(); Assert.assertTrue(RoomBaseAbstractPage.isErrorMessageCorrect(RESOURCE_NAME_DUPLICATED)); resourceInfoPage.clickCancelResourceBtn(); }
Source:
<code>public Member getMember(String activityId, String memberId) throws ActivityServiceException { if (StringUtil.isEmpty(activityId)||StringUtil.isEmpty(memberId)){ throw new ActivityServiceException(null, "Null activityId / memberId"); } String requestUri = ActivityServiceUrlBuilder.populateURL(ActivityAction.ACL.getActivityAction()); try { <START> Map<String, String> params = new LinkedHashMap<String, String>(); <END> params.put("activityUuid", activityId); if(EntityUtil.isEmail(memberId)){ params.put("email", memberId); }else{ params.put("memberid", memberId); } return (Member) getEntity(requestUri, params, new MemberFeedHandler(this)); } catch (Exception e) { throw new ActivityServiceException(e); } }</code><technical_language>specific reason for replacing HashMap LinkedHashMap</technical_language>

Target:
public Member getMember(String activityId, String memberId) throws ActivityServiceException { if (StringUtil.isEmpty(activityId)||StringUtil.isEmpty(memberId)){ throw new ActivityServiceException(null, "Null activityId / memberId"); } String requestUri = ActivityServiceUrlBuilder.populateURL(ActivityAction.ACL.getActivityAction()); try { Map<String, String> params = new HashMap<String, String>(); params.put("activityUuid", activityId); if(EntityUtil.isEmail(memberId)){ params.put("email", memberId); }else{ params.put("memberid", memberId); } return (Member) getEntity(requestUri, params, new MemberFeedHandler(this)); } catch (Exception e) { throw new ActivityServiceException(e); } }
Source:
<code>public boolean filter(K key, T persistent) { boolean filtered = false; if (operator.equals(Operator.MUST_PASS_ONE)) { for (Filter<K, T> filter: filters) { if (!filter.filter(key, persistent)) { return !filtered; } } } else if (operator.equals(Operator.MUST_PASS_ALL)) { for (Filter<K, T> filter: filters) { if (filter.filter(key, persistent)) { return !filtered; } } } else { throw new IllegalStateException(operator + " not yet implemented!"); } return filtered; <START> } <END></code><technical_language>I this good, annoying here, more readable if a switch statement instead? Enum values do trick ;)</technical_language>

Target:
public boolean filter(K key, T persistent) { boolean filtered = false; switch (operator.toString()) { case "MUST_PASS_ALL": for (Filter<K, T> filter: filters) { if (!filter.filter(key, persistent)) { return !filtered; } } break; case "MUST_PASS_ONE": for (Filter<K, T> filter: filters) { if (filter.filter(key, persistent)) { return !filtered; } } break; default: throw new IllegalStateException(operator + " not yet implemented!"); } return filtered; }
Source:
<code>public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeQuotaParam = (String) serverContext.getServerConfig().get("--log-size-quota-percentage"); <START> logSizeLimitPercentage = Double.parseDouble(logSizeQuotaParam); <END> initStreamLogDirectory(); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }</code><technical_language>rename logSizeQuotaParam another name? name of 'logSizeQuota' for resource</technical_language>

Target:
public StreamLogFiles(ServerContext serverContext, boolean noVerify) { logDir = Paths.get(serverContext.getServerConfig().get("--log-path").toString(), "log"); writeChannels = new ConcurrentHashMap<>(); channelsToSync = new HashSet<>(); this.verify = !noVerify; this.dataStore = StreamLogDataStore.builder().dataStore(serverContext.getDataStore()).build(); String logSizeLimitPercentageParam = (String)serverContext.getServerConfig().get("--log-size-quota-percentage"); final double logSizeLimitPercentage = Double.parseDouble(logSizeLimitPercentageParam); if (logSizeLimitPercentage < 0.0 || 100.0 < logSizeLimitPercentage) { String msg = String.format("Invalid quota: quota(%d)% must be between 0-100%", logSizeLimitPercentage); throw new LogUnitException(msg); } long fileSystemCapacity = initStreamLogDirectory(); logSizeLimit = (long)(fileSystemCapacity * logSizeLimitPercentage / 100.0); long initialLogSize = estimateSize(logDir); log.info("StreamLogFiles: size is bytes, limit {}", logDir, initialLogSize, logSizeLimit); logSizeQuota = new ResourceQuota("LogSizeQuota", logSizeLimit); logSizeQuota.consume(initialLogSize); verifyLogs(); logMetadata = new LogMetadata(); initializeLogMetadata(); if (Math.max(logMetadata.getGlobalTail(), 0L) < getTrimMark()) { syncTailSegment(getTrimMark() - 1); } }
Source:
<code>public void verifyDecoratorOrder() { DecoratedMacPoolFactory factory = new DecoratedMacPoolFactory(lockedObjectFactorySpy); MacPool decoratedPool = factory.createDecoratedPool(poolId, macPool, Arrays.asList(macPoolDecoratorA, macPoolDecoratorB)); assertThat(decoratedPool, is(macPoolDecoratorB)); <START> assertThat(macPoolDecoratorB.getMacPool(), is(macPoolDecoratorA)); <END> assertThat(macPoolDecoratorA.getMacPool(), is(macPool)); }</code><technical_language>avoid this new getMacPool method AgrumentCaptor verifying expected macPool object is passed</technical_language>

Target:
public void verifyDecoratorOrder() { DecoratedMacPoolFactory factory = createDecoratedMacPoolFactoryWithDisabledLocking(); MacPool decoratedPool = factory.createDecoratedPool(poolId, macPool, Arrays.asList(macPoolDecoratorA, macPoolDecoratorB)); assertThat(decoratedPool, is(macPoolDecoratorB)); ArgumentCaptor<MacPool> firstDecoratorMacPoolArgumentCaptor = ArgumentCaptor.forClass(MacPool.class); verify(macPoolDecoratorB).setMacPool(firstDecoratorMacPoolArgumentCaptor.capture()); verify(macPoolDecoratorB).setMacPoolId(any()); assertThat(firstDecoratorMacPoolArgumentCaptor.getValue(), is(macPoolDecoratorA)); ArgumentCaptor<MacPool> secondDecoratorMacPoolArgumentCaptor = ArgumentCaptor.forClass(MacPool.class); verify(macPoolDecoratorA).setMacPool(secondDecoratorMacPoolArgumentCaptor.capture()); verify(macPoolDecoratorA).setMacPoolId(any()); assertThat(secondDecoratorMacPoolArgumentCaptor.getValue(), is(macPool)); Mockito.verifyNoMoreInteractions(macPoolDecoratorA, macPoolDecoratorB, macPool); }
Source:
<code>private void tagCommentLine(String text, int line, int column) { final Matcher offMatcher = offCommentFormat.matcher(text); if (offMatcher.find()) { <START> addTag(offMatcher.group(0), line, column, ReportingOptions.NONE); <END> } else { final Matcher onMatcher = onCommentFormat.matcher(text); if (onMatcher.find()) { addTag(onMatcher.group(0), line, column, ReportingOptions.REPORT); } } }</code><technical_language>this is another insane code blow mind reading. original true/false jest a flag in Tag class for ON/OFF type of tags. is a reporting option. is a type of Tag. types of Tag - OFF. TagType {ON, OFF} code offMatcher match results in creation of tag type: if (offMatcher.find()) { addTag(offMatcher.group(0), line, column, Tag.TagType.OFF); Tag changes to: - private final boolean reportingOn; + private final TagType tagType;</technical_language>

Target:
private void tagCommentLine(String text, int line, int column) { final Matcher offMatcher = offCommentFormat.matcher(text); if (offMatcher.find()) { addTag(offMatcher.group(0), line, column, TagType.OFF); } else { final Matcher onMatcher = onCommentFormat.matcher(text); if (onMatcher.find()) { addTag(onMatcher.group(0), line, column, TagType.ON); } } }
Source:
<code>public void deleteEntity(Entity entity) { String fieldToRemove = null; String valueToRemove = null; for(String field : docDef.fields()) { if(entity.get(field) != null) { fieldToRemove = field; valueToRemove = (String)entity.get(field); break; } } SearchResponse existsResponse = client.prepareSearch(INDEX_NAME) .setTypes(docDef.getEntityField()) .setQuery(QueryBuilders.existsQuery(fieldToRemove)) .get(); String script = null; <START> if(existsResponse != null && existsResponse.getHits() != null && existsResponse.getHits().totalHits() > 0) { <END> script = "ctx._source." + fieldToRemove+".remove('"+ valueToRemove + "')"; } UpdateRequest updateRequest = new UpdateRequest(INDEX_NAME, docDef.getEntityField(), entity.getId()) .script(new Script(script)); try { client.update(updateRequest).get(); }catch(Exception e) { throw new TextIndexException("Unable to delete entity.", e); } LOGGER.debug("deleting content related to entity: " + entity.getId()); }</code><technical_language>Similar update operation, this a race condition if multiple deletes happen simultaneously. do atomic delete here, scripted in a is error thrown if field delete exist in index</technical_language>

Target:
public void deleteEntity(Entity entity) { String fieldToRemove = null; String valueToRemove = null; for(String field : docDef.fields()) { if(entity.get(field) != null) { fieldToRemove = field; if(entity.getLanguage()!= null && !entity.getLanguage().isEmpty()) { fieldToRemove = normalizeFieldName(fieldToRemove, entity.getLanguage()); } valueToRemove = (String)entity.get(field); break; } } if(fieldToRemove != null && valueToRemove != null) { LOGGER.debug("deleting content related to entity: " + entity.getId()); String deleteScript = DELETE_SCRIPT.replaceAll("<fieldToRemove>", fieldToRemove); Map<String,Object> params = new HashMap<>(); params.put("valueToRemove", valueToRemove); UpdateRequest updateRequest = new UpdateRequest(indexName, docDef.getEntityField(), entity.getId()) .script(new Script(Script.DEFAULT_SCRIPT_TYPE, Script.DEFAULT_SCRIPT_LANG,deleteScript,params)); try { client.update(updateRequest).get(); }catch(Exception e) { if( ExceptionUtils.getRootCause(e) instanceof DocumentMissingException) { LOGGER.debug("Trying to delete values from a missing document. Ignoring deletion of entity: ", entity); } else { throw new TextIndexException("Unable to delete entity.", e); } } } }
Source:
<code>public void handleError(HttpCommand command, HttpResponse response) { String message = errorParser.apply(response); Exception exception = new HttpResponseException(command, response, message); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: <START> exception = new ResourceNotFoundException(message, exception); <END> break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }</code><technical_language>This is a common pattern in jclouds APIs: if attempt delete a resource exist, do fail operation in desired state. this need changed</technical_language>

Target:
public void handleError(HttpCommand command, HttpResponse response) { String message = errorParser.apply(response); Exception exception = new HttpResponseException(command, response, message); try { message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } } finally { closeQuietly(response.getPayload()); command.setException(exception); } }
Source:
<code>private void abandonrestoreButtonEnablement() { Map<String, ActionInfo> actions = fChangeInfo.getActions(); <START> ActionInfo key = actions.get("abandon"); <END> if (key != null && key.isEnabled()) { if (fChangeInfo.getStatus().compareTo("ABANDONED") == 0) { fAbandon.setEnabled(false); fRestore.setEnabled(true); } else { fAbandon.setEnabled(true); fRestore.setEnabled(false); } } else { fAbandon.setEnabled(false); fRestore.setEnabled(false); } }</code><technical_language>actions null anonymous, need test null pointer</technical_language>

Target:
private void abandonrestoreButtonEnablement() { Map<String, ActionInfo> actions = fChangeInfo.getActions(); if (actions != null) { ActionInfo abandon = actions.get(ABANDON); ActionInfo restore = actions.get(RESTORE); if (abandon != null && abandon.isEnabled()) { fAbandon.setEnabled(true); fRestore.setEnabled(false); } else if (restore != null && restore.isEnabled()) { fAbandon.setEnabled(false); fRestore.setEnabled(true); } else { fAbandon.setEnabled(false); fRestore.setEnabled(false); } } }
Source:
<code>protected void innerDraw(GC gc) { <START> Object lineWidth = fLineWidth; <END> int oldLineWidth = gc.getLineWidth(); Rectangle bounds = getBounds(); gc.setLineWidth((lineWidth instanceof Integer) ? (int) fLineWidth : 1); if (getForegroundColor() != null) { gc.drawRoundRectangle(bounds.x-1, bounds.y-1, bounds.width+2, bounds.height+2, fArc, fArc); } gc.fillRoundRectangle(bounds.x, bounds.y, bounds.width, bounds.height, fArc, fArc); if (fLabel != null && !fLabel.isEmpty() && bounds.width > bounds.height) { gc.setForeground(Utils.getDistinctColor(getBackgroundColor().rgb)); Utils.drawText(gc, fLabel, bounds.x, bounds.y, bounds.width, bounds.height, true, true); } gc.setLineWidth(oldLineWidth); }</code><technical_language>else int</technical_language>

Target:
protected void innerDraw(GC gc) { Rectangle bounds = getBounds(); gc.fillRoundRectangle(bounds.x, bounds.y, bounds.width, bounds.height, fArc, fArc); if (fLabel != null && !fLabel.isEmpty() && bounds.width > bounds.height) { gc.setForeground(Utils.getDistinctColor(getBackgroundColor().rgb)); Utils.drawText(gc, fLabel, bounds.x, bounds.y, bounds.width, bounds.height, true, true); } }
Source:
<code><START> public String genomicToEnsemblRestRegion(GenomicLocation genomicLocation) <END> { if (genomicLocation == null) { return null; } String chr = this.chromosomeNormalizer(genomicLocation.getChromosome().trim()); Integer start = genomicLocation.getStart(); Integer end = genomicLocation.getEnd(); String ref = genomicLocation.getReferenceAllele().trim(); String var = genomicLocation.getVariantAllele().trim(); String prefix = ""; if(!ref.equals(var)) { prefix = longestCommonPrefix(ref, var); } if (prefix.length() > 0) { ref = ref.substring(prefix.length()); var = var.substring(prefix.length()); int nStart = start; int nEnd = end; nStart += prefix.length(); if (ref.length() == 0) { nStart -= 1; } start = nStart; } String region; if (start < 1) { region = null; } else if(ref.equals("-") || ref.length() == 0) { try { region = chr + ":" + String.valueOf(start + 1) + "-" + start + ":1/" + var; } catch (NumberFormatException e) { return null; } } else if(var.equals("-") || var.length() == 0) { region = chr + ":" + start + "-" + end + ":1/-"; } else if (ref.length() > 1 || var.length() > 1) { region = chr + ":" + start + "-" + end + ":1/" + var; } else { region = chr + ":" + start + "-" + start + ":1/" + var; } return region; }</code><technical_language>nice some tests for trivial methods this one</technical_language>

Target:
public String genomicToEnsemblRestRegion(GenomicLocation genomicLocation) { if (genomicLocation == null) { return null; } GenomicLocation normalizedGenomicLocation = normalizeGenomicLocation(genomicLocation); String chr = normalizedGenomicLocation.getChromosome(); Integer start = normalizedGenomicLocation.getStart(); Integer end = normalizedGenomicLocation.getEnd(); String ref = normalizedGenomicLocation.getReferenceAllele().trim(); String var = normalizedGenomicLocation.getVariantAllele().trim(); String region; if (start < 1) { region = null; } else if(ref.equals("-") || ref.length() == 0) { try { region = chr + ":" + String.valueOf(start + 1) + "-" + start + ":1/" + var; } catch (NumberFormatException e) { return null; } } else if(var.equals("-") || var.length() == 0) { region = chr + ":" + start + "-" + end + ":1/-"; } else if (ref.length() > 1 || var.length() > 1) { region = chr + ":" + start + "-" + end + ":1/" + var; } else { region = chr + ":" + start + "-" + start + ":1/" + var; } return region; }
Source:
<code>public CookieInterceptor(String username, String password, String baseURL) { try { this.sessionURL = new URL(String.format("%s/_session", baseURL)); username = URLEncoder.encode(username, "UTF-8"); password = URLEncoder.encode(password, "UTF-8"); this.sessionRequestBody = String.format("name=%s&password=%s", username, password) .getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); <START> } catch (MalformedURLException e) { <END> throw new RuntimeException(e); } }</code><technical_language>move existing logging for this remove other MalformedURLException catch</technical_language>

Target:
public CookieInterceptor(String username, String password, String baseURL) { try { this.sessionURL = new URL(String.format("%s/_session", baseURL)); username = URLEncoder.encode(username, "UTF-8"); password = URLEncoder.encode(password, "UTF-8"); this.sessionRequestBody = String.format("name=%s&password=%s", username, password) .getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } catch (MalformedURLException e) { logger.log(Level.SEVERE, "Failed to create URL for _session endpoint", e); throw new RuntimeException(e); } }
Source:
<code>public void applyState(XSiteState[] chunk) throws Exception { if (trace) { log.tracef("Received state: %s", extractKeys(chunk)); } else if (debug) { <START> log.debugf("Received state: %s keys", chunk.length); <END> } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }</code><technical_language>trace log allow easily entries are, informative debug log :) Long lines in log a PITA deal with, I suggest logging number of entries debug level a separate line for processed/skipped entry</technical_language>

Target:
public void applyState(XSiteState[] chunk) throws Exception { if (debug) { log.debugf("Received state: %s keys", chunk.length); } if (transactionManager != null) { applyStateInTransaction(chunk); } else { applyStateInNonTransaction(chunk); } }
Source:
<code>private void peekDrawerInvalidate() { if (mPeekScroller.computeScrollOffset()) { final int oldX = mOffsetPixels; final int x = mPeekScroller.getCurrX(); if (x != oldX) setOffsetPixels(x); if (!mPeekScroller.isFinished()) { <START> ViewCompat.postOnAnimation(this, mPeekRunnable); <END> return; } else if (mPeekDelay > 0) { mPeekStartRunnable = new Runnable() { @Override public void run() { startPeek(); } }; postDelayed(mPeekStartRunnable, mPeekDelay); } } completePeek(); }</code><technical_language>I this is in r7 support library (the Maven)</technical_language>

Target:
private void peekDrawerInvalidate() { if (mPeekScroller.computeScrollOffset()) { final int oldX = mOffsetPixels; final int x = mPeekScroller.getCurrX(); if (x != oldX) setOffsetPixels(x); if (!mPeekScroller.isFinished()) { postOnAnimation(mPeekRunnable); return; } else if (mPeekDelay > 0) { mPeekStartRunnable = new Runnable() { @Override public void run() { startPeek(); } }; postDelayed(mPeekStartRunnable, mPeekDelay); } } completePeek(); }
Source:
<code>public boolean isAddressValid(String address) { if (address.endsWith("L")) { String address_noL = address.substring(0, address.length() - 1); <START> if (address_noL.length() != 20) { <END> return false; } for (char addressCharacter : address_noL.toCharArray()) { if (!Character.isDigit(addressCharacter)) { return false; } } return true; }else{ return false; } }</code><technical_language>Java camel-case convention for naming, please</technical_language>

Target:
public boolean isAddressValid(String address) { if (address.endsWith("L")) { String addressWithoutL = address.substring(0, address.length() - 1); if (addressWithoutL.length() != 20) { return false; } for (char addressCharacter : addressWithoutL.toCharArray()) { if (!Character.isDigit(addressCharacter)) { return false; } } return true; }else{ return false; } }
Source:
<code>public synchronized Map<String, Optional<MemoryInfo>> getWorkerMemoryInfo() { Map<String, Optional<MemoryInfo>> memoryInfo = new HashMap<>(); AllNodes allNodes = nodeManager.getAllNodes(); Set<Node> workers = union(union(allNodes.getActiveNodes(), allNodes.getInactiveNodes()), allNodes.getShuttingDownNodes()); for (Entry<String, RemoteNodeMemory> entry : nodes.entrySet()) { Optional<Node> worker = workers.stream() .filter(node -> node.getNodeIdentifier().equals(entry.getKey())) .findFirst(); String workerId = entry.getKey(); if (worker.isPresent()) { <START> workerId += " [" + worker.get().getHostAndPort().getHostText() + "]"; <END> } memoryInfo.put(workerId, entry.getValue().getInfo()); } return memoryInfo; }</code><technical_language>add Node RemoteNodeMemory</technical_language>

Target:
public synchronized Map<String, Optional<MemoryInfo>> getWorkerMemoryInfo() { Map<String, Optional<MemoryInfo>> memoryInfo = new HashMap<>(); for (Entry<String, RemoteNodeMemory> entry : nodes.entrySet()) { String workerId = entry.getKey() + " [" + entry.getValue().getNode().getHostAndPort().getHostText() + "]"; memoryInfo.put(workerId, entry.getValue().getInfo()); } return memoryInfo; }
Source:
<code><START> protected void writeOtherDevices(VmBase vmBase, XmlTextWriter write) { <END> List<VmDevice> devices = vmBase.getUnmanagedDeviceList(); Collection<VmDevice> managedDevices = vmBase.getManagedVmDeviceMap().values(); for (VmDevice device : managedDevices) { if (VmDeviceType.SOUND.getName().equals(device.getType()) || VmDeviceType.USB.getName().equals(device.getDevice()) || VmDeviceType.SPICEVMC.getName().equals(device.getDevice())) { devices.add(device); } } for (VmDevice vmDevice : devices) { _writer.WriteStartElement("Item"); _writer.WriteStartElement("rasd:ResourceType"); _writer.WriteRaw(OvfHardware.OTHER); _writer.WriteEndElement(); _writer.WriteStartElement("rasd:InstanceId"); _writer.WriteRaw((String.valueOf(vmDevice.getId().getDeviceId()))); _writer.WriteEndElement(); writeVmDeviceInfo(vmDevice); _writer.WriteEndElement(); } }</code><technical_language>OvfReader ? If export a VM USB devices import another system</technical_language>

Target:
protected void writeOtherDevices(VmBase vmBase, XmlTextWriter write) { List<VmDevice> devices = vmBase.getUnmanagedDeviceList(); Collection<VmDevice> managedDevices = vmBase.getManagedVmDeviceMap().values(); for (VmDevice device : managedDevices) { if (VmDeviceCommonUtils.isSpecialDevice(device.getDevice(), device.getType())) { devices.add(device); } } for (VmDevice vmDevice : devices) { _writer.WriteStartElement("Item"); _writer.WriteStartElement("rasd:ResourceType"); _writer.WriteRaw(OvfHardware.OTHER); _writer.WriteEndElement(); _writer.WriteStartElement("rasd:InstanceId"); _writer.WriteRaw((String.valueOf(vmDevice.getId().getDeviceId()))); _writer.WriteEndElement(); writeVmDeviceInfo(vmDevice); _writer.WriteEndElement(); } }
Source:
<code>public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", _uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " + "listener: {}", _uid, _path, _listener); } else { <START> CallbackProcessor callbackProcessorRef = _batchCallbackProcessor.get(); <END> if (callbackProcessorRef != null) { callbackProcessorRef.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }</code><technical_language>reverse way? I guess. CallbackProcessor **callbackProcessor** = **_batchCallbackProcessorRef**.get();</technical_language>

Target:
public void enqueueTask(NotificationContext changeContext) throws Exception { if (_batchModeEnabled && changeContext.getType() == NotificationContext.Type.CALLBACK) { logger.debug("Callbackhandler {}, Enqueuing callback", _uid ); if (!isReady()) { logger.info("CallbackHandler is not ready, ignore change callback from path: {}, for " + "listener: {}", _uid, _path, _listener); } else { CallbackProcessor callbackProcessor = _batchCallbackProcessorRef.get(); if (callbackProcessor != null) { callbackProcessor.queueEvent(changeContext.getType(), changeContext); } else { throw new HelixException( "Failed to process callback in batch mode. Batch Callback Processor does not exist."); } } } else { invoke(changeContext); } if (_monitor != null) { _monitor.increaseCallbackUnbatchedCounters(); } }
Source:
<code>public void shouldBeHealthyForOneLeaderElectionPerMinute() { <START> markLeaderElectionsAtSpecifiedInterval(3, 60); <END> assertThat(leaderElectionHealthCheck.leaderElectionRateHealthStatus()) .isEqualTo(LeaderElectionHealthStatus.HEALTHY); }</code><technical_language>nit: pass Duration markLeaderElections(...) for readability</technical_language>

Target:
public void shouldBeHealthyForOneLeaderElectionPerMinute() { markLeaderElectionsAtSpecifiedInterval(3, Duration.ofSeconds(60)); assertThat(leaderElectionHealthCheck.leaderElectionRateHealthStatus()) .isEqualTo(LeaderElectionHealthStatus.HEALTHY); }
Source:
<code>public void setUp() throws Exception { when(location.toString()).thenReturn("dw-thing.jar"); when(location.getVersion()).thenReturn(Optional.of("1.0.0")); bootstrap.addCommand(command); <START> this.cli = new Cli(location, bootstrap, stdOut, stdErr); <END> }</code><technical_language>need for this, a local variable name</technical_language>

Target:
public void setUp() throws Exception { final JarLocation location = mock(JarLocation.class); final Bootstrap<Configuration> bootstrap = new Bootstrap<>(app); when(location.toString()).thenReturn("dw-thing.jar"); when(location.getVersion()).thenReturn(Optional.of("1.0.0")); bootstrap.addCommand(command); cli = new Cli(location, bootstrap, stdOut, stdErr); }
Source:
<code>private static String getUri(String rawUrl, String apiUri) { if (StringUtils.isNotBlank(rawUrl)) { return getRawUrlUri(rawUrl); } else if (isBlank(apiUri)) { <START> return "<LINK_0>"; <END> }else { return apiUri; } }</code><technical_language>suggestion return GitHubServerConfig.GITHUB_URL;</technical_language>

Target:
private static String getUri(String rawUrl, String apiUri) { if (StringUtils.isNotBlank(rawUrl)) { return getRawUrlUri(rawUrl); } else if (isBlank(apiUri)) { return GitHubServerConfig.GITHUB_URL; }else { return apiUri; } }
Source:
<code>public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.debug ("Error while constructing new ObjectMapper",e); <START> } <END> return writer.toString(); }</code><technical_language>this a log.error statement. needs space ","</technical_language>

Target:
public String toString() { StringWriter writer = new StringWriter(); try { new ObjectMapper().writeValue(writer, graph); } catch (Exception e) { log.error ("Error while constructing new ObjectMapper", e); } return writer.toString(); }
Source:
<code>private boolean verifyLayout(View target, Set<Integer> rules) { ViewGroup parent = (ViewGroup) target.getParent(); SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); <START> for (int i = 0; i < count; i++) { <END> View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>(); int size = idToChild.size(); for (int i = 0; i < size; i++) { final View child = idToChild.valueAt(i); final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams(); int[] layoutRules = childLayoutParams.getRules(); ArrayList<View> dependencies = new ArrayList<View>(); for (int rule : rules) { int dependencyId = layoutRules[rule]; if (dependencyId > 0 && dependencyId != child.getId()) { dependencies.add(idToChild.get(dependencyId)); } } dependencyGraph.put(child, dependencies); } return hasCycle(dependencyGraph); }</code><technical_language>circular dependencies views siblings? is, a view refer another view of parent aligning</technical_language>

Target:
private boolean verifyLayout(View target, Set<Integer> rules) { ViewGroup parent = (ViewGroup) target.getParent(); SparseArray<View> idToChild = new SparseArray<View>(); int count = parent.getChildCount(); for (int i = 0; i < count; i++) { View child = parent.getChildAt(i); int childId = child.getId(); if (childId > 0) { idToChild.put(childId, child); } } ArrayMap<View, ArrayList<View>> dependencyGraph = new ArrayMap<View, ArrayList<View>>(); int size = idToChild.size(); for (int i = 0; i < size; i++) { final View child = idToChild.valueAt(i); final RelativeLayout.LayoutParams childLayoutParams = (RelativeLayout.LayoutParams) child.getLayoutParams(); int[] layoutRules = childLayoutParams.getRules(); ArrayList<View> dependencies = new ArrayList<View>(); for (int rule : rules) { int dependencyId = layoutRules[rule]; if (dependencyId > 0 && dependencyId != child.getId()) { dependencies.add(idToChild.get(dependencyId)); } } dependencyGraph.put(child, dependencies); } return mCycleDetector.hasCycle(dependencyGraph); }
Source:
<code>public Task update(UpdateTaskPayload updateTaskPayload) { <START> org.activiti.engine.task.Task internalTask = taskService.createTaskQuery().taskId(updateTaskPayload.getTaskId()).singleResult(); <END> if (internalTask == null) { throw new NotFoundException("Unable to find task for the given id: " + updateTaskPayload.getTaskId()); } int updates=0; String oldValue,newValue; if ((newValue = updateTaskPayload.getName()) != null) { oldValue = internalTask.getName(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setName(newValue); } } if ((newValue = updateTaskPayload.getDescription()) != null) { oldValue = internalTask.getDescription(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setDescription(newValue); } } if (updateTaskPayload.getPriority() != null) { if (internalTask.getPriority()!=updateTaskPayload.getPriority()) { updates++; internalTask.setPriority(updateTaskPayload.getPriority()); } } if (updateTaskPayload.getDueDate() != null) { if (!Objects.equals(internalTask.getDueDate(),updateTaskPayload.getDueDate())) { updates++; internalTask.setDueDate(updateTaskPayload.getDueDate()); } } if ((newValue=updateTaskPayload.getParentTaskId()) != null) { oldValue = internalTask.getParentTaskId(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setParentTaskId(newValue); } } if ((newValue=updateTaskPayload.getFormKey()) != null) { oldValue = internalTask.getFormKey(); if (!Objects.equals(oldValue,newValue)) { updates++; internalTask.setFormKey(newValue); } } if (updates > 0) { taskService.saveTask(internalTask); } return taskConverter.from(taskService.createTaskQuery().taskId(updateTaskPayload.getTaskId()).singleResult()); }</code><technical_language>Lets avoid duplication TaskRuntimeImpl here. difference in TaskRuntimeImpl need check assignee. extract this code a new class (TaskUpdater) check assignee if parameter checkAssignee is true</technical_language>

Target:
public Task update(UpdateTaskPayload updateTaskPayload) { return taskRuntimeHelper.applyUpdateTaskPayload(true, updateTaskPayload); }
Source:
<code>public FutureCompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) { requireNonNull(action, "action"); <START> return thenCombineAsync(other, (ignoreValue, ignoreError) -> { <END> action.run(); return null; }, executor); }</code><technical_language>Nit: ignoreOtherValue ignoreError</technical_language>

Target:
public FutureCompletionStage<Void> runAfterBothAsync(CompletionStage<?> other, Runnable action, Executor executor) { requireNonNull(action, "action"); return thenCombineAsync(other, (ignoreOtherValue, ignoreError) -> { action.run(); return null; }, executor); }
Source:
<code>public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); <START> doReturn(newPosixConnection.getId()).when(command).isConnWithSameDetailsExists(newPosixConnection, null); <END> ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }</code><technical_language>need this line all. test check else</technical_language>

Target:
public void addNotEmptyIdConnection() { StorageServerConnections newPosixConnection = createPosixConnection("multipass.my.domain.tlv.company.com:/export/allstorage/data1", StorageType.POSIXFS, "nfs", "timeo=30"); newPosixConnection.setId(Guid.newGuid().toString()); parameters.setStorageServerConnection(newPosixConnection); parameters.setVdsId(Guid.Empty); ValidateTestUtils.runAndAssertValidateFailure(command, EngineMessage.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); }
Source:
<code>public void init(Config.Scope config) { Integer maxDetail = config.getInt("max-detail-length", 0); <START> maxDetailLength = (maxDetail == null) ? 0 : maxDetail; <END> }</code><technical_language>maxDetail null, do: maxDetailLength = config.getInt("max-detail-length", 0);</technical_language>

Target:
public void init(Config.Scope config) { maxDetailLength = config.getInt("max-detail-length", 0); }
Source:
<code>public void testExplicitPropertyMappings() { <START> Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("database", "jdbc://127.0.0.1:8001") .put("suites-table-name", "suite_source") .put("queries-table-name", "query_source") .put("suite-name", "test1") .build(); BenchmarkSuiteConfig expected = new BenchmarkSuiteConfig() .setDatabase("jdbc://127.0.0.1:8001") .setSuitesTableName("suite_source") .setQueriesTableName("query_source") .setSuite("test1"); <END> assertFullMapping(properties, expected); }</code><technical_language>here, order consistent BenchmarkSuiteConfig</technical_language>

Target:
public void testExplicitPropertyMappings() { Map<String, String> properties = new ImmutableMap.Builder<String, String>() .put("suite", "test1") .put("suites-table-name", "suite_source") .put("queries-table-name", "query_source") .build(); BenchmarkSuiteConfig expected = new BenchmarkSuiteConfig() .setSuite("test1") .setSuitesTableName("suite_source") .setQueriesTableName("query_source"); assertFullMapping(properties, expected); }
Source:
<code>public List<MimeMessage> generateNewInstructorAccountJoinEmail(InstructorAttributes instructor,String shortName, String institute) throws AddressException,MessagingException,UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); MimeMessage messageToAdmin = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); MimeMessage messageWithJoinLinkOnly = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); List<MimeMessage> messages = new ArrayList<MimeMessage>(); messages.add(messageToUser); messages.add(messageToAdmin); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); messageToAdmin.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT_COPY + " " + shortName+" "+ "[" + instructor.email + "]")); String joinUrl = ""; if (instructor != null) { String key; key = StringHelper.encrypt(instructor.key); joinUrl = Config.APP_URL + Const.ActionURIs.INSTRUCTOR_COURSE_JOIN; joinUrl = Url.addParamToUrl(joinUrl, Const.ParamsNames.REGKEY, key); joinUrl = Url.addParamToUrl(joinUrl, Const.ParamsNames.INSTRUCTOR_INSTITUTION, institute); <START> } <END> for(MimeMessage message : messages){ String emailBody = EmailTemplates.NEW_INSTRCUTOR_ACCOUNT_WELCOME; emailBody = emailBody.replace("${userName}", shortName); emailBody = emailBody.replace("${joinUrl}",joinUrl); message.setContent(emailBody, "text/html"); } messageWithJoinLinkOnly.setContent(joinUrl, "text/html"); messages.add(messageWithJoinLinkOnly); return messages; }</code><technical_language>This block previously a loop. is loop. affect this works</technical_language>

Target:
public List<MimeMessage> generateNewInstructorAccountJoinEmail(InstructorAttributes instructor,String shortName, String institute) throws AddressException,MessagingException,UnsupportedEncodingException { MimeMessage messageToUser = getEmptyEmailAddressedToEmail(instructor.email); MimeMessage messageToAdmin = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); MimeMessage messageWithJoinLinkOnly = getEmptyEmailAddressedToEmail(Config.SUPPORT_EMAIL); List<MimeMessage> messages = new ArrayList<MimeMessage>(); messages.add(messageToUser); messages.add(messageToAdmin); messageToUser.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT + " " + shortName)); messageToAdmin.setSubject(String.format(SUBJECT_PREFIX_NEW_INSTRUCTOR_ACCOUNT_COPY + " " + shortName+" "+ "[" + instructor.email + "]")); String joinUrl = generateNewInstructorAccountJoinLink(instructor, institute); for(MimeMessage message : messages){ String emailBody = EmailTemplates.NEW_INSTRCUTOR_ACCOUNT_WELCOME; emailBody = emailBody.replace("${userName}", shortName); emailBody = emailBody.replace("${joinUrl}",joinUrl); message.setContent(emailBody, "text/html"); } messageWithJoinLinkOnly.setContent(joinUrl, "text/html"); messages.add(messageWithJoinLinkOnly); return messages; }
Source:
<code>public void testCleanUpExceptionSuppressing() throws Exception { OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); streamConfig.setStreamOperator(new FailingTwiceOperator()); streamConfig.setOperatorID(new OperatorID()); testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new StreamRecord<>("Doesn't matter", 0)); try { testHarness.waitForTaskCompletion(); } catch (Exception ex) { Assert.assertTrue(ex.getCause() instanceof ExpectedTestException); <START> Assert.assertTrue( <END> ex.getCause() .getSuppressed()[0] .getMessage() .equals("Dispose Exception. This exception should be suppressed")); } }</code><technical_language>nit: IDE suggests replace assertTrue assertEquals</technical_language>

Target:
public void testCleanUpExceptionSuppressing() throws Exception { OneInputStreamTaskTestHarness<String, String> testHarness = new OneInputStreamTaskTestHarness<>( OneInputStreamTask::new, BasicTypeInfo.STRING_TYPE_INFO, BasicTypeInfo.STRING_TYPE_INFO); testHarness.setupOutputForSingletonOperatorChain(); StreamConfig streamConfig = testHarness.getStreamConfig(); streamConfig.setStreamOperator(new FailingTwiceOperator()); streamConfig.setOperatorID(new OperatorID()); testHarness.invoke(); testHarness.waitForTaskRunning(); testHarness.processElement(new StreamRecord<>("Doesn't matter", 0)); try { testHarness.waitForTaskCompletion(); } catch (Exception ex) { if (!(ex.getCause() instanceof ExpectedTestException)) { throw ex; } if (!(Iterables.getOnlyElement(asList(ex.getCause().getSuppressed())) instanceof FailingTwiceOperator.DisposeException)) { throw ex; } } }
Source:
<code>public void startup() throws Exception { super.startup(); <START> try { <END> clientId = generateClientId(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] could not generate client ID. Is this machine connected to the internet?"); throw e; } StreamingConnectionFactory factory = new StreamingConnectionFactory(clusterId,clientId); factory.setNatsUrl("nats://" + this.serverHost + ":" + this.serverPort); stanConnection = factory.createConnection(); }</code><technical_language>a lot of similarity NATS sender receiver. Create a NATSClient class manages clientID connection. subscription optional</technical_language>

Target:
public void startup() throws Exception { super.startup(); client.startup(); }
Source:
<code>private void createIndexToolOutputTable(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { return; } HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); <START> tableDescriptor.setValue("DISABLE_TABLE_SOR", "true"); <END> tableDescriptor.setValue(ColumnFamilyDescriptorBuilder.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); }</code><technical_language>a property open source HBase Phoenix recognizes</technical_language>

Target:
private void createIndexToolOutputTable(Connection connection) throws Exception { ConnectionQueryServices queryServices = connection.unwrap(PhoenixConnection.class).getQueryServices(); Admin admin = queryServices.getAdmin(); if (admin.tableExists(TableName.valueOf(OUTPUT_TABLE_NAME))) { return; } HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(OUTPUT_TABLE_NAME)); tableDescriptor.setValue(ColumnFamilyDescriptorBuilder.TTL, String.valueOf(MetaDataProtocol.DEFAULT_LOG_TTL)); HColumnDescriptor columnDescriptor = new HColumnDescriptor(QueryConstants.DEFAULT_COLUMN_FAMILY); tableDescriptor.addFamily(columnDescriptor); admin.createTable(tableDescriptor); }