auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected Collection<Event> analyzePosition(Position position) { Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); if (device == null) { return null; } if (!Context.getDeviceManager().isLatestPosition(position) || !position.getValid()) { return null; } Collection<Event> events = new ArrayList<>(); double speed = position.getSpeed(); double speedLimit = 0; if (device.getAttributes().containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) device.getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); } if (speedLimit == 0 && checkGroups) { long groupId = device.getGroupId(); while (groupId != 0) { if (Context.getDeviceManager().getGroupById(groupId).getAttributes() .containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) Context.getDeviceManager().getGroupById(groupId) .getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); if (speedLimit != 0) { break; } } if (Context.getDeviceManager().getGroupById(groupId) != null) { groupId = Context.getDeviceManager().getGroupById(groupId).getGroupId(); } else { groupId = 0; } } } if (speedLimit == 0) { try { Server server = Context.getDataManager().getServer(); if (server.getAttributes().containsKey(ATTRIBUTE_SPEED_LIMIT)) { speedLimit = Double.parseDouble((String) server.getAttributes().get(ATTRIBUTE_SPEED_LIMIT)); } } catch (SQLException error) { Log.warning(error); } } double oldSpeed = 0; if (riseOnce) { Position lastPosition = Context.getDeviceManager().getLastPosition(position.getDeviceId()); if (lastPosition != null) { oldSpeed = lastPosition.getSpeed(); } } speedLimit = UnitsConverter.knotsFromKph(speedLimit); if (speedLimit != 0 && speed > speedLimit && oldSpeed <= speedLimit) { try { if (Context.getDataManager().getLastEvents( position.getDeviceId(), Event.TYPE_DEVICE_OVERSPEED, suppressRepeated).isEmpty()) { events.add(new Event(Event.TYPE_DEVICE_OVERSPEED, position.getDeviceId(), position.getId())); } } catch (SQLException error) { Log.warning(error); } } return events; }

Target:
protected Collection<Event> analyzePosition(Position position) { Device device = Context.getIdentityManager().getDeviceById(position.getDeviceId()); if (device == null) { return null; } if (!Context.getDeviceManager().isLatestPosition(position) || !position.getValid()) { return null; } Collection<Event> events = new ArrayList<>(); double speed = position.getSpeed(); double speedLimit = 0; String speedLimitAttribute = Context.getDeviceManager().lookupAttribute(device.getId(), ATTRIBUTE_SPEED_LIMIT); if (speedLimitAttribute != null) { speedLimit = Double.parseDouble(speedLimitAttribute); } if (speedLimit == 0) { return null; } double oldSpeed = 0; if (notRepeat) { Position lastPosition = Context.getDeviceManager().getLastPosition(position.getDeviceId()); if (lastPosition != null) { oldSpeed = lastPosition.getSpeed(); } } speedLimit = UnitsConverter.knotsFromKph(speedLimit); if (speed > speedLimit && oldSpeed <= speedLimit) { events.add(new Event(Event.TYPE_DEVICE_OVERSPEED, position.getDeviceId(), position.getId())); } return events; }
Source:
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())); assertTrue("Missing table name in error message", message.contains("\"check_table\"")); } catch (Exception e) { fail("Incorrect exception is occurred"); } connection.close(); }

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:
@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) { throw new IllegalArgumentException( "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)); }

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:
public boolean tagExists(String tagName) throws GitException { try (Repository repo = getRepository()) { Ref tag = repo.getRefDatabase().exactRef(R_TAGS + tagName); return tag != null; } catch (IOException e) { throw new GitException(e); } }

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:
public void onDestroy() { if (mMediaUploadHandler != null) { mMediaUploadHandler.cancelInProgressUploads(); mMediaUploadHandler.unregister(); } if (mPostUploadHandler != null) { mPostUploadHandler.cancelInProgressUploads(); mPostUploadHandler.unregister(); } ConcurrentHashMap<Integer, List<MediaModel>> tmpMap = new ConcurrentHashMap<>(); 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(); }

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:
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()); mWebView.execJavaScriptFromString("ZSSEditor.insertVideo('" + mediaUrl + "', '" + 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); } } } }); }

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:
public void afterSend(MetricsContext context, boolean result) { long start = ((DefaultChannelMetricsContext) context).start; 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); } }

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:
public int getExtraData(int index, int x, int y, int z) { extendExtraDataTo(index); Integer prevValue = extraData.get(index).get(new Vector3i(x, y, z)); if (prevValue == null) { return 0; } return prevValue; }

Target:
public int getExtraData(int index, int x, int y, int z) { return getExtraDataLayer(index).getOrDefault(new Vector3i(x, y, z), 0); }
Source:
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()); } } } factory.entityToJson(entity); } return this; }

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:
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(); return !includedInFeature && (!showProducts || !includedInProduct); } return true; }

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:
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; }

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:
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())) { sb.append(info.lines_inserted()) .append(" lines"); } else { sb.append("+") .append(info.lines_inserted()) .append(", -") .append(info.lines_deleted()); } } sb.closeTd(); }

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:
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 (MalformedQueryException | TopologyBuilderException e) { throw new KafkaStreamsFactoryException("Could not create a KafkaStreams processing topology for query " + query.getQueryId(), e); } }

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:
public boolean equals(Object o) { if (this.getClass() != o.getClass()) return false; ActionParameter actionParameter = (ActionParameter) o; return actionParameter.getName() == this.getName(); }

Target:
public boolean equals(Object o) { if (o instanceof ActionParameter) return false; ActionParameter actionParameter = (ActionParameter) o; return this.getName().equals(actionParameter.getName()); }
Source:
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-create"); runTests(this::validateKey); return null; }

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:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; if (!other.getClass().equals(this.getClass())) { throw new IllegalArgumentException("Incompatible class (" + other.getClass().getSimpleName() + ")"); } else { return (ILScore)other; } }

Target:
protected ILScore convert(InformationLoss<?> other) { if (other == null) return null; return (ILScore)other; }
Source:
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")) { return EnumSet.of(ElementKind.valueOf("MODULE")); } throw new BugInCF("Unrecognized ElementType: " + elementType); } }

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:
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." + 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; } } }

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:
public String encode(CharSequence rawPassword) { String salt; if(version != null) { 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); }

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:
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, vdsNumaNodesSupplier); }

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:
private void runTxOnCacheStop(TransactionConcurrency conc, TransactionIsolation iso, Ignite ig, boolean runConc) throws Exception { if ((conc == TransactionConcurrency.OPTIMISTIC) && (MvccFeatureChecker.forcedMvcc())) return; CountDownLatch destroyLatch = new CountDownLatch(1); final IgniteCache<Integer, byte[]> cache = ig.getOrCreateCache(destroyCacheCfg); final IgniteCache<Integer, byte[]> cache2 = ig.getOrCreateCache(surviveCacheCfg); TestRecordingCommunicationSpi spi = TestRecordingCommunicationSpi.spi(ig); IgniteInternalFuture f0 = GridTestUtils.runAsync(() -> { try { destroyLatch.await(); IgniteInternalFuture fInt = GridTestUtils.runAsync(() -> { try { U.sleep(rnd.nextInt(500)); } catch (IgniteInterruptedCheckedException e) { } spi.stopBlock(); }); cache.destroy(); fInt.get(); } catch (Exception e) { e.printStackTrace(); } }); spi.blockMessages((node, msg) -> { if (msg instanceof GridNearTxPrepareRequest) { destroyLatch.countDown(); return runConc; } return false; }); IgniteInternalFuture f1 = GridTestUtils.runAsync(() -> { byte[] val = new byte[1024]; try (Transaction tx = ig.transactions().txStart(conc, iso, 1_000, 2)) { try { cache.put(100, val); cache2.put(100, val); } catch (IgniteCacheRestartingException e) { e.restartFuture().get(); } tx.commit(); } catch (IgniteException e) { assertTrue(X.hasCause(e, IgniteTxTimeoutCheckedException.class) || X.hasCause(e, CacheInvalidStateException.class) || X.hasCause(e, IgniteException.class)); } }); f1.get(); f0.get(); try { assertTrue(cache2.get(100) == cache.get(100)); } catch (IllegalStateException e) { assertTrue(X.hasCause(e, CacheStoppedException.class)); } spi.stopBlock(); }

Target:
private void runTxOnCacheStop(TransactionConcurrency conc, TransactionIsolation iso, Ignite ig, boolean runConc) throws Exception { if ((conc == TransactionConcurrency.OPTIMISTIC) && (MvccFeatureChecker.forcedMvcc())) return; CountDownLatch destroyLatch = new CountDownLatch(1); final IgniteCache<Integer, byte[]> cache = ig.getOrCreateCache(destroyCacheCfg); final IgniteCache<Integer, byte[]> cache2 = ig.getOrCreateCache(surviveCacheCfg); TestRecordingCommunicationSpi spi = TestRecordingCommunicationSpi.spi(ig); IgniteInternalFuture f0 = GridTestUtils.runAsync(() -> { try { destroyLatch.await(); IgniteInternalFuture f = GridTestUtils.runAsync(() -> { doSleep(rnd.nextInt(500)); spi.stopBlock(); }); cache.destroy(); f.get(); } catch (Exception e) { e.printStackTrace(); } }); spi.blockMessages((node, msg) -> { if (msg instanceof GridNearTxPrepareRequest) { destroyLatch.countDown(); return runConc; } return false; }); IgniteInternalFuture f1 = GridTestUtils.runAsync(() -> { byte[] val = new byte[1024]; try (Transaction tx = ig.transactions().txStart(conc, iso, 1_000, 2)) { cache.put(100, val); cache2.put(100, val); tx.commit(); } catch (IgniteException e) { assertTrue(X.hasCause(e, IgniteTxTimeoutCheckedException.class) || X.hasCause(e, CacheInvalidStateException.class) || X.hasCause(e, IgniteException.class)); } }); f1.get(); f0.get(); try { assertEquals(cache2.get(100), cache.get(100)); } catch (IllegalStateException e) { assertTrue(X.hasCause(e, CacheStoppedException.class)); } spi.stopBlock(); }
Source:
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"); if(dnsServerAddress != null) { 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; }

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:
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 >> $runDir/console 2>&1 </dev/null &",clazz,args) ).execute(); }

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:
public E first(E defaultValue) { if (managedMode) { checkValidView(); if (!view.isEmpty()) { return get(0); } } else if (unmanagedList != null && unmanagedList.size() > 0) { return unmanagedList.get(0); } return defaultValue; }

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

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:
private void chunkGc() { Iterator<Cube> cubeIt = cubeCache.watchedCubesIterator(); 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(); } } }

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:
public boolean equals(Object o) { if (this == o) return true; if (o == null || !getClass().isAssignableFrom(o.getClass())) return false; NamedObject that = (NamedObject)o; if (!myName.equals(that.myName)) return false; if (!myValues.equals(that.myValues)) return false; return true; }

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:
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); 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(); addEmailPropsToFlow(flow, flowProps); } catch (final FileNotFoundException e) { logger.error("Error loading flow yaml files", e); } } }

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:
public void detach() { if (vungleBanner != null && vungleBanner.getParent() != null) { ((ViewGroup) vungleBanner.getParent()).removeView(vungleBanner); 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; } }

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:
public void setAndGet() { StatusCache cache = new StatusCache(); StatusDTO status = new StatusDTO() .result(true) .timeUTC(new Date().toInstant().atOffset(ZoneOffset.UTC)); cache.setStatus(status); assertEquals(status, cache.getStatus()); }

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:
private TimestampStorage createDatabaseTimestampStorage( DatabaseTsBoundPersisterConfiguration timestampBoundPersistence) { DatabaseTsBoundPersisterConfiguration persisterConfiguration = timestampBoundPersistence; ServiceDiscoveringDatabaseTimeLockSupplier dbTimeLockSupplier = new ServiceDiscoveringDatabaseTimeLockSupplier( metricsManager, persisterConfiguration.keyValueServiceConfig(), createLeaderConfig()); return ImmutableTimestampStorage.builder() .timestampCreator(new DbBoundTimestampCreator(dbTimeLockSupplier)) .persistentNamespaceContext(PersistentNamespaceContexts.dbBound( dbTimeLockSupplier.getTimestampSeriesProvider())) .build(); }

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:
public void build(TopologyBuilder bldr, Set<String> stageNames) { StreamletUtils.require(false, "build() in StreamletShadow should NOT be invoked"); }

Target:
public void build(TopologyBuilder bldr, Set<String> stageNames) { throw new UnsupportedOperationException("build() in StreamletShadow should NOT be invoked"); }
Source:
public void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { if (vc.getNAlleles() > 2) { filters.add(Mutect2Engine.TRIALLELIC_SITE_FILTER_NAME); } }

Target:
private static void applyTriallelicFilter(final VariantContext vc, final Collection<String> filters) { if (vc.getNAlleles() > 2) { filters.add(GATKVCFConstants.TRIALLELIC_SITE_FILTER_NAME); } }
Source:
public IClimateManipulatorBuilder createManipulator(ClimateType type) { return new ClimateManipulator.Builder() .setAllowBackwards() .setDefault(defaultState) .setCurrent(currentState) .setTarget(targetedState) .setChangeSupplier(housing::getChangeForState) .setType(type) .setOnFinish(this::setCurrent); }

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:
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 { if (temporary) return false; } return true; }

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:
public FileHostKeyCertificateProvider(Path... files) { this(Arrays.asList(files)); }

Target:
public FileHostKeyCertificateProvider(Path... files) { this(Arrays.asList(ValidateUtils.checkNotNullAndNotEmpty(files, "No path provided"))); }
Source:
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); data.putBoolean(MF_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()); }

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:
private void checkName(Tree issueLocation, @Nullable String name) { if (name != null && PURE_FUNCTIONS.contains(name)) { context().newIssue(this, issueLocation, "The return value of \"" + name + "\" must be used."); } }

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:
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 { 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"); } 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"); } }

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"); } }