auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void duplicateParameterPathRegistration_throwsException() { ConfigureRoutes mutable = new ConfigureRoutes(); mutable.setRoute(":param", ParamTarget.class); Assert.assertTrue(mutable.hasRouteTarget(ParamTarget.class)); Assert.assertEquals(ParamTarget.class, mutable .getNavigationRouteTarget("123").getRouteTarget().getTarget()); try { mutable.setRoute(":param", ParamTarget.class); Assert.fail("Parameter route is already registered"); } catch (InvalidRouteConfigurationException e) { } }

Target:
public void duplicateParameterPathRegistration_throwsException() { ConfigureRoutes mutable = new ConfigureRoutes(); mutable.setRoute(":param", ParamTarget.class); Assert.assertTrue(mutable.hasRouteTarget(ParamTarget.class)); Assert.assertEquals(ParamTarget.class, mutable .getNavigationRouteTarget("123").getRouteTarget().getTarget()); exceptionRule.expect(AmbiguousRouteConfigurationException.class); exceptionRule.reportMissingExceptionWithMessage( "Duplicate parameter routes shouldn't be accepted."); exceptionRule.expectMessage( "Navigation targets must have unique routes, found navigation targets 'com.vaadin.flow.router.internal.ConfigureRoutesTest$ParamTarget' and 'com.vaadin.flow.router.internal.ConfigureRoutesTest$ParamTarget' with parameter have the same route."); mutable.setRoute(":param", ParamTarget.class); }
Source:
public void actionPerformed(ActionEvent e) { String chosenfile = e.getActionCommand(); File nodeFile = new File(chosenfile); if (chosenfile.endsWith(".nwk")) { System.out.println("phylo tree"); FileSelector.lastopened.add(nodeFile); application.makePhyloTree(nodeFile); } else if (chosenfile.endsWith(".node.graph")) { FileSelector.lastopened.add(nodeFile); File edgeFile = FileSelector.getOtherExtension(nodeFile, ".node.graph", ".edge.graph"); application.makeGraph(nodeFile, edgeFile, null); } else { FileSelector.lastopened.add(nodeFile); File[] files = FileSelector.getFilesFromFolder(nodeFile, ".node.graph", ".edge.graph", ".nwk"); application.makeGraph(files[0], files[1], files[2]); } }

Target:
public void actionPerformed(ActionEvent e) { String chosenfile = e.getActionCommand(); File file = new File(chosenfile); if (chosenfile.endsWith(".nwk")) { FileSelector.lastopened.add(file); application.makePhyloTree(file); } else if (chosenfile.endsWith(".node.graph")) { FileSelector.lastopened.add(file); File edgeFile = FileSelector.getOtherExtension(file, ".node.graph", ".edge.graph"); application.makeGraph(file, edgeFile, null); } else { FileSelector.lastopened.add(file); File[] files = FileSelector.getFilesFromFolder(file, ".node.graph", ".edge.graph", ".nwk"); application.makeGraph(files[0], files[1], files[2]); } }
Source:
public void stopTerminal() { if (connected) { Jso jso = Jso.create(); jso.addField("type", "kill"); socket.send(jso.serialize()); } }

Target:
public void stopTerminal() { if (connected) { Jso jso = Jso.create(); jso.addField("type", "close"); socket.send(jso.serialize()); } }
Source:
public Builder setCell( String family, ByteString columnQualifier, ByteString value ) { final com.google.bigtable.v2.Mutation.SetCell.Builder setCell = com.google.bigtable.v2.Mutation.SetCell .newBuilder() .setFamilyName(family) .setColumnQualifier(columnQualifier) .setTimestampMicros(TimeUnit.MILLISECONDS.toMicros(DateTime.now().getMillis())) .setValue(value); mutations.add( com.google.bigtable.v2.Mutation .newBuilder() .setSetCell(setCell) .build() ); return this; }

Target:
public Builder setCell( String family, ByteString columnQualifier, ByteString value ) { final com.google.bigtable.v2.Mutation.SetCell.Builder setCell = com.google.bigtable.v2.Mutation.SetCell .newBuilder() .setFamilyName(family) .setColumnQualifier(columnQualifier) .setTimestampMicros(-1) .setValue(value); mutations.add( com.google.bigtable.v2.Mutation .newBuilder() .setSetCell(setCell) .build() ); return this; }
Source:
public AirGoogleMapOptions useViewLifecycleInFragment(boolean useViewLifecycleInFragment) { return this; }

Target:
public AirGoogleMapOptions useViewLifecycleInFragment(boolean useViewLifecycleInFragment) { options.useViewLifecycleInFragment(useViewLifecycleInFragment); return this; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; GlusterVolumeAdvancedDetails other = (GlusterVolumeAdvancedDetails) obj; if (capacityInfo == null) { if (other.capacityInfo != null) return false; } else if (!capacityInfo.equals(other.capacityInfo)) return false; if (serviceInfo == null) { if (other.serviceInfo != null) return false; } else if (!serviceInfo.equals(other.serviceInfo)) return false; if (volumeId == null) { if (other.volumeId != null) return false; } else if (!volumeId.equals(other.volumeId)) return false; return true; }

Target:
public boolean equals(Object obj) { if (!(obj instanceof GlusterVolumeAdvancedDetails)) { return false; } if (this == obj) return true; GlusterVolumeAdvancedDetails otherVolumeAdvancedDetails = (GlusterVolumeAdvancedDetails) obj; if (!ObjectUtils.objectsEqual(capacityInfo, otherVolumeAdvancedDetails.getCapacityInfo())) { return false; } if (!ObjectUtils.objectsEqual(serviceInfo, otherVolumeAdvancedDetails.getServiceInfo())) { return false; } if (!ObjectUtils.objectsEqual(updatedAt, otherVolumeAdvancedDetails.getUpdatedAt())) { return false; } if (!ListUtils.listsEqual(brickDetails, otherVolumeAdvancedDetails.getBrickDetails())) { return false; } if (!ObjectUtils.objectsEqual(volumeId, otherVolumeAdvancedDetails.getVolumeId())) { return false; } return true; }
Source:
public double getAvailableRAMInGB() { OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); double totRAMAvailable = bean.getTotalPhysicalMemorySize() / GIGABYTE; double totalRAMUsed = 0; for (LocalNode localNode : ProActiveRuntimeImpl.getProActiveRuntime().getLocalNodes()) { if (localNode.getProperty(RamSchedulingPolicy.RAM_VARIABLE_NAME) != null) { totalRAMUsed += Double .parseDouble(localNode.getProperty(RamSchedulingPolicy.RAM_VARIABLE_NAME)); } } double ramInBytes = totRAMAvailable - totalRAMUsed; return ramInBytes; }

Target:
public double getAvailableRAMInGB() { OperatingSystemMXBean bean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); double totRAMAvailable = ((double) bean.getTotalPhysicalMemorySize()) / GIGABYTE; double totalRAMUsed = 0; for (LocalNode localNode : ProActiveRuntimeImpl.getProActiveRuntime().getLocalNodes()) { if (localNode.getProperty(RamSchedulingPolicy.RAM_VARIABLE_NAME) != null) { totalRAMUsed += Double .parseDouble(localNode.getProperty(RamSchedulingPolicy.RAM_VARIABLE_NAME)); } } double ramInBytes = totRAMAvailable - totalRAMUsed; return ramInBytes; }
Source:
public void updateBlog(Blog blog) throws ClientServicesException { if (null == blog){ throw new ClientServicesException(null,"null blog"); } try { if(blog.getFieldsMap().get(AtomXPath.title)== null) blog.setTitle(blog.getTitle()); if(blog.getFieldsMap().get(AtomXPath.summary)== null) blog.setSummary(blog.getSummary()); if(!blog.getFieldsMap().toString().contains(BlogXPath.tags.toString())) blog.setTags(blog.getTags()); BlogSerializer serializer = new BlogSerializer(blog); String payload = serializer.updatePayload(); Map<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/atom+xml"); String updateBlogUrl = BlogUrls.GET_UPDATE_REMOVE_BLOG.format(this, BlogUrlParts.blogHandle.get(defaultHomepageHandle), BlogUrlParts.entryAnchor.get(blog.getUid())); getClientService().put(updateBlogUrl, null,headers, payload,ClientService.FORMAT_NULL); } catch (Exception e) { throw new ClientServicesException(e, "error updating blog"); } }

Target:
public void updateBlog(Blog blog) throws ClientServicesException { if (null == blog){ throw new ClientServicesException(null,"null blog"); } try { if(blog.getFieldsMap().get(AtomXPath.title)== null) blog.setTitle(blog.getTitle()); if(blog.getFieldsMap().get(AtomXPath.summary)== null) blog.setSummary(blog.getSummary()); if(!blog.getFieldsMap().toString().contains(BlogXPath.tags.toString())) blog.setTags(blog.getTags()); BlogSerializer serializer = new BlogSerializer(blog); String payload = serializer.updatePayload(); String updateBlogUrl = BlogUrls.GET_UPDATE_REMOVE_BLOG.format(this, BlogUrlParts.blogHandle.get(defaultHomepageHandle), BlogUrlParts.entryAnchor.get(blog.getUid())); getClientService().put(updateBlogUrl, null, getAtomHeaders(), payload,ClientService.FORMAT_NULL); } catch (Exception e) { throw new ClientServicesException(e, "error updating blog"); } }
Source:
public void testRegistrationOk() throws WebconnectionException { authenticator.performCatrobatRegister(testEmail, "de", "at", sharedPreferences.edit()); verify(listenerMock, never()).onError(anyInt(), anyString()); verify(listenerMock, atLeastOnce()).onSuccess(); token = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); boolean tokenOk = new CatrobatServerCalls().checkToken(token, testUser, BASE_URL_TEST_HTTPS); assertTrue(tokenOk); }

Target:
public void testRegistrationOk() throws WebconnectionException { authenticator.performCatrobatRegister(testEmail, "de", "at"); verify(listenerMock, never()).onError(anyInt(), anyString()); verify(listenerMock, atLeastOnce()).onSuccess(); token = sharedPreferences.getString(Constants.TOKEN, Constants.NO_TOKEN); assertTrue(new CatrobatServerCalls().checkToken(token, testUser, BASE_URL_TEST_HTTPS)); }
Source:
public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof NuxeoGroupImpl) { String name = getName(); String otherName = ((NuxeoGroupImpl) other).getName(); if (name == null) { return otherName == null; } else { return name.equals(otherName); } } return false; }

Target:
public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof NuxeoGroupImpl) { String name = getName(); String otherName = ((NuxeoGroupImpl) other).getName(); return Objects.equals(name, otherName); } return false; }
Source:
private void handleOnDemandRegistration(Class<?>... classes) { ArrayList<Class<?>> notIndexedYet = new ArrayList<>(classes.length); for (Class<?> type : classes) { if (!clusterRegistry.containsKey(type)) { notIndexedYet.add(type); } } if (!notIndexedYet.isEmpty()) { Class<?>[] toAdd = notIndexedYet.toArray(new Class[notIndexedYet.size()]); updateSearchFactory(toAdd); updateClusterRegistry(toAdd); } }

Target:
private void handleOnDemandRegistration(Class<?>... classes) { List<Class<?>> reducedSet = new ArrayList<>(classes.length); for (Class<?> type : classes) { if (!clusterRegistry.containsKey(type)) { reducedSet.add(type); } } if (!reducedSet.isEmpty()) { Class<?>[] toAdd = reducedSet.toArray(new Class[reducedSet.size()]); updateSearchFactory(toAdd); updateClusterRegistry(toAdd); } }
Source:
public Mono<Closeable> start(ConnectionAcceptor acceptor) { Mono<? extends NettyContext> serverMono = server .newHandler((in, out) -> { in.context().addHandler("server-length-codec", new RSocketLengthCodec()); NettyDuplexConnection connection = new NettyDuplexConnection(in, out, in.context()); acceptor.apply(connection).subscribe(); return out.neverComplete(); }); serverMono.map(s -> s.address()).subscribe(address); return serverMono.map(NettyContextClosable::new); }

Target:
public Mono<NettyContextCloseable> start(ConnectionAcceptor acceptor) { return server.newHandler((in, out) -> { in.context().addHandler("server-length-codec", new RSocketLengthCodec()); NettyDuplexConnection connection = new NettyDuplexConnection(in, out, in.context()); acceptor.apply(connection).subscribe(); return out.neverComplete(); }).map(NettyContextCloseable::new); }
Source:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { builder.field( "dynamicField", FieldType.OBJECT ) .mappedOn( Elasticsearch.class ) .dynamic( DynamicType.TRUE ); builder.field( "dynamicStrict", FieldType.OBJECT ); }

Target:
public void configureFieldMetadata(String name, FieldMetadataBuilder builder) { FieldMetadataCreationContext field = builder.field( name, FieldType.OBJECT ); if ( dynamicType != null ) { field.mappedOn( Elasticsearch.class ) .dynamic( dynamicType ); } }
Source:
public Iterable<Object> hydrate() { MutableInt counter = new MutableInt(0); List<Object> queryResults = getResults().stream() .map((result) -> { return result instanceof Object[] ? (Object []) result : new Object[] { result }; }) .map((result) -> coerceObjectToEntity(result, counter)) .collect(Collectors.toList()); if (getStitchList().shouldStitch()) { populateObjectLookupTable(); getStitchList().stitch(); } return queryResults; }

Target:
public Iterable<Object> hydrate() { MutableInt counter = new MutableInt(0); List<Object> queryResults = getResults().stream() .map((result) -> coerceObjectToEntity(result, counter)) .collect(Collectors.toList()); if (getStitchList().shouldStitch()) { populateObjectLookupTable(); getStitchList().stitch(); } return queryResults; }
Source:
private void setupQueries() { Set<GeoHashQuery> oldQueries = (this.queries == null) ? new HashSet<GeoHashQuery>() : this.queries; Set<GeoHashQuery> newQueries = GeoHashQuery.queriesAtLocation(center.latitude, center.longitude, radius); this.queries = newQueries; for (GeoHashQuery query: oldQueries) { if (!newQueries.contains(query)) { firebaseQueries.get(query).removeEventListener(this.childEventLister); firebaseQueries.remove(query); outstandingQueries.remove(query); } } for (final GeoHashQuery query: newQueries) { if (!oldQueries.contains(query)) { outstandingQueries.add(query); Firebase firebase = this.geoFire.getFirebase(); Query firebaseQuery = firebase.startAt(query.getStartValue()).endAt(query.getEndValue()); firebaseQuery.addChildEventListener(this.childEventLister); addValueToReadyListener(firebaseQuery, query); firebaseQueries.put(query, firebaseQuery); } } for(Map.Entry<String, LocationInfo> info: this.locationInfos.entrySet()) { LocationInfo oldLocationInfo = info.getValue(); this.updateLocationInfo(info.getKey(), oldLocationInfo.location); } Iterator<Map.Entry<String, LocationInfo>> it = this.locationInfos.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, LocationInfo> entry = it.next(); if (!this.geoHashQueriesContainGeoHash(entry.getValue().geoHash)) { it.remove(); } } checkAndFireReady(); }

Target:
private void setupQueries() { Set<GeoHashQuery> oldQueries = (this.queries == null) ? new HashSet<GeoHashQuery>() : this.queries; Set<GeoHashQuery> newQueries = GeoHashQuery.queriesAtLocation(center, radius); this.queries = newQueries; for (GeoHashQuery query: oldQueries) { if (!newQueries.contains(query)) { firebaseQueries.get(query).removeEventListener(this.childEventLister); firebaseQueries.remove(query); outstandingQueries.remove(query); } } for (final GeoHashQuery query: newQueries) { if (!oldQueries.contains(query)) { outstandingQueries.add(query); Firebase firebase = this.geoFire.getFirebase(); Query firebaseQuery = firebase.startAt(query.getStartValue()).endAt(query.getEndValue()); firebaseQuery.addChildEventListener(this.childEventLister); addValueToReadyListener(firebaseQuery, query); firebaseQueries.put(query, firebaseQuery); } } for(Map.Entry<String, LocationInfo> info: this.locationInfos.entrySet()) { LocationInfo oldLocationInfo = info.getValue(); this.updateLocationInfo(info.getKey(), oldLocationInfo.location); } Iterator<Map.Entry<String, LocationInfo>> it = this.locationInfos.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, LocationInfo> entry = it.next(); if (!this.geoHashQueriesContainGeoHash(entry.getValue().geoHash)) { it.remove(); } } checkAndFireReady(); }
Source:
private String getThreeWayOverlay(final Diff diff) { final Conflict conflict = diff.getConflict(); final DifferenceKind diffKind = diff.getKind(); final DifferenceSource source = diff.getSource(); ConflictKind conflictKind = null; if (hasDirectOrIndirectConflict(REAL).apply(diff)) { conflictKind = REAL; } else if (or(hasConflict(PSEUDO), allRefining(hasConflict(PSEUDO))).apply(diff)) { conflictKind = PSEUDO; } String path = ""; if (conflict != null || conflictKind != null) { if ((conflict != null && conflict.getKind() == PSEUDO) || conflictKind == PSEUDO) { path += "p"; } path += "conf"; if (source == DifferenceSource.RIGHT) { path += "r_"; } } else { switch (source) { case LEFT: path += "r_out"; break; case RIGHT: path += "r_in"; break; default: break; } } switch (diffKind) { case ADD: path += ADD_OV; break; case DELETE: path += DEL_OV; break; case CHANGE: case MOVE: path += CHG_OV; break; default: break; } return path; }

Target:
private String getThreeWayOverlay(final Diff diff) { final Conflict conflict = diff.getConflict(); final DifferenceKind diffKind = diff.getKind(); final DifferenceSource source = diff.getSource(); ConflictKind conflictKind = null; if (hasDirectOrIndirectConflict(REAL).apply(diff)) { conflictKind = REAL; } else if (or(hasConflict(PSEUDO), allAtomicRefining(hasConflict(PSEUDO))).apply(diff)) { conflictKind = PSEUDO; } String path = ""; if (conflict != null || conflictKind != null) { if ((conflict != null && conflict.getKind() == PSEUDO) || conflictKind == PSEUDO) { path += "p"; } path += "conf"; if (source == DifferenceSource.RIGHT) { path += "r_"; } } else { switch (source) { case LEFT: path += "r_out"; break; case RIGHT: path += "r_in"; break; default: break; } } switch (diffKind) { case ADD: path += ADD_OV; break; case DELETE: path += DEL_OV; break; case CHANGE: case MOVE: path += CHG_OV; break; default: break; } return path; }
Source:
public Response<Set<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || Strings.isNullOrEmpty(input.hashtags)) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> oldHashtags = notes.getHashtags(); Set<String> hashtags = new HashSet<String>(); if (oldHashtags != null) { hashtags.addAll(oldHashtags); } hashtags.addAll(Arrays.asList(input.hashtags.split(","))); update.setHashtags(hashtags); update.commit(); return Response.ok(hashtags); }

Target:
public Response<Set<String>> apply(ChangeResource req, Input input) throws AuthException, OrmException, IOException, BadRequestException { if (input == null || Strings.isNullOrEmpty(input.hashtags)) { throw new BadRequestException("Hashtags are required"); } ChangeControl control = req.getControl(); if (!control.canEditHashtags()) { throw new AuthException("Editing hashtags not permitted"); } ChangeUpdate update = updateFactory.create(control); ChangeNotes notes = control.getNotes().load(); Set<String> oldHashtags = notes.getHashtags(); Set<String> hashtags = new HashSet<String>(); if (oldHashtags != null) { hashtags.addAll(oldHashtags); } hashtags.addAll(Arrays.asList(input.hashtags.split(","))); update.setHashtags(hashtags); update.commit(); return Response.ok(hashtags); }
Source:
public boolean deleteAllExpiredObjects() { try { this.persistenceEntryManager.remove(String.format("%s,%s", new Object[]{getExpiredObjOu(), getOxdDn()}), ExpiredObject.class, null, 100); LOG.debug("Removed all expired_objects successfully. "); return true; } catch (Exception e) { LOG.error("Failed to remove expired_objects. ", e); } return false; }

Target:
public boolean deleteAllExpiredObjects() { try { final Calendar cal = Calendar.getInstance(); final Date currentTime = cal.getTime(); Filter exirationDateFilter = Filter.createLessOrEqualFilter("exp", this.persistenceEntryManager.encodeTime(baseDn, currentTime)); this.persistenceEntryManager.remove(String.format("%s,%s", new Object[]{getExpiredObjOu(), getOxdDn()}), ExpiredObject.class, exirationDateFilter, this.configuration.getPersistenceManagerRemoveCount()); LOG.debug("Removed all expired_objects successfully. "); return true; } catch (Exception e) { LOG.error("Failed to remove expired_objects. ", e); } return false; }
Source:
protected String getBlockNameForDirection(EnumFacing direction) { Block b = cb.getBundleWorldObj().getBlockState(cb.getLocation().getLocation(direction).getBlockPos()).getBlock(); if (b != null && b != Blocks.air) { return b.getLocalizedName(); } return null; }

Target:
protected String getBlockNameForDirection(EnumFacing direction) { World world = cb.getBundleWorldObj(); BlockPos blockPos = cb.getLocation().getLocation(direction).getBlockPos(); if (world.isAirBlock(blockPos)) { return null; } Block b = world.getBlockState(blockPos).getBlock(); if (b != null && b != EnderIO.blockConduitBundle) { return b.getLocalizedName(); } return null; }
Source:
private RepoCollection updateCollection(InputCollection inputCollection, Timestamp timestamp, RepoCollection existingRepoCollection, Timestamp creationDate) throws RepoException { if (areCollectionsSimilar(inputCollection.getKey(), inputCollection.getBucketName(), inputCollection.getObjects(), inputCollection.getTag(), existingRepoCollection)){ return existingRepoCollection; } try{ return createCollection(inputCollection.getKey(), inputCollection.getBucketName(), timestamp, existingRepoCollection.getBucketId(), inputCollection.getObjects(), inputCollection.getTag(), creationDate, inputCollection.getUserMetadata()); } catch(SQLIntegrityConstraintViolationException e){ log.debug("Error trying to version a collection, key: " + inputCollection.getKey() + " . SQLIntegrityConstraintViolationException: " + e.getMessage()); throw new RepoException(RepoException.Type.CantCreateCollectionVersionWithNoOrig); } catch(SQLException e){ log.debug("SQLException: " + e.getMessage()); throw new RepoException(e); } }

Target:
private RepoCollection updateCollection(InputCollection inputCollection, Timestamp timestamp, RepoCollection existingRepoCollection, Timestamp creationDate) throws RepoException { if (areCollectionsSimilar(inputCollection, existingRepoCollection)){ return existingRepoCollection; } RepoCollection repoCollection = new RepoCollection(inputCollection.getKey(), existingRepoCollection.getBucketId(), inputCollection.getBucketName(), Status.USED); repoCollection.setTimestamp(timestamp); repoCollection.setTag(inputCollection.getTag()); repoCollection.setCreationDate(creationDate); repoCollection.setUserMetadata(inputCollection.getUserMetadata()); try{ return createCollection(repoCollection, inputCollection.getObjects()); } catch(SQLIntegrityConstraintViolationException e){ log.debug("Error trying to version a collection, key: " + inputCollection.getKey() + " . SQLIntegrityConstraintViolationException: " + e.getMessage()); throw new RepoException(RepoException.Type.CantCreateCollectionVersionWithNoOrig); } catch(SQLException e){ log.debug("SQLException: " + e.getMessage()); throw new RepoException(e); } }
Source:
boolean isCacheable() { return true; }

Target:
boolean isCacheable() { return false; }
Source:
public void record(Trace trace) { if (trace.getNodes() != null && trace.getNodes().size() > 0) { Node rootNode = trace.getNodes().get(0); if (this.deploymentMetaData != null) { if (!rootNode.hasProperty(Constants.PROP_SERVICE_NAME) && this.deploymentMetaData.getServiceName() != null) { rootNode.getProperties().add(new Property(Constants.PROP_SERVICE_NAME, this.deploymentMetaData.getServiceName())); } if (!rootNode.hasProperty(Constants.PROP_BUILD_STAMP) && this.deploymentMetaData.getBuildStamp() != null) { rootNode.getProperties().add(new Property(Constants.PROP_BUILD_STAMP, this.deploymentMetaData.getBuildStamp())); } } } backingTraceRecorder.record(trace); }

Target:
public void record(Trace trace) { if (trace.getNodes() != null && trace.getNodes().size() > 0) { Node rootNode = trace.getNodes().get(0); if (this.deploymentMetaData != null) { if (this.deploymentMetaData.getServiceName() != null && !rootNode.hasProperty(Constants.PROP_SERVICE_NAME)) { rootNode.getProperties().add(new Property(Constants.PROP_SERVICE_NAME, this.deploymentMetaData.getServiceName())); } if (this.deploymentMetaData.getBuildStamp() != null && !rootNode.hasProperty(Constants.PROP_BUILD_STAMP)) { rootNode.getProperties().add(new Property(Constants.PROP_BUILD_STAMP, this.deploymentMetaData.getBuildStamp())); } } } backingTraceRecorder.record(trace); }
Source:
public InterpreterResult interpret(String markdownText, InterpreterContext interpreterContext) { String html; try { html = parser.render(markdownText); } catch (Exception e) { LOGGER.error("Exception in MarkdownInterpreter while interpret ", e); return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e)); } return new InterpreterResult(Code.SUCCESS, "%html " + html); }

Target:
public InterpreterResult interpret(String markdownText, InterpreterContext interpreterContext) { String html; try { html = parser.render(markdownText); } catch (RuntimeException e) { LOGGER.error("Exception in MarkdownInterpreter while interpret ", e); return new InterpreterResult(Code.ERROR, InterpreterUtils.getMostRelevantMessage(e)); } return new InterpreterResult(Code.SUCCESS, "%html " + html); }
Source:
public static NIC map(VmNetworkInterface entity, NIC template) { NIC model = template != null ? template : new NIC(); if (entity.getVmId() != null) { model.setVm(new VM()); model.getVm().setId(entity.getVmId().toString()); } if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getName() != null) { model.setName(entity.getName()); } if (entity.getMacAddress() != null) { model.setMac(new MAC()); model.getMac().setAddress(entity.getMacAddress()); } if (entity.getNetworkName() != null) { model.setNetwork(new Network()); model.getNetwork().setName(entity.getNetworkName()); } model.setLinked(entity.isLinked()); model.setInterface(map(entity.getType())); model.setActive(entity.isPlugged()); model.setPlugged(entity.isPlugged()); if (!StringUtils.isEmpty(entity.getCustomProperties())) { CustomProperties hooks = new CustomProperties(); hooks.getCustomProperty().addAll(CustomPropertiesParser.parse(entity.getCustomProperties(), false)); model.setCustomProperties(hooks); } return model; }

Target:
public static NIC map(VmNetworkInterface entity, NIC template) { NIC model = template != null ? template : new NIC(); if (entity.getVmId() != null) { model.setVm(new VM()); model.getVm().setId(entity.getVmId().toString()); } if (entity.getId() != null) { model.setId(entity.getId().toString()); } if (entity.getName() != null) { model.setName(entity.getName()); } if (entity.getMacAddress() != null) { model.setMac(new MAC()); model.getMac().setAddress(entity.getMacAddress()); } if (entity.getNetworkName() != null) { model.setNetwork(new Network()); model.getNetwork().setName(entity.getNetworkName()); } model.setLinked(entity.isLinked()); model.setInterface(map(entity.getType())); model.setActive(entity.isPlugged()); model.setPlugged(entity.isPlugged()); if (entity.getCustomProperties() != null && !entity.getCustomProperties().isEmpty()) { CustomProperties hooks = new CustomProperties(); hooks.getCustomProperty().addAll(CustomPropertiesParser.parse( DevicePropertiesUtils.getInstance().convertProperties(entity.getCustomProperties()), false)); model.setCustomProperties(hooks); } return model; }
Source:
public void initialise() { List<AssetUri> uris = Lists.newArrayList(); for (AssetUri uri : assetManager.listAssets(AssetType.SOUND)) { uris.add(uri); } BehaviorTree defaultTree = null; for (AssetUri uri : assetManager.listAssets(AssetType.BEHAVIOR)) { BehaviorTree asset = assetManager.loadAsset(uri, BehaviorTree.class); if (asset != null) { trees.add(asset); if (asset.getURI().getAssetName().equals("default")) { defaultTree = asset; } } } createGlobalEntity(defaultTree); }

Target:
public void initialise() { List<AssetUri> uris = Lists.newArrayList(); for (AssetUri uri : assetManager.listAssets(AssetType.SOUND)) { uris.add(uri); } for (AssetUri uri : assetManager.listAssets(AssetType.BEHAVIOR)) { BehaviorTree asset = assetManager.loadAsset(uri, BehaviorTree.class); if (asset != null) { trees.add(asset); } } }
Source:
void foo1() throws InvalidKeyException, InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchPaddingException, UnsupportedEncodingException, IllegalBlockSizeException, BadPaddingException { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); IvParameterSpec iv = new IvParameterSpec(bytes); }

Target:
void foo1() throws Exception { byte[] bytes = "111".getBytes("UTF-8"); random.nextBytes(bytes); IvParameterSpec iv = new IvParameterSpec(bytes); }
Source:
public SerializedPage serialize(Slice slice, int positionCount) { int uncompressedSize = slice.length(); byte markers = PageCodecMarker.none(); if (compressor.isPresent()) { ByteBuffer compressionBuffer = ByteBuffer.allocate(compressor.get().maxCompressedLength(uncompressedSize)); compressor.get().compress(slice.toByteBuffer(), compressionBuffer); compressionBuffer.flip(); if ((((double) compressionBuffer.remaining()) / uncompressedSize) <= MINIMUM_COMPRESSION_RATIO) { slice = Slices.wrappedBuffer(compressionBuffer); markers = COMPRESSED.set(markers); } } if (spillCipher.isPresent()) { slice = Slices.wrappedBuffer(spillCipher.get().encrypt(slice.toByteBuffer())); markers = ENCRYPTED.set(markers); } else { if (slice.length() < uncompressedSize) { slice = Slices.copyOf(slice); } } return new SerializedPage(slice, markers, positionCount, uncompressedSize); }

Target:
public SerializedPage serialize(Slice slice, int positionCount) { checkArgument(slice.isCompact(), "slice is not compact"); int uncompressedSize = slice.length(); byte markers = PageCodecMarker.none(); if (compressor.isPresent()) { int maxCompressedSize = compressor.get().maxCompressedLength(uncompressedSize); ensureCompressionBufferCapacity(maxCompressedSize); int compressedSize = compressor.get().compress((byte[]) slice.getBase(), 0, uncompressedSize, compressionBuffer, 0, maxCompressedSize); if ((((double) compressedSize) / uncompressedSize) <= MINIMUM_COMPRESSION_RATIO) { slice = Slices.copyOf(Slices.wrappedBuffer(compressionBuffer, 0, compressedSize)); markers = COMPRESSED.set(markers); } } if (spillCipher.isPresent()) { slice = Slices.wrappedBuffer(spillCipher.get().encrypt(slice.toByteBuffer())); markers = ENCRYPTED.set(markers); } return new SerializedPage(slice, markers, positionCount, uncompressedSize); }
Source:
public MulePackageBuilder withTestClasses(File folder) { checkArgument(folder != null, "The folder must not be null"); checkArgument(folder.exists(), "The folder must must exists"); testClassesFolder = folder; return this; }

Target:
public MulePackageBuilder withTestClasses(File folder) { checkArgument(folder != null, "The folder must not be null"); checkArgument(folder.exists(), "The folder must exists"); testClassesFolder = folder; return this; }
Source:
public void removeMeta(Session session, int id) { if (id > 0 && !starting) { SearchRow r = meta.getTemplateSimpleRow(false); r.setValue(0, ValueInt.get(id)); boolean wasLocked = lockMeta(session); try { Cursor cursor = metaIdIndex.find(session, r, r); if (cursor.next()) { if (SysProperties.CHECK) { if (lockMode != Constants.LOCK_MODE_OFF && !wasLocked) { throw DbException.throwInternalError(); } } Row found = cursor.get(); meta.removeRow(session, found); if (SysProperties.CHECK) { checkMetaFree(session, id); } } } finally { if (!wasLocked) { unlockMeta(session); } } if (isMVStore()) { session.releaseDatabaseObjectId(id); } else { synchronized (this) { objectIds.clear(id); } } } }

Target:
public void removeMeta(Session session, int id) { if (id > 0 && !starting) { SearchRow r = meta.getTemplateSimpleRow(false); r.setValue(0, ValueInt.get(id)); boolean wasLocked = lockMeta(session); try { Cursor cursor = metaIdIndex.find(session, r, r); if (cursor.next()) { if (SysProperties.CHECK) { if (lockMode != Constants.LOCK_MODE_OFF && !wasLocked) { throw DbException.throwInternalError(); } } Row found = cursor.get(); meta.removeRow(session, found); if (SysProperties.CHECK) { checkMetaFree(session, id); } } } finally { if (!wasLocked) { unlockMeta(session); } } if (isMVStore()) { session.scheduleDatabaseObjectIdForRelease(id); } else { synchronized (this) { objectIds.clear(id); } } } }
Source:
public void testEvtOpenChannelEnum() throws Exception { EVT_HANDLE channelHandle = null; List<String> channelList = new ArrayList<String>(); try { channelHandle = Wevtapi.INSTANCE.EvtOpenChannelEnum(null, 0); if (channelHandle == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } Memory buff = new Memory(1024); IntByReference buffUsed = new IntByReference(); while (true) { buff.clear(); if (!Wevtapi.INSTANCE.EvtNextChannelPath(channelHandle, (int) buff.size(), buff, buffUsed)) { if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_NO_MORE_ITEMS) { break; } else if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_INSUFFICIENT_BUFFER) { buff = new Memory(buffUsed.getValue()); if (!Wevtapi.INSTANCE.EvtNextChannelPath(channelHandle, (int) buff.size(), buff, buffUsed)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } } channelList.add(buff.getWideString(0)); } assertThat(channelList.size() > 0, is(true)); } finally { if (channelHandle != null) { Wevtapi.INSTANCE.EvtClose(channelHandle); } } }

Target:
public void testEvtOpenChannelEnum() throws Exception { EVT_HANDLE channelHandle = null; List<String> channelList = new ArrayList<String>(); try { channelHandle = Wevtapi.INSTANCE.EvtOpenChannelEnum(null, 0); if (channelHandle == null) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } char[] buff = new char[1024]; IntByReference buffUsed = new IntByReference(); while (true) { if (!Wevtapi.INSTANCE.EvtNextChannelPath(channelHandle, buff.length, buff, buffUsed)) { if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_NO_MORE_ITEMS) { break; } else if (Kernel32.INSTANCE.GetLastError() == WinError.ERROR_INSUFFICIENT_BUFFER) { buff = new char[buffUsed.getValue()]; if (!Wevtapi.INSTANCE.EvtNextChannelPath(channelHandle, buff.length, buff, buffUsed)) { throw new Win32Exception(Kernel32.INSTANCE.GetLastError()); } } } channelList.add(Native.toString(buff)); } assertThat(channelList.size() > 0, is(true)); } finally { if (channelHandle != null) { Wevtapi.INSTANCE.EvtClose(channelHandle); } } }
Source:
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { this.pipeline = pipeline; return this; }

Target:
public ConfigurationClientBuilder pipeline(HttpPipeline pipeline) { if (this.pipeline != null && pipeline == null) { logger.info("HttpPipeline is being set to 'null' when it was previously configured."); } this.pipeline = pipeline; return this; }
Source:
public void start() { CacheMode mode = configuration.clustering().cacheMode(); isFetchEnabled = (mode.isDistributed() || mode.isReplicated()) && (configuration.clustering().stateTransfer().fetchInMemoryState() || configuration.persistence().fetchPersistentState()); initRpcOptions(); configuration.clustering().attributes().attribute(ClusteringConfiguration.REMOTE_TIMEOUT) .addListener((a, o) -> initRpcOptions()); stateRequestExecutor = new LimitedExecutor("StateRequest-" + cacheName, stateTransferExecutor, 1); }

Target:
public void start() { CacheMode mode = configuration.clustering().cacheMode(); isFetchEnabled = (mode.isDistributed() || mode.isReplicated()) && (configuration.clustering().stateTransfer().fetchInMemoryState() || configuration.persistence().fetchPersistentState()); synchronousRpcOptions = rpcManager.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS) .timeout(timeout, TimeUnit.MILLISECONDS).build(); synchronousIgnoreLeaversRpcOptions = rpcManager.getRpcOptionsBuilder(ResponseMode.SYNCHRONOUS_IGNORE_LEAVERS) .timeout(timeout, TimeUnit.MILLISECONDS).build(); stateRequestExecutor = new LimitedExecutor("StateRequest-" + cacheName, stateTransferExecutor, 1); }
Source:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) throws IllegalArgumentException { super.configurePipeline(pipelineConfigurer); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Row field must be given as a property."); Schema inputSchema = pipelineConfigurer.getStageConfigurer().getInputSchema(); if (inputSchema != null) { validateInputAndOutputSchemaFields(inputSchema); boolean rowFieldPresent = false; for (Schema.Field field : inputSchema.getFields()) { if (!field.getSchema().getType().isSimpleType()) { throw new IllegalArgumentException( String.format("Field '%s' is not of simple type, All fields for table sink should of simple type", field.getName())); } if (field.getName().equals(tableSinkConfig.getRowField())) { rowFieldPresent = true; } } if (!rowFieldPresent) { throw new IllegalArgumentException( String.format("Row field key : '%s' is not present in the input schema", tableSinkConfig.getRowField())); } } }

Target:
public void configurePipeline(PipelineConfigurer pipelineConfigurer) { super.configurePipeline(pipelineConfigurer); Preconditions.checkArgument(!Strings.isNullOrEmpty(tableSinkConfig.getRowField()), "Row field must be given as a property."); Schema outputSchema = SchemaValidator.validateOutputSchemaAndInputSchemaIfPresent(tableSinkConfig.getSchemaStr(), tableSinkConfig.getRowField(), pipelineConfigurer); pipelineConfigurer.getStageConfigurer().setOutputSchema(outputSchema); }
Source:
private static void parseFlags(@NotNull FormatState state) { String knownFlags = "#0+- "; StringBuilder flags = new StringBuilder(state.flags); while (state.nBytes < state.format.length()) { if (knownFlags.indexOf(state.format.charAt(state.nBytes)) != -1) { flags.append(state.format.charAt(state.nBytes)); } else { state.flags = flags.toString(); return; } state.nBytes++; } state.flags = flags.toString(); }

Target:
private static void parseFlags(@NotNull FormatState state) { String knownFlags = "#0+- "; StringBuilder flags = new StringBuilder(state.flags); while (state.nBytes < state.format.length()) { if (StringUtil.containsChar(knownFlags, state.format.charAt(state.nBytes))) { flags.append(state.format.charAt(state.nBytes)); } else { state.flags = flags.toString(); return; } state.nBytes++; } state.flags = flags.toString(); }
Source:
public static void deleteSshKeys(String account, Set<Integer> sequenceNumbers, AsyncCallback<VoidResult> cb) { CountingCallback ccb = new CountingCallback(sequenceNumbers.size(), cb); for (int seq : sequenceNumbers) { new RestApi("/accounts/").id(account).view("sshkeys").id(seq) .delete(ccb); } }

Target:
public static void deleteSshKeys(String account, Set<Integer> sequenceNumbers, AsyncCallback<VoidResult> cb) { CallbackGroup group = new CallbackGroup(); for (int seq : sequenceNumbers) { new RestApi("/accounts/").id(account).view("sshkeys").id(seq) .delete(group.add(cb)); cb = CallbackGroup.emptyCallback(); } }
Source:
public synchronized void onResponseComplete(Exception exception) { if (requestComplete.compareAndSet(false, true)) { this.exception = exception; try { if (!responseMetadataFinalized.get() && exception != null) { String allow = getHeader(RestUtils.Headers.ALLOW); responseMetadata.put(RESPONSE_HEADERS_KEY, new JSONObject()); if (allow != null && !allow.isEmpty()) { setHeader(RestUtils.Headers.ALLOW, allow); } setHeader(RestUtils.Headers.CONTENT_TYPE, "text/plain; charset=UTF-8"); ResponseStatus status = ResponseStatus.InternalServerError; if (exception instanceof RestServiceException) { status = ResponseStatus.getResponseStatus(((RestServiceException) exception).getErrorCode()); } responseMetadata.put(RESPONSE_STATUS_KEY, status); bodyBytes.write(exception.toString().getBytes()); responseMetadataFinalized.set(true); } close(); if (restRequest != null) { restRequest.getMetricsTracker().nioMetricsTracker.markRequestCompleted(); restRequest.close(); } onEventComplete(Event.OnRequestComplete); } catch (Exception e) { } } }

Target:
public synchronized void onResponseComplete(Exception exception) { if (requestComplete.compareAndSet(false, true)) { this.exception = exception; try { if (!responseMetadataFinalized.get() && exception != null) { String allow = getHeader(RestUtils.Headers.ALLOW); responseMetadata.put(RESPONSE_HEADERS_KEY, new JSONObject()); if (!Utils.isNullOrEmpty(allow)) { setHeader(RestUtils.Headers.ALLOW, allow); } setHeader(RestUtils.Headers.CONTENT_TYPE, "text/plain; charset=UTF-8"); ResponseStatus status = ResponseStatus.InternalServerError; if (exception instanceof RestServiceException) { status = ResponseStatus.getResponseStatus(((RestServiceException) exception).getErrorCode()); } responseMetadata.put(RESPONSE_STATUS_KEY, status); bodyBytes.write(exception.toString().getBytes()); responseMetadataFinalized.set(true); } close(); if (restRequest != null) { restRequest.getMetricsTracker().nioMetricsTracker.markRequestCompleted(); restRequest.close(); } onEventComplete(Event.OnRequestComplete); } catch (Exception e) { } } }
Source:
public void mamTest() throws Exception { if (!mamManager.isSupportedByServer()) { return; } Jid userOne = JidCreate.from(conOne.getUser().toString().split("/")[0]); Jid userTwo = JidCreate.from(conTwo.getUser().toString().split("/")[0]); MamQueryResult mamQueryResult = mamManager.queryArchive(userTwo); if (mamQueryResult.forwardedMessages.isEmpty()) { Message message = new Message(); message.setBody("test-message"); message.setFrom(userOne); message.setTo(userTwo); conOne.sendStanza(message); mamQueryResult = mamManager.queryArchive(userTwo); } Assert.assertFalse(mamQueryResult.forwardedMessages.isEmpty()); }

Target:
public void mamTest() throws Exception { Jid userOne = conOne.getUser().asEntityBareJid(); Jid userTwo = conTwo.getUser().asEntityBareJid(); String messageId = UUID.randomUUID().toString(); String messageBody = "test message"; Message message = prepareMessage(userTwo, messageId, messageBody); conOne.sendStanza(message); Message mamMessage = getConTwoLastMessageSentFrom(userOne); Assert.assertEquals(messageId, mamMessage.getStanzaId()); Assert.assertEquals(messageBody, mamMessage.getBody()); Assert.assertEquals(conOne.getUser(), mamMessage.getFrom()); Assert.assertEquals(userTwo, mamMessage.getTo()); }
Source:
public boolean validatePanel() { errorLabel.setVisible(false); String path = getImageFilePath(); if (path == null || path.isEmpty()) { return false; } warnIfPathIsInvalid(path); boolean isExist = new File(path).exists(); return (isExist); }

Target:
boolean validatePanel() { errorLabel.setVisible(false); String path = getImageFilePath(); if (path == null || path.isEmpty()) { return false; } warnIfPathIsInvalid(path); boolean isExist = new File(path).exists(); return (isExist); }
Source:
protected String getProjectLocation() { IProject createdProject = projectProvider.getProject(); return createdProject.getLocation().toOSString(); }

Target:
protected String getProjectLocation() { IProject createdProject = projectProvider.getProject(); return createdProject.getLocation().toString(); }
Source:
public TransferFormsTableView(TransferFormsTableViewModel model, String[] headers) { super(model); this.headers = headers; setName("forms"); addMouseListener(new MouseAdapterBuilder().onClick(this::relayClickToButton).build()); Dimension formNameDims = TableCustomizer.getHeaderDimension(getHeader(FORM_NAME_COL), this); Dimension statusDims = TableCustomizer.getHeaderDimension(getHeader(STATUS_COL), this); TableCustomizer.customizeHeader(getTableHeader()); TableCustomizer.customizeTable(this); TableColumnModel columns = getColumnModel(); columns.getColumn(SELECTED_CHECKBOX_COL).setMinWidth(40); columns.getColumn(SELECTED_CHECKBOX_COL).setMaxWidth(40); columns.getColumn(SELECTED_CHECKBOX_COL).setPreferredWidth(40); columns.getColumn(FORM_NAME_COL).setMinWidth(formNameDims.width + 25); columns.getColumn(FORM_NAME_COL).setPreferredWidth(formNameDims.width + 25); columns.getColumn(STATUS_COL).setMinWidth(statusDims.width + 25); columns.getColumn(STATUS_COL).setPreferredWidth(statusDims.width + 25); columns.getColumn(DETAIL_BUTTON_COL).setCellRenderer(UI::cellWithButton); columns.getColumn(DETAIL_BUTTON_COL).setMinWidth(40); columns.getColumn(DETAIL_BUTTON_COL).setMaxWidth(40); columns.getColumn(DETAIL_BUTTON_COL).setPreferredWidth(40); setFillsViewportHeight(true); TableRowSorter<TransferFormsTableViewModel> sorter = sortBy(getModel(), FORM_NAME_COL, ASCENDING); setRowSorter(sorter); sorter.sort(); }

Target:
public TransferFormsTableView(TransferFormsTableViewModel model, String[] headers) { super(model); this.headers = headers; setName("forms"); addMouseListener(new MouseAdapterBuilder().onClick(this::relayClickToButton).build()); Dimension formNameDims = getHeaderDimension(this, getHeader(FORM_NAME_COL)); Dimension statusDims = getHeaderDimension(this, getHeader(STATUS_COL)); customizeHeader(getTableHeader()); customizeTable(this); TableColumnModel columns = getColumnModel(); columns.getColumn(SELECTED_CHECKBOX_COL).setMinWidth(40); columns.getColumn(SELECTED_CHECKBOX_COL).setMaxWidth(40); columns.getColumn(SELECTED_CHECKBOX_COL).setPreferredWidth(40); columns.getColumn(FORM_NAME_COL).setMinWidth(formNameDims.width + 25); columns.getColumn(FORM_NAME_COL).setPreferredWidth(formNameDims.width + 25); columns.getColumn(STATUS_COL).setMinWidth(statusDims.width + 25); columns.getColumn(STATUS_COL).setPreferredWidth(statusDims.width + 25); columns.getColumn(DETAIL_BUTTON_COL).setCellRenderer(UI::cellWithButton); columns.getColumn(DETAIL_BUTTON_COL).setMinWidth(40); columns.getColumn(DETAIL_BUTTON_COL).setMaxWidth(40); columns.getColumn(DETAIL_BUTTON_COL).setPreferredWidth(40); setFillsViewportHeight(true); TableRowSorter<TransferFormsTableViewModel> sorter = sortBy(getModel(), FORM_NAME_COL, ASCENDING); setRowSorter(sorter); sorter.sort(); }
Source:
public void testRenameNewNameExists() throws Exception { typeContext = new LabelClientTypeContext(store, LabelType.METRIC, metrics, eventBus, MAX_CACHE_SIZE); typeContext.createId("newName"); typeContext.rename("oldName", "newName"); }

Target:
public void testRenameNewNameExists() throws Exception { typeContext = new LabelClientTypeContext(store, LabelType.METRIC, metrics, eventBus, MAX_CACHE_SIZE); typeContext.createId("newName").get(); try { typeContext.rename("oldName", "newName").get(); fail("Should have thrown an exception, can not rename to a name that is already taken."); } catch (ExecutionException exception) { assertTrue(exception.getCause() instanceof IllegalArgumentException); } }