auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void readIntoDirectly(byte[] byteArray, long position, int length) throws IOException { long sizeInBytes = sizeInBytes(); if (position < startOffset || position >= sizeInBytes) { throw new IndexOutOfBoundsException( "Provided position [" + position + "] is out of bounds for the segment [" + file.getAbsolutePath() + "] with size [" + sizeInBytes + "]"); } if (position + length > sizeInBytes) { metrics.overflowReadError.inc(); throw new IndexOutOfBoundsException( "Cannot read from segment [" + file.getAbsolutePath() + "] from position [" + position + "] for size [" + length + "] because it exceeds the size [" + sizeInBytes + "]"); } <START> DirectRandomAccessFile directFile = new DirectRandomAccessFile(file, "r", 2 * 1024 * 1024); <END> directFile.seek(position); directFile.read(byteArray, 0, length); directFile.close(); }</code><technical_language>do need a new DirectRandomAccessFile instance time, is a read method in a file position line 243 FileChannel. If do need open time, try resources syntax: java try (DirectRandomAccessFile directFile = new DirectRandomAccessFile(file, "r", 2 * 1024 * 1024)) { directFile.seek(position); directFile.read(byteArray, 0, length); } This ensure close() called if read fails</technical_language>

Target:
void readIntoDirectly(byte[] byteArray, long position, int length) throws IOException { validateReadRange(position, length); try (DirectRandomAccessFile directFile = new DirectRandomAccessFile(file, "r", 2 * 1024 * 1024)) { directFile.seek(position); directFile.read(byteArray, 0, length); } }
Source:
<code>public void cleanup() { <START> memoryStore.putLocal(Centroids.class.getName(), initialCentroids); <END> }</code><technical_language>I Java memoryStore.putLocal(Centroids.class.getName(), ...); instead of Java keyValueStore.put(Centroids.class, ...); I is need Centroids class anymore, keys (or rather, dataTypes?) strings now. In fact, logistic regression a static field KEY_ROWS</technical_language>

Target:
public void cleanup() { memoryStore.putLocal(KEY_CENTROIDS, initialCentroids); }
Source:
<code>private void propagate(RuntimeLayout runtimeLayout, long globalAddress, @Nullable ILogData data) { int numUnits = runtimeLayout.getLayout().getSegmentLength(globalAddress); for (int i = 1; i < numUnits; i++) { <START> log.trace("Propogate[{}]: chain {}/{}", Token.of(runtimeLayout.getLayout().getEpoch(), <END> globalAddress), i + 1, numUnits); try { if (data != null) { CFUtils.getUninterruptibly( runtimeLayout.getLogUnitClient(globalAddress, i) .write(data), OverwriteException.class); } else { Token token = new Token(runtimeLayout.getLayout().getEpoch(), globalAddress); CFUtils.getUninterruptibly(runtimeLayout .getLogUnitClient(globalAddress, i) .fillHole(token), OverwriteException.class); } } catch (OverwriteException oe) { log.trace("Propogate[{}]: Completed by other writer", globalAddress); } } }</code><technical_language>this, please correct typo in 'propagate' in catch clause.</technical_language>

Target:
private void propagate(RuntimeLayout runtimeLayout, long globalAddress, @Nullable ILogData data) { int numUnits = runtimeLayout.getLayout().getSegmentLength(globalAddress); for (int i = 1; i < numUnits; i++) { log.trace("Propagate[{}]: chain {}/{}", Token.of(runtimeLayout.getLayout().getEpoch(), globalAddress), i + 1, numUnits); try { if (data != null) { CFUtils.getUninterruptibly( runtimeLayout.getLogUnitClient(globalAddress, i) .write(data), OverwriteException.class); } else { Token token = new Token(runtimeLayout.getLayout().getEpoch(), globalAddress); CFUtils.getUninterruptibly(runtimeLayout .getLogUnitClient(globalAddress, i) .fillHole(token), OverwriteException.class); } } catch (OverwriteException oe) { log.info("Propagate[{}]: Completed by other writer", globalAddress); } } }
Source:
<code>public Response add(GlusterVolume volume) { validateParameters(volume, "name", "volumeType", "glusterBricks"); <START> <END> GlusterVolumeEntity volumeEntity = getMapper(GlusterVolume.class, GlusterVolumeEntity.class).map(volume, null); volumeEntity.setClusterId(asGuid(clusterId)); return performCreation(VdcActionType.CreateGlusterVolume, new CreateGlusterVolumeParameters(volumeEntity), new QueryIdResolver(VdcQueryType.GetGlusterVolumeById, GetGlusterVolumeByIdQueryParameters.class), true); }</code><technical_language>Gluster Bricks business entities, added in context: .../volumes/{volume:id}/bricks (not here, is): .../volumes/{volume:id} verify user passed bricks; in fact user pass bricks in this context. This raises question of create, temporarily, a volume bricks, add bricks it. Basically, creating 'empty' volume. debate for Quotas - a Quota limitations. limitations business-entities in right, a Quota limitation is meaningless. eventually decided creating 'empty' quota, adding limitations afterwards, is legal. Do decision here</technical_language>

Target:
public Response add(GlusterVolume volume) { validateParameters(volume, "name", "volumeType", "bricks"); GlusterVolumeEntity volumeEntity = getMapper(GlusterVolume.class, GlusterVolumeEntity.class).map(volume, null); volumeEntity.setClusterId(asGuid(cluster.getId())); mapBricks(volume, volumeEntity); return performCreation(VdcActionType.CreateGlusterVolume, new CreateGlusterVolumeParameters(volumeEntity), new QueryIdResolver(VdcQueryType.GetGlusterVolumeById, GetGlusterVolumeByIdQueryParameters.class), true); }
Source:
<code>public void setAttributesAsText(Object element, String text) { Descriptor descriptor = mDescriptorMap.get(element.getClass()); <START> if (descriptor != null && descriptor instanceof TextViewDescriptor) { <END> TextViewDescriptor textViewDescriptor = (TextViewDescriptor) descriptor; textViewDescriptor.setAttributeAsText((TextView) element, text); } }</code><technical_language>This code this forwarded a method NodeDescriptor. making a trip time need add setAttributeAsText() support for new type. This entails adding a pair of methods ChainedDescriptor (it's a pretty straightforward pattern there)</technical_language>

Target:
public void setAttributesAsText(Object element, String text) { verifyThreadAccess(); Descriptor descriptor = mDescriptorMap.get(element.getClass()); if (descriptor != null) { descriptor.setAttributesAsText(element, text); } }
Source:
<code>public static ExchangeException adapt(LatokenException e) { String message = e.getMessage(); if (StringUtils.isEmpty(message)) { message = "Operation failed without any error message"; } switch (e.getHttpStatusCode()) { case HttpURLConnection.HTTP_BAD_REQUEST: <START> case HttpURLConnection.HTTP_UNAUTHORIZED: END> return new ExchangeException(message, e); case 428: return new RateLimitExceededException(message, e); } return new ExchangeException(message, e); }</code><technical_language>ExchangeSecurityException for 401</technical_language>

Target:
public static ExchangeException adapt(LatokenException e) { String message = e.getMessage(); if (StringUtils.isEmpty(message)) { message = "Operation failed without any error message"; } switch (e.getHttpStatusCode()) { case HttpURLConnection.HTTP_BAD_REQUEST: return new ExchangeException(message, e); case HttpURLConnection.HTTP_UNAUTHORIZED: return new ExchangeSecurityException(message, e); case 428: return new RateLimitExceededException(message, e); } return new ExchangeException(message, e); }
Source:
<code>public ZonedNanoTimeStamp(long epoch_millis, ZoneId zone) { if (zone == null) { throw new IllegalArgumentException("Zone cannot be null."); } timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(epoch_millis), zone); <START> epoch = Instant.from(timestamp).getEpochSecond(); <END> nanos = Instant.from(timestamp).getNano(); }</code><technical_language>do millisec/1000 minimize garbage. Instant.from(timestamp) create a new object of Instant time. In fact for current code. for more for nano</technical_language>

Target:
public ZonedNanoTimeStamp(long epoch_millis, ZoneId zone) { if (zone == null) { throw new IllegalArgumentException("Zone cannot be null."); } timestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(epoch_millis), zone); epoch = timestamp.toEpochSecond(); nanos = timestamp.getNano(); }
Source:
<code>public void testFetchWithBlobNoneFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( server2)) { RevBlob blob1 = remote2.blob("foobar"); RevBlob blob2 = remote2.blob("fooba"); RevTree tree = remote2.tree(remote2.file("1", blob1), remote2.file("2", blob2)); RevCommit commit = remote2.commit(tree); remote2.update("master", commit); server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { @Override public UploadPack create(Object req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { UploadPack up = new UploadPack(db); return up; } }, null); uri = testProtocol.register(ctx, server2); try (Transport tn = testProtocol.open(uri, client, "server2")) { <START> tn.setFilterSpec(FilterSpec.withBlobLimit((0))); <END> tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(commit.name()))); assertTrue(client.getObjectDatabase().has(tree.toObjectId())); assertFalse(client.getObjectDatabase().has(blob1.toObjectId())); assertFalse(client.getObjectDatabase().has(blob2.toObjectId())); } } }</code><technical_language>nit: set of parens</technical_language>

Target:
public void testFetchWithBlobNoneFilter() throws Exception { InMemoryRepository server2 = newRepo("server2"); try (TestRepository<InMemoryRepository> remote2 = new TestRepository<>( server2)) { RevBlob blob1 = remote2.blob("foobar"); RevBlob blob2 = remote2.blob("fooba"); RevTree tree = remote2.tree(remote2.file("1", blob1), remote2.file("2", blob2)); RevCommit commit = remote2.commit(tree); remote2.update("master", commit); server2.getConfig().setBoolean("uploadpack", null, "allowfilter", true); testProtocol = new TestProtocol<>(new UploadPackFactory<Object>() { @Override public UploadPack create(Object req, Repository db) throws ServiceNotEnabledException, ServiceNotAuthorizedException { UploadPack up = new UploadPack(db); return up; } }, null); uri = testProtocol.register(ctx, server2); try (Transport tn = testProtocol.open(uri, client, "server2")) { tn.setFilterSpec(FilterSpec.withBlobLimit(0)); tn.fetch(NullProgressMonitor.INSTANCE, Collections.singletonList(new RefSpec(commit.name()))); assertTrue(client.getObjectDatabase().has(tree.toObjectId())); assertFalse(client.getObjectDatabase().has(blob1.toObjectId())); assertFalse(client.getObjectDatabase().has(blob2.toObjectId())); } } }
Source:
<code>public void onReceive(final Object o) throws Exception { String eventTypeForLogging = "unknown"; Optional<String> uriForLogging = Optional.empty(); try { if (o instanceof NeedEvent) { eventTypeForLogging = "NeedEvent"; NeedEvent needEvent = (NeedEvent) o; uriForLogging = Optional.ofNullable(needEvent.getUri()); if (needEvent.getEventType().equals(NeedEvent.TYPE.ACTIVE)) { processActiveNeedEvent(needEvent); } else if (needEvent.getEventType().equals(NeedEvent.TYPE.INACTIVE)) { processInactiveNeedEvent(needEvent); } else { unhandled(o); } } else if (o instanceof BulkNeedEvent) { eventTypeForLogging = "BulkNeedEvent"; log.info("received bulk need event, processing need events ...", ((BulkNeedEvent) o).getNeedEvents().size()); for (NeedEvent event : ((BulkNeedEvent) o).getNeedEvents()) { processActiveNeedEvent(event); } } else { eventTypeForLogging = "unhandled"; unhandled(o); } } catch (Exception e) { log.info(String.format("Caught exception when processing %s event %s. More info on loglevel 'debug'", eventTypeForLogging, uriForLogging.orElse("[no uri available]"))); log.debug("caught exception", e); <START> e.printStackTrace(); <END> } }</code><technical_language>this needs removed merge</technical_language>

Target:
public void onReceive(final Object o) throws Exception { String eventTypeForLogging = "unknown"; Optional<String> uriForLogging = Optional.empty(); try { if (o instanceof NeedEvent) { eventTypeForLogging = "NeedEvent"; NeedEvent needEvent = (NeedEvent) o; uriForLogging = Optional.ofNullable(needEvent.getUri()); if (needEvent.getEventType().equals(NeedEvent.TYPE.ACTIVE)) { processActiveNeedEvent(needEvent); } else if (needEvent.getEventType().equals(NeedEvent.TYPE.INACTIVE)) { processInactiveNeedEvent(needEvent); } else { unhandled(o); } } else if (o instanceof BulkNeedEvent) { eventTypeForLogging = "BulkNeedEvent"; log.info("received bulk need event, processing need events ...", ((BulkNeedEvent) o).getNeedEvents().size()); for (NeedEvent event : ((BulkNeedEvent) o).getNeedEvents()) { processActiveNeedEvent(event); } } else { eventTypeForLogging = "unhandled"; unhandled(o); } } catch (Exception e) { log.info(String.format("Caught exception when processing %s event %s. More info on loglevel 'debug'", eventTypeForLogging, uriForLogging.orElse("[no uri available]"))); log.debug("caught exception", e); if(log.isDebugEnabled()){ e.printStackTrace(); } } }
Source:
<code>public void onConnect(String room, String serverAddress) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); <START> lastServerPreferences.saveLastConnectedServer(serverAddress); <END> joinHangoutRoom(room); }</code><technical_language>is this a temporary hack? : I saving state View, I do of model (looks called a service in case). i.e. of humanTelepresenceService.connectTo(serverAddress) compose humanTelepresenceService of SharedPreferences/LongtermStorage</technical_language>

Target:
public void onConnect(String room, String serverAddress) { debugView.showPermanently(getString(R.string.connected)); switchableView.setDisplayedChild(1); joinHangoutRoom(room); }
Source:
<code><START> private Observable<ContentProviderOperation> createOperation(@NonNull final U item, @NonNull final Uri uri) { <END> return Observable .fromCallable(() -> { try { locker.acquire(uri); Log.v(TAG, "Locked URI " + uri); } catch (InterruptedException e) { Log.e(TAG, "Thread interrupted", e); return NO_OPERATION; } final Cursor cursor = contentResolver.query(uri, getProjection(), null, null, null); U newItem = item; if (cursor == null || !cursor.moveToFirst()) { if (cursor != null) { cursor.close(); } Log.v(TAG, "Create insertion operation for " + uri); return ContentProviderOperation.newInsert(uri) .withValues(getContentValuesForItem(newItem)) .build(); } final U currentItem = read(cursor); boolean valuesEqual = newItem.equals(currentItem); if (!valuesEqual) { Log.v(TAG, "Merging values at " + uri); newItem = mergeValues(currentItem, newItem); valuesEqual = newItem.equals(currentItem); } cursor.close(); if (valuesEqual) { Log.v(TAG, "Data already up to date at " + uri); locker.release(uri); return NO_OPERATION; } Log.v(TAG, "Create update operation for " + uri); return ContentProviderOperation.newUpdate(uri) .withValues(getContentValuesForItem(newItem)) .build(); }) .filter(operation -> !NO_OPERATION.equals(operation)) .subscribeOn(Schedulers.io()); }</code><technical_language>This is loong method</technical_language>

Target:
private Observable<ContentProviderOperation> createOperation(@NonNull final U item, @NonNull final Uri uri) { return Observable .fromCallable(() -> { locker.acquire(uri); final Cursor cursor = contentResolver.query(uri, getProjection(), null, null, null); if (cursor == null || !cursor.moveToFirst()) { if (cursor != null) { cursor.close(); } Log.v(TAG, "Create insertion operation for " + uri); return ContentProviderOperation.newInsert(uri) .withValues(getContentValuesForItem(item)) .build(); } final U currentItem = read(cursor); final U newItem = mergedItem(currentItem, item); cursor.close(); if (!newItem.equals(currentItem)) { Log.v(TAG, "Create update operation for " + uri); return ContentProviderOperation.newUpdate(uri) .withValues(getContentValuesForItem(newItem)) .build(); } Log.v(TAG, "Data already up to date at " + uri); return NO_OPERATION; }) .onErrorReturn(e -> NO_OPERATION) .doOnNext(operation -> releaseIfNoOp(operation, uri)) .filter(ContentProviderStoreCoreBase::isValidOperation); }
Source:
<code>public Attribute getAttribute(PerunSession sess, Member member, Group group, String attributeName) throws InternalErrorException, AttributeNotExistsException { try { <START> return jdbc.queryForObject("select " + getAttributeMappingSelectQuery("mem") + " from attr_names " + <END> "left join member_group_attr_values mem on id=mem.attr_id and mem.group_id=? and member_id=? " + "where attr_name=?", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), attributeName); } catch(EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute name: \"" + attributeName +"\"", ex); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }</code><technical_language>problem name above</technical_language>

Target:
public Attribute getAttribute(PerunSession sess, Member member, Group group, String attributeName) throws InternalErrorException, AttributeNotExistsException { try { return jdbc.queryForObject("select " + getAttributeMappingSelectQuery("mem_gr") + " from attr_names " + "left join member_group_attr_values mem_gr on id=mem_gr.attr_id and mem_gr.group_id=? and member_id=? " + "where attr_name=?", new AttributeRowMapper(sess, this, null), group.getId(), member.getId(), attributeName); } catch(EmptyResultDataAccessException ex) { throw new AttributeNotExistsException("Attribute name: \"" + attributeName +"\"", ex); } catch(RuntimeException ex) { throw new InternalErrorException(ex); } }
Source:
<code>private void pop() <START> { <END> assert !_stack.isEmpty() : "Trying to pop empty stack"; DataComplex tmp = _stack.pop(); if (tmp instanceof DataMapBuilder) { tmp = ((DataMapBuilder) tmp).convertToDataMap(); } if (_stack.isEmpty()) { _result = (T) tmp; _expectedTokens = NONE; } else { _isCurrList = _stack.peek() instanceof DataList; if (!_isCurrList) { _currField = _currFieldStack.pop(); } addValue(tmp); updateExpected(); } }</code><technical_language>This protected. Protobuf for example do this more efficiently DataMapBuilder is a length prefixed encoding format</technical_language>

Target:
private void pop() { assert !_stack.isEmpty() : "Trying to pop empty stack"; DataComplex tmp = _stack.pop(); tmp = postProcessDataComplex(tmp); if (_stack.isEmpty()) { _result = (T) tmp; _expectedTokens = NONE; } else { _isCurrList = _stack.peek() instanceof DataList; if (!_isCurrList) { _currField = _currFieldStack.pop(); } addValue(tmp); updateExpected(); } }
Source:
<code>public void replaceInvalidEmptyStringMacAddressesWithNull(List<VmNetworkInterface> vmNetworkInterfaces) { vmNetworkInterfaces.stream() <START> .filter(this::hasEmptyStringMacAddress) <END> .forEach(e->e.setMacAddress(null)); }</code><technical_language>easier StringUtils.isEmpty()? .filter(e -> StringUtils.isEmpty(e.getMacAddress())</technical_language>

Target:
public void replaceInvalidEmptyStringMacAddressesWithNull(List<VmNetworkInterface> vmNetworkInterfaces) { vmNetworkInterfaces.stream() .filter((vmNetworkInterface) -> StringUtils.isEmpty(vmNetworkInterface.getMacAddress())) .forEach(e->e.setMacAddress(null)); }
Source:
<code>public ExtendedUserData(User user, PermissionsInterface authorizer) { Hibernate.initialize(user.getEntries()); try { this.canChangeUsername = user.getEntries().stream().noneMatch(Entry::getIsPublished) && !authorizer.isSharing(user) && user.getOrganizations().size() == 0; } catch (Exception e) { <START> LOG.error("SAM is improperly configured."); <END> this.canChangeUsername = false; } }</code><technical_language>Log exception a param</technical_language>

Target:
public ExtendedUserData(User user, PermissionsInterface authorizer) { Hibernate.initialize(user.getEntries()); try { this.canChangeUsername = user.getEntries().stream().noneMatch(Entry::getIsPublished) && !authorizer.isSharing(user) && user.getOrganizations().size() == 0; } catch (Exception e) { LOG.error("SAM is improperly configured.", e); this.canChangeUsername = false; } }
Source:
<code>private static STRtree buildRTree(LongArrayList addresses, List<List<Block>> channels, int geometryChannel, Optional<Integer> radiusChannel, Optional<Integer> partitionChannel) { STRtree rtree = new STRtree(); Operator relateOperator = OperatorFactoryLocal.getInstance().getOperator(Operator.Type.Relate); for (int position = 0; position < addresses.size(); position++) { long pageAddress = addresses.getLong(position); int blockIndex = decodeSliceIndex(pageAddress); int blockPosition = decodePosition(pageAddress); Block block = channels.get(geometryChannel).get(blockIndex); if (block.isNull(blockPosition)) { continue; } Slice slice = block.getSlice(blockPosition, 0, block.getSliceLength(blockPosition)); OGCGeometry ogcGeometry = deserialize(slice); verify(ogcGeometry != null); if (ogcGeometry.isEmpty()) { continue; } double radius = radiusChannel.map(channel -> DOUBLE.getDouble(channels.get(channel).get(blockIndex), blockPosition)).orElse(0.0); if (radius < 0) { continue; } if (!radiusChannel.isPresent()) { accelerateGeometry(ogcGeometry, relateOperator); } int partition = -1; if (partitionChannel.isPresent()) { Block partitionBlock = channels.get(partitionChannel.get()).get(blockIndex); partition = toIntExact(INTEGER.getLong(partitionBlock, blockPosition)); } <START> rtree.insert(GeometryUtils.getJtsEnvelope(ogcGeometry, radius), new GeometryWithPosition(ogcGeometry, partition, position)); <END> } rtree.build(); return rtree; }</code><technical_language>I add empty envelopes R-Tree. match anyway</technical_language>

Target:
private static STRtree buildRTree(LongArrayList addresses, List<List<Block>> channels, int geometryChannel, Optional<Integer> radiusChannel, Optional<Integer> partitionChannel) { STRtree rtree = new STRtree(); Operator relateOperator = OperatorFactoryLocal.getInstance().getOperator(Operator.Type.Relate); for (int position = 0; position < addresses.size(); position++) { long pageAddress = addresses.getLong(position); int blockIndex = decodeSliceIndex(pageAddress); int blockPosition = decodePosition(pageAddress); Block block = channels.get(geometryChannel).get(blockIndex); if (block.isNull(blockPosition)) { continue; } Slice slice = block.getSlice(blockPosition, 0, block.getSliceLength(blockPosition)); OGCGeometry ogcGeometry = deserialize(slice); verify(ogcGeometry != null); if (ogcGeometry.isEmpty()) { continue; } double radius = radiusChannel.map(channel -> DOUBLE.getDouble(channels.get(channel).get(blockIndex), blockPosition)).orElse(0.0); if (radius < 0) { continue; } if (!radiusChannel.isPresent()) { accelerateGeometry(ogcGeometry, relateOperator); } int partition = -1; if (partitionChannel.isPresent()) { Block partitionBlock = channels.get(partitionChannel.get()).get(blockIndex); partition = toIntExact(INTEGER.getLong(partitionBlock, blockPosition)); } rtree.insert(getJtsEnvelope(ogcGeometry, radius), new GeometryWithPosition(ogcGeometry, partition, position)); } rtree.build(); return rtree; }
Source:
<code>public IntegrationFlow inTcpGateway() { return IntegrationFlows.from(Tcp.inboundGateway(server1())) <START> .transform(new ObjectToStringTransformer()) <END> .<String, String>transform(String::toUpperCase) .get(); }</code><technical_language>pick. Transformers factory</technical_language>

Target:
public IntegrationFlow inTcpGateway() { return IntegrationFlows.from(Tcp.inboundGateway(server1())) .transform(Transformers.objectToString()) .<String, String>transform(String::toUpperCase) .get(); }
Source:
<code>private void validateAnswer(Context context) { <START> if (!isClicked) { <END> isClicked = true; try { Phone phone = new Phone(mCustomEditText.getText().toString()); hideKeyboard(mCustomEditText); Validation.getInstance().removeInputError(mCustomEditText); String value = phone.getValue(); notifyAnswerChanged(value); } catch (InvalidPhoneException e) { Validation.getInstance().addinvalidInput(mCustomEditText, context.getString(R.string.dynamic_error_phone_format)); mCustomEditText.setError(context.getString(R.string.dynamic_error_phone_format)); } isClicked = false; } }</code><technical_language>@idelcano applied solution for avoid multiclick generates duplicate code for QuestionView, in more generic solution</technical_language>

Target:
public void validateAnswer(Context context) { try { Phone phone = new Phone(mCustomEditText.getText().toString()); hideKeyboard(mCustomEditText); Validation.getInstance().removeInputError(mCustomEditText); String value = phone.getValue(); notifyAnswerChanged(value); } catch (InvalidPhoneException e) { Validation.getInstance().addinvalidInput(mCustomEditText, context.getString(R.string.dynamic_error_phone_format)); mCustomEditText.setError(context.getString(R.string.dynamic_error_phone_format)); } }
Source:
<code>public static final boolean isStorageWritable() { <START> return Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED; <END> }</code><technical_language>This imho implemented equals comparing Strings null safe I suggest: return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());</technical_language>

Target:
public static final boolean isStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
<code>Object convertSingle(Object value) { if (typeSystem.supportsAsNativeType(value.getClass())) { return typeSystem.getMappedToNativeTypeAdapter(value.getClass()).apply(value); } else { <START> Map<String, Object> help = convertParameters(Collections.singletonMap("u", value)); <END> return help.get("u"); } }</code><technical_language>suggestion String fixedKey = "u"; return convertParameters(Collections.singletonMap(fixedKey, value)).get(fixedKey);</technical_language>

Target:
private Object convertSingle(Object value) { if (typeSystem.supportsAsNativeType(value.getClass())) { return typeSystem.getMappedToNativeTypeAdapter(value.getClass()).apply(value); } else { String fixedKey = "u"; return convertParameters(Collections.singletonMap(fixedKey, value)).get(fixedKey); } }
Source:
<code>public void show(CollectedDataNode node) { FileDialog fileDialog = new FileDialog(getDisplay().getActiveShell(), SWT.SAVE); <START> fileDialog.setText("Save"); <END> fileDialog.setFilterPath("C:/"); String[] filterExt = { "*.txt", "*.doc", ".rtf", "*.*" }; fileDialog.setFilterExtensions(filterExt); String selected = fileDialog.open(); if (selected != null && selected.length() > 0) { PlotDataParser parser = new PlotDataParser(node); DataParserResult result = parser.parseEntries(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); String data = gson.toJson(result); try (Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(selected), "UTF-8"))) { writer.write(data); } catch (IOException e) { e.printStackTrace(); } } }</code><technical_language>Export JSON</technical_language>

Target:
public void show(CollectedDataNode node) { FileDialog fileDialog = new FileDialog(getDisplay().getActiveShell(), SWT.SAVE); fileDialog.setText("Export to JSON"); String[] filter = { "*.json", "*.*" }; fileDialog.setFilterExtensions(filter); String fileName = fileDialog.open(); if (fileName != null && fileName.length() > 0) { PlotDataParser parser = new PlotDataParser(node); DataParserResult result = parser.parseEntries(); List<PlotItem> dataset = result.dataset; Gson gson = new GsonBuilder().setPrettyPrinting().create(); String data = gson.toJson(dataset); try (Writer writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))) { writer.write(data); } catch (IOException e) { e.printStackTrace(); } } }
Source:
<code>protected void getTopicList() { if (getTopicListTask != null) { getTopicListTask.cancel(true); } getTopicListTask = new GetTopicListTask(getActivity(), courseData.getCourse().getId()) { @Override public void onSuccess(CourseTopics courseTopics) { final ArrayList<DiscussionTopic> allTopics = new ArrayList<>(); allTopics.addAll(courseTopics.getNonCoursewareTopics()); allTopics.addAll(courseTopics.getCoursewareTopics()); final TopicSpinnerAdapter adapter = new TopicSpinnerAdapter(container.getContext(), DiscussionTopicDepth.createFromDiscussionTopics(allTopics)); topicsSpinner.setAdapter(adapter); { if (!discussionTopic.isAllType() && !discussionTopic.isFollowingType()) { int selectedTopicIndex; if (discussionTopic.getIdentifier() == null) { <START> selectedTopicIndex = adapter.getPosition(discussionTopic.getChildren().get(0)); <END> } else { selectedTopicIndex = adapter.getPosition(discussionTopic); } if (selectedTopicIndex >= 0) { topicsSpinner.setSelection(selectedTopicIndex); } } } } @Override public void onException(Exception ex) { logger.error(ex); } }; getTopicListTask.setMessageCallback(null); getTopicListTask.execute(); }</code><technical_language>need a non-empty check children here; if select top-level topics, fallback default</technical_language>

Target:
protected void getTopicList() { if (getTopicListTask != null) { getTopicListTask.cancel(true); } getTopicListTask = new GetTopicListTask(getActivity(), courseData.getCourse().getId()) { @Override public void onSuccess(CourseTopics courseTopics) { final ArrayList<DiscussionTopic> allTopics = new ArrayList<>(); allTopics.addAll(courseTopics.getNonCoursewareTopics()); allTopics.addAll(courseTopics.getCoursewareTopics()); final TopicSpinnerAdapter adapter = new TopicSpinnerAdapter(container.getContext(), DiscussionTopicDepth.createFromDiscussionTopics(allTopics)); topicsSpinner.setAdapter(adapter); { if (!discussionTopic.isAllType() && !discussionTopic.isFollowingType()) { int selectedTopicIndex = -1; if (discussionTopic.getIdentifier() == null) { if (!discussionTopic.getChildren().isEmpty()) { selectedTopicIndex = adapter.getPosition(discussionTopic.getChildren().get(0)); } } else { selectedTopicIndex = adapter.getPosition(discussionTopic); } if (selectedTopicIndex >= 0) { topicsSpinner.setSelection(selectedTopicIndex); } } } } @Override public void onException(Exception ex) { logger.error(ex); } }; getTopicListTask.setMessageCallback(null); getTopicListTask.execute(); }
Source:
<code>public String toString() { <START> return id + ": " + msg; <END> }</code><technical_language>Instead of message, evaluate topic generate a good string message</technical_language>

Target:
public String toString() { if (getTopic() .equals(ExtensionEventFactory.buildTopic(ExtensionEventFactory.EXTENSION_INSTALLED_EVENT_TOPIC, id))) { return "Extension '" + id + "' has been installed."; } else if (getTopic().equals( ExtensionEventFactory.buildTopic(ExtensionEventFactory.EXTENSION_UNINSTALLED_EVENT_TOPIC, id))) { return "Extension '" + id + "' has been uninstalled."; } else { return id + ": " + (msg != null ? msg : "Operation failed."); } }
Source:
<code>public Object[] transform(String sourceData) throws FormatException { if (sourceData == null) { return null; } <START> Tokenizer tokenizer = new Tokenizer(new StringReader(sourceData), m_csvPreference, m_strictquotes, m_escape, <END> DEFAULT_COLUMN_LIMIT_SIZE, 0); CsvListReader csvReader = new CsvListReader(tokenizer, m_csvPreference); List<String> dataList; try { dataList = csvReader.read(); } catch (IOException | SuperCsvException e) { throw new FormatException("Fail to parse csv data", e); } finally { try { if (csvReader != null) csvReader.close(); } catch (IOException e) { throw new FormatException(e); } } String[] data = dataList.toArray(new String[0]); normalize(data); return data; }</code><technical_language>discussed reusing objects reinstantiating for row, I showed a couple approaches</technical_language>

Target:
public Object[] transform(String sourceData) throws FormatException { try { Object list[] = m_parser.parseLine(sourceData); if (list != null) { for (int i = 0; i < list.length; i++) { if ("NULL".equals(list[i]) || Constants.CSV_NULL.equals(list[i]) || Constants.QUOTED_CSV_NULL.equals(list[i])) { list[i] = null; } } } return list; } catch (IOException e) { throw new FormatException("failed to format " + sourceData, e); } }
Source:
<code>static void validateFile( OrcWriteValidation writeValidation, OrcDataSource input, List<Type> types, DateTimeZone hiveStorageTimeZone, OrcEncoding orcEncoding, OrcReaderOptions orcReaderOptions) throws OrcCorruptionException { ImmutableMap.Builder<Integer, Type> readTypes = ImmutableMap.builder(); for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) { readTypes.put(columnIndex, types.get(columnIndex)); } try { OrcReader orcReader = new OrcReader( input, orcEncoding, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), Optional.of(writeValidation), orcReaderOptions, false, new NoopOrcAggregatedMemoryContext()); try (OrcBatchRecordReader orcRecordReader = orcReader.createBatchRecordReader( readTypes.build(), OrcPredicate.TRUE, hiveStorageTimeZone, <START> new NoopOrcAggregatedMemoryContext(), <END> INITIAL_BATCH_SIZE)) { while (orcRecordReader.nextBatch() >= 0) { } } } catch (IOException e) { throw new OrcCorruptionException(e, input.getId(), "Validation failed"); } }</code><technical_language>a static final variable in class NoopOrcAggregatedMemoryContext "new" time</technical_language>

Target:
static void validateFile( OrcWriteValidation writeValidation, OrcDataSource input, List<Type> types, DateTimeZone hiveStorageTimeZone, OrcEncoding orcEncoding, OrcReaderOptions orcReaderOptions) throws OrcCorruptionException { ImmutableMap.Builder<Integer, Type> readTypes = ImmutableMap.builder(); for (int columnIndex = 0; columnIndex < types.size(); columnIndex++) { readTypes.put(columnIndex, types.get(columnIndex)); } try { OrcReader orcReader = new OrcReader( input, orcEncoding, new StorageOrcFileTailSource(), new StorageStripeMetadataSource(), Optional.of(writeValidation), NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, orcReaderOptions, false); try (OrcBatchRecordReader orcRecordReader = orcReader.createBatchRecordReader( readTypes.build(), OrcPredicate.TRUE, hiveStorageTimeZone, NOOP_ORC_AGGREGATED_MEMORY_CONTEXT, INITIAL_BATCH_SIZE)) { while (orcRecordReader.nextBatch() >= 0) { } } } catch (IOException e) { throw new OrcCorruptionException(e, input.getId(), "Validation failed"); } }
Source:
<code>public StreamsDatum(Object document, String id, DateTime timestamp) { <START> this(document, id, timestamp, null); <END> }</code><technical_language>If this is calling constructor line 66, passing null for metadata is inconstant empty hash in constructors 34 38</technical_language>

Target:
public StreamsDatum(Object document, String id, DateTime timestamp) { this(document, id, timestamp, null, new HashMap<String, Object>()); }
Source:
<code>private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(MeterReadsGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessagesResponse.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(FaultResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(AlarmRegister.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(AdministrativeStatusTypeResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainerGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(GetAttributeValuesResponse.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(FirmwareVersionResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(UpdateFirmwareResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(AssociationLnObjectsResponseData.class, this.adhocMapper); <START> CLASS_TO_MAPPER_MAP.put(GetConfigurationObjectResponse.class, this.configurationMapper); <END> CLASS_TO_MAPPER_MAP.put(ProfileGenericDataResponse.class, this.monitoringMapper); }</code><technical_language>longer a custom converter, this line is superfluous</technical_language>

Target:
private void postConstruct() { CLASS_TO_MAPPER_MAP.put(MeterReads.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(MeterReadsGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(EventMessagesResponse.class, this.managementMapper); CLASS_TO_MAPPER_MAP.put(ActionResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(FaultResponse.class, this.commonMapper); CLASS_TO_MAPPER_MAP.put(AlarmRegister.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(AdministrativeStatusTypeResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainer.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(PeriodicMeterReadsContainerGas.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(GetAttributeValuesResponse.class, this.monitoringMapper); CLASS_TO_MAPPER_MAP.put(FirmwareVersionResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(UpdateFirmwareResponse.class, this.configurationMapper); CLASS_TO_MAPPER_MAP.put(AssociationLnObjectsResponseData.class, this.adhocMapper); CLASS_TO_MAPPER_MAP.put(ProfileGenericDataResponse.class, this.monitoringMapper); }
Source:
<code>public String computeNewVersionRange(String originalVersionRange, String originalReferencedVersion, String newReferencedVersion) { if (originalVersionRange == null) { return null; } VersionRange referencingVersionRange = VersionRange.valueOf(originalVersionRange); Version referencedVersion = parseBaseVersion(originalReferencedVersion); Version referencedNewVersion = parseBaseVersion(newReferencedVersion); <START> referencingVersionRange = <END> computeNewVersionRange(referencingVersionRange, referencedVersion, referencedNewVersion); return referencingVersionRange.toString(); }</code><technical_language>reusing variable a bit confusing me. creating a new versionRange object declare a new local variable "newVersionRange" ? this name "(old/original)VersionRange" "newVersionRange"</technical_language>

Target:
public String computeNewVersionRange(String originalVersionRange, String originalReferencedVersion, String newReferencedVersion) { if (originalVersionRange == null) { return null; } VersionRange originalVersionRangeObject = VersionRange.valueOf(originalVersionRange); Version originalReferencedVersionObject = parseBaseVersion(originalReferencedVersion); Version newReferencedVersionObject = parseBaseVersion(newReferencedVersion); VersionRange newVersionRangeObject = computeNewVersionRange(originalVersionRangeObject, originalReferencedVersionObject, newReferencedVersionObject); return newVersionRangeObject.toString(); }
Source:
<code>public void verifySuggestVideoOrArticleButtonNotClickable() { waitForElementByElement(submitButton); waitForElementNotClickableByElement(submitButton); <START> PageObjectLogging.log("VerifySuggestVideoOrArticleButtonNotClickable", "Verify that 'Suggest Video' or 'Article' submit button button is disabled", true); <END> }</code><technical_language>1. line shorter, 2. methods name changed, change parameter Verify verify</technical_language>

Target:
public void verifySuggestVideoOrArticleButtonNotClickable() { waitForElementByElement(submitButton); waitForElementNotClickableByElement(submitButton); PageObjectLogging.log( "verifySuggestVideoOrArticleButtonNotClickable", "Verify that 'Suggest Video' or 'Article' submit button button is disabled", true ); }
Source:
<code>public static IThreadDMData getThreadData(final int threadId) throws InterruptedException, ExecutionException, TimeoutException { final AsyncCompletionWaitor wait = new AsyncCompletionWaitor(); final DataRequestMonitor<IThreadDMData> rm = new DataRequestMonitor<IThreadDMData>( fSession.getExecutor(), null) { @Override protected void handleCompleted() { if (isSuccess()) { wait.setReturnInfo(getData()); } wait.waitFinished(getStatus()); } }; final IProcessDMContext processContext = DMContexts.getAncestorOfType( SyncUtil.getContainerContext(), IProcessDMContext.class); fProcessesService.getExecutor().submit(new Runnable() { @Override public void run() { IThreadDMContext threadDmc = fProcessesService .createThreadContext(processContext, Integer.toString(threadId)); fProcessesService.getExecutionData(threadDmc, rm); } }); wait.waitUntilDone(TestsPlugin.massageTimeout(2000)); assertTrue(wait.getMessage(), wait.isOK()); IThreadDMData threadData = (IThreadDMData) wait.getReturnInfo(); Assert.assertNotNull("Thread data not returned for thread id = " + threadId, threadData); wait.waitReset(); return threadData; <START> } <END></code><technical_language>this is a new method a simpler waitor. a Query instead, this is safe this context worry hanging UI thread tests. method example: i.e. getFrameData</technical_language>

Target:
public static IThreadDMData getThreadData(final int threadId) throws InterruptedException, ExecutionException, TimeoutException { final IProcessDMContext processContext = DMContexts.getAncestorOfType( SyncUtil.getContainerContext(), IProcessDMContext.class); Query<IThreadDMData> query = new Query<IThreadDMData>() { @Override protected void execute(DataRequestMonitor<IThreadDMData> rm) { IThreadDMContext threadDmc = fProcessesService .createThreadContext(processContext, Integer.toString(threadId)); fProcessesService.getExecutionData(threadDmc, rm); } }; fSession.getExecutor().execute(query); return query.get(500, TimeUnit.MILLISECONDS); }
Source:
<code>public String toString() { if (isError()) { return "Error <START> AcessToken <END> [error=" + error + ", error_description=" + errorDescription + ", error_uri=" + errorUri + "]"; } else { return "AccessToken [access_token=" + accessToken + ", token_type=" + tokenType + "]"; } }</code><technical_language>Access</technical_language>

Target:
public String toString() { if (isError()) { return "Error AccessToken [error=" + error + ", error_description=" + errorDescription + ", error_uri=" + errorUri + "]"; } else { return "AccessToken [access_token=" + accessToken + ", token_type=" + tokenType + "]"; } }
Source:
<code>public Collection<String> getNames() { <START> return Collections.unmodifiableSet(names); <END> }</code><technical_language>This calculated invocation instead of unconditionally allocating a HashSet for for statement</technical_language>

Target:
public Collection<String> getNames() { final Set<String> names = new HashSet<>(named.keySet()); namedArgumentFinder.forEach(args -> names.addAll(args.getNames())); return Collections.unmodifiableSet(names); }
Source:
<code><START> public ConstraintBasedAlgorithm(List<HardConstraint> hardConstraints, <END> List<SoftConstraint> softConstraints, SoftConstraintWeightModel softConstraintWeightModel) { _hardConstraints = hardConstraints; _softConstraints = softConstraints; _softConstraintsWeightModel = softConstraintWeightModel; }</code><technical_language>If factory, allow another caller construct algorithm instance, right? protect, please</technical_language>

Target:
ConstraintBasedAlgorithm(List<HardConstraint> hardConstraints, List<SoftConstraint> softConstraints, SoftConstraintWeightModel softConstraintWeightModel) { _hardConstraints = hardConstraints; _softConstraints = softConstraints; _softConstraintsWeightModel = softConstraintWeightModel; }
Source:
<code>public String ensureIndexed(List<Object> fieldNames, String indexName) { <START> return IndexCreator.ensureIndexed(Index.setUp(fieldNames, indexName), <END> database, datastore, queue); }</code><technical_language>setUp creates Index object setting index itself. Is this class method -> instance of object pattern typically name setUp? E.g., in objc convention of [Index indexNamed:indexName forFields:fieldNames] -- is a convention Index.indexFor(fieldNames, indexName) for Java</technical_language>

Target:
public String ensureIndexed(List<Object> fieldNames, String indexName) { return IndexCreator.ensureIndexed(Index.getInstance(fieldNames, indexName), database, datastore, queue); }
Source:
<code>protected TickRateModulation doBusWork() { if( !this.canDoBusWork() ) { return TickRateModulation.IDLE; } final TileEntity te = this.getConnectedTE(); if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ) ) { try { final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ); final IMEMonitor<IAEFluidStack> inv = this.getProxy().getStorage().getInventory( this.getChannel() ); if( fh != null ) { for( int i = 0; i < this.getConfig().getSlots(); i++ ) { IAEItemStack stack = this.getConfig().getAEStackInSlot( i ); if( stack != null && stack.getDefinition() != null ) { IFluidHandlerItem ifh = stack.getDefinition().getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ); if( ifh == null ) { throw new NullPointerException( "IFluidHandlerItem is null" ); } AEFluidStack toExtract = AEFluidStack.fromFluidStack( ifh.drain( Integer.MAX_VALUE, false ) ); toExtract.setStackSize( this.calculateAmountToSend() ); IAEFluidStack out = inv.extractItems( toExtract, Actionable.SIMULATE, this.source ); if( out != null ) { int wasInserted = fh.fill( out.getFluidStack(), true ); if( wasInserted > 0 ) { inv.extractItems( toExtract, Actionable.MODULATE, this.source ); return TickRateModulation.FASTER; } } } } return TickRateModulation.SLOWER; } } <START> catch( GridAccessException e ) <END> { e.printStackTrace(); } } return TickRateModulation.SLEEP; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') log rethrow this exception. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
protected TickRateModulation doBusWork() { if( !this.canDoBusWork() ) { return TickRateModulation.IDLE; } final TileEntity te = this.getConnectedTE(); if( te != null && te.hasCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ) ) { try { final IFluidHandler fh = te.getCapability( CapabilityFluidHandler.FLUID_HANDLER_CAPABILITY, this.getSide().getFacing() ); final IMEMonitor<IAEFluidStack> inv = this.getProxy().getStorage().getInventory( this.getChannel() ); if( fh != null ) { for( int i = 0; i < this.getConfig().getSlots(); i++ ) { IAEItemStack stack = this.getConfig().getAEStackInSlot( i ); if( stack != null && stack.getDefinition() != null ) { IFluidHandlerItem ifh = stack.getDefinition().getCapability( CapabilityFluidHandler.FLUID_HANDLER_ITEM_CAPABILITY, null ); if( ifh == null ) { throw new NullPointerException( "IFluidHandlerItem is null" ); } AEFluidStack toExtract = AEFluidStack.fromFluidStack( ifh.drain( Integer.MAX_VALUE, false ) ); toExtract.setStackSize( this.calculateAmountToSend() ); IAEFluidStack out = inv.extractItems( toExtract, Actionable.SIMULATE, this.source ); if( out != null ) { int wasInserted = fh.fill( out.getFluidStack(), true ); if( wasInserted > 0 ) { inv.extractItems( toExtract, Actionable.MODULATE, this.source ); return TickRateModulation.FASTER; } } } } return TickRateModulation.SLOWER; } } catch( GridAccessException e ) { } } return TickRateModulation.SLEEP; }
Source:
<code>public String getUserData() { if (userData != null) { try { <START> userData = URLDecoder.decode(userData, "UTF-8"); <END> } catch (UnsupportedEncodingException e) { throw new InvalidParameterValueException("Url decoding of userdata failed."); } } return userData; }</code><technical_language>do do this if is allready UTF-8</technical_language>

Target:
public String getUserData() { return userData; }
Source:
<code>public void detectExposureTo3rdPartyInHREF() throws HttpMalformedHeaderException, URIException { String testURI = "<LINK_1>"; String body = "<html>\n<body>\n<h2>HTML Links</h2>\n" + "<p><a href=\"<LINK_0>\">Testing ZAP</a>" + "</p>\n" + "</body>\n</html>"; HttpMessage msg = createHttpMessageWithRespBody(body); msg.getRequestHeader().setURI(new URI(testURI, false)); rule.scanHttpRequestSend(msg, -1); <START> assertEquals(2, alertsRaised.size()); <END> }</code><technical_language>For alert assert risk (http https)</technical_language>

Target:
public void detectExposureTo3rdPartyInHREF() throws HttpMalformedHeaderException, URIException { String testURI = "<LINK_1>"; String body = "<html>\n<body>\n<h2>HTML Links</h2>\n" + "<p><a href=\"<LINK_2>\">Testing ZAP</a>" + "</p>\n" + "</body>\n</html>"; HttpMessage msg = createHttpMessageWithRespBody(body); msg.getRequestHeader().setURI(new URI(testURI, false)); rule.scanHttpResponseReceive(msg, -1, new Source(body)); assertEquals(2, alertsRaised.size()); assertEquals(Alert.RISK_MEDIUM, alertsRaised.get(2 - 1).getRisk()); }