auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public @Nonnull EnvVars getEnvironment(@Nonnull TaskListener log) throws IOException, InterruptedException { Computer c = Computer.currentComputer(); Node n = c==null ? null : c.getNode(); EnvVars env = getParent().getEnvironment(n,log); env.putAll(getParent().getEnvironment(n,log)); FilePath ws = getWorkspace(); if (ws!=null) env.put("WORKSPACE", ws.getRemote()); project.getScm().buildEnvVars(this,env); for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) ec.buildEnvironmentFor(this,env,log); if (buildEnvironments!=null) for (Environment e : buildEnvironments) e.buildEnvVars(env); for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) a.buildEnvVars(this,env); env.putAll(getCharacteristicEnvVars()); EnvVars.resolve(env); return env; }

Target:
public @Nonnull EnvVars getEnvironment(@Nonnull TaskListener log) throws IOException, InterruptedException { Computer c = Computer.currentComputer(); Node n = c==null ? null : c.getNode(); EnvVars env = new EnvVars(); if (n != null) { env.putAll(getParent().getEnvironment(n,log)); } FilePath ws = getWorkspace(); if (ws!=null) env.put("WORKSPACE", ws.getRemote()); project.getScm().buildEnvVars(this,env); for (EnvironmentContributor ec : EnvironmentContributor.all().reverseView()) ec.buildEnvironmentFor(this,env,log); if (buildEnvironments!=null) for (Environment e : buildEnvironments) e.buildEnvVars(env); for (EnvironmentContributingAction a : getActions(EnvironmentContributingAction.class)) a.buildEnvVars(this,env); env.putAll(getCharacteristicEnvVars()); EnvVars.resolve(env); return env; }
Source:
public void setUp() { cmd = spy(new ReconstructMasterDomainCommand<>(new ReconstructMasterParameters())); masterDomainIsoMap = new StoragePoolIsoMap(masterStorageDomainId, storagePoolId, StorageDomainStatus.Active); regularDomainIsoMap = new StoragePoolIsoMap(regularStorageDomainId, storagePoolId, StorageDomainStatus.Active); StorageDomain masterStorageDomain = new StorageDomain(); masterStorageDomain.setStoragePoolIsoMapData(masterDomainIsoMap); doReturn(Arrays.asList(masterDomainIsoMap, regularDomainIsoMap)).when(storagePoolIsoMapDao).getAllForStoragePool(storagePoolId); StoragePool storagePool = new StoragePool(); storagePool.setId(storagePoolId); StoragePoolValidator storagePoolValidator = spy(new StoragePoolValidator(storagePool)); doReturn(storagePoolIsoMapDao).when(storagePoolValidator).getStoragePoolIsoMapDao(); doReturn(masterStorageDomain).when(cmd).getStorageDomain(); doReturn(storagePool).when(cmd).getStoragePool(); doReturn(storagePoolValidator).when(cmd).createStoragePoolValidator(); }

Target:
public void setUp() { cmd = spy(new ReconstructMasterDomainCommand<>(new ReconstructMasterParameters())); initializeStorageDomains(); initializeStoragePool(); initializeStoragePoolValidator(); }
Source:
private void writeValidConfigFiles() throws FileNotFoundException{ PrintWriter writer1 = new PrintWriter(PROPERTY_1); writer1.println("sonar.foo=bar"); writer1.close(); PrintWriter writer2 = new PrintWriter(PROPERTY_2); writer2.println("sonar.bar=bazz"); writer2.close(); }

Target:
private void writeValidConfigFiles() throws IOException { FileUtils.writeStringToFile(new File(PROPERTY_1), "sonar.foo=bar"); FileUtils.writeStringToFile(new File(PROPERTY_2), "sonar.bar=bazz"); }
Source:
public boolean match(Object value) { try { if (expected == null) { return false; } Object actual = ObjectGraph.from(value).navigate(attribute).value(); return expected.matcher(asString(actual)).matches(); } catch (JXPathException e) { throw new MatcherException(String.format("Could not navigate to specific path: '%s'", attribute), e); } }

Target:
public boolean match(Object value) { try { Object actual = ObjectGraph.from(value).navigate(attribute).value(); return expected.matcher(asString(actual)).matches(); } catch (JXPathException e) { throw new MatcherException(String.format("Could not navigate to specific path: '%s'", attribute), e); } }
Source:
public boolean matches(final WebContext context) { CommonHelper.assertNotBlank("headerName", headerName); final Optional<String> headerValue = context.getRequestHeader(this.headerName); final boolean headerNull = expectedValue == null && !headerValue.isPresent(); final boolean headerMatches = headerValue.isPresent() && pattern != null && pattern.matcher(headerValue.get()).matches(); return headerNull || headerMatches; }

Target:
public boolean matches(final WebContext context) { CommonHelper.assertNotBlank("headerName", headerName); final Optional<String> headerValue = context.getRequestHeader(this.headerName); final boolean headerNull = expectedValue == null && !headerValue.isPresent(); final boolean headerMatches = headerValue.flatMap( hv -> Optional.ofNullable(pattern).map(p -> p.matcher(hv).matches()) ).orElse(false); return headerNull || headerMatches; }
Source:
private void deliver(BitmapHunter hunter) { if (hunter.isCancelled()) { return; } Result result = hunter.getResult(); if (result != null) { if (result instanceof Result.Bitmap) { Bitmap bitmap = ((Result.Bitmap) result).getBitmap(); bitmap.prepareToDraw(); } } Message message = mainThreadHandler.obtainMessage(HUNTER_COMPLETE, hunter); if (hunter.getPriority() == Picasso.Priority.HIGH) { mainThreadHandler.sendMessageAtFrontOfQueue(message); } else { mainThreadHandler.sendMessage(message); } logDelivery(hunter); }

Target:
private void deliver(BitmapHunter hunter) { if (hunter.isCancelled()) { return; } Result result = hunter.getResult(); if (result != null) { if (result instanceof Result.Bitmap) { Bitmap bitmap = ((Result.Bitmap) result).getBitmap(); bitmap.prepareToDraw(); } } Message message = mainThreadHandler.obtainMessage(HUNTER_COMPLETE, hunter); if (hunter.priority == Picasso.Priority.HIGH) { mainThreadHandler.sendMessageAtFrontOfQueue(message); } else { mainThreadHandler.sendMessage(message); } logDelivery(hunter); }
Source:
private static void printGroup(GroupInfo group, boolean detailed) { System.out.println(String.format("Group id: %s\n Group name: %s \n active: %s", Base64.encodeBytes(group.groupId), group.name, group.active)); if (detailed) { System.out.println(" Members:"); for (String member : group.members) { System.out.println(" " + member); } } }

Target:
private static void printGroup(GroupInfo group, boolean detailed) { if (detailed) { System.out.println(String.format("Id: %s Name: %s Active: %s Members: %s", Base64.encodeBytes(group.groupId), group.name, group.active, group.members)); } else { System.out.println(String.format("Id: %s Name: %s Active: %s", Base64.encodeBytes(group.groupId), group.name, group.active)); } }
Source:
protected void executeQueryCommand() { Job jobWithSteps = jobRepository.getJobWithSteps(getParameters().getId()); if (getParameters().isFiltered()) { Guid userId = getUserID(); if (jobWithSteps.getOwnerId().equals(userId) && jobWithSteps.getEngineSessionSeqId() == getEngineSessionSeqId()) { getQueryReturnValue().setReturnValue(jobWithSteps); } } else { getQueryReturnValue().setReturnValue(jobWithSteps); } }

Target:
protected void executeQueryCommand() { Job jobWithSteps = jobRepository.getJobWithSteps(getParameters().getId()); if (getParameters().isFiltered()) { if (jobWithSteps.getEngineSessionSeqId() == getEngineSessionSeqId()) { getQueryReturnValue().setReturnValue(jobWithSteps); } } else { getQueryReturnValue().setReturnValue(jobWithSteps); } }
Source:
public static IonDatagram[] roundTripDatagram(IonDatagram input) throws IOException{ IonSystem system = IonSystemBuilder.standard().build(); IonLoader loader = system.getLoader(); ByteArrayOutputStream textOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream binaryOutputStream = new ByteArrayOutputStream(); IonWriter textWriter = IonTextWriterBuilder.standard().build(textOutputStream); IonWriter binaryWriter = IonBinaryWriterBuilder.standard().build(binaryOutputStream); IonReader reader = system.newReader(input); textWriter.writeValues(reader); textWriter.close(); reader = system.newReader(input); binaryWriter.writeValues(reader); binaryWriter.close(); IonDatagram[] data = new IonDatagram[3]; data[0] = input; data[1] = loader.load(new ByteArrayInputStream(textOutputStream.toByteArray())); data[2] = loader.load(new ByteArrayInputStream(binaryOutputStream.toByteArray())); return data; }

Target:
public static IonDatagram[] roundTripDatagram(IonDatagram input) throws IOException { IonSystem system = IonSystemBuilder.standard().build(); IonLoader loader = system.getLoader(); ByteArrayOutputStream textOutputStream = new ByteArrayOutputStream(); ByteArrayOutputStream binaryOutputStream = new ByteArrayOutputStream(); IonReader textReader = null, binaryReader = null; IonWriter textWriter = null, binaryWriter = null; IonDatagram[] data = new IonDatagram[3]; try { textReader = system.newReader(input); textWriter = IonTextWriterBuilder.standard().build(textOutputStream); textWriter.writeValues(textReader); binaryWriter = IonBinaryWriterBuilder.standard().build(binaryOutputStream); binaryReader = system.newReader(input); binaryWriter.writeValues(binaryReader); } finally { textWriter.close(); binaryWriter.close(); textReader.close(); binaryReader.close(); } data[0] = input; data[1] = loader.load(new ByteArrayInputStream(textOutputStream.toByteArray())); data[2] = loader.load(new ByteArrayInputStream(binaryOutputStream.toByteArray())); return data; }
Source:
ReplicationConfig(final Injector injector, final WorkQueue workQueue, final RemoteConfig rc, final Config cfg, SchemaFactory<ReviewDb> db, final ReplicationUser.Factory replicationUserFactory) { remote = rc; delay = Math.max(0, getInt(rc, cfg, "replicationdelay", 15)); final int poolSize = Math.max(0, getInt(rc, cfg, "threads", 1)); final String poolName = "ReplicateTo-" + rc.getName(); pool = workQueue.createQueue(poolSize, poolName); String[] authGroupNames = cfg.getStringList("remote", rc.getName(), "authGroup"); authEnabled = authGroupNames.length > 0; Set<AccountGroup.Id> authGroups = ReplicationConfig.groupsFor(db, authGroupNames); final ReplicationUser remoteUser = replicationUserFactory.create(authGroups); projectControlFactory = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(CurrentUser.class).toInstance(remoteUser); } }).getInstance(ProjectControl.Factory.class); opFactory = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PushReplication.ReplicationConfig.class).toInstance( ReplicationConfig.this); bind(RemoteConfig.class).toInstance(remote); bind(PushOp.Factory.class).toProvider( FactoryProvider.newFactory(PushOp.Factory.class, PushOp.class)); } }).getInstance(PushOp.Factory.class); }

Target:
ReplicationConfig(final Injector injector, final WorkQueue workQueue, final RemoteConfig rc, final Config cfg, SchemaFactory<ReviewDb> db, final ReplicationUser.Factory replicationUserFactory) { remote = rc; delay = Math.max(0, getInt(rc, cfg, "replicationdelay", 15)); final int poolSize = Math.max(0, getInt(rc, cfg, "threads", 1)); final String poolName = "ReplicateTo-" + rc.getName(); pool = workQueue.createQueue(poolSize, poolName); String[] authGroupNames = cfg.getStringList("remote", rc.getName(), "authGroup"); authEnabled = authGroupNames.length > 0; Set<AccountGroup.Id> authGroups = groupsFor(db, authGroupNames); final ReplicationUser remoteUser = replicationUserFactory.create(authGroups); projectControlFactory = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(CurrentUser.class).toInstance(remoteUser); } }).getInstance(ProjectControl.Factory.class); opFactory = injector.createChildInjector(new AbstractModule() { @Override protected void configure() { bind(PushReplication.ReplicationConfig.class).toInstance( ReplicationConfig.this); bind(RemoteConfig.class).toInstance(remote); bind(PushOp.Factory.class).toProvider( FactoryProvider.newFactory(PushOp.Factory.class, PushOp.class)); } }).getInstance(PushOp.Factory.class); }
Source:
protected void postLoad(Group group, Version loadedVersion) { EList<Viewpoint> ownedViewpoints = group.getOwnedViewpoints(); for (Viewpoint viewpoint : ownedViewpoints) { for (TableDescription tableDescription : Iterables.filter(viewpoint.getOwnedRepresentations(), TableDescription.class)) { Iterator<EObject> creationTools = Iterators.filter(tableDescription.eAllContents(), Predicates.instanceOf(CreateTool.class)); while (creationTools.hasNext()) { AbstractToolDescription tool = (AbstractToolDescription) creationTools.next(); tool.setElementsToSelect(ELEMENTS_TO_SELECT_EXPRESSION); } } if (!Iterables.filter(viewpoint.getOwnedJavaExtensions(), new Predicate<JavaExtension>() { @Override public boolean apply(JavaExtension input) { return JAVA_EXTENSION_QUALIFIED_NAME.equals(input.getQualifiedClassName()); } }).iterator().hasNext()) { JavaExtension javaExtension = DescriptionFactory.eINSTANCE.createJavaExtension(); javaExtension.setQualifiedClassName(JAVA_EXTENSION_QUALIFIED_NAME); viewpoint.getOwnedJavaExtensions().add(javaExtension); } } }

Target:
protected void postLoad(Group group, Version loadedVersion) { if (loadedVersion.compareTo(MIGRATION_VERSION) < 0) { EList<Viewpoint> ownedViewpoints = group.getOwnedViewpoints(); for (Viewpoint viewpoint : ownedViewpoints) { boolean atLeastOneChange = false; for (TableDescription tableDescription : Iterables.filter(viewpoint.getOwnedRepresentations(), TableDescription.class)) { Iterator<CreateTool> creationTools = Iterators.filter(tableDescription.eAllContents(), CreateTool.class); while (creationTools.hasNext()) { CreateTool tool = creationTools.next(); tool.setElementsToSelect(ELEMENTS_TO_SELECT_EXPRESSION); atLeastOneChange = true; } } if (atLeastOneChange) { if (!Iterables.any(viewpoint.getOwnedJavaExtensions(), new Predicate<JavaExtension>() { @Override public boolean apply(JavaExtension input) { return JAVA_EXTENSION_QUALIFIED_NAME.equals(input.getQualifiedClassName()); } })) { JavaExtension javaExtension = DescriptionFactory.eINSTANCE.createJavaExtension(); javaExtension.setQualifiedClassName(JAVA_EXTENSION_QUALIFIED_NAME); viewpoint.getOwnedJavaExtensions().add(javaExtension); } } } } }
Source:
public void of(TableReader reader, int columnIndex) { this.symbolMapReader = reader.getSymbolMapReader(columnIndex); this.numberOfSymbols = symbolMapReader.size(); this.reader = reader; this.recordA.of(reader, columnIndex); this.recordB.of(reader, columnIndex); }

Target:
public void of(TableReader reader, int columnIndex) { this.reader = reader; this.symbolMapReader = reader.getSymbolMapReader(columnIndex); this.numberOfSymbols = symbolMapReader.size() + (symbolMapReader.containsNullValue() ? 1 : 0); this.recordA.reset(); }
Source:
private Collection<Snapshot> getSnapshotsToBeExportedWithMemory() { if (getParameters().getCopyCollapse()) { Snapshot activeSnapshot = snapshotDao.get(getVmId(), SnapshotType.ACTIVE); return !activeSnapshot.getMemoryVolume().isEmpty() ? Collections.singleton(activeSnapshot) : Collections.emptyList(); } else { return snapshotDao.getAll(getVmId()).stream().filter(s -> !StringUtils.EMPTY.equals(s.getMemoryVolume())) .map(Function.identity()).collect(Collectors.toList()); } }

Target:
private Collection<Snapshot> getSnapshotsToBeExportedWithMemory() { if (getParameters().getCopyCollapse()) { Snapshot activeSnapshot = snapshotDao.get(getVmId(), SnapshotType.ACTIVE); return !activeSnapshot.getMemoryVolume().isEmpty() ? Collections.singleton(activeSnapshot) : Collections.emptyList(); } else { return snapshotDao.getAll(getVmId()).stream().filter(s -> !StringUtils.EMPTY.equals(s.getMemoryVolume())) .collect(Collectors.toList()); } }
Source:
static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; URI baseURI = withHost; if (!withHost.toString().endsWith("/")){ baseURI = URI.create(withHost.toString() + "/"); } return baseURI.resolve(original); }

Target:
static URI addHostIfMissing(URI original, URI withHost) { checkNotNull(withHost, "URI withHost cannot be null"); checkArgument(withHost.getHost() != null, "URI withHost must have host:" + withHost); if (original == null) return null; if (original.getHost() != null) return original; String host = withHost.toString(); URI baseURI = host.endsWith("/") ? withHost : URI.create(host + "/"); return baseURI.resolve(original); }
Source:
private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMap(Type type) { Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(type); if (NULL_TYPE_HANDLER_MAP.equals(jdbcHandlerMap)) { return null; } if (jdbcHandlerMap == null && type instanceof Class) { Class<?> clazz = (Class<?>) type; if (clazz.isEnum() || (clazz.isAnonymousClass() && clazz.getEnclosingClass().isEnum())) { clazz = clazz.isAnonymousClass() ? clazz.getEnclosingClass() : clazz; jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(clazz, clazz); if (jdbcHandlerMap == null) { register(clazz, getInstance(clazz, defaultEnumTypeHandler)); return typeHandlerMap.get(clazz); } } else { jdbcHandlerMap = getJdbcHandlerMapForSuperclass(clazz); } } typeHandlerMap.put(type, jdbcHandlerMap == null ? NULL_TYPE_HANDLER_MAP : jdbcHandlerMap); return jdbcHandlerMap; }

Target:
private Map<JdbcType, TypeHandler<?>> getJdbcHandlerMap(Type type) { Map<JdbcType, TypeHandler<?>> jdbcHandlerMap = typeHandlerMap.get(type); if (NULL_TYPE_HANDLER_MAP.equals(jdbcHandlerMap)) { return null; } if (jdbcHandlerMap == null && type instanceof Class) { Class<?> clazz = (Class<?>) type; if (Enum.class.isAssignableFrom(clazz)) { Class<?> enumClass = clazz.isAnonymousClass() ? clazz.getSuperclass() : clazz; jdbcHandlerMap = getJdbcHandlerMapForEnumInterfaces(enumClass, enumClass); if (jdbcHandlerMap == null) { register(enumClass, getInstance(enumClass, defaultEnumTypeHandler)); return typeHandlerMap.get(enumClass); } } else { jdbcHandlerMap = getJdbcHandlerMapForSuperclass(clazz); } } typeHandlerMap.put(type, jdbcHandlerMap == null ? NULL_TYPE_HANDLER_MAP : jdbcHandlerMap); return jdbcHandlerMap; }
Source:
public void visit(String name, Object value) { checkNotNull(name, "name"); switch (name) { case "id": if (!(value instanceof String)) { throw new InvalidPluginException("Plugin annotation has invalid element 'id'"); } this.id = (String) value; return; case "version": if (!(value instanceof String)) { throw new InvalidPluginException("Plugin annotation has invalid element 'version'"); } this.version = (String) value; return; case "optional": if (!(value instanceof Boolean)) { throw new InvalidPluginException("Plugin annotation has invalid element 'optional'"); } this.optional = (boolean) value; return; default: super.visit(name, value); } }

Target:
public void visit(String name, Object value) { checkNotNull(name, "name"); switch (name) { case "id": if (!(value instanceof String)) { throw new InvalidPluginException("Dependency annotation has invalid element 'id'"); } this.id = (String) value; return; case "version": if (!(value instanceof String)) { throw new InvalidPluginException("Dependency annotation has invalid element 'version'"); } this.version = (String) value; return; case "optional": if (!(value instanceof Boolean)) { throw new InvalidPluginException("Dependency annotation has invalid element 'optional'"); } this.optional = (boolean) value; return; default: super.visit(name, value); } }
Source:
public void referenceNonExistentCaseId() { MockDataUtils.parseIntoSandbox(this.getClass().getResourceAsStream("/case_create_basic.xml"), sandbox); EvaluationContext ec = MockDataUtils.getInstanceContexts(sandbox, "casedb", CaseTestUtils.CASE_INSTANCE); Assert.assertTrue(CaseTestUtils.xpathEval(ec, "instance('casedb')/casedb/case[@case_id = 'no-case']", "")); }

Target:
public void referenceNonExistentCaseId() throws XPathSyntaxException { MockDataUtils.parseIntoSandbox(this.getClass().getResourceAsStream("/case_create_basic.xml"), sandbox); EvaluationContext ec = MockDataUtils.buildContextWithInstance(sandbox, "casedb", CaseTestUtils.CASE_INSTANCE); Assert.assertTrue(CaseTestUtils.xpathEvalAndCompare(ec, "instance('casedb')/casedb/case[@case_id = 'no-case']", "")); }
Source:
public void onNext(FailedEvaluator evaluator) { LOG.log(Level.WARNING, "Container:{0} failed", evaluator.getId()); HeronWorker worker = multiKeyWorkerMap.lookupByEvaluatorId(evaluator.getId()); if (worker == null) { LOG.log(Level.WARNING, "Unknown executor id for failed container: {0}, skip renew action", evaluator.getId()); return; } LOG.log(Level.INFO, "Trying to relaunch executor {0} running on failed container {1}", new Object[]{worker.workerId, evaluator.getId()}); multiKeyWorkerMap.detachEvaluatorAndRemove(worker); try { launchContainerForExecutor(worker); } catch (ContainerAllocationException e) { LOG.log(Level.SEVERE, "Failed to relaunch failed container: " + worker.workerId, e); } }

Target:
public void onNext(FailedEvaluator evaluator) { LOG.log(Level.WARNING, "Container:{0} failed", evaluator.getId()); Optional<HeronWorker> worker = multiKeyWorkerMap.lookupByEvaluatorId(evaluator.getId()); if (!worker.isPresent()) { LOG.log(Level.WARNING, "Unknown executor id for failed container: {0}, skip renew action", evaluator.getId()); return; } LOG.log(Level.INFO, "Trying to relaunch executor {0} running on failed container {1}", new Object[]{worker.get().workerId, evaluator.getId()}); multiKeyWorkerMap.detachEvaluatorAndRemove(worker.get()); try { launchContainerForExecutor(worker.get()); } catch (ContainerAllocationException e) { LOG.log(Level.SEVERE, "Failed to relaunch failed container: " + worker.get().workerId, e); } }
Source:
private RefUpdate.Result modify(TreeOperation op, ChangeEdit edit, String file, byte[] content) throws AuthException, IOException, InvalidChangeOperationException { if (!currentUser.get().isIdentifiedUser()) { throw new AuthException("Authentication required"); } IdentifiedUser me = (IdentifiedUser) currentUser.get(); Repository repo = gitManager.openRepository(edit.getChange().getProject()); try { RevWalk rw = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter(); ObjectReader reader = repo.newObjectReader(); try { String refName = edit.getRefName(); RevCommit prevEdit = edit.getEditCommit(); RevCommit base = prevEdit.getParent(0); base = rw.parseCommit(base); if (base.getParentCount() == 0) { throw new InvalidChangeOperationException( "Modify edit against root commit not implemented"); } ObjectId newTree = writeNewTree(op, repo, rw, inserter, prevEdit, reader, file, content, base); if (ObjectId.equals(newTree, prevEdit.getTree())) { throw new InvalidChangeOperationException("no changes were made"); } ObjectId commit = createCommit(me, inserter, prevEdit, base, newTree); inserter.flush(); return update(repo, me, refName, rw, prevEdit, commit); } finally { rw.release(); inserter.release(); reader.release(); } } finally { repo.close(); } }

Target:
private RefUpdate.Result modify(TreeOperation op, ChangeEdit edit, String file, byte[] content) throws AuthException, IOException, InvalidChangeOperationException { if (!currentUser.get().isIdentifiedUser()) { throw new AuthException("Authentication required"); } IdentifiedUser me = (IdentifiedUser) currentUser.get(); Repository repo = gitManager.openRepository(edit.getChange().getProject()); try { RevWalk rw = new RevWalk(repo); ObjectInserter inserter = repo.newObjectInserter(); ObjectReader reader = repo.newObjectReader(); try { String refName = edit.getRefName(); RevCommit prevEdit = edit.getEditCommit(); if (prevEdit.getParentCount() == 0) { throw new InvalidChangeOperationException( "Modify edit against root commit not implemented"); } RevCommit base = prevEdit.getParent(0); base = rw.parseCommit(base); ObjectId newTree = writeNewTree(op, repo, rw, inserter, prevEdit, reader, file, content, base); if (ObjectId.equals(newTree, prevEdit.getTree())) { throw new InvalidChangeOperationException("no changes were made"); } ObjectId commit = createCommit(me, inserter, prevEdit, base, newTree); inserter.flush(); return update(repo, me, refName, rw, prevEdit, commit); } finally { rw.release(); inserter.release(); reader.release(); } } finally { repo.close(); } }
Source:
private String getInboundReplyToHeader(WebServiceContext context) { MessageContext messageContext = context.getMessageContext(); if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) { return null; } Message message = ((WrappedMessageContext) messageContext).getWrappedMessage(); AddressingProperties maps = (AddressingProperties) message.get(NhincConstants.INBOUND_REPLY_TO_HEADER); return (maps.getReplyTo().getAddress().getValue()); }

Target:
private String getInboundReplyToHeader(WebServiceContext context) { MessageContext messageContext = context.getMessageContext(); if (messageContext == null || !(messageContext instanceof WrappedMessageContext)) { return null; } Message message = ((WrappedMessageContext) messageContext).getWrappedMessage(); AddressingProperties maps = (AddressingProperties) message.get(NhincConstants.INBOUND_REPLY_TO_HEADER); return maps.getReplyTo().getAddress().getValue(); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeStatsEstimate that = (PlanNodeStatsEstimate) o; return Double.compare(that.outputRowCount, outputRowCount) == 0 && Double.compare(that.outputSizeInBytes, outputSizeInBytes) == 0 && Objects.equals(symbolStatistics, that.symbolStatistics); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PlanNodeStatsEstimate that = (PlanNodeStatsEstimate) o; return Double.compare(outputRowCount, that.outputRowCount) == 0 && Objects.equals(symbolStatistics, that.symbolStatistics); }
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rule<?> rule = (Rule<?>) o; return Objects.equals(ruleType, rule.ruleType) && Objects.equals(name, rule.name) && Objects.equals(visibility, rule.visibility) && Objects.equals(labels, rule.labels) && Objects.equals(extraBuckOpts, rule.extraBuckOpts); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Rule<?> rule = (Rule<?>) o; return Objects.equals(name, rule.name); }
Source:
protected <T, X> void createObserverMethod(RIBean<X> declaringBean, BeanManagerImpl beanManager, EnhancedAnnotatedMethod<T, ? super X> method, Set<ObserverInitializationContext<?, ?>> observerMethodInitializers, boolean isAsync) { ObserverMethodImpl<T, X> observer = ObserverFactory.create(method, declaringBean, beanManager, isAsync); ObserverInitializationContext<T, X> observerMethodInitializer = ObserverInitializationContext.of(observer, method); if (Observers.CONTAINER_LIFECYCLE_EVENT_TYPES.contains(Reflections.getRawType(observer.getObservedType()))) { if (isAsync) { throw EventLogger.LOG.asyncContainerLifecycleEventObserver(observer, Formats.formatAsStackTraceElement(method.getJavaMember())); } if (method.isStatic()) { throw EventLogger.LOG.staticContainerLifecycleEventObserver(observer, Formats.formatAsStackTraceElement(method.getJavaMember())); } } observerMethodInitializers.add(observerMethodInitializer); }

Target:
protected <T, X> void createObserverMethod(RIBean<X> declaringBean, BeanManagerImpl beanManager, EnhancedAnnotatedMethod<T, ? super X> method, Set<ObserverInitializationContext<?, ?>> observerMethodInitializers, boolean isAsync) { ObserverMethodImpl<T, X> observer = ObserverFactory.create(method, declaringBean, beanManager, isAsync); ObserverInitializationContext<T, X> observerMethodInitializer = ObserverInitializationContext.of(observer, method); if (Observers.isContainerLifecycleObserverMethod(observer)) { if (isAsync) { throw EventLogger.LOG.asyncContainerLifecycleEventObserver(observer, Formats.formatAsStackTraceElement(method.getJavaMember())); } if (method.isStatic()) { throw EventLogger.LOG.staticContainerLifecycleEventObserver(observer, Formats.formatAsStackTraceElement(method.getJavaMember())); } } observerMethodInitializers.add(observerMethodInitializer); }
Source:
private Cohort getCohort() { return cohort; }

Target:
public Cohort getCohort() { return cohort; }
Source:
public synchronized void asyncRefresh() { Duration sinceUpdate = nanosSince(lastUpdateNanos.get()); if (sinceUpdate.toMillis() > 1_000 && future.get() == null) { ListenableFuture<Integer> responseFuture = thriftClient.getServerState(); future.compareAndSet(null, responseFuture); Futures.addCallback(responseFuture, new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer result) { lastUpdateNanos.set(System.nanoTime()); future.compareAndSet(responseFuture, null); if (result != null) { nodeState.set(Optional.of(NodeState.valueOf(result))); } } @Override public void onFailure(Throwable t) { lastUpdateNanos.set(System.nanoTime()); future.compareAndSet(responseFuture, null); } }, directExecutor()); } }

Target:
public void asyncRefresh() { Duration sinceUpdate = nanosSince(lastUpdateNanos.get()); if (sinceUpdate.toMillis() > 1_000 && requestInflight.compareAndSet(false, true)) { ListenableFuture<Integer> responseFuture = thriftClient.getServerState(); Futures.addCallback(responseFuture, new FutureCallback<Integer>() { @Override public void onSuccess(@Nullable Integer result) { lastUpdateNanos.set(System.nanoTime()); requestInflight.compareAndSet(true, false); if (result != null) { nodeState.set(Optional.of(NodeState.valueOf(result))); } } @Override public void onFailure(Throwable t) { lastUpdateNanos.set(System.nanoTime()); requestInflight.compareAndSet(true, false); } }, directExecutor()); } }
Source:
protected boolean isPassthrough( StepField originalFieldName ) { String[] inFields = baseStepMeta.getFieldInStream(); String origFieldName = originalFieldName.getFieldName(); boolean isPassthrough = true; for ( int i = 0; i < inFields.length; i++ ) { if ( inFields[i].equals( origFieldName ) && Const.isEmpty( baseStepMeta.getFieldOutStream()[i] ) ) { isPassthrough = false; } } return isPassthrough; }

Target:
protected boolean isPassthrough( StepField originalFieldName ) { String[] inFields = baseStepMeta.getFieldInStream(); String origFieldName = originalFieldName.getFieldName(); for ( int i = 0; i < inFields.length; i++ ) { if ( inFields[i].equals( origFieldName ) && Const.isEmpty( baseStepMeta.getFieldOutStream()[i] ) ) { return false; } } return true; }
Source:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); return Collections.singletonList(getRawImageType(pImageIndex)).iterator(); }

Target:
public Iterator<ImageTypeSpecifier> getImageTypes(int pImageIndex) throws IOException { checkBounds(pImageIndex); return Arrays.asList(getRawImageType(pImageIndex)).iterator(); }
Source:
public static String generateToString(final ImmutableList<String> enumValues) { final StringBuilder outputBuilder = new StringBuilder(); final int numEnumValues = enumValues.size(); if (numEnumValues <= 0) { LOG.warn("Empty enumValues list."); return ""; } for (int currentEnum = 0; currentEnum < numEnumValues; currentEnum++) { outputBuilder.append(indent(1)); if (currentEnum > 0) { outputBuilder.append("} else "); } final String currentEnumName = enumValues.get(currentEnum); outputBuilder.append("if (input == ").append(currentEnumName).append(") {\n"); outputBuilder.append(indent(2)).append("return \"").append(currentEnumName).append("\";\n"); } outputBuilder.append(indent(1)).append("} else {\n"); outputBuilder.append(indent(2)).append("return \"\";\n"); outputBuilder.append(indent(1)).append("}\n"); return outputBuilder.toString(); }

Target:
public static String generateToString(final ImmutableList<String> enumValues) { if (isEmpty(enumValues)) { LOG.warn("Empty enumValues list."); return ""; } final int numEnumValues = enumValues.size(); final StringBuilder outputBuilder = new StringBuilder(); for (int currentEnum = 0; currentEnum < numEnumValues; currentEnum++) { outputBuilder.append(indent(1)); if (currentEnum > 0) { outputBuilder.append("} else "); } final String currentEnumName = enumValues.get(currentEnum); outputBuilder.append("if (input == ").append(currentEnumName).append(") {\n"); outputBuilder.append(indent(2)).append("return \"").append(currentEnumName).append("\";\n"); } outputBuilder.append(indent(1)).append("} else {\n"); outputBuilder.append(indent(2)).append("return \"\";\n"); outputBuilder.append(indent(1)).append("}\n"); return outputBuilder.toString(); }
Source:
public @Nullable String transform(String filename, String source) throws TransformationException { Objects.requireNonNull(filename, "the given parameter 'filename' must not be null"); Objects.requireNonNull(source, "the given parameter 'source' must not be null"); final long startTime = System.currentTimeMillis(); logger.debug("about to transform '{}' by the JavaScript '{}'", source, filename); String result = ""; try { final CompiledScript cScript = manager.getScript(filename); final Bindings bindings = cScript.getEngine().createBindings(); bindings.put("input", source); result = String.valueOf(cScript.eval(bindings)); return result; } catch (ScriptException e) { throw new TransformationException("An error occurred while executing script. " + e.getMessage(), e); } finally { logger.trace("JavaScript execution elapsed ms. Result: {}", System.currentTimeMillis() - startTime, result); } }

Target:
public @Nullable String transform(String filename, String source) throws TransformationException { if (filename == null || source == null) { throw new TransformationException("the given parameters 'filename' and 'source' must not be null"); } final long startTime = System.currentTimeMillis(); logger.debug("about to transform '{}' by the JavaScript '{}'", source, filename); String result = ""; try { final CompiledScript cScript = manager.getScript(filename); final Bindings bindings = cScript.getEngine().createBindings(); bindings.put("input", source); result = String.valueOf(cScript.eval(bindings)); return result; } catch (ScriptException e) { throw new TransformationException("An error occurred while executing script. " + e.getMessage(), e); } finally { logger.trace("JavaScript execution elapsed ms. Result: {}", System.currentTimeMillis() - startTime, result); } }
Source:
void shouldSerializeCustomProblem() { final int balance = 10; final int debit = 100; final Problem problem = new InsufficientFundsProblem(balance, debit); final String json = gson.toJson(problem); assertThat("json", Objects.nonNull(json)); with(json) .assertThat("$.type", is(InsufficientFundsProblem.TYPE_VALUE)) .assertThat("$.title", is("Insufficient Funds")) .assertThat("$.status", is(BAD_REQUEST.getStatusCode())) .assertThat("$.balance", is(balance)) .assertThat("$.debit", is(debit)); }

Target:
void shouldSerializeCustomProblem() { final int balance = 10; final int debit = 100; final InsufficientFundsProblem problem = new InsufficientFundsProblem(balance, debit); problem.set("foo", "bar"); final String json = gson.toJson(problem); assertThat("json", Objects.nonNull(json)); System.out.println(json); with(json) .assertThat("$.*", hasSize(6)) .assertThat("$.type", is(InsufficientFundsProblem.TYPE_VALUE)) .assertThat("$.title", is("Insufficient Funds")) .assertThat("$.status", is(BAD_REQUEST.getStatusCode())) .assertThat("$.foo", is("bar")) .assertThat("$.balance", is(balance)) .assertThat("$.debit", is(debit)); }
Source:
public Object evalRaw(DataInstance model, EvaluationContext evalContext) { try { return FunctionUtils.unpack(expr.eval(model, evalContext)); } catch (XPathUnsupportedException e) { if (xpath != null) { throw new XPathUnsupportedException(xpath); } else { if (evalContext.isConstraint) { String contextMessage = String.format(" Question with id: \'%s\' has issue with condition expression: \'%s\'", evalContext.getContextRef().getNameLast(), expr); e.setMessagePrefix(contextMessage); } throw e; } } }

Target:
public Object evalRaw(DataInstance model, EvaluationContext evalContext) { try { return FunctionUtils.unpack(expr.eval(model, evalContext)); } catch (XPathUnsupportedException e) { if (xpath != null) { throw new XPathUnsupportedException(xpath); } else { String contextMessage = String.format("Error calculating expression: \"%s\", being calculated for \"%s\"", expr.toPrettyString(), evalContext.getContextRef()); throw new XPathUnsupportedException(contextMessage); } } }
Source:
private void tryPushItem() { boolean emptySlot = false; for (IExtInvSlot slot : InventoryIterator.get(this)) { if (slot.getStack().getCount() == slot.maxStackSize()) { ItemStack left = TrainTransferHelper.INSTANCE.pushStack(this, slot.getStack()); if (InvTools.isEmpty(left)) { emptySlot = true; } slot.setStack(left); } else if (!slot.hasStack()) { emptySlot = true; } } if (emptySlot) return; for (IExtInvSlot slot : InventoryIterator.get(this)) { ItemStack left = TrainTransferHelper.INSTANCE.pushStack(this, slot.getStack()); slot.setStack(left); if (InvTools.isEmpty(left)) { return; } } }

Target:
private void tryPushItem() { boolean emptySlot = false; for (IExtInvSlot slot : InventoryIterator.get(this)) { if (slot.getStack().getCount() == slot.getMaxStackSize()) { ItemStack left = TrainTransferHelper.INSTANCE.pushStack(this, slot.getStack()); if (InvTools.isEmpty(left)) { emptySlot = true; } slot.setStack(left); } else if (!slot.hasStack()) { emptySlot = true; } } if (emptySlot) return; for (IExtInvSlot slot : InventoryIterator.get(this)) { ItemStack left = TrainTransferHelper.INSTANCE.pushStack(this, slot.getStack()); slot.setStack(left); if (InvTools.isEmpty(left)) { return; } } }
Source:
public static void startAndSetupContainer() throws Exception { LOGGER.info("*** starting server"); controller.start(); ManagementClient managementClient = controller.getClient(); LOGGER.info("*** will configure server now"); serverSetup(managementClient.getControllerClient()); LOGGER.info("*** reloading server"); reloadServer(); }

Target:
public static void startAndSetupContainer() throws Exception { controller.start(); ManagementClient managementClient = controller.getClient(); serverSetup(managementClient.getControllerClient()); reloadServer(); }
Source:
public CharSequence getPageTitle(int position) { if (position < mTabsTitle.length) return mTabsTitle[position]; return null; }

Target:
public CharSequence getPageTitle(int position) { return mTabsTitle[position]; }
Source:
public DiscoveryResult build() { return new DiscoveryResultImpl(thingTypeUID, thingUID, bridgeUID, properties, representationProperty, label, ttl, null); }

Target:
public DiscoveryResult build() { return new DiscoveryResultImpl(thingTypeUID, thingUID, bridgeUID, properties, representationProperty, label, ttl); }
Source:
private ConfigurationBuilder getConfigurationBuilder(ConfigurationBuilderHolder holder, String name, boolean template, String baseConfigurationName) { if (holder.getNamedConfigurationBuilders().get(name) != null) { throw log.duplicateCacheName(name); } ConfigurationBuilder builder = holder.newConfigurationBuilder(name).template(template); if (baseConfigurationName != null) { ConfigurationBuilder baseConfigurationBuilder = holder.getNamedConfigurationBuilders().get(baseConfigurationName); if (baseConfigurationBuilder == null) { throw log.undeclaredConfiguration(baseConfigurationName, name); } Configuration baseConfiguration = baseConfigurationBuilder.build(); if (!baseConfiguration.isTemplate()) { throw log.noConfiguration(baseConfigurationName); } builder.read(baseConfiguration); } return builder; }

Target:
private ConfigurationBuilder getConfigurationBuilder(ConfigurationBuilderHolder holder, String name, boolean template, String baseConfigurationName) { if (holder.getNamedConfigurationBuilders().containsKey(name)) { throw log.duplicateCacheName(name); } ConfigurationBuilder builder = holder.newConfigurationBuilder(name).template(template); if (baseConfigurationName != null) { ConfigurationBuilder baseConfigurationBuilder = holder.getNamedConfigurationBuilders().get(baseConfigurationName); if (baseConfigurationBuilder == null) { throw log.undeclaredConfiguration(baseConfigurationName, name); } Configuration baseConfiguration = baseConfigurationBuilder.build(); if (!baseConfiguration.isTemplate()) { throw log.noConfiguration(baseConfigurationName); } builder.read(baseConfiguration); } return builder; }
Source:
final void uncheckedSet(boolean reverse, IntsRef ref, int value) { if (reverse && !storeBothDirections) throw new IllegalArgumentException(getName() + ": value for reverse direction would overwrite forward direction. Enable 'storeBothDirections' or always use reverse==true when storing the value"); if (reverse) { int flags = ref.ints[bwdDataIndex + ref.offset]; flags &= ~bwdMask; value <<= bwdShift; ref.ints[bwdDataIndex + ref.offset] = flags | value; } else { int flags = ref.ints[fwdDataIndex + ref.offset]; flags &= ~fwdMask; value <<= fwdShift; ref.ints[fwdDataIndex + ref.offset] = flags | value; } }

Target:
final void uncheckedSet(boolean reverse, IntsRef ref, int value) { if (reverse && !storeTwoDirections) throw new IllegalArgumentException(getName() + ": value for reverse direction would overwrite forward direction. Enable storeTwoDirections for this EncodedValue or don't use setReverse"); if (reverse) { int flags = ref.ints[bwdDataIndex + ref.offset]; flags &= ~bwdMask; value <<= bwdShift; ref.ints[bwdDataIndex + ref.offset] = flags | value; } else { int flags = ref.ints[fwdDataIndex + ref.offset]; flags &= ~fwdMask; value <<= fwdShift; ref.ints[fwdDataIndex + ref.offset] = flags | value; } }
Source:
public ClientStats getClientStats() { return null; }

Target:
public ClientStats getClientStats() { throw new UnsupportedOperationException(); }
Source:
protected void EndSuccessfully() { EndActionOnAllImageGroups(); VM vm = getVm(); if (vm != null) { VmHandler.UnLockVm(vm.getId()); endDiskRelatedActions(vm); if (getParameters().getCopyCollapse()) { this.endCopyCollapseOperations(vm); } else { this.endDefaultOps(vm); } } else { setCommandShouldBeLogged(false); log.warn("ExportVmCommand::EndMoveVmCommand: Vm is null - not performing full EndAction"); } setSucceeded(true); }

Target:
protected void EndSuccessfully() { EndActionOnAllImageGroups(); VM vm = getVm(); VmHandler.UnLockVm(vm.getId()); endDiskRelatedActions(vm); if (getParameters().getCopyCollapse()) { this.endCopyCollapseOperations(vm); } else { this.endDefaultOps(vm); } setSucceeded(true); }
Source:
protected String inferHostname(Entity entity) { String hostname = entity.getAttribute(Attributes.HOSTNAME); String url = entity.getAttribute(WebAppService.ROOT_URL); if (url!=null) { try { URL u = new URL(url); String hostname2 = u.getHost(); if (hostname==null) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns using URL to redirect to (HOSTNAME attribute is preferred, but not available)", url, entity); hostname = hostname2; } else if (!hostname.equals(hostname2)) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns URL of does not match advertised HOSTNAME {}; using hostname, not URL", url, hostname); } if (u.getPort() > 0 && u.getPort() != 80 && u.getPort() != 443) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns detected non-standard port in URL for {}; forwarding may not work", url, entity); } } catch (MalformedURLException e) { log.warn("Invalid URL for entity in {}", new Object[] {url, entity, this}); } } return hostname; }

Target:
protected String inferHostname(Entity entity) { String hostname = entity.getAttribute(Attributes.HOSTNAME); String url = entity.getAttribute(WebAppService.ROOT_URL); if (url!=null) { try { URL u = new URL(url); String hostname2 = u.getHost(); if (hostname==null) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns "+this+" using URL to redirect to (HOSTNAME attribute is preferred, but not available)", url, entity); hostname = hostname2; } else if (!hostname.equals(hostname2)) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns "+this+" URL of "+entity+" does not match advertised HOSTNAME {}; using hostname, not URL", url, hostname); } if (u.getPort() > 0 && u.getPort() != 80 && u.getPort() != 443) { if (!entitiesWithoutGeoInfo.contains(entity)) log.warn("GeoDns "+this+" detected non-standard port in URL for {}; forwarding may not work", url, entity); } } catch (MalformedURLException e) { log.warn("Invalid URL for entity in {}", new Object[] {url, entity, this}); } } return hostname; }
Source:
public void terminateEarly() { future.cancel(false); synchronized (this) { if (solverStatus == SolverStatus.SOLVING_SCHEDULED) { solvingTerminated(); } else if (solverStatus == SolverStatus.SOLVING_ACTIVE) { solver.terminateEarly(); } else if (solverStatus == SolverStatus.NOT_SOLVING) { } else { throw new IllegalStateException("Unsupported solverStatus (" + solverStatus + ")."); } } try { terminatedLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("The terminateEarly() call is interrupted.", e); } }

Target:
public void terminateEarly() { future.cancel(false); SolverStatus solverStatus = solverStatusReference.get(); switch (solverStatus) { case SOLVING_SCHEDULED: solvingTerminated(); break; case SOLVING_ACTIVE: solver.terminateEarly(); break; case NOT_SOLVING: break; default: throw new IllegalStateException("Unsupported solverStatus (" + solverStatus + ")."); } try { terminatedLatch.await(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); logger.warn("The terminateEarly() call is interrupted.", e); } }
Source:
void complete() { final T value = getAndSet(null); if (value != null) { emit(value); } actual.onComplete(); }

Target:
void complete() { if (wip.decrementAndGet() == 0) { final T value = getAndSet(null); if (value != null) { emit(value); } actual.onComplete(); } }
Source:
FluxMd5Wrapper(Flux<ByteBuffer> data, byte[] md5) { this.data = data; this.md5 = md5 == null ? null : md5.clone(); }

Target:
FluxMd5Wrapper(Flux<ByteBuffer> data, byte[] md5) { this.data = data; this.md5 = CoreUtils.clone(md5); }
Source:
private void rebase(int locusPosition) { for (Counter counter : arrays) { int[] array = counter.array; System.arraycopy(array, locusPosition - offset, array, 0, arrayLength - locusPosition + offset); Arrays.fill(array, arrayLength - locusPosition + offset, arrayLength, 0); } offset = locusPosition; }

Target:
private void rebase(int locusPosition) { if (locusPosition < offset) { throw new IllegalArgumentException("Position in the reference sequence is lesser than offset."); } for (Counter counter : arrays) { final int[] array = counter.array; final int skipLength = locusPosition - offset; System.arraycopy(array, skipLength, array, 0, arrayLength - skipLength); Arrays.fill(array, arrayLength - skipLength, arrayLength, 0); } offset = locusPosition; }
Source:
private void replacePodsVolumesWithCommon(Map<String, PodData> pods, String commonPVCName) { for (PodData pod : pods.values()) { Set<String> pvcVolumes = new HashSet<>(); Iterator<io.fabric8.kubernetes.api.model.Volume> volumeIterator = pod.getSpec().getVolumes().iterator(); while (volumeIterator.hasNext()) { io.fabric8.kubernetes.api.model.Volume volume = volumeIterator.next(); if (volume.getPersistentVolumeClaim() != null) { pvcVolumes.add(volume.getName()); volumeIterator.remove(); } } pod.getSpec() .getVolumes() .add( new VolumeBuilder() .withName(commonPVCName) .withNewPersistentVolumeClaim() .withClaimName(commonPVCName) .endPersistentVolumeClaim() .build()); Stream.concat( pod.getSpec().getContainers().stream(), pod.getSpec().getInitContainers().stream()) .flatMap(c -> c.getVolumeMounts().stream()) .forEach( volumeMount -> { if (pvcVolumes.contains(volumeMount.getName())) { volumeMount.setName(commonPVCName); } }); } }

Target:
private void replacePodsVolumesWithCommon(Map<String, PodData> pods, String commonPVCName) { for (PodData pod : pods.values()) { Set<String> pvcSourcedVolumes = reducePVCSourcedVolumes(pod.getSpec().getVolumes()); pod.getSpec() .getVolumes() .add( new VolumeBuilder() .withName(commonPVCName) .withNewPersistentVolumeClaim() .withClaimName(commonPVCName) .endPersistentVolumeClaim() .build()); Stream.concat( pod.getSpec().getContainers().stream(), pod.getSpec().getInitContainers().stream()) .flatMap(c -> c.getVolumeMounts().stream()) .filter(vm -> pvcSourcedVolumes.contains(vm.getName())) .forEach(vm -> vm.setName(commonPVCName)); } }