auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testCurrentSchemaPropertyNotVisibilityTableDuringFunctionCreation() throws SQLException { Properties properties = new Properties(); properties.setProperty(PGProperty.CURRENT_SCHEMA.getName(), "public,schema2"); Connection connection = TestUtil.openDB(properties); TestUtil.execute("create table schema1.check_table (test_col text)", connection); TestUtil.execute("insert into schema1.check_table (test_col) values ('test_value')", connection); try { TestUtil.execute("create or replace function schema2.check_fun (txt text) returns text as $$" + " select test_col from check_table" + "$$ language sql immutable", connection); } catch (PSQLException e) { String sqlState = e.getSQLState(); String message = e.getMessage(); assertThat("Incorrect sql error code", sqlState, equalTo(PSQLState.RELATION_DOES_NOT_EXIST.getState())); <START> assertTrue("Missing table name in error message", message.contains("\"check_table\"")); <END> } catch (Exception e) { fail("Incorrect exception is occurred"); } connection.close(); }</code><technical_language>thing: Missing table name in error message. 1) is clear is missing 2) is clear is missing. Assert message "\"check_table\" contained in exception message ...". Note: assertion **hides** original message, analysis hard. assertThat(..., message, contains("...")) add message message parameter</technical_language>

Target:
public void testCurrentSchemaPropertyNotVisibilityTableDuringFunctionCreation() throws SQLException { Properties properties = new Properties(); properties.setProperty(PGProperty.CURRENT_SCHEMA.getName(), "public,schema2"); try (Connection connection = TestUtil.openDB(properties)) { TestUtil.execute("create table schema1.check_table (test_col text)", connection); TestUtil.execute("insert into schema1.check_table (test_col) values ('test_value')", connection); TestUtil.execute("create or replace function schema2.check_fun (txt text) returns text as $$" + " select test_col from check_table" + "$$ language sql immutable", connection); } catch (PSQLException e) { String sqlState = e.getSQLState(); String message = e.getMessage(); assertThat("Test creates function in schema 'schema2' and this function try use table \"check_table\" " + "from schema 'schema1'. We expect here sql error code - " + PSQLState.UNDEFINED_TABLE + ", because search_path does not contains schema 'schema1' and " + "postgres does not see table \"check_table\"", sqlState, equalTo(PSQLState.UNDEFINED_TABLE.getState()) ); assertThat( "Test creates function in schema 'schema2' and this function try use table \"check_table\" " + "from schema 'schema1'. We expect here that sql error message will be contains \"check_table\", " + "because search_path does not contains schema 'schema1' and postgres does not see " + "table \"check_table\"", message, containsString("\"check_table\"") ); } }
Source:
<code>@Override public Float convert(JsonParser parser, Supplier<String> contentString) { String version = null; try { if (enterPath(parser, "version", "number") != null) version = parser.getText(); } catch (RuntimeException | IOException possiblyParseException) { <START> throw new IllegalArgumentException( <END> "could not parse .version.number in response: " + contentString.get()); } if (version == null) { throw new IllegalArgumentException( ".version.number not found in response: " + contentString.get()); } return Float.valueOf(version.substring(0, 3)); }</code><technical_language>phone expand this file if duping next line, commet instead is fine</technical_language>

Target:
@Override public Float convert(JsonParser parser, Supplier<String> contentString) { String version = null; try { if (enterPath(parser, "version", "number") != null) version = parser.getText(); } catch (RuntimeException | IOException possiblyParseException) { } if (version == null) { throw new IllegalArgumentException( ".version.number not found in response: " + contentString.get()); } return Float.valueOf(version.substring(0, 3)); }
Source:
<code>public boolean tagExists(String tagName) throws GitException { try (Repository repo = getRepository()) { <START> Ref tag = repo.getRefDatabase().exactRef(R_TAGS + tagName); <END> return tag != null; } catch (IOException e) { throw new GitException(e); } }</code><technical_language>Is reason exactRef() is called Repository here? is called Repository in other places changed. I suggest call more consistently troughout file. Current occurencs of getRefDatabase() - lines [539](<LINK_3>, [731](<LINK_0>, [770](<LINK_1>, [1758](<LINK_2> Line [1758](<LINK_2> is additionally a candidate for getRefsByPrefix() instead of getRefs()</technical_language>

Target:
public boolean tagExists(String tagName) throws GitException { try (Repository repo = getRepository()) { Ref tag = repo.exactRef(R_TAGS + tagName); return tag != null; } catch (IOException e) { throw new GitException(e); } }
Source:
<code>public void onDestroy() { if (mMediaUploadHandler != null) { mMediaUploadHandler.cancelInProgressUploads(); mMediaUploadHandler.unregister(); } if (mPostUploadHandler != null) { mPostUploadHandler.cancelInProgressUploads(); mPostUploadHandler.unregister(); } <START> ConcurrentHashMap<Integer, List<MediaModel>> tmpMap = new ConcurrentHashMap<>(); <END> tmpMap.putAll(sCompletedMediaByPost); tmpMap.putAll(sFailedMediaByPost); for (Integer postId : tmpMap.keySet()) { PostModel updatedPost = updatePostWithCurrentlyCompletedUploads(mPostStore.getPostByLocalPostId(postId)); updatedPost = updatePostWithCurrentlyFailedUploads(updatedPost); mDispatcher.dispatch(PostActionBuilder.newUpdatePostAction(updatedPost)); } mDispatcher.unregister(this); AppLog.i(T.MAIN, "UploadService > Destroyed"); super.onDestroy(); }</code><technical_language>This a plain Map</technical_language>

Target:
public void onDestroy() { if (mMediaUploadHandler != null) { mMediaUploadHandler.cancelInProgressUploads(); mMediaUploadHandler.unregister(); } if (mPostUploadHandler != null) { mPostUploadHandler.cancelInProgressUploads(); mPostUploadHandler.unregister(); } updatePostModelWithCompletedAndFailedUploads(); mDispatcher.unregister(this); AppLog.i(T.MAIN, "UploadService > Destroyed"); super.onDestroy(); }
Source:
<code>public void appendMediaFile(final MediaFile mediaFile, final String mediaUrl, ImageLoader imageLoader) { if (!mDomHasLoaded) { mWaitingMediaFiles.put(mediaUrl, mediaFile); return; } mWebView.post(new Runnable() { @Override public void run() { if (URLUtil.isNetworkUrl(mediaUrl)) { String mediaId = mediaFile.getMediaId(); if (mediaFile.isVideo()) { String videoPressId = ShortcodeUtils.getVideoPressIdFromShortCode( mediaFile.getVideoPressShortCode()); <START> mWebView.execJavaScriptFromString("ZSSEditor.insertVideo('" + mediaUrl + "', '" + <END> mediaFile.getThumbnailURL() + "', '" + videoPressId + "');"); } else { mWebView.execJavaScriptFromString("ZSSEditor.insertImage('" + mediaUrl + "', '" + mediaId + "');"); } } else { String id = mediaFile.getMediaId(); if (mediaFile.isVideo()) { String posterUrl = StringUtils.notNullStr(mediaFile.getThumbnailURL()); mWebView.execJavaScriptFromString("ZSSEditor.insertLocalVideo(" + id + ", '" + posterUrl + "');"); mWebView.execJavaScriptFromString("ZSSEditor.setProgressOnVideo(" + id + ", " + 0 + ");"); mUploadingMedia.put(id, MediaType.VIDEO); } else { mWebView.execJavaScriptFromString("ZSSEditor.insertLocalImage(" + id + ", '" + mediaUrl + "');"); mWebView.execJavaScriptFromString("ZSSEditor.setProgressOnImage(" + id + ", " + 0 + ");"); mUploadingMedia.put(id, MediaType.IMAGE); } } } }); }</code><technical_language>I if mediaUrl abused (with infos coming server) if escape (same for other calls execJavaScriptFromString a mediaUrl)</technical_language>

Target:
public void appendMediaFile(final MediaFile mediaFile, final String mediaUrl, ImageLoader imageLoader) { if (!mDomHasLoaded) { mWaitingMediaFiles.put(mediaUrl, mediaFile); return; } final String safeMediaUrl = Utils.escapeQuotes(mediaUrl); mWebView.post(new Runnable() { @Override public void run() { if (URLUtil.isNetworkUrl(mediaUrl)) { String mediaId = mediaFile.getMediaId(); if (mediaFile.isVideo()) { String posterUrl = Utils.escapeQuotes(StringUtils.notNullStr(mediaFile.getThumbnailURL())); String videoPressId = ShortcodeUtils.getVideoPressIdFromShortCode( mediaFile.getVideoPressShortCode()); mWebView.execJavaScriptFromString("ZSSEditor.insertVideo('" + safeMediaUrl + "', '" + posterUrl + "', '" + videoPressId + "');"); } else { mWebView.execJavaScriptFromString("ZSSEditor.insertImage('" + safeMediaUrl + "', '" + mediaId + "');"); } } else { String id = mediaFile.getMediaId(); if (mediaFile.isVideo()) { String posterUrl = Utils.escapeQuotes(StringUtils.notNullStr(mediaFile.getThumbnailURL())); mWebView.execJavaScriptFromString("ZSSEditor.insertLocalVideo(" + id + ", '" + posterUrl + "');"); mWebView.execJavaScriptFromString("ZSSEditor.setProgressOnVideo(" + id + ", " + 0 + ");"); mUploadingMedia.put(id, MediaType.VIDEO); } else { mWebView.execJavaScriptFromString("ZSSEditor.insertLocalImage(" + id + ", '" + safeMediaUrl + "');"); mWebView.execJavaScriptFromString("ZSSEditor.setProgressOnImage(" + id + ", " + 0 + ");"); mUploadingMedia.put(id, MediaType.IMAGE); } } } }); }
Source:
<code>public void afterSend(MetricsContext context, boolean result) { <START> long start = ((DefaultChannelMetricsContext) context).start; <END> long now = System.nanoTime(); long elapsed = now - start; if (result && this.fullStatsEnabled) { this.sendSuccessRatio.success(now); this.sendDuration.appendNanos(elapsed); } else { if (this.fullStatsEnabled) { this.sendSuccessRatio.failure(now); this.sendErrorCount.incrementAndGet(); } this.sendErrorRate.increment(); } if (logger.isTraceEnabled()) { logger.trace("Elapsed: " + this.name + ": " + elapsed); } }</code><technical_language>protect wrong context type</technical_language>

Target:
public void afterSend(MetricsContext context, boolean result) { if (result && isFullStatsEnabled()) { long now = System.nanoTime(); this.sendSuccessRatio.success(now); this.sendDuration.appendNanos(now - ((DefaultChannelMetricsContext) context).start); } else { if (isFullStatsEnabled()) { this.sendSuccessRatio.failure(System.nanoTime()); this.sendErrorRate.increment(); } this.sendErrorCount.incrementAndGet(); } if (logger.isTraceEnabled()) { logger.trace("Elapsed: " + this.name + ": " + ((System.nanoTime() - ((DefaultChannelMetricsContext) context).start) / 1000000.) + "ms"); } }
Source:
<code><START> public int getExtraData(int index, int x, int y, int z) { <END> extendExtraDataTo(index); Integer prevValue = extraData.get(index).get(new Vector3i(x, y, z)); if (prevValue == null) { return 0; } return prevValue; }</code><technical_language>This simplified (assuming Java 1.8 is used) public int getExtraData(int index, Vector3i pos, int value) { extendExtraDataTo(index); return extraData.get(index).getOrDefault(new Vector3i(x, y, z), 0); }</technical_language>

Target:
public int getExtraData(int index, int x, int y, int z) { return getExtraDataLayer(index).getOrDefault(new Vector3i(x, y, z), 0); }
Source:
<code>public EventBuilder setEventData(Eventful entity) { if (entity != null) { if (entity instanceof Named && ((Named) entity).getName() != null) { event.setTargetName(((Named) entity).getName()); } if (entity instanceof Owned) { Owner entityOwner = ((Owned) entity).getOwner(); if (entityOwner != null && entityOwner.getId() != null) { event.setOwnerId(entityOwner.getId()); } } if (entity instanceof Entitlement) { event.setReferenceType(Event.ReferenceType.POOL); Pool referencedPool = ((Entitlement) entity).getPool(); if (referencedPool != null && referencedPool.getId() != null) { event.setReferenceId(referencedPool.getId()); } } if ((String) entity.getId() != null) { event.setEntityId((String) entity.getId()); if (entity instanceof ConsumerProperty) { Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer(); if (owningConsumer != null && owningConsumer.getId() != null) { event.setConsumerId(owningConsumer.getId()); } } } <START> factory.entityToJson(entity); <END> } return this; }</code><technical_language>java protected String entityToJson(Object entity) { String newEntityJson = ""; // TODO: Throw auditing exception // Drop data consumer do want serialized, Jackson // care XmlTransient annotations here: try { newEntityJson = mapper.writeValueAsString(entity); } catch (Exception e) { log.warn("Unable jsonify: " + entity); log.error("jsonification failed!", e); } return newEntityJson; } is run entityToJson. I side effects happen in code</technical_language>

Target:
public EventBuilder setEventData(Eventful entity) { if (entity != null) { if (entity instanceof Named && ((Named) entity).getName() != null) { event.setTargetName(((Named) entity).getName()); } if (entity instanceof Owned) { Owner entityOwner = ((Owned) entity).getOwner(); if (entityOwner != null && entityOwner.getId() != null) { event.setOwnerId(entityOwner.getId()); } } if (entity instanceof Entitlement) { event.setReferenceType(Event.ReferenceType.POOL); Pool referencedPool = ((Entitlement) entity).getPool(); if (referencedPool != null && referencedPool.getId() != null) { event.setReferenceId(referencedPool.getId()); } } if ((String) entity.getId() != null) { event.setEntityId((String) entity.getId()); if (entity instanceof ConsumerProperty) { Consumer owningConsumer = ((ConsumerProperty) entity).getConsumer(); if (owningConsumer != null && owningConsumer.getId() != null) { event.setConsumerId(owningConsumer.getId()); } } } } return this; }
Source:
<code>public boolean select(Viewer viewer, Object parentElement, Object element) { if (parentElement instanceof FeatureAndProductInput && element instanceof IFeatureModel) { IFeatureModel featureModel = (IFeatureModel) element; FeatureAndProductInput input = (FeatureAndProductInput) parentElement; boolean showProducts = input.isIncludeProducts(); String featureId = featureModel.getFeature().getId(); boolean includedInFeature = !fFeatureIndex.getIncludingFeatures(featureId).isEmpty(); boolean includedInProduct = !fFeatureIndex.getIncludingProducts(featureId).isEmpty(); <START> return !includedInFeature && (!showProducts || !includedInProduct); <END> } return true; }</code><technical_language>I split up, a bit hard read. if (includedInFeature) return false; if (showProducts && includedInProduct) return false;</technical_language>

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (parentElement instanceof DeferredFeaturesViewInput && element instanceof IFeatureModel) { DeferredFeaturesViewInput input = (DeferredFeaturesViewInput) parentElement; IFeatureModel featureModel = (IFeatureModel) element; boolean showProducts = input.getFeaturesViewInput().isIncludeProducts(); String featureId = featureModel.getFeature().getId(); boolean includedInFeature = !input.getFeaturesViewInput().getIncludingFeatures(featureId).isEmpty(); boolean includedInProduct = !input.getFeaturesViewInput().getIncludingProducts(featureId).isEmpty(); if (includedInFeature) { return false; } else if (showProducts && includedInProduct) { return false; } } return true; }
Source:
<code>public static Object normaliseValue(Object currVal) throws SQLException { if (currVal==null) return null; TypeTransformer tn=TypeNormaliserFactory.getNormaliser(currVal.getClass()); <START> if (tn!=null) currVal=tn.transform(currVal); <END> return currVal; }</code><technical_language>touching lines, reformat add space = !=</technical_language>

Target:
public static Object normaliseValue(Object currVal) throws SQLException { if (currVal == null) { return null; } TypeTransformer tn = TypeNormaliserFactory.getNormaliser(currVal.getClass()); if (tn != null) { currVal = tn.transform(currVal); } return currVal; }
Source:
<code>private void columnDelta1(SafeHtmlBuilder sb, FileInfo info) { sb.openTd().setStyleName(R.css().deltaColumn1()); if (!Patch.COMMIT_MSG.equals(info.path()) && !info.binary() && !ChangeType.DELETED.matches(info.status())) { if (ChangeType.ADDED.matches(info.status())) { <START> sb.append(info.lines_inserted()) .append(" lines"); <END> } else { sb.append("+") .append(info.lines_inserted()) .append(", -") .append(info.lines_deleted()); } } sb.closeTd(); }</code><technical_language>a formatting for newly added files? simply sb.append("+") .append(info.lines_inserted()) ? This formatting more consistent</technical_language>

Target:
private void columnDelta1(SafeHtmlBuilder sb, FileInfo info) { sb.openTd().setStyleName(R.css().deltaColumn1()); if (!Patch.COMMIT_MSG.equals(info.path()) && !info.binary()) { if (Gerrit.getUserAccount().getGeneralPreferences() .isSizeBarInChangeTable()) { sb.append(info.lines_inserted() + info.lines_deleted()); } else if (!ChangeType.DELETED.matches(info.status())) { if (ChangeType.ADDED.matches(info.status())) { sb.append(info.lines_inserted()) .append(" lines"); } else { sb.append("+") .append(info.lines_inserted()) .append(", -") .append(info.lines_deleted()); } } } sb.closeTd(); }
Source:
<code>public KafkaStreams make(final String ryaInstance, final StreamsQuery query) throws KafkaStreamsFactoryException { requireNonNull(ryaInstance); requireNonNull(query); final Properties streamsProps = new Properties(); streamsProps.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersConfig); streamsProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "RyaStreams-Query-" + query.getQueryId()); streamsProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance); final String resultsTopic = KafkaTopics.queryResultsTopic(query.getQueryId()); try { final TopologyBuilder topologyBuilder = topologyFactory.build(query.getSparql(), statementsTopic, resultsTopic, new RandomUUIDFactory()); return new KafkaStreams(topologyBuilder, new StreamsConfig(streamsProps)); <START> } catch (MalformedQueryException | TopologyBuilderException e) { <END> throw new KafkaStreamsFactoryException("Could not create a KafkaStreams processing topology for query " + query.getQueryId(), e); } }</code><technical_language>add final Exceptions</technical_language>

Target:
public KafkaStreams make(final String ryaInstance, final StreamsQuery query) throws KafkaStreamsFactoryException { requireNonNull(ryaInstance); requireNonNull(query); final Properties streamsProps = new Properties(); streamsProps.setProperty(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServersConfig); streamsProps.put(StreamsConfig.APPLICATION_ID_CONFIG, "RyaStreams-Query-" + query.getQueryId()); streamsProps.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); final String statementsTopic = KafkaTopics.statementsTopic(ryaInstance); final String resultsTopic = KafkaTopics.queryResultsTopic(query.getQueryId()); try { final TopologyBuilder topologyBuilder = topologyFactory.build(query.getSparql(), statementsTopic, resultsTopic, new RandomUUIDFactory()); return new KafkaStreams(topologyBuilder, new StreamsConfig(streamsProps)); } catch (final MalformedQueryException | TopologyBuilderException e) { throw new KafkaStreamsFactoryException("Could not create a KafkaStreams processing topology for query " + query.getQueryId(), e); } }
Source:
<code>public boolean equals(Object o) { if (this.getClass() != o.getClass()) return false; ActionParameter actionParameter = (ActionParameter) o; <START> return actionParameter.getName() == this.getName(); <END> }</code><technical_language>comparing Object.equals(actionParam.getNames(), this.getName()) - account for nulls - == Checks for reference equality logical equality</technical_language>

Target:
public boolean equals(Object o) { if (o instanceof ActionParameter) return false; ActionParameter actionParameter = (ActionParameter) o; return this.getName().equals(actionParameter.getName()); }
Source:
<code>public Void call() throws Exception { init(); OzoneConfiguration ozoneConfiguration = createOzoneConfiguration(); rpcClient = OzoneClientFactory.getRpcClient(ozoneConfiguration); try (InputStream stream = rpcClient.getObjectStore().getVolume(volumeName) .getBucket(bucketName).readKey(generateObjectName(0))) { referenceDigest = getDigest(stream); } <START> timer = getMetrics().timer("key-create"); <END> runTests(this::validateKey); return null; }</code><technical_language>suggestion timer = getMetrics().timer("key-validate");</technical_language>

Target:
public Void call() throws Exception { init(); OzoneConfiguration ozoneConfiguration = createOzoneConfiguration(); rpcClient = OzoneClientFactory.getRpcClient(ozoneConfiguration); try (InputStream stream = rpcClient.getObjectStore().getVolume(volumeName) .getBucket(bucketName).readKey(generateObjectName(0))) { referenceDigest = getDigest(stream); } timer = getMetrics().timer("key-validate"); runTests(this::validateKey); return null; }
Source:
<code>protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; <START> if (!other.getClass().equals(this.getClass())) { <END> throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } else { return (ILScore)other; } }</code><technical_language>Is this needed? this removed for efficiency reasons (but I this method is used...)</technical_language>

Target:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; return (ILScore)other; }
Source:
<code>public static EnumSet<ElementKind> getElementKindsForElementType(ElementType elementType) { switch (elementType) { case TYPE: return EnumSet.of( ElementKind.CLASS, ElementKind.INTERFACE, ElementKind.ANNOTATION_TYPE, ElementKind.ENUM); case FIELD: return EnumSet.of(ElementKind.FIELD, ElementKind.ENUM_CONSTANT); case METHOD: return EnumSet.of(ElementKind.METHOD); case PARAMETER: return EnumSet.of(ElementKind.PARAMETER); case CONSTRUCTOR: return EnumSet.of(ElementKind.CONSTRUCTOR); case LOCAL_VARIABLE: return EnumSet.of( ElementKind.LOCAL_VARIABLE, ElementKind.RESOURCE_VARIABLE, ElementKind.EXCEPTION_PARAMETER); case ANNOTATION_TYPE: return EnumSet.of(ElementKind.ANNOTATION_TYPE); case PACKAGE: return EnumSet.of(ElementKind.PACKAGE); case TYPE_PARAMETER: return EnumSet.of(ElementKind.TYPE_PARAMETER); case TYPE_USE: return EnumSet.noneOf(ElementKind.class); default: if (elementType.name().equals("MODULE")) { <START> return EnumSet.of(ElementKind.valueOf("MODULE")); <END> } throw new BugInCF("Unrecognized ElementType: " + elementType); } }</code><technical_language>valueOf get constant instead of noneOf me</technical_language>

Target:
public static EnumSet<ElementKind> getElementKindsForElementType(ElementType elementType) { switch (elementType) { case TYPE: return EnumSet.copyOf(ElementUtils.classElementKinds()); case FIELD: return EnumSet.of(ElementKind.FIELD, ElementKind.ENUM_CONSTANT); case METHOD: return EnumSet.of(ElementKind.METHOD); case PARAMETER: return EnumSet.of(ElementKind.PARAMETER); case CONSTRUCTOR: return EnumSet.of(ElementKind.CONSTRUCTOR); case LOCAL_VARIABLE: return EnumSet.of( ElementKind.LOCAL_VARIABLE, ElementKind.RESOURCE_VARIABLE, ElementKind.EXCEPTION_PARAMETER); case ANNOTATION_TYPE: return EnumSet.of(ElementKind.ANNOTATION_TYPE); case PACKAGE: return EnumSet.of(ElementKind.PACKAGE); case TYPE_PARAMETER: return EnumSet.of(ElementKind.TYPE_PARAMETER); case TYPE_USE: return EnumSet.noneOf(ElementKind.class); default: if (elementType.name().equals("MODULE")) { return EnumSet.of(ElementKind.valueOf("MODULE")); } if (elementType.name().equals("RECORD_COMPONENT")) { return EnumSet.of(ElementKind.valueOf("RECORD_COMPONENT")); } throw new BugInCF("Unrecognized ElementType: " + elementType); } }
Source:
<code>public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final int hashValue = partitionKeyFields.stream() <START> .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? "data." + pkf : pkf) <END> .map(wrapFunction(okf -> traversableJsonEvent.get(okf).toString().hashCode())) .mapToInt(hc -> hc) .sum(); final int partitionIndex = abs(hashValue) % partitions.size(); return partitions.get(partitionIndex); } catch (ExceptionWrapper e) { final Exception original = e.getWrapped(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }</code><technical_language>need create constant field data used. EventTypeValidation#wrapSchemaInData, hard for understand else happen</technical_language>

Target:
public String calculatePartition(final EventType eventType, final JSONObject event, final List<String> partitions) throws InvalidPartitionKeyFieldsException { final List<String> partitionKeyFields = eventType.getPartitionKeyFields(); if (partitionKeyFields.isEmpty()) { throw new RuntimeException("Applying " + this.getClass().getSimpleName() + " although event type " + "has no partition key fields configured."); } try { final JsonPathAccess traversableJsonEvent = new JsonPathAccess(event); final int hashValue = partitionKeyFields.stream() .map(pkf -> EventCategory.DATA.equals(eventType.getCategory()) ? DATA_PATH_PREFIX + pkf : pkf) .map(wrapFunction(okf -> traversableJsonEvent.get(okf).toString().hashCode())) .mapToInt(hc -> hc) .sum(); final int partitionIndex = abs(hashValue) % partitions.size(); return partitions.get(partitionIndex); } catch (ExceptionWrapper e) { final Exception original = e.getWrapped(); if (original instanceof InvalidPartitionKeyFieldsException) { throw (InvalidPartitionKeyFieldsException) original; } else { throw e; } } }
Source:
<code>public String encode(CharSequence rawPassword) { String salt; <START> if(version != null) { <END> if (strength > 0) { if (random != null) { salt = BCrypt.gensalt(version, strength, random); } else { System.out.println(version); salt = BCrypt.gensalt(version, strength); } } else { salt = BCrypt.gensalt(version); } } else { if (strength > 0) { if (random != null) { salt = BCrypt.gensalt(strength, random); } else { salt = BCrypt.gensalt(strength); } } else { salt = BCrypt.gensalt(); } } return BCrypt.hashpw(rawPassword.toString(), salt); }</code><technical_language>this check code paths, version is final non-null a default of $2y</technical_language>

Target:
public String encode(CharSequence rawPassword) { String salt; if (strength > 0) { if (random != null) { salt = BCrypt.gensalt(version.getVersion(), strength, random); } else { salt = BCrypt.gensalt(version.getVersion(), strength); } } else { salt = BCrypt.gensalt(version.getVersion()); } return BCrypt.hashpw(rawPassword.toString(), salt); }
Source:
<code>protected VmAnalyzer <START> getVmAnalyzer(Pair<VM, VmInternalData> monitoredVm) { <END> return new VmAnalyzer( monitoredVm.getFirst(), monitoredVm.getSecond(), updateStatistics, vdsManager, auditLogDirector, resourceManager, vmStaticDao, vmDynamicDao, vmDao, vmNetworkInterfaceDao, vdsDao, diskDao, vmJobDao, vmNumaNodeDao, vdsNumaNodesSupplier); }</code><technical_language>nice if pass in vdsManager cached numa nodes. VmAnalyzerFactory is stateless injected in VmsMonitoring</technical_language>

Target:
protected VmAnalyzer getVmAnalyzer(Pair<VM, VmInternalData> monitoredVm) { return new VmAnalyzer( monitoredVm.getFirst(), monitoredVm.getSecond(), updateStatistics, vdsManager, auditLogDirector, resourceManager, vmStaticDao, vmDynamicDao, vmDao, vmNetworkInterfaceDao, vdsDao, diskDao, vmJobDao, vmNumaNodeDao, vdsNumaNodesProvider); }
Source:
<code>public static <T extends DnsRecord> List<T> dnsQuery(Class<T> cls, String domain, String dnsServerAddress) throws DnsException { List<T> dnsRecordList = new ArrayList<T>(); try { Hashtable<String, String> env = new Hashtable<String, String>(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); <START> if(dnsServerAddress != null) { <END> env.put("java.naming.provider.url", "dns://" + dnsServerAddress); } DirContext ictx = new InitialDirContext(env); Attributes contextAttributes = ictx.getAttributes(domain, new String[] {EWSConstants.SRVRECORD}); if (contextAttributes != null) { NamingEnumeration<?> attributes = contextAttributes.getAll(); if (attributes != null) { while (attributes.hasMore()) { Attribute attr = (Attribute) attributes.next(); NamingEnumeration<?> srvValues = attr.getAll(); if (srvValues != null) { while (srvValues.hasMore()) { T dnsRecord = cls.newInstance(); dnsRecord.load((String) srvValues.next()); dnsRecordList.add(dnsRecord); } } } } } } catch (NamingException ne) { throw new DnsException(ne.getMessage()); } catch (Exception e) { throw new DnsException(e.getMessage()); } return dnsRecordList; }</code><technical_language>sense string is blank</technical_language>

Target:
public static <T extends DnsRecord> List<T> dnsQuery(Class<T> cls, String domain, String dnsServerAddress) throws DnsException { List<T> dnsRecordList = new ArrayList<T>(); try { DirContext ictx = new InitialDirContext(getEnv(dnsServerAddress)); Attributes contextAttributes = ictx.getAttributes(domain, new String[] {EWSConstants.SRVRECORD}); if (contextAttributes != null) { NamingEnumeration<?> attributes = contextAttributes.getAll(); if (attributes != null) { while (attributes.hasMore()) { Attribute attr = (Attribute) attributes.next(); NamingEnumeration<?> srvValues = attr.getAll(); if (srvValues != null) { while (srvValues.hasMore()) { T dnsRecord = cls.newInstance(); dnsRecord.load((String) srvValues.next()); dnsRecordList.add(dnsRecord); } } } } } } catch (NamingException ne) { throw new DnsException(ne.getMessage()); } catch (Exception e) { throw new DnsException(e.getMessage()); } return dnsRecordList; }
Source:
<code>public void launch() { VanillaJavaApp entity = getEntity(); String clazz = entity.getMainClass(); String args = getArgs(); Map flags = new HashMap(); flags.put("usePidFile", true); newScript(flags, LAUNCHING). body.append( format("echo \"launching: java $JAVA_OPTS -cp \'lib/*\' %s %s\"",clazz,args), <START> format("java $JAVA_OPTS -cp \"lib/*\" %s %s >> $runDir/console 2>&1 </dev/null &",clazz,args) <END> ).execute(); }</code><technical_language>$runDir right</technical_language>

Target:
public void launch() { VanillaJavaApp entity = getEntity(); String clazz = entity.getMainClass(); String args = getArgs(); Map flags = new HashMap(); flags.put("usePidFile", true); newScript(flags, LAUNCHING). body.append( format("echo \"launching: java $JAVA_OPTS -cp \'lib/*\' %s %s\"",clazz,args), format("java $JAVA_OPTS -cp \"lib/*\" %s %s >> %s/console 2>&1 </dev/null &",getRunDir(),clazz,args) ).execute(); }
Source:
<code>public E first(E defaultValue) { if (managedMode) { checkValidView(); if (!view.isEmpty()) { return get(0); } <START> } else if (unmanagedList != null && unmanagedList.size() > 0) { <END> return unmanagedList.get(0); } return defaultValue; }</code><technical_language>!isEmpty() instead of size() > 0</technical_language>

Target:
public E first(E defaultValue) { return firstImpl(false, defaultValue); }
Source:
<code>public void createSnapshot(String workspaceId) { <START> notification = new Notification("Creating snapshot...", Notification.Status.PROGRESS); <END> notificationManager.showNotification(notification); workspaceService.createSnapshot(workspaceId) .catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { creationError(error.getMessage()); } }); }</code><technical_language>move "Creating snapshot..." localization</technical_language>

Target:
public void createSnapshot(String workspaceId) { notification = new Notification(locale.createSnapshotProgress(), Notification.Status.PROGRESS); notificationManager.showNotification(notification); workspaceService.createSnapshot(workspaceId) .catchError(new Operation<PromiseError>() { @Override public void apply(PromiseError error) throws OperationException { creationError(error.getMessage()); } }); }
Source:
<code>private void chunkGc() { <START> Iterator<Cube> cubeIt = cubeCache.watchedCubesIterator(); <END> while (cubeIt.hasNext()) { if (cubeCache.tryUnloadCube(cubeIt.next())) { cubeIt.remove(); } } Iterator<IColumn> columnIt = cubeCache.columnsIterator(); while (columnIt.hasNext()) { if (cubeCache.tryUnloadColumn(columnIt.next())) { columnIt.remove(); } } }</code><technical_language>If iterate watched cubes here, non-watched cubes get unloaded, defeats purpose of chunk GC</technical_language>

Target:
private void chunkGc() { Iterator<Cube> cubeIt = cubeCache.cubesIterator(); while (cubeIt.hasNext()) { if (cubeCache.tryUnloadCube(cubeIt.next())) { cubeIt.remove(); } } Iterator<IColumn> columnIt = cubeCache.columnsIterator(); while (columnIt.hasNext()) { if (cubeCache.tryUnloadColumn(columnIt.next())) { columnIt.remove(); } } }
Source:
<code>public boolean equals(Object o) { if (this == o) return true; if (o == null || <START> !getClass().isAssignableFrom(o.getClass())) return <END> false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; }</code><technical_language>this equals assymetrical, if this is a subclass of o this.equals(o) true while o.equals(this) false</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof NamedObject)) return false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; }
Source:
<code>private void convertYamlFiles(final File projectDir) { final File[] flowFiles = projectDir.listFiles(new SuffixFilter(FLOW_YAML_SUFFIX)); for (final File file : flowFiles) { final FlowBeanLoader loader = new FlowBeanLoader(); try { final FlowBean flowBean = loader.load(file); <START> final AzkabanFlow azkabanFlow = loader.toAzkabanFlow(loader.getFlowName(file), flowBean); <END> final Flow flow = new Flow(azkabanFlow.getName()); flow.setAzkabanFlow(azkabanFlow); this.flowMap.put(azkabanFlow.getName(), flow); final Props flowProps = azkabanFlow.getProps(); addEmailPropsToFlow(flow, flowProps); } catch (final FileNotFoundException e) { logger.error("Error loading flow yaml files", e); } } }</code><technical_language>do validate config file</technical_language>

Target:
private void convertYamlFiles(final File projectDir) { final File[] flowFiles = projectDir.listFiles(new SuffixFilter(FLOW_FILE_SUFFIX)); for (final File file : flowFiles) { final FlowBeanLoader loader = new FlowBeanLoader(); try { final FlowBean flowBean = loader.load(file); final AzkabanFlow azkabanFlow = loader.toAzkabanFlow(loader.getFlowName(file), flowBean); final Flow flow = new Flow(azkabanFlow.getName()); flow.setAzkabanFlow(azkabanFlow); this.flowMap.put(azkabanFlow.getName(), flow); final Props flowProps = azkabanFlow.getProps(); FlowLoaderUtils.addEmailPropsToFlow(flow, flowProps); } catch (final FileNotFoundException e) { logger.error("Error loading flow yaml files", e); } } }
Source:
<code>public void detach() { <START> if (vungleBanner != null && vungleBanner.getParent() != null) { ((ViewGroup) vungleBanner.getParent()).removeView(vungleBanner); <END> Log.d(TAG, "Vungle banner adapter cleanUp: destroyAd # " + vungleBanner.hashCode()); vungleBanner.destroyAd(); vungleBanner = null; } if (vungleMRECBanner != null) { View adView = vungleMRECBanner.renderNativeView(); if (adView != null && adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } Log.d(TAG, "Vungle banner adapter cleanUp: finishDisplayingAd # " + vungleMRECBanner.hashCode()); vungleMRECBanner.finishDisplayingAd(); vungleMRECBanner = null; } }</code><technical_language>suggestion if (vungleBanner != null) { if (vungleBanner.getParent() != null) { ((ViewGroup) vungleBanner.getParent()).removeView(vungleBanner); } Log.d(TAG, "Vungle banner adapter cleanUp: destroyAd # " + vungleBanner.hashCode()); vungleBanner.destroyAd(); vungleBanner = null; }</technical_language>

Target:
public void detach() { if (vungleBanner != null) { if (vungleBanner.getParent() != null) { ((ViewGroup) vungleBanner.getParent()).removeView(vungleBanner); } } if (vungleMRECBanner != null) { View adView = vungleMRECBanner.renderNativeView(); if (adView != null && adView.getParent() != null) { ((ViewGroup) adView.getParent()).removeView(adView); } } }
Source:
<code>public void setAndGet() { StatusCache cache = new StatusCache(); StatusDTO status = new StatusDTO() .result(true) <START> .timeUTC(new Date().toInstant().atOffset(ZoneOffset.UTC)); <END> cache.setStatus(status); assertEquals(status, cache.getStatus()); }</code><technical_language>for changes in this file, OffsetDateTime.now() directly</technical_language>

Target:
public void setAndGet() { StatusCache cache = new StatusCache(); StatusDTO status = new StatusDTO() .result(true) .timeUTC(OffsetDateTime.now()); cache.setStatus(status); assertEquals(status, cache.getStatus()); }
Source:
<code>private TimestampStorage createDatabaseTimestampStorage( DatabaseTsBoundPersisterConfiguration timestampBoundPersistence) { <START> DatabaseTsBoundPersisterConfiguration persisterConfiguration <END> = timestampBoundPersistence; ServiceDiscoveringDatabaseTimeLockSupplier dbTimeLockSupplier = new ServiceDiscoveringDatabaseTimeLockSupplier( metricsManager, persisterConfiguration.keyValueServiceConfig(), createLeaderConfig()); return ImmutableTimestampStorage.builder() .timestampCreator(new DbBoundTimestampCreator(dbTimeLockSupplier)) .persistentNamespaceContext(PersistentNamespaceContexts.dbBound( dbTimeLockSupplier.getTimestampSeriesProvider())) .build(); }</code><technical_language>oops</technical_language>

Target:
private TimestampStorage createDatabaseTimestampStorage( DatabaseTsBoundPersisterConfiguration timestampBoundPersistence) { ServiceDiscoveringDatabaseTimeLockSupplier dbTimeLockSupplier = new ServiceDiscoveringDatabaseTimeLockSupplier( metricsManager, timestampBoundPersistence.keyValueServiceConfig(), createLeaderConfig()); return ImmutableTimestampStorage.builder() .timestampCreator(new DbBoundTimestampCreator(dbTimeLockSupplier)) .persistentNamespaceContext(PersistentNamespaceContexts.dbBound( dbTimeLockSupplier.getTimestampSeriesProvider())) .build(); }
Source:
<code>public void build(TopologyBuilder bldr, Set<String> stageNames) { <START> StreamletUtils.require(false, "build() in StreamletShadow should NOT be invoked"); <END> }</code><technical_language>UnsupportedOperationException more convenient? Also, for **Row**: 111</technical_language>

Target:
public void build(TopologyBuilder bldr, Set<String> stageNames) { throw new UnsupportedOperationException("build() in StreamletShadow should NOT be invoked"); }
Source:
<code>public void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { <START> if (vc.getNAlleles() > 2) { <END> filters.add(Mutect2Engine.TRIALLELIC_SITE_FILTER_NAME); } }</code><technical_language>Previously checked if more 1 alleles pass TLOD NLOD thresholds, number of alleles. checking number of alleles filter strict</technical_language>

Target:
private static void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { if (vc.getNAlleles() > 2) { filters.add(GATKVCFConstants.TRIALLELIC_SITE_FILTER_NAME); } }
Source:
<code>public IClimateManipulatorBuilder createManipulator(ClimateType type) { return new ClimateManipulator.Builder() <START> .setAllowBackwards() <END> .setDefault(defaultState) .setCurrent(currentState) .setTarget(targetedState) .setChangeSupplier(housing::getChangeForState) .setType(type) .setOnFinish(this::setCurrent); }</code><technical_language>This breaks humidity implementation of habitat humidity controlled fluids this allows humidity consuming water sense. is a setAllowBackwards() in TileHabitatFormer#updateTemperature for regulation of temperature</technical_language>

Target:
public IClimateManipulatorBuilder createManipulator(ClimateType type) { return new ClimateManipulator.Builder() .setDefault(defaultState) .setCurrent(currentState) .setTarget(targetedState) .setChangeSupplier(housing::getChangeForState) .setType(type) .setOnFinish(this::setCurrent); }
Source:
<code>public boolean execute(WordsEnvironment environment) throws WordsRuntimeException { ASTValue predicateValue = predicate.eval(environment); assert predicateValue.type == ASTValue.ValueType.BOOLEAN : "Predicate has type " + predicateValue.type.toString(); if (predicateValue.booleanValue == true) { statementList.eval(environment); } else { <START> if (temporary) <END> return false; } return true; }</code><technical_language>This lack of braces follow style guide</technical_language>

Target:
public boolean execute(WordsEnvironment environment) throws WordsProgramException { ASTValue predicateValue; try { predicateValue = predicate.eval(environment); } catch (WordsRuntimeException e) { throw new WordsProgramException(predicate, e); } assert predicateValue.type == ASTValue.ValueType.BOOLEAN : "Predicate has type " + predicateValue.type.toString(); if (predicateValue.booleanValue == true) { try { statementList.eval(environment); } catch (WordsRuntimeException e) { throw new WordsProgramException(statementList, e); } } else { if (temporary) { return false; } } return true; }
Source:
<code>public FileHostKeyCertificateProvider(Path... files) { <START> this(Arrays.asList(files)); <END> }</code><technical_language>ValidateUtils.notEmpty(files)</technical_language>

Target:
public FileHostKeyCertificateProvider(Path... files) { this(Arrays.asList(ValidateUtils.checkNotNullAndNotEmpty(files, "No path provided"))); }
Source:
<code>public void testFullManifestConfig() { String buildUuid = "123"; String appVersion = "v1.0"; String releaseStage = "debug"; String endpoint = "<LINK_1>"; String sessionEndpoint = "<LINK_0>"; Bundle data = new Bundle(); data.putString(MF_BUILD_UUID, buildUuid); data.putString(MF_APP_VERSION, appVersion); data.putString(MF_RELEASE_STAGE, releaseStage); data.putString(MF_SESSIONS_ENDPOINT, sessionEndpoint); data.putString(MF_ENDPOINT, endpoint); data.putBoolean(MF_SEND_THREADS, false); data.putBoolean(MF_ENABLE_EXCEPTION_HANDLER, false); data.putBoolean(MF_PERSIST_USER_BETWEEN_SESSIONS, true); <START> data.putBoolean(MF_AUTO_CAPTURE_SESSIONS, true); <END> Configuration newConfig = Client.populateConfigFromManifest(new Configuration("api-key"), data); assertEquals(buildUuid, newConfig.getBuildUUID()); assertEquals(appVersion, newConfig.getAppVersion()); assertEquals(releaseStage, newConfig.getReleaseStage()); assertEquals(endpoint, newConfig.getEndpoint()); assertEquals(sessionEndpoint, newConfig.getSessionEndpoint()); assertEquals(false, newConfig.getSendThreads()); assertEquals(false, newConfig.getEnableExceptionHandler()); assertEquals(true, newConfig.getPersistUserBetweenSessions()); assertEquals(true, newConfig.shouldAutoCaptureSessions()); }</code><technical_language>this test a whole, public interface is tested more if raw string values instead of internal constants representing manifest keys. In case a typo ends in MF_AUTO_CAPTURE_SESSIONS, this test catch all</technical_language>

Target:
public void testFullManifestConfig() { String buildUuid = "123"; String appVersion = "v1.0"; String releaseStage = "debug"; String endpoint = "<LINK_1>"; String sessionEndpoint = "<LINK_0>"; Bundle data = new Bundle(); data.putString("com.bugsnag.android.BUILD_UUID", buildUuid); data.putString("com.bugsnag.android.APP_VERSION", appVersion); data.putString("com.bugsnag.android.RELEASE_STAGE", releaseStage); data.putString("com.bugsnag.android.SESSIONS_ENDPOINT", sessionEndpoint); data.putString("com.bugsnag.android.ENDPOINT", endpoint); data.putBoolean("com.bugsnag.android.SEND_THREADS", false); data.putBoolean("com.bugsnag.android.ENABLE_EXCEPTION_HANDLER", false); data.putBoolean("com.bugsnag.android.PERSIST_USER_BETWEEN_SESSIONS", true); data.putBoolean("com.bugsnag.android.AUTO_CAPTURE_SESSIONS", true); Configuration newConfig = Client.populateConfigFromManifest(new Configuration("api-key"), data); assertEquals(buildUuid, newConfig.getBuildUUID()); assertEquals(appVersion, newConfig.getAppVersion()); assertEquals(releaseStage, newConfig.getReleaseStage()); assertEquals(endpoint, newConfig.getEndpoint()); assertEquals(sessionEndpoint, newConfig.getSessionEndpoint()); assertEquals(false, newConfig.getSendThreads()); assertEquals(false, newConfig.getEnableExceptionHandler()); assertEquals(true, newConfig.getPersistUserBetweenSessions()); assertEquals(true, newConfig.shouldAutoCaptureSessions()); }
Source:
<code>private void checkName(Tree issueLocation, @Nullable String name) { <START> if (name != null && PURE_FUNCTIONS.contains(name)) { <END> context().newIssue(this, issueLocation, "The return value of \"" + name + "\" must be used."); } }</code><technical_language>I learn, function names apparently case insensitive in PHP (<LINK_0>, I convert in lowerCase testing if contained in set</technical_language>

Target:
private void checkName(Tree issueLocation, @Nullable String name) { if (name != null && PURE_FUNCTIONS.contains(name.toLowerCase(Locale.ROOT))) { context().newIssue(this, issueLocation, "The return value of \"" + name + "\" must be used."); } }
Source:
<code>public void testCreateSocketAddressWithURICache() throws Throwable { InetSocketAddress addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(1000, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(1000, addr.getPort()); try { <START> addr = NetUtils.createSocketAddr( <END> "127.0.0.1:blahblah", 1000, "myconfig", true); fail("Should have failed to parse bad port"); } catch (IllegalArgumentException iae) { assertInException(iae, "myconfig"); } try { addr = NetUtils.createSocketAddr( "127.0.0.1:blahblah", 1000, "myconfig", true); fail("Should have failed to parse bad port"); } catch (IllegalArgumentException iae) { assertInException(iae, "myconfig"); } }</code><technical_language>nit: addr useless? need assign addr anymore</technical_language>

Target:
public void testCreateSocketAddressWithURICache() throws Throwable { InetSocketAddress addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1:12345", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(12345, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(1000, addr.getPort()); addr = NetUtils.createSocketAddr( "127.0.0.1", 1000, "myconfig", true); assertEquals("127.0.0.1", addr.getAddress().getHostAddress()); assertEquals(1000, addr.getPort()); try { NetUtils.createSocketAddr( "127.0.0.1:blahblah", 1000, "myconfig", true); fail("Should have failed to parse bad port"); } catch (IllegalArgumentException iae) { assertInException(iae, "myconfig"); } try { NetUtils.createSocketAddr( "127.0.0.1:blahblah", 1000, "myconfig", true); fail("Should have failed to parse bad port"); } catch (IllegalArgumentException iae) { assertInException(iae, "myconfig"); } }