auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public GetSpecificAttributeValueResponse getSpecificAttributeValueResponse( @RequestPayload final GetSpecificAttributeValueAsyncRequest request) throws OsgpException { GetSpecificAttributeValueResponse response = null; try { response = new GetSpecificAttributeValueResponse(); final MeterResponseData meterResponseData = this.meterResponseDataService .dequeue(request.getCorrelationUid()); response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (ResponseMessageResultType.OK == meterResponseData.getResultType()) { response.setAttributeValueData((String) meterResponseData.getMessageData()); } else if (meterResponseData.getMessageData() instanceof OsgpException) { throw (OsgpException) meterResponseData.getMessageData(); } else { throw new TechnicalException(ComponentType.WS_SMART_METERING, <START> String.format("An exception occurred %s.", "Get specific attribute value"), null); <END> } } catch (final Exception e) { this.handleException(e); } return response; }</code><technical_language>This potentially looses information String message data result is OK returned exception in response in older code. If OsgpException type message data handled alternative level String data in older code, earlier working preserved; wrong other handling OsgpException message data? other type of Throwable in result handle adding in a new TechnicalException instead of leaving null in changed code. other String Throwable handled a TechnicalException, in final else of changed code. I String.format a hard coded String for %s. write exception message</technical_language>

Target:
public GetSpecificAttributeValueResponse getSpecificAttributeValueResponse( @RequestPayload final GetSpecificAttributeValueAsyncRequest request) throws OsgpException { GetSpecificAttributeValueResponse response = null; try { response = new GetSpecificAttributeValueResponse(); final MeterResponseData meterResponseData = this.meterResponseDataService .dequeue(request.getCorrelationUid()); response.setResult(OsgpResultType.fromValue(meterResponseData.getResultType().getValue())); if (ResponseMessageResultType.OK == meterResponseData.getResultType()) { response.setAttributeValueData((String) meterResponseData.getMessageData()); } else if (meterResponseData.getMessageData() instanceof OsgpException) { throw (OsgpException) meterResponseData.getMessageData(); } else if (meterResponseData.getMessageData() instanceof Exception) { throw new TechnicalException(ComponentType.WS_SMART_METERING, "An exception occurred: Get specific attribute value", (Exception) meterResponseData.getMessageData()); } else { throw new TechnicalException(ComponentType.WS_SMART_METERING, "An exception occurred: Get specific attribute value", null); } } catch (final Exception e) { this.handleException(e); } return response; }
Source:
<code>default Optional<MetaAnnotation> getAnnotation(final MetaClass annotationClass) { <START> return getAnnotation((Class<? extends Annotation>) annotationClass.unsafeAsClass()); <END> }</code><technical_language>reason for a safe implementation getAnnotations</technical_language>

Target:
default Optional<MetaAnnotation> getAnnotation(final MetaClass annotationClass) { return getAnnotations().stream().filter(a -> a.annotationType().equals(annotationClass)).findFirst(); }
Source:
<code>public void shouldSetDeadToTrueIfSetDeathdate() { Person p = new Person(); Date deathDate = new Date(); p.setDeathDate(deathDate); <START> assert (p.getDead()); <END> }</code><technical_language>intentionally decided "Assert.assertTrue()" provided in ticket description</technical_language>

Target:
public void shouldSetDeadToTrueIfSetDeathdate() { Person p = new Person(); Date deathDate = new Date(); p.setDeathDate(deathDate); assertTrue ("Person must be dead(setDead(true)) inorder have a deathDate set for him", p.getDead()); }
Source:
<code>private void createSecretKey() { <START> String inputPepper = "Open Sesame"; <END> secretKey = BCrypt.hashpw(getUsername() + inputPepper + getPassword(), ApplicationConstants.DB_PASSWORD_BCRYPT_PEPPER); }</code><technical_language>This possibly put in ApplicationConstants well</technical_language>

Target:
private void createSecretKey() { secretKey = BCrypt.hashpw(getUsername() + ApplicationConstants.DB_PASSWORD_LITERAL_PEPPER + getPassword(), ApplicationConstants.DB_PASSWORD_BCRYPT_PEPPER); }
Source:
<code>public int getStateTableIndex(ITimeEvent event) { if (event instanceof TimeEvent && ((TimeEvent) event).hasValue()) { int status = ((TimeEvent) event).getValue(); <START> return Arrays.asList(STATES).indexOf(getMatchingState(status)); <END> } if (event instanceof NullTimeEvent) { return INVISIBLE; } return TRANSPARENT; }</code><technical_language>a new array list created event here. garbage collector in world, overwhelmed quantity of objects a while... Cache list</technical_language>

Target:
public int getStateTableIndex(ITimeEvent event) { if (event instanceof TimeEvent && ((TimeEvent) event).hasValue()) { int status = ((TimeEvent) event).getValue(); return STATE_LIST.indexOf(getMatchingState(status)); } if (event instanceof NullTimeEvent) { return INVISIBLE; } return TRANSPARENT; }
Source:
<code>public void revokeLocalBiasForSegments(Set<Integer> segments) { <START> Iterator<Object> it = localBias.keySet().iterator(); <END> while (it.hasNext()) { if (segments.contains(keyPartitioner.getSegment(it.next()))) { it.remove(); } } }</code><technical_language>suggestion localBias.keySet().removeIf(o -> segments.contains(keyPartitioner.getSegment(o)));</technical_language>

Target:
public void revokeLocalBiasForSegments(Set<Integer> segments) { localBias.keySet().removeIf(key -> segments.contains(keyPartitioner.getSegment(key))); }
Source:
<code>public String portsAsString() { StringBuilder sb = new StringBuilder(); if (this.ports != null) { Iterator<PortMapping> it = this.ports.iterator(); <START> while (it.hasNext()) { <END> final PortMapping port = it.next(); if (sb.length() > 0) { sb.append(", "); } if (port.ip != null) { sb.append(port.ip).append(":"); } if (port.publicPort > 0) { sb.append(port.privatePort).append("->").append(port.publicPort); } else { sb.append(port.privatePort); } sb.append("/").append(port.type); } } return sb.toString(); }</code><technical_language>Consider replacing this while for? for (PortMapping port : this.ports) { if (sb.length() > 0) { sb.append(", "); } if (port.ip != null) { sb.append(port.ip).append(":"); } if (port.publicPort > 0) { sb.append(port.privatePort).append("->").append(port.publicPort); } else { sb.append(port.privatePort); } sb.append("/").append(port.type); }</technical_language>

Target:
public String portsAsString() { StringBuilder sb = new StringBuilder(); if (this.ports != null) { for (PortMapping port : this.ports) { if (sb.length() > 0) { sb.append(", "); } if (port.ip != null) { sb.append(port.ip).append(":"); } if (port.publicPort > 0) { sb.append(port.privatePort).append("->").append(port.publicPort); } else { sb.append(port.privatePort); } sb.append("/").append(port.type); } } return sb.toString(); }
Source:
<code>@Test public void testNotFilterForm() { String sql = "select count(distinct \"the_month\") from " + "\"foodmart\" where \"the_month\" <> \'October\'"; <START> sql(sql, FOODMART) <END> .returnsOrdered("EXPR$0=11"); }</code><technical_language>add expected druid filter and/or plan druid is filter calcite</technical_language>

Target:
@Test public void testNotFilterForm() { String sql = "select count(distinct \"the_month\") from " + "\"foodmart\" where \"the_month\" <> \'October\'"; String druidFilter = "'filter':{'type':'not'," + "'field':{'type':'selector','dimension':'the_month','value':'October'}}"; sql(sql, FOODMART) .queryContains(druidChecker(druidFilter)) .returnsOrdered("EXPR$0=11"); }
Source:
<code>private ContainerPort getFirstPort(List<ContainerPort> ports) { ContainerPort port = null; for (ContainerPort containerPort : ports) { <START> if (port == null) { <END> port = containerPort; } else { if (containerPort.getContainerPort() < port.getContainerPort()) { port = containerPort; } } } return port; }</code><technical_language>iterator</technical_language>

Target:
private ContainerPort getFirstPort(List<ContainerPort> ports) { if (ports.isEmpty()) { return null; } final Iterator<ContainerPort> portsIterator = ports.iterator(); ContainerPort firstPort = portsIterator.next(); while (portsIterator.hasNext()) { final ContainerPort port = portsIterator.next(); if (port.getContainerPort() < firstPort.getContainerPort()) { firstPort = port; } } return firstPort; }
Source:
<code>void commitLocal() throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException { if (transaction instanceof ImportedTransaction) { throw Log.log.commitOnImported(); } int oldVal; do { oldVal = completionBits.get(); <START> if ((oldVal & BIT_PREPARE_OR_ROLLBACK) == 0 || (oldVal & BIT_COMMIT_OR_FORGET) != 0) { <END> throw Log.log.invalidTxnState(); } } while (! completionBits.compareAndSet(oldVal, oldVal | BIT_COMMIT_OR_FORGET | BIT_PREPARE_OR_ROLLBACK | BIT_BEFORE_COMP)); transaction.commit(); }</code><technical_language>In this case want '!=' this essentially says, "If prepared rolled back, if committed forgotten, throw exception"</technical_language>

Target:
void commitLocal() throws HeuristicRollbackException, RollbackException, HeuristicMixedException, SystemException { if (transaction instanceof ImportedTransaction) { throw Log.log.commitOnImported(); } transaction.commit(); }
Source:
<code>public CompositeCodec(Map<Class<?>, Codec> delegates, Codec defaultCodec) { Assert.notNull(defaultCodec, "'defaultCodec' cannot be null"); this.defaultCodec = defaultCodec; <START> this.delegates = delegates; <END> }</code><technical_language>new HashMap(delegates) - a reference caller's map - change it</technical_language>

Target:
public CompositeCodec(Map<Class<?>, Codec> delegates, Codec defaultCodec) { Assert.notNull(defaultCodec, "'defaultCodec' cannot be null"); this.defaultCodec = defaultCodec; this.delegates = new HashMap<Class<?>, Codec>(delegates); }
Source:
<code>public static List<String> PdhEnumObjectItemCounters(String szDataSource, String szMachineName, String szObjectName, int dwDetailLevel) { List<String> counters = new ArrayList<String>(); DWORDByReference pcchCounterListLength = new DWORDByReference(new DWORD(0)); DWORDByReference pcchInstanceListLength = new DWORDByReference(new DWORD(0)); Pdh.INSTANCE.PdhEnumObjectItems(szDataSource, szMachineName, szObjectName, null, pcchCounterListLength, null, pcchInstanceListLength, dwDetailLevel, 0); if (pcchCounterListLength.getValue().intValue() < 1 || pcchInstanceListLength.getValue().intValue() < 1) { return counters; <START> } <END> Memory mszCounterList = new Memory(pcchCounterListLength.getValue().intValue() * CHAR_TO_BYTES); Memory mszInstanceList = new Memory(pcchInstanceListLength.getValue().intValue() * CHAR_TO_BYTES); Pdh.INSTANCE.PdhEnumObjectItems(szDataSource, szMachineName, szObjectName, mszCounterList, pcchCounterListLength, mszInstanceList, pcchInstanceListLength, dwDetailLevel, 0); int offset = 0; while (offset < mszCounterList.size()) { String s = null; if (CHAR_TO_BYTES == 1) { s = mszCounterList.getString(offset); } else { s = mszCounterList.getWideString(offset); } if (s.isEmpty()) { break; } counters.add(s); offset += (s.length() + 1) * CHAR_TO_BYTES; } return counters; }</code><technical_language>Is possible, of lists content? I special case 0-elements case replace memory a null pointer. experience is expected usage of API</technical_language>

Target:
public static List<String> PdhEnumObjectItemCounters(String szDataSource, String szMachineName, String szObjectName, int dwDetailLevel) { List<String> counters = new ArrayList<String>(); DWORDByReference pcchCounterListLength = new DWORDByReference(new DWORD(0)); DWORDByReference pcchInstanceListLength = new DWORDByReference(new DWORD(0)); Pdh.INSTANCE.PdhEnumObjectItems(szDataSource, szMachineName, szObjectName, null, pcchCounterListLength, null, pcchInstanceListLength, dwDetailLevel, 0); if (pcchCounterListLength.getValue().intValue() < 1) { return counters; } Memory mszCounterList = new Memory(pcchCounterListLength.getValue().intValue() * CHAR_TO_BYTES); pcchInstanceListLength.getValue().setValue(0); Pdh.INSTANCE.PdhEnumObjectItems(szDataSource, szMachineName, szObjectName, mszCounterList, pcchCounterListLength, null, pcchInstanceListLength, dwDetailLevel, 0); int offset = 0; while (offset < mszCounterList.size()) { String s = null; if (CHAR_TO_BYTES == 1) { s = mszCounterList.getString(offset); } else { s = mszCounterList.getWideString(offset); } if (s.isEmpty()) { break; } counters.add(s); offset += (s.length() + 1) * CHAR_TO_BYTES; } return counters; }
Source:
<code>public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); <START> Prefs.crashedBeforeActivityCreated(false); <END> ActivityUtil.requestFullUserOrientation(this); setTheme(); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }</code><technical_language>If understanding this patch correctly, idea is if reached this point, in infinite crash loop -- is right</technical_language>

Target:
public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); ActivityUtil.requestFullUserOrientation(this); setTheme(); removeSplashBackground(); if (getSupportActionBar() != null) { getSupportActionBar().setDisplayHomeAsUpEnabled(true); } forceOverflowMenuIcon(this); }
Source:
<code>public void VEAddMapTests_003_InsertMapFromZeroState() { wikiURL = urlBuilder.getUrlForWiki(URLsContent.veDisabledTestMainPage); int expectedMapNum = 1; VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); VisualEditorAddMapDialog mapDialog = (VisualEditorAddMapDialog) ve.openDialogFromMenu(InsertDialog.MAP); CreateAMapComponentObject map = mapDialog.clickCreateAMapButton(); CreateRealMapComponentObject realMap = map.clickRealMap(); realMap.verifyRealMapPreviewImage(); realMap.typeMapName(InteractiveMapsContent.mapName); CreatePinTypesComponentObject pinDialog = realMap.clickNext(); pinDialog.typePinTypeTitle(InteractiveMapsContent.pinTypeName, InteractiveMapsContent.pinTypeIndex); InteractiveMapPageObject createdMap = pinDialog.clickSave(); createdMap.verifyMapOpened(); mapID = createdMap.getEmbedMapID(); <START> createdMap.verifyControButtonsAreVisible(); <END> }</code><technical_language>of miss L (probably I wrote this method) . Please change name of this method verifyControlButtonsAreVisible</technical_language>

Target:
public void VEAddMapTests_003_InsertMapFromZeroState() { wikiURL = urlBuilder.getUrlForWiki(URLsContent.veDisabledTestMainPage); int expectedMapNum = 1; VisualEditorPageObject ve = base.launchVisualEditorWithMainEdit(articleName, wikiURL); VisualEditorAddMapDialog mapDialog = (VisualEditorAddMapDialog) ve.openDialogFromMenu(InsertDialog.MAP); CreateAMapComponentObject map = mapDialog.clickCreateAMapButton(); CreateRealMapComponentObject realMap = map.clickRealMap(); realMap.verifyRealMapPreviewImage(); realMap.typeMapName(InteractiveMapsContent.mapName); CreatePinTypesComponentObject pinDialog = realMap.clickNext(); pinDialog.typePinTypeTitle(InteractiveMapsContent.pinTypeName, InteractiveMapsContent.pinTypeIndex); createdMap = pinDialog.clickSave(); createdMap.verifyMapOpened(); mapID = createdMap.getEmbedMapID(); createdMap.verifyControlButtonsAreVisible(); }
Source:
<code>private void parseChunkHeader(String line, HashMap<String, String> chunkOptions) { String modeId = display_.getModeId(); Pattern pattern = null; if (modeId == "mode/rmarkdown") pattern = RegexUtil.RE_RMARKDOWN_CHUNK_BEGIN; else if (modeId == "mode/sweave") pattern = RegexUtil.RE_SWEAVE_CHUNK_BEGIN; else if (modeId == "mode/rhtml") pattern = RegexUtil.RE_RHTML_CHUNK_BEGIN; if (pattern == null) return; Match match = pattern.match(line, 0); if (match == null) return; String extracted = match.getGroup(1); chunkPreamble_ = extractChunkPreamble(extracted, modeId); String chunkLabel = ChunkContextUi.extractChunkLabel(extracted); if (!StringUtil.isNullOrEmpty(chunkLabel)) <START> tbChunkLabel_.setText(ChunkContextUi.extractChunkLabel(extracted)); <END> int argsStartIdx = StringUtil.isNullOrEmpty(chunkLabel) ? extracted.indexOf(' ') : extracted.indexOf(','); String arguments = extracted.substring(argsStartIdx + 1); TextCursor cursor = new TextCursor(arguments); cursor.consumeUntilRegex("[^\\s,]"); int startIndex = 0; do { if (!cursor.fwdToCharacter('=', false)) break; int equalsIndex = cursor.getIndex(); int endIndex = arguments.length(); if (cursor.fwdToCharacter(',', true) || cursor.fwdToCharacter(' ', true)) { endIndex = cursor.getIndex(); } chunkOptions.put( arguments.substring(startIndex, equalsIndex).trim(), arguments.substring(equalsIndex + 1, endIndex).trim()); startIndex = cursor.getIndex() + 1; } while (cursor.moveToNextCharacter()); }</code><technical_language>I re-use chunkLabel here. (I realize this is coming in diff part of refactor worth changing while in this code)</technical_language>

Target:
private void parseChunkHeader(String line, HashMap<String, String> chunkOptions) { String modeId = display_.getModeId(); Pattern pattern = null; if (modeId == "mode/rmarkdown") pattern = RegexUtil.RE_RMARKDOWN_CHUNK_BEGIN; else if (modeId == "mode/sweave") pattern = RegexUtil.RE_SWEAVE_CHUNK_BEGIN; else if (modeId == "mode/rhtml") pattern = RegexUtil.RE_RHTML_CHUNK_BEGIN; if (pattern == null) return; Match match = pattern.match(line, 0); if (match == null) return; String extracted = match.getGroup(1); chunkPreamble_ = extractChunkPreamble(extracted, modeId); String chunkLabel = ChunkContextUi.extractChunkLabel(extracted); if (!StringUtil.isNullOrEmpty(chunkLabel)) tbChunkLabel_.setText(chunkLabel); int argsStartIdx = StringUtil.isNullOrEmpty(chunkLabel) ? extracted.indexOf(' ') : extracted.indexOf(','); String arguments = extracted.substring(argsStartIdx + 1); TextCursor cursor = new TextCursor(arguments); cursor.consumeUntilRegex("[^\\s,]"); int startIndex = 0; do { if (!cursor.fwdToCharacter('=', false)) break; int equalsIndex = cursor.getIndex(); int endIndex = arguments.length(); if (cursor.fwdToCharacter(',', true) || cursor.fwdToCharacter(' ', true)) { endIndex = cursor.getIndex(); } chunkOptions.put( arguments.substring(startIndex, equalsIndex).trim(), arguments.substring(equalsIndex + 1, endIndex).trim()); startIndex = cursor.getIndex() + 1; } while (cursor.moveToNextCharacter()); }
Source:
<code>private void zipFiles() { Logger.log(TAG, "Zipping Files"); ZipTask mZipTask = new ZipTask(toBeTransferredDirectory, zipFilePath) { @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.zip.unsuccessful", e.getMessage())); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, Integer result) { <START> if (result == ZipTask.RESULT_SUCCESS) { <END> receiver.onZipSuccesful(); } else { receiver.onZipError(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } }; mZipTask.connect(CommCareWiFiDirectActivity.this); mZipTask.execute(); }</code><technical_language>Do need unbox result intValue()? sure, manually unbox in other places</technical_language>

Target:
private void zipFiles() { Logger.log(TAG, "Zipping Files"); ZipTask mZipTask = new ZipTask(toBeTransferredDirectory, zipFilePath) { @Override protected void deliverUpdate(CommCareWiFiDirectActivity receiver, String... update) { receiver.updateProgress(update[0], taskId); receiver.myStatusText.setText(update[0]); } @Override protected void deliverError(CommCareWiFiDirectActivity receiver, Exception e) { receiver.myStatusText.setText(localize("wifi.direct.zip.unsuccessful", e.getMessage())); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } @Override protected void deliverResult(CommCareWiFiDirectActivity receiver, ZipTaskResult result) { if (result == ZipTaskResult.Success) { receiver.onZipSuccesful(); } else { receiver.onZipError(); receiver.transplantStyle(receiver.myStatusText, R.layout.template_text_notification_problem); } } }; mZipTask.connect(CommCareWiFiDirectActivity.this); mZipTask.execute(); }
Source:
<code>public void run() { while (running) { if (holder.getSurface().isValid()) { Canvas canvas = holder.lockCanvas(); updateField(); onDraw(canvas); holder.unlockCanvasAndPost(canvas); } } <START> } <END></code><technical_language>Please return time logging</technical_language>

Target:
public void run() { while (running) { if (holder.getSurface().isValid()) { long startTime = System.nanoTime(); Canvas canvas = holder.lockCanvas(); updateField(); onDraw(canvas); holder.unlockCanvasAndPost(canvas); long finishTime = System.nanoTime(); Log.i("TIME", "Circle: " + (finishTime - startTime) / 1000000); } } }
Source:
<code>public void readRateLimitShouldBeRespectedByConcurrentReadingThreads() throws InterruptedException { int numThreads = 5; int numReadsPerThread = 10; ExecutorService executorService = Executors.newFixedThreadPool(numThreads); List<Future<List<Todo>>> futures = new ArrayList<>(numThreads); long start = System.nanoTime(); IntStream.range(0, numThreads).forEach(i -> futures.add(executorService.submit(() -> { List<Todo> results = new ArrayList<>(numReadsPerThread); IntStream.range(0, numReadsPerThread) .forEach(j -> results.addAll(readOneBatchOfSize(1))); return results; }))); executorService.shutdown(); Preconditions.checkState(executorService.awaitTermination(30L, TimeUnit.SECONDS), "Read tasks did not finish in 30s"); <START> long timeTakenToReadInSeconds = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); <END> assertThatAllReadsWereSuccessful(futures, numReadsPerThread); long actualReadRate = (numThreads * numReadsPerThread * ONE_TODO_SIZE_IN_BYTES) / timeTakenToReadInSeconds; assertThat(actualReadRate).isLessThan(readBytesPerSecond + (readBytesPerSecond / 10 )); }</code><technical_language>Note this rounds nearest second, mess calculations (i.e. 1,999,999,999 ns 1 s)</technical_language>

Target:
public void readRateLimitShouldBeRespectedByConcurrentReadingThreads() throws InterruptedException { int numThreads = 5; int numReadsPerThread = 10; ExecutorService executorService = Executors.newFixedThreadPool(numThreads); List<Future<List<Todo>>> futures = new ArrayList<>(numThreads); long start = System.nanoTime(); IntStream.range(0, numThreads).forEach(i -> futures.add(executorService.submit(() -> { List<Todo> results = new ArrayList<>(numReadsPerThread); IntStream.range(0, numReadsPerThread) .forEach(j -> results.addAll(readOneBatchOfSize(1))); return results; }))); executorService.shutdown(); Preconditions.checkState(executorService.awaitTermination(30L, TimeUnit.SECONDS), "Read tasks did not finish in 30s"); long readTime = System.nanoTime() - start; assertThatAllReadsWereSuccessful(futures, numReadsPerThread); double actualBytesRead = numThreads * numReadsPerThread * ONE_TODO_SIZE_IN_BYTES; double maxReadBytesLimit = readBytesPerSecond * ((double) readTime / TimeUnit.SECONDS.toNanos(1) + 5 ); assertThat(actualBytesRead).isLessThan(maxReadBytesLimit); }
Source:
<code>public synchronized void start() throws IOException { if (started) { LOGGER.debug("Endpoint at is already started", getUri()); return; } if (!this.coapstack.hasDeliverer()) { setMessageDeliverer(new ClientMessageDeliverer()); } if (this.executor == null) { <START> int threadCount = config.getInt(Keys.PROTOCOL_STAGE_THREAD_COUNT); <END> ThreadFactory factory = new DaemonThreadFactory("CoapEndpoint-" + connector + '#'); LOGGER.info("Endpoint requires an executor to start, using default daemon thread executor", getUri(), threadCount); setExecutor(ExecutorsUtil.newScheduledThreadPool(threadCount, factory)); addObserver(new EndpointObserver() { @Override public void started(final Endpoint endpoint) { } @Override public void stopped(final Endpoint endpoint) { } @Override public void destroyed(final Endpoint endpoint) { executor.shutdown(); } }); } if (exchangeExecutor == null) { exchangeExecutor = ExecutorsUtil.stripes(executor); } try { LOGGER.debug("Starting endpoint at {}", getUri()); started = true; matcher.start(); connector.start(); for (EndpointObserver obs : observers) { obs.started(this); } startExecutor(); LOGGER.info("Started endpoint at {}", getUri()); } catch (IOException e) { stop(); throw e; } }</code><technical_language>changing number of thread 1 Keys.PROTOCOL_STAGE_THREAD_COUNT ? I this impact tests create endpoints default value. For real case, executor is created in coapServer Keys.PROTOCOL_STAGE_THREAD_COUNT</technical_language>

Target:
public synchronized void start() throws IOException { if (running) { LOGGER.debug("Endpoint at is already started", getUri()); return; } if (!this.coapstack.hasDeliverer()) { setMessageDeliverer(new ClientMessageDeliverer()); } if (this.executor == null) { int threadCount = config.getInt(Keys.PROTOCOL_STAGE_THREAD_COUNT); ThreadFactory factory = new DaemonThreadFactory("CoapEndpoint-" + connector + '#'); LOGGER.info("Endpoint requires an executor to start, using default daemon thread executor", getUri(), threadCount); setExecutor(ExecutorsUtil.newScheduledThreadPool(threadCount, factory)); addObserver(new EndpointObserver() { @Override public void started(final Endpoint endpoint) { } @Override public void stopped(final Endpoint endpoint) { } @Override public void destroyed(final Endpoint endpoint) { exchangeExecutor.shutdown(); } }); } exchangeExecutor = ExecutorsUtil.stripes(executor); try { LOGGER.debug("Starting endpoint at {}", getUri()); running = true; matcher.start(); connector.start(); for (EndpointObserver obs : observers) { obs.started(this); } startExecutor(); LOGGER.info("Started endpoint at {}", getUri()); } catch (IOException e) { stop(); throw e; } }
Source:
<code>public static HaxeComponentType typeOf(PsiElement element) { if (element instanceof HaxeClassDeclaration || element instanceof HaxeExternClassDeclaration || element instanceof HaxeGenericListPart || element instanceof HaxeAbstractClassDeclaration) { return CLASS; } if (element instanceof HaxeEnumDeclaration) { return ENUM; } if (element instanceof HaxeInterfaceDeclaration || element instanceof HaxeExternInterfaceDeclaration) { return INTERFACE; } if (element instanceof HaxeTypedefDeclaration) { return TYPEDEF; } if (element instanceof HaxeMethodDeclaration) { return METHOD; } if (element instanceof HaxeLocalFunctionDeclaration || element instanceof HaxeFunctionLiteral) { return FUNCTION; } if (element instanceof HaxeFieldDeclaration || element instanceof HaxeEnumValueDeclaration || element instanceof HaxeAnonymousTypeField) { return FIELD; } if (element instanceof HaxeLocalVarDeclaration || element instanceof HaxeForStatement) { return VARIABLE; } if (element instanceof HaxeParameter) { return PARAMETER; } <START> if (element instanceof HaxeFieldDeclaration) { <END> return CLASSVARIABLE; } return null; }</code><technical_language>doing, this line reached of line 171/169. And, in fact, CLASSVARIABLE is used. (Also doing.)</technical_language>

Target:
public static HaxeComponentType typeOf(PsiElement element) { if (element instanceof HaxeClassDeclaration || element instanceof HaxeExternClassDeclaration || element instanceof HaxeGenericListPart || element instanceof HaxeAbstractClassDeclaration) { return CLASS; } if (element instanceof HaxeEnumDeclaration) { return ENUM; } if (element instanceof HaxeInterfaceDeclaration || element instanceof HaxeExternInterfaceDeclaration) { return INTERFACE; } if (element instanceof HaxeTypedefDeclaration) { return TYPEDEF; } if (element instanceof HaxeMethodDeclaration) { return METHOD; } if (element instanceof HaxeLocalFunctionDeclaration || element instanceof HaxeFunctionLiteral) { return FUNCTION; } if (element instanceof HaxeFieldDeclaration || element instanceof HaxeEnumValueDeclaration || element instanceof HaxeAnonymousTypeField) { return FIELD; } if (element instanceof HaxeLocalVarDeclaration || element instanceof HaxeForStatement) { return VARIABLE; } if (element instanceof HaxeParameter) { return PARAMETER; } return null; }
Source:
<code>public Iterator<Object[]> pLohData(){ <START> List<Object[]> listOfDoubles = new ArrayList<>(); <END> for(int i=1;i<20; i++) { listOfDoubles.add(new Object[]{i/40D}); } return listOfDoubles.iterator(); }</code><technical_language>final</technical_language>

Target:
public Iterator<Object[]> pLohData() { final List<Object[]> listOfDoubles = new ArrayList<>(); for (int i = 1; i < 20; i++) { listOfDoubles.add(new Object[]{i / 40D}); } return listOfDoubles.iterator(); }
Source:
<code>protected <T> T get(String url, TypeReference<T> type) { HttpResponse response = get(url); <START> JsonNode node = getJsonNode(response); <END> return mapper.convertValue(node, type); }</code><technical_language>For consistency get(String, Class), worthwhile write a getResponseBodyAsType(HttpResponse, TypeReference)? least, avoid invoking Jackson mapper twice</technical_language>

Target:
protected <T> T get(String url, TypeReference<T> type) { HttpResponse response = get(url); return getResponseBodyAsType(response, type); }
Source:
<code>private int getJsonFieldPotentialOverhead(String fieldName, Map<String, Object> descriptionMap) { return String.format("\"%s\":\"\"", fieldName).length() + <START> (descriptionMap.size() >= 1 ? 1 : 0); END> }</code><technical_language>try descriptionMap.isEmpty instead</technical_language>

Target:
private int getJsonFieldPotentialOverhead(String fieldName, Map<String, Object> descriptionMap) { return String.format("\"%s\":\"\"", fieldName).length() + (descriptionMap.isEmpty() ? 0 : 1); }
Source:
<code>public static String getProjectAbsolutePath(String... path) { StringBuilder builder = new StringBuilder(); for (String fragment : path) { builder.append("/" + fragment); } String filePath = ""; <START> filePath = System.getProperty("user.dir"); <END> File file = new File(filePath + builder.toString()); if (!file.exists()) { throw new RedDeerException("Resource file does not exists within project path " + filePath + builder.toString()); } return file.getAbsolutePath(); }</code><technical_language>declare initialise empty string immediately overwritten system property</technical_language>

Target:
public static String getProjectAbsolutePath(String... path) { StringBuilder builder = new StringBuilder(); for (String fragment : path) { builder.append("/" + fragment); } String filePath = System.getProperty("user.dir"); File file = new File(filePath + builder.toString()); if (!file.exists()) { throw new RedDeerException("Resource file does not exists within project path " + filePath + builder.toString()); } return file.getAbsolutePath(); }
Source:
<code>protected void visitLiteralGeometry(Literal expression) throws IOException { Geometry geom = (Geometry) evaluateLiteral(expression, Geometry.class); if (geom instanceof LinearRing) { geom = geom.getFactory().createLineString(((LinearRing) geom).getCoordinateSequence()); } <START> Optional<Object> typenameOpt = <END> Optional.ofNullable(currentGeometry) .map(GeometryDescriptor::getUserData) .map(m -> m.get(JDBCDataStore.JDBC_NATIVE_TYPENAME)); if (typenameOpt.filter(t -> "geography".equals(t)).isPresent()) { out.write("ST_GeogFromText('"); out.write(geom.toText()); out.write("')"); } else { out.write("ST_GeomFromText('"); out.write(geom.toText()); if (currentSRID == null && currentGeometry != null) { out.write("', ST_SRID(\"" + currentGeometry.getLocalName() + "\"))"); } else { out.write("', " + currentSRID + ")"); } } }</code><technical_language>This block convoluted. happen currentGeometry is null? If necessary, please encapsulate a isGeography() method. Implementation of isGeography method wise, chain filter/map end Optional<Boolean> tested directly, e.g., like: Optional.ofNullable(currentGeometry) .map(GeometryDescriptor::getUserData) .map(m -> m.get(JDBCDataStore.JDBC_NATIVE_TYPENAME)) .map(v -> "geography".equals(v)) .orElse(false) This method hide "maybe null" handling return a primive boolean</technical_language>

Target:
protected void visitLiteralGeometry(Literal expression) throws IOException { Geometry geom = (Geometry) evaluateLiteral(expression, Geometry.class); if (geom instanceof LinearRing) { geom = geom.getFactory().createLineString(((LinearRing) geom).getCoordinateSequence()); } Object typename = currentGeometry.getUserData().get(JDBCDataStore.JDBC_NATIVE_TYPENAME); if ("geography".equals(typename)) { out.write("ST_GeogFromText('"); out.write(geom.toText()); out.write("')"); } else { out.write("ST_GeomFromText('"); out.write(geom.toText()); if (currentSRID == null && currentGeometry != null) { out.write("', ST_SRID(\"" + currentGeometry.getLocalName() + "\"))"); } else { out.write("', " + currentSRID + ")"); } } }
Source:
<code>private static <T> void addOsgiServices(Class<T> contract, Map<String, T> services) { if (!Util.isOSGiContext()) { return; } ClassLoader loader = ServiceFinder.class.getClassLoader(); if ((loader != null) && (loader instanceof org.osgi.framework.BundleReference)) { final BundleContext bundleContext = ((BundleReference) loader).getBundle().getBundleContext(); final ServiceTracker<T, T> serviceTracker = new ServiceTracker<T, T>(bundleContext, contract.getName(), null); serviceTracker.open(); try { final Object[] osgiServices = serviceTracker.getServices(); if (osgiServices != null) { for (Object osgiService : osgiServices) { <START> services.putIfAbsent(osgiService.getClass().getName(), (T) osgiService); <END> } } } catch (Exception e) { } } }</code><technical_language>add log messages method above</technical_language>

Target:
private static <T> void addOsgiServices(Class<T> contract, Map<String, T> services) { if (!Util.isOSGiContext()) { return; } ClassLoader loader = ServiceFinder.class.getClassLoader(); if ((loader != null) && (loader instanceof org.osgi.framework.BundleReference)) { final BundleContext bundleContext = ((BundleReference) loader).getBundle().getBundleContext(); final ServiceTracker<T, T> serviceTracker = new ServiceTracker<T, T>(bundleContext, contract.getName(), null); serviceTracker.open(); try { final Object[] osgiServices = serviceTracker.getServices(); if (osgiServices != null) { for (Object osgiService : osgiServices) { if (services.putIfAbsent(osgiService.getClass().getName(), (T) osgiService) == null) { LOG.debugf("Loading service impl: %s", osgiService.getClass().getSimpleName()); } else { LOG.debugf("Ignoring already loaded service: %s", osgiService.getClass().getSimpleName()); } } } } catch (Exception e) { } } }
Source:
<code>public void setEndpointState(InputStream endpointState) { <START> checkCallContext(); <END> callContext.withEndpointState(NodeConverter.InputStreamToBytes(endpointState)); }</code><technical_language>previous version of this method need change? call setEndpointState(byte[]) do right thing</technical_language>

Target:
public void setEndpointState(InputStream endpointState) { setEndpointState(NodeConverter.InputStreamToBytes(endpointState)); }
Source:
<code>public int first() { if(size == 0) { <START> return 0; <END> } short firstKey = keys[0]; Container container = values[0]; return firstKey << 16 | container.first(); }</code><technical_language>Is this good policy return 0 is elements in RoaringArray (or a RoaringBitmap) ? I thought 0 a valid value. simply throw error NoSuchElementException, Collections.max in JDK. Note remark applies locations return 0 a default containers empty</technical_language>

Target:
public int first() { assertNonEmpty(); short firstKey = keys[0]; Container container = values[0]; return firstKey << 16 | container.first(); }
Source:
<code>public static void smite(Player player, CommandSender sender, String reason) { FUtil.bcastMsg(player.getName() + " has been a naughty, naughty boy.", ChatColor.RED); if (reason != null) { FUtil.bcastMsg(" Reason: " + reason + " (" + sender.getName() + ")", ChatColor.RED); }else { FUtil.bcastMsg("Smited by: " + sender.getName(), ChatColor.RED); } player.setOp(false); player.setGameMode(GameMode.SURVIVAL); player.getInventory().clear(); final Location targetPos = player.getLocation(); final World world = player.getWorld(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(world, targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z); world.strikeLightning(strike_pos); } } player.setHealth(0.0); player.sendMessage(ChatColor.YELLOW + "You've been smitten by: " + sender.getName()); if (reason != null) { player.sendMessage(ChatColor.YELLOW + sender.getName() + " smited you for, " + reason); } <START> <END> }</code><technical_language>Useless extra line</technical_language>

Target:
public static void smite(Player player, CommandSender sender, String reason) { FUtil.bcastMsg(player.getName() + " has been a naughty, naughty boy.", ChatColor.RED); if (reason != null) { FUtil.bcastMsg(" Reason: " + reason + " (" + sender.getName() + ")", ChatColor.RED); } else { FUtil.bcastMsg("Smitten by: " + sender.getName(), ChatColor.RED); } player.setOp(false); player.setGameMode(GameMode.SURVIVAL); player.getInventory().clear(); final Location targetPos = player.getLocation(); final World world = player.getWorld(); for (int x = -1; x <= 1; x++) { for (int z = -1; z <= 1; z++) { final Location strike_pos = new Location(world, targetPos.getBlockX() + x, targetPos.getBlockY(), targetPos.getBlockZ() + z); world.strikeLightning(strike_pos); } } player.setHealth(0.0); if (reason != null) { player.sendMessage(ChatColor.YELLOW + "You were smitten for, " + reason); } }
Source:
<code>public void testPurgeDeletedVault() { api().purgeVault(LOCATION, vaultName); <START> Object[] args = { resourceGroupName, vaultName, false }; <END> checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not purged before timeout"); }</code><technical_language>Unused args</technical_language>

Target:
public void testPurgeDeletedVault() { api().purgeVault(LOCATION, vaultName); checkState(deletedVaultStatus.create(resourceGroupName, true).apply(vaultName), "vault was not purged before timeout"); }
Source:
<code>public void visitMethod(MethodTree tree) { if (isExcluded(tree)) { return; } Symbol.MethodSymbol symbol = tree.symbol(); methodReferences.push(new MethodReference(symbol)); scan(tree.parameters()); scan(tree.block()); MethodReference reference = methodReferences.pop(); ClassTree classTree = (ClassTree) tree.parent(); <START> if ((tree.isOverriding() != null && tree.isOverriding()) || classTree.is(Tree.Kind.ENUM)) { <END> return; } if ((symbol.isPrivate() || symbol.isFinal() || classTree.symbol().isFinal()) && !symbol.isStatic() && !reference.hasNonStaticReference()) { context.reportIssue(this, tree.simpleName(), "Make \"" + symbol.name() + "\" a \"static\" method."); } }</code><technical_language>I replace (tree.isOverriding() != null && tree.isOverriding()) Boolean.TRUE.equals(tree.isOverriding())</technical_language>

Target:
public void visitMethod(MethodTree tree) { if (isExcluded(tree)) { return; } Symbol.MethodSymbol symbol = tree.symbol(); methodReferences.push(new MethodReference(symbol)); scan(tree.parameters()); scan(tree.block()); MethodReference reference = methodReferences.pop(); ClassTree classTree = (ClassTree) tree.parent(); if (Boolean.TRUE.equals(tree.isOverriding()) || classTree.is(Tree.Kind.ENUM)) { return; } if ((symbol.isPrivate() || symbol.isFinal() || classTree.symbol().isFinal()) && !symbol.isStatic() && !reference.hasNonStaticReference()) { context.reportIssue(this, tree.simpleName(), "Make \"" + symbol.name() + "\" a \"static\" method."); } }
Source:
<code>protected boolean canDetect(JsonPointer pointer) { <START> return pointer != null && (pointer.toString().endsWith("$ref") || pointer.toString().endsWith("operationRef")); <END> }</code><technical_language>(pointer.toString().endsWith("$ref") is a standard reference, while .endsWith("operationRef") is not. extracting check for "operationRef" in a hook method clear a customization</technical_language>

Target:
protected boolean canDetect(JsonPointer pointer) { return pointer != null && pointer.toString().endsWith("$ref"); }
Source:
<code>void checkConnected(long timeout) { if (_zkclient == null || _zkclient.isClosed()) { throw new HelixException( "HelixManager (ZkClient) is not connected. Call HelixManager#connect()"); } boolean isConnected = isConnected(); if (!isConnected && timeout > 0) { LOG.warn( "zkClient to " + _zkAddress + " is not connected, wait for " + _waitForConnectedTimeout + "ms."); isConnected = _zkclient.waitUntilConnected(_waitForConnectedTimeout, TimeUnit.MILLISECONDS); } if (!isConnected) { LOG.error("zkClient is not connected after waiting " + timeout + "ms." + ", clusterName: " + _clusterName + ", zkAddress: " + _zkAddress); throw new HelixException( "HelixManager is not connected within retry timeout for cluster " + _clusterName); } <START> _sessionId = ZKUtil.toHexSessionId(_zkclient.getSessionId()); <END> }</code><technical_language>This some issues. If session is updated randomly, a new session populated new session handling is done</technical_language>

Target:
void checkConnected(long timeout) { if (_zkclient == null || _zkclient.isClosed()) { throw new HelixException( "HelixManager (ZkClient) is not connected. Call HelixManager#connect()"); } boolean isConnected = isConnected(); if (!isConnected && timeout > 0) { LOG.warn("zkClient to " + getZkConnectionInfo() + " is not connected, wait for " + _waitForConnectedTimeout + "ms."); isConnected = _zkclient.waitUntilConnected(_waitForConnectedTimeout, TimeUnit.MILLISECONDS); } if (!isConnected) { LOG.error("zkClient is not connected after waiting " + timeout + "ms." + ", clusterName: " + _clusterName + ", zkAddress: " + getZkConnectionInfo()); throw new HelixException( "HelixManager is not connected within retry timeout for cluster " + _clusterName); } }
Source:
<code>public void apply(Project project) { <START> SarosIntellijExtension e = <END> project.getExtensions().create("sarosIntellij", SarosIntellijExtension.class); createIntelliJConfigurationTask(project); disableBuildSearchableOptions(project); }</code><technical_language>local variable e is used</technical_language>

Target:
public void apply(Project project) { SarosIntellijExtension sarosExtension = project.getExtensions().create(EXTENSION_NAME, SarosIntellijExtension.class); project.afterEvaluate(p -> configureIntellijAfterEvaluate(p, sarosExtension)); project.getPluginManager().apply(IntelliJPlugin.class); }
Source:
<code>public List<LogLag> getLagPerPartition(String name, String group) { LogLag[] ret; Properties props = (Properties) consumerProperties.clone(); props.put(ConsumerConfig.GROUP_ID_CONFIG, group); try (KafkaConsumer<String, Bytes> consumer = new KafkaConsumer<>(props)) { List<TopicPartition> topicPartitions = new ArrayList<>(); consumer.partitionsFor(getTopicName(name)).forEach( <START> meta -> topicPartitions.add(new TopicPartition(meta.topic(), meta.partition()))); <END> ret = new LogLag[topicPartitions.size()]; Map<TopicPartition, Long> endOffsets = consumer.endOffsets(topicPartitions); for (TopicPartition topicPartition : topicPartitions) { long committedOffset = 0L; OffsetAndMetadata committed = consumer.committed(topicPartition); if (committed != null) { committedOffset = committed.offset(); } Long endOffset = endOffsets.get(topicPartition); if (endOffset == null) { endOffset = 0L; } ret[topicPartition.partition()] = new LogLag(committedOffset, endOffset); } } return Arrays.asList(ret); }</code><technical_language>a full Stream usage</technical_language>

Target:
public List<LogLag> getLagPerPartition(String name, String group) { Properties props = (Properties) consumerProperties.clone(); props.put(ConsumerConfig.GROUP_ID_CONFIG, group); try (KafkaConsumer<String, Bytes> consumer = new KafkaConsumer<>(props)) { List<TopicPartition> topicPartitions = consumer.partitionsFor(getTopicName(name)) .stream() .map(meta -> new TopicPartition(meta.topic(), meta.partition())) .collect(Collectors.toList()); LogLag[] ret = new LogLag[topicPartitions.size()]; Map<TopicPartition, Long> endOffsets = consumer.endOffsets(topicPartitions); for (TopicPartition topicPartition : topicPartitions) { long committedOffset = 0L; OffsetAndMetadata committed = consumer.committed(topicPartition); if (committed != null) { committedOffset = committed.offset(); } Long endOffset = endOffsets.get(topicPartition); if (endOffset == null) { endOffset = 0L; } ret[topicPartition.partition()] = new LogLag(committedOffset, endOffset); } return Arrays.asList(ret); } }
Source:
<code>private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); final Timeout pendingRequestTimeout = record.newTimeout(timeout -> { <START> requestExpirator.execute(record::expire); <END> }); record.whenComplete((response, error) -> { this.pendingRequests.remove(id); pendingRequestTimeout.cancel(); }); return record; }); }</code><technical_language>Clarification(non-blocking): idea if netty duplex channel support timeout OOB</technical_language>

Target:
private RntbdRequestRecord addPendingRequestRecord(final ChannelHandlerContext context, final RntbdRequestRecord record) { return this.pendingRequests.compute(record.transportRequestId(), (id, current) -> { reportIssueUnless(current == null, context, "id: {}, current: {}, request: {}", record); final Timeout pendingRequestTimeout = record.newTimeout(timeout -> { requestExpirationExecutor.execute(record::expire); }); record.whenComplete((response, error) -> { this.pendingRequests.remove(id); pendingRequestTimeout.cancel(); }); return record; }); }
Source:
<code>private static Profile fetch(final XML xml) { <START> final Profile profile = new GithubProfile( <END> Profiles.github().repos().get( new Coordinates.Simple( xml.xpath( " ).get(0) ) ), xml.xpath( " ).get(0) ); return profile; }</code><technical_language>@xupyprmv afraid need some unit tests</technical_language>

Target:
private Profile fetch(final XML xml) throws IOException { final Profile profile; final List<String> type = xml.xpath(" if (type.isEmpty() || !Profiles.MERGE.equals(type.get(0))) { profile = new GithubProfile( new TalkIssues(Profiles.github(), xml).get().repo() ); } else { final Profile master = new GithubProfile( new TalkIssues(Profiles.github(), xml).get().repo() ); profile = this.merged( master, xml.xpath(" xml.xpath( " ).get(0) ); } return profile; }
Source:
<code>public void initIsolatedDomainGroup() { <START> account = gd.getAccountService().createAccount(new Account(LOGIN, "nnPvcGXU7f", "FistName", "LastName"), getProperty("domain")); <END> }</code><technical_language>typo: "fist"</technical_language>

Target:
public void initIsolatedDomainGroup() { account = gd.getAccountService().createAccount(new Account(LOGIN, "nnPvcGXU7f", "FirstName", "LastName"), getProperty("domain")); }
Source:
<code>private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey("Login")) { throw new NullPointerException("Login can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } <START> for (char ch: ClientLoginConstrains.NOT_ALLOWED_CHARS) { <END> if (data.getFirst("Login").indexOf(ch) > -1) { String msg = String.format("Login %s contains invalid character: %s ",data.getFirst("Login"), ch); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } } }</code><technical_language>this reused ClientLoginConstraints</technical_language>

Target:
private void validate(final MultivaluedMap<String, String> data) throws RuntimeException { if (!data.containsKey("Login")) { throw new NullPointerException("Login can not be null."); } else if (!data.containsKey("Password")) { throw new NullPointerException("Password can not be null."); } if (!ClientLoginConstrains.isValidClientLogin(data.getFirst("Login"))) { String msg = String.format("Login %s contains invalid character(s)",data.getFirst("Login")); if (logger.isDebugEnabled()) { logger.debug(msg); } throw new IllegalArgumentException(msg); } }