auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static ImmutableWorkerInfo selectWorker( final Task task, final Map<String, ImmutableWorkerInfo> allWorkers, final WorkerTaskRunnerConfig workerTaskRunnerConfig, @Nullable final AffinityConfig affinityConfig, final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector ) { final Map<String, ImmutableWorkerInfo> runnableWorkers = allWorkers .values() .stream() .filter(worker -> worker.canRunTask(task) && worker.isValidVersion(workerTaskRunnerConfig.getMinWorkerVersion())) .collect(Collectors.toMap(w -> w.getWorker().getHost(), Function.identity())); if (affinityConfig == null) { return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers)); } else { final Map<String, ImmutableWorkerInfo> nonAffinityWorkers = runnableWorkers .entrySet() .stream() .filter(entry -> !affinityConfig.getAffinityWorkers().contains(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); final List<String> dataSourceWorkers = affinityConfig.getAffinity().get(task.getDataSource()); if (dataSourceWorkers == null) { return workerSelector.apply(ImmutableMap.copyOf(nonAffinityWorkers)); } else { final Set<String> dataSourceWorkerHosts = ImmutableSet.copyOf(dataSourceWorkers); final Map<String, ImmutableWorkerInfo> dataSourceWorkerMap = runnableWorkers .entrySet() .stream() .filter(entry -> dataSourceWorkerHosts.contains(entry.getKey())) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); final ImmutableWorkerInfo selected = workerSelector.apply(ImmutableMap.copyOf(dataSourceWorkerMap)); if (selected != null) { return selected; } else if (affinityConfig.isStrong()) { return null; } else { return workerSelector.apply(ImmutableMap.copyOf(nonAffinityWorkers)); } } } }

Target:
public static ImmutableWorkerInfo selectWorker( final Task task, final Map<String, ImmutableWorkerInfo> allWorkers, final WorkerTaskRunnerConfig workerTaskRunnerConfig, @Nullable final AffinityConfig affinityConfig, final Function<ImmutableMap<String, ImmutableWorkerInfo>, ImmutableWorkerInfo> workerSelector ) { final Map<String, ImmutableWorkerInfo> runnableWorkers = allWorkers .values() .stream() .filter(worker -> worker.canRunTask(task) && worker.isValidVersion(workerTaskRunnerConfig.getMinWorkerVersion())) .collect(Collectors.toMap(w -> w.getWorker().getHost(), Function.identity())); if (affinityConfig == null) { return workerSelector.apply(ImmutableMap.copyOf(runnableWorkers)); } else { final Set<String> dataSourceWorkers = affinityConfig.getAffinity().get(task.getDataSource()); if (dataSourceWorkers == null) { return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers)); } else { final ImmutableMap<String, ImmutableWorkerInfo> dataSourceWorkerMap = ImmutableMap.copyOf(Maps.filterKeys(runnableWorkers, dataSourceWorkers::contains)); final ImmutableWorkerInfo selected = workerSelector.apply(dataSourceWorkerMap); if (selected != null) { return selected; } else if (affinityConfig.isStrong()) { return null; } else { return workerSelector.apply(getNonAffinityWorkers(affinityConfig, runnableWorkers)); } } } }
Source:
public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { if (cbh == null) throw ElytronMessages.log.mechCallbackHandlerMissing().toSaslException(); if (props == null) props = Collections.emptyMap(); if (! matches(props)) return null; String selectedMech = select(mechanisms); if (selectedMech == null) return null; Boolean utf8 = (Boolean)props.get(WildFlySasl.USE_UTF8); Charset charset = (utf8==null || utf8.booleanValue()) ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1; String qopsString = (String)props.get(Sasl.QOP); String[] qops = qopsString==null ? null : qopsString.split(","); String supportedCipherOpts = (String)props.get(WildFlySasl.SUPPORTED_CIPHER_NAMES); String[] ciphers = supportedCipherOpts == null ? DEFAULT_CIPHERS : supportedCipherOpts.split(","); final DigestSaslClient client = new DigestSaslClient(selectedMech, protocol, serverName, cbh, authorizationId, false, charset, qops, ciphers, providers); client.init(); return client; }

Target:
public SaslClient createSaslClient(String[] mechanisms, String authorizationId, String protocol, String serverName, Map<String, ?> props, CallbackHandler cbh) throws SaslException { Assert.checkNotNullParam("cbh", cbh); if (props == null) props = Collections.emptyMap(); if (! matches(props)) return null; String selectedMech = select(mechanisms); if (selectedMech == null) return null; Boolean utf8 = (Boolean)props.get(WildFlySasl.USE_UTF8); Charset charset = (utf8==null || utf8.booleanValue()) ? StandardCharsets.UTF_8 : StandardCharsets.ISO_8859_1; String qopsString = (String)props.get(Sasl.QOP); String[] qops = qopsString==null ? null : qopsString.split(","); String supportedCipherOpts = (String)props.get(WildFlySasl.SUPPORTED_CIPHER_NAMES); String[] ciphers = supportedCipherOpts == null ? DEFAULT_CIPHERS : supportedCipherOpts.split(","); final DigestSaslClient client = new DigestSaslClient(selectedMech, protocol, serverName, cbh, authorizationId, false, charset, qops, ciphers, providers); client.init(); return client; }
Source:
public UpdaterIssuesSelector getIssueSelector() { UpdaterIssuesSelector uis = this.issueSelector; if (uis == null) uis = new Updater.DefaultUpdaterIssuesSelector(); return (this.issueSelector = uis); }

Target:
public UpdaterIssueSelector getIssueSelector() { UpdaterIssueSelector uis = this.issueSelector; if (uis == null) uis = new DefaultUpdaterIssueSelector(); return (this.issueSelector = uis); }
Source:
public double[] transformToDoubleValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new double[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } int numDocs = projectionBlock.getNumDocs(); double sumRes; switch (_argument.getResultMetadata().getDataType()) { case INT: int[][] intValuesMV = _argument.transformToIntValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { sumRes = 0; for (int j = 0; j < intValuesMV[i].length; j++) { sumRes += intValuesMV[i][j]; } _results[i] = sumRes / intValuesMV[i].length; } break; case LONG: long[][] longValuesMV = _argument.transformToLongValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { sumRes = 0; for (int j = 0; j < longValuesMV[i].length; j++) { sumRes += longValuesMV[i][j]; } _results[i] = sumRes / longValuesMV[i].length; } break; case FLOAT: float[][] floatValuesMV = _argument.transformToFloatValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { sumRes = 0; for (int j = 0; j < floatValuesMV[i].length; j++) { sumRes += floatValuesMV[i][j]; } _results[i] = sumRes / floatValuesMV[i].length; } break; case DOUBLE: double[][] doubleValuesMV = _argument.transformToDoubleValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { sumRes = 0; for (int j = 0; j < doubleValuesMV[i].length; j++) { sumRes += doubleValuesMV[i][j]; } _results[i] = sumRes / doubleValuesMV[i].length; } break; default: throw new IllegalStateException(); } return _results; }

Target:
public double[] transformToDoubleValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new double[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } int numDocs = projectionBlock.getNumDocs(); switch (_argument.getResultMetadata().getDataType()) { case INT: int[][] intValuesMV = _argument.transformToIntValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { double sumRes = 0; for (int value : intValuesMV[i]) { sumRes += value; } _results[i] = sumRes / intValuesMV[i].length; } break; case LONG: long[][] longValuesMV = _argument.transformToLongValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { double sumRes = 0; for (long value : longValuesMV[i]) { sumRes += value; } _results[i] = sumRes / longValuesMV[i].length; } break; case FLOAT: float[][] floatValuesMV = _argument.transformToFloatValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { double sumRes = 0; for (float value : floatValuesMV[i]) { sumRes += value; } _results[i] = sumRes / floatValuesMV[i].length; } break; case DOUBLE: double[][] doubleValuesMV = _argument.transformToDoubleValuesMV(projectionBlock); for (int i = 0; i < numDocs; i++) { double sumRes = 0; for (double value : doubleValuesMV[i]) { sumRes += value; } _results[i] = sumRes / doubleValuesMV[i].length; } break; default: throw new IllegalStateException(); } return _results; }
Source:
public void testHashCodeSame() { RuntimeSettingProvider runtimeSettingProvider1 = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jarRuntimeInfo1 = new JdbcRuntimeInfo(runtimeSettingProvider1, "anyRuntimeClassName"); int hashCode1 = jarRuntimeInfo1.hashCode(); RuntimeSettingProvider runtimeSettingProvider2 = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jarRuntimeInfo2 = new JdbcRuntimeInfo(runtimeSettingProvider2, "anyRuntimeClassName"); int hashCode2 = jarRuntimeInfo2.hashCode(); assertEquals(269161086, hashCode1); assertEquals(269161086, hashCode2); assertEquals(hashCode1, hashCode2); }

Target:
public void testHashCodeSame() { RuntimeSettingProvider runtimeSettingProvider1 = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jdbcRuntimeInfo1 = new JdbcRuntimeInfo(runtimeSettingProvider1, "anyRuntimeClassName"); int hashCode1 = jdbcRuntimeInfo1.hashCode(); RuntimeSettingProvider runtimeSettingProvider2 = createPropsWithDriverName("org.talend.Driver1"); JdbcRuntimeInfo jdbcRuntimeInfo2 = new JdbcRuntimeInfo(runtimeSettingProvider2, "anyRuntimeClassName"); int hashCode2 = jdbcRuntimeInfo2.hashCode(); assertEquals(jdbcRuntimeInfo1, jdbcRuntimeInfo2); assertEquals(hashCode1, hashCode2); }
Source:
public final Map<K, V> removeAllWithHash(int keyHash) { Map<K, V> invalidated = new HashMap<K, V>(); int hash = spread(keyHash); for (Node<K, V>[] tab = table; ; ) { Node<K, V> f; int n, i; if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null) break; else if (f.hash == MOVED) tab = helpTransfer(tab, f); else { Map<K, V> nodes = null; synchronized (f) { if (tabAt(tab, i) == f) { nodes = nodesAt(f); setTabAt(tab, i, null); invalidated.putAll(nodes); } } if (nodes != null) { addCount(-nodes.size(), -nodes.size()); } } } return invalidated; }

Target:
public final Map<K, V> removeAllWithHash(int keyHash) { Map<K, V> invalidated = new HashMap<K, V>(); int hash = spread(keyHash); for (Node<K, V>[] tab = table; ; ) { Node<K, V> f; int n, i; if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null) break; else if (f.hash == MOVED) tab = helpTransfer(tab, f); else { int nodesCount = 0; synchronized (f) { if (tabAt(tab, i) == f) { nodesCount = nodesAt(f, invalidated); setTabAt(tab, i, null); } } if (nodesCount > 0) { addCount(-nodesCount, -nodesCount); } } } return invalidated; }
Source:
public void run() throws Exception { MaxwellAbstractRowsEvent event; this.start(); for(;;) { event = getEvent(); if ( event == null ) continue; if ( !skipEvent(event)) { producer.push(event); BinlogPosition p = eventBinlogPosition(event); } } }

Target:
public void run() throws Exception { MaxwellAbstractRowsEvent event; this.start(); for(;;) { event = getEvent(); if ( event == null ) continue; if ( !skipEvent(event)) { producer.push(event); } } }
Source:
public ImmutableList<InsightsLastSeen> getAll(final Long accountId) { final PrimaryKey key = new PrimaryKey(AttributeName.ACCOUNT_ID.shortName(), accountId); final Item item = table.getItem(key); if (item == null) { LOGGER.debug("debug=get-all-last-seen-insights-fail-insight-missing account_id={}", accountId); final List<InsightsLastSeen> insightsLastSeen = new ArrayList<>(); return ImmutableList.copyOf(insightsLastSeen); } final ImmutableList<InsightsLastSeen> insightsLastSeen = fromItem(accountId, item); return insightsLastSeen; }

Target:
public ImmutableList<InsightsLastSeen> getAll(final Long accountId) { final PrimaryKey key = new PrimaryKey(AttributeName.ACCOUNT_ID.shortName(), accountId); final Item item = table.getItem(key); if (item == null) { LOGGER.debug("msg=get-all-last-seen-insights-fail-insight-missing account_id={}", accountId); final List<InsightsLastSeen> insightsLastSeen = new ArrayList<>(); return ImmutableList.copyOf(insightsLastSeen); } final ImmutableList<InsightsLastSeen> insightsLastSeen = fromItem(accountId, item); return insightsLastSeen; }
Source:
public void resourceChanged(IResourceChangeEvent event) { try { IResourceDelta d = event.getDelta(); if (d == null || !autoIgnoreDerived()) return; final Set<IPath> toBeIgnored = new HashSet<IPath>(); d.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) == 0) return false; int flags = delta.getFlags(); if ((flags != 0) && ((flags & IResourceDelta.DERIVED_CHANGED) == 0)) return false; final IResource r = delta.getResource(); if ((r.getProject() != null) && (RepositoryMapping.getMapping(r) == null)) return false; if (r.isTeamPrivateMember()) return false; if (r.isDerived()) { try { if (!RepositoryUtil.isIgnored(r.getLocation())) toBeIgnored.add(r.getLocation()); } catch (IOException e) { logError( MessageFormat.format( CoreText.Activator_ignoreResourceFailed, r.getFullPath()), e); } return false; } return true; } }); if (toBeIgnored.size() > 0) JobUtil.scheduleUserJob(new IgnoreOperation(toBeIgnored), CoreText.Activator_autoIgnoreDerivedResources, JobFamilies.AUTO_IGNORE); } catch (CoreException e) { Activator.logError(e.getMessage(), e); return; } }

Target:
public void resourceChanged(IResourceChangeEvent event) { try { IResourceDelta d = event.getDelta(); if (d == null || !autoIgnoreDerived()) return; final Set<IPath> toBeIgnored = new LinkedHashSet<IPath>(); d.accept(new IResourceDeltaVisitor() { public boolean visit(IResourceDelta delta) throws CoreException { if ((delta.getKind() & (IResourceDelta.ADDED | IResourceDelta.CHANGED)) == 0) return false; int flags = delta.getFlags(); if ((flags != 0) && ((flags & IResourceDelta.DERIVED_CHANGED) == 0)) return false; final IResource r = delta.getResource(); if ((r.getProject() != null) && (RepositoryMapping.getMapping(r) == null)) return false; if (r.isTeamPrivateMember()) return false; if (r.isDerived()) { try { if (!RepositoryUtil.isIgnored(r.getLocation())) toBeIgnored.add(r.getLocation()); } catch (IOException e) { logError( MessageFormat.format( CoreText.Activator_ignoreResourceFailed, r.getFullPath()), e); } return false; } return true; } }); if (toBeIgnored.size() > 0) JobUtil.scheduleUserJob(new IgnoreOperation(toBeIgnored), CoreText.Activator_autoIgnoreDerivedResources, JobFamilies.AUTO_IGNORE); } catch (CoreException e) { Activator.logError(e.getMessage(), e); return; } }
Source:
public void stop() { if (isAlive.get()) { stop(handle); } }

Target:
public void stop() { if (isAlive.getAndSet(false)) { stop(handle); } }
Source:
public void run() throws ConfigError, IOException, UnhandledEvent { FlowVisor.setInstance(this); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); FVLog.log(LogLevel.INFO, null, "initializing poll loop"); FVEventLoop pollLoop = new FVEventLoop(); sliceLimits = new SlicerLimits(); JettyServer.spawnJettyServer(FVConfig.getJettyPort()); if (port == 0) port = FVConfig.getListenPort(); if (TopologyController.isConfigured()) handlers.add(TopologyController.spawn(pollLoop)); OFSwitchAcceptor acceptor = new OFSwitchAcceptor(pollLoop, port, 16,FVConfig.getClearFlowTableOnConnect()); acceptor.setSlicerLimits(sliceLimits); handlers.add(acceptor); try { this.apiServer = APIServer.spawn(); } catch (Exception e) { FVLog.log(LogLevel.FATAL, null, "failed to spawn APIServer"); e.printStackTrace(); System.exit(-1); } boolean flowdb = false; try { if (FVConfig.getFlowTracking()) flowdb = true; } catch (ConfigError e) { FVConfig.setFlowTracking(false); this.checkPointConfig(); } if (!flowdb) FVLog.log(LogLevel.INFO, null, "flowdb: Disabled"); pollLoop.doEventLoop(); }

Target:
public void run() throws ConfigError, IOException, UnhandledEvent { FlowVisor.setInstance(this); Runtime.getRuntime().addShutdownHook(new ShutdownHook()); FVLog.log(LogLevel.INFO, null, "initializing poll loop"); FVEventLoop pollLoop = new FVEventLoop(); sliceLimits = new SlicerLimits(); JettyServer.spawnJettyServer(FVConfig.getJettyPort()); if (port == 0) port = FVConfig.getListenPort(); if (TopologyController.isConfigured()) handlers.add(TopologyController.spawn(pollLoop)); OFSwitchAcceptor acceptor = new OFSwitchAcceptor(pollLoop, port, 16); acceptor.setSlicerLimits(sliceLimits); handlers.add(acceptor); try { this.apiServer = APIServer.spawn(); } catch (Exception e) { FVLog.log(LogLevel.FATAL, null, "failed to spawn APIServer"); e.printStackTrace(); System.exit(-1); } boolean flowdb = false; try { if (FVConfig.getFlowTracking()) flowdb = true; } catch (ConfigError e) { FVConfig.setFlowTracking(false); this.checkPointConfig(); } if (!flowdb) FVLog.log(LogLevel.INFO, null, "flowdb: Disabled"); pollLoop.doEventLoop(); }
Source:
private static Geometry readPolygon(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createPolygon(); } int pointCount = input.readInt(); int[] startIndexes = new int[partCount]; for (int i = 0; i < partCount; i++) { startIndexes[i] = input.readInt(); } int[] partLengths = new int[partCount]; if (partCount > 1) { partLengths[0] = startIndexes[1]; for (int i = 1; i < partCount - 1; i++) { partLengths[i] = startIndexes[i + 1] - startIndexes[i]; } } partLengths[partCount - 1] = pointCount - startIndexes[partCount - 1]; List<Polygon> polygons = new ArrayList<>(); LinearRing shell = null; List<LinearRing> holes = new ArrayList<>(); for (int i = 0; i < partCount; i++) { Coordinate[] coordinates = readCoordinates(input, partLengths[i]); if (isClockwise(coordinates)) { if (shell != null) { polygons.add(GEOMETRY_FACTORY.createPolygon(shell, holes.toArray(new LinearRing[0]))); } shell = GEOMETRY_FACTORY.createLinearRing(coordinates); holes.clear(); } else { holes.add(GEOMETRY_FACTORY.createLinearRing(coordinates)); } } polygons.add(GEOMETRY_FACTORY.createPolygon(shell, holes.toArray(new LinearRing[0]))); if (polygons.size() == 1) { return polygons.get(0); } else { return GEOMETRY_FACTORY.createMultiPolygon(polygons.toArray(new Polygon[0])); } }

Target:
private static Geometry readPolygon(SliceInput input) { requireNonNull(input, "input is null"); skipEnvelope(input); int partCount = input.readInt(); if (partCount == 0) { return GEOMETRY_FACTORY.createPolygon(); } int pointCount = input.readInt(); int[] startIndexes = new int[partCount]; for (int i = 0; i < partCount; i++) { startIndexes[i] = input.readInt(); } int[] partLengths = new int[partCount]; if (partCount > 1) { partLengths[0] = startIndexes[1]; for (int i = 1; i < partCount - 1; i++) { partLengths[i] = startIndexes[i + 1] - startIndexes[i]; } } partLengths[partCount - 1] = pointCount - startIndexes[partCount - 1]; LinearRing shell = null; List<LinearRing> holes = new ArrayList<>(); List<Polygon> polygons = new ArrayList<>(); for (int i = 0; i < partCount; i++) { Coordinate[] coordinates = readCoordinates(input, partLengths[i]); if (!isClockwise(coordinates)) { holes.add(GEOMETRY_FACTORY.createLinearRing(coordinates)); continue; } if (shell != null) { polygons.add(GEOMETRY_FACTORY.createPolygon(shell, holes.toArray(new LinearRing[0]))); } shell = GEOMETRY_FACTORY.createLinearRing(coordinates); holes.clear(); } polygons.add(GEOMETRY_FACTORY.createPolygon(shell, holes.toArray(new LinearRing[0]))); if (polygons.size() == 1) { return polygons.get(0); } return GEOMETRY_FACTORY.createMultiPolygon(polygons.toArray(new Polygon[0])); }
Source:
public final void destroy() throws IOException { queryRunner.close(); queryRunner = null; embeddedElasticsearch.close(); }

Target:
public final void destroy() throws IOException { try (Closer closer = Closer.create()) { closer.register(queryRunner); closer.register(embeddedElasticsearch); } catch (IOException e) { throw new UncheckedIOException(e); } }
Source:
public void returnsNumberOfAllowedRequests(String account, String method, int expectedNumberOfAllowedRequests) { when(rateLimiterKey.getMethod()).thenReturn(method); assertThat(rateLimitManager.getAllowedNumberOfRequests(rateLimiterKey, account), is(expectedNumberOfAllowedRequests)); }

Target:
public void returnsNumberOfAllowedRequests(String account, String method, int expectedNumberOfAllowedRequests) { var rateLimiterKey = new RateLimiterKey("path", "key-type", method); assertThat(rateLimitManager.getAllowedNumberOfRequests(rateLimiterKey, account), is(expectedNumberOfAllowedRequests)); }
Source:
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String id, Authentication principal, HttpServletRequest request) { OAuth2AuthorizedClient result = delegate.loadAuthorizedClient(id, principal, request); if (result != null) { return (T) result; } if (repo.isAuthzClient(id) && !repo.getAuthorizationProperties().get(id).getOnDemand()) { OAuth2AuthorizedClient client = loadAuthorizedClient(defaultClientRegistrationId(), principal, request); return (T) createInitAuthzClient(client, id, principal); } return null; }

Target:
public <T extends OAuth2AuthorizedClient> T loadAuthorizedClient(String id, Authentication principal, HttpServletRequest request) { OAuth2AuthorizedClient result = delegate.loadAuthorizedClient(id, principal, request); if (result != null) { return (T) result; } if (repo.isAuthzClient(id)) { OAuth2AuthorizedClient client = loadAuthorizedClient(defaultClientRegistrationId(), principal, request); return (T) createInitAuthzClient(client, id, principal); } return null; }
Source:
public void testTokenFetch() { long millis = System.currentTimeMillis(); final String username = "someusername" + millis; final String password = "somepassword" + millis; final String repeat = password; CompatCreateAccountResult createAccountResult; new AMLoginInfoTask() { @Override public void onCatch(Throwable caught) { L.e("AMLoginInfoTask failed: " + caught.getMessage()); } @Override public void onFinish(AMLoginInfoResult result) { if (result.getEnabled()) { L.i("Logging in with AuthManager"); AMSubject subject = new AMSubject(username, password, repeat, null); subject.execute(); handleCreateAccountResult(subject.await()); } else { L.i("Logging in with legacy login"); Subject subject = new Subject(username, password, null); subject.execute(); handleCreateAccountResult(subject.await()); } } }.execute(); }

Target:
public void testTokenFetch() { long millis = System.currentTimeMillis(); final String username = "someusername" + millis; final String password = "somepassword" + millis; final String repeat = password; new AMLoginInfoTask() { @Override public void onCatch(Throwable caught) { L.e(caught); fail(); } @Override public void onFinish(AMLoginInfoResult result) { if (result.getEnabled()) { L.i("Logging in with AuthManager"); isAuthManagerEnabled = true; amSubject = new AMSubject(username, password, repeat, null); amSubject.execute(); } else { L.i("Logging in with legacy login"); legacySubject = new Subject(username, password, null); legacySubject.execute(); } } }.execute(); CompatCreateAccountResult result = isAuthManagerEnabled ? amSubject.await() : legacySubject.await(); handleCreateAccountResult(result); }
Source:
public ObjectInformation( final long id, final String name, final String typeString, final Date savedDate, final int version, final WorkspaceUser savedBy, final ResolvedWorkspaceID workspaceID, final String chksum, final long size, final UncheckedUserMetadata meta) { if (id < 1) { throw new IllegalArgumentException("id must be > 0"); } if (version < 1) { throw new IllegalArgumentException("version must be > 0"); } if (size < 1) { throw new IllegalArgumentException("size must be > 0"); } if (name == null || name.isEmpty()) { throw new IllegalArgumentException("name is null or empty"); } if (typeString == null || typeString.isEmpty()) { throw new IllegalArgumentException("typeString is null or empty"); } if (chksum == null|| chksum.isEmpty()) { throw new IllegalArgumentException("chksum is null or empty"); } if (savedDate == null) { throw new NullPointerException("savedDate"); } if (savedBy == null) { throw new NullPointerException("savedBy"); } if (workspaceID == null) { throw new NullPointerException("workspaceID"); } this.id = id; this.name = name; this.type = typeString; this.savedDate = savedDate; this.version = version; this.savedBy = savedBy; this.workspaceID = workspaceID.getID(); this.workspaceName = workspaceID.getName(); this.chksum = chksum; this.size = size; this.meta = meta; final List<Reference> refs = new LinkedList<>(); refs.add(new Reference(workspaceID.getID(), id, version)); this.refpath = Collections.unmodifiableList(refs); }

Target:
public ObjectInformation( final long id, final String name, final String typeString, final Date savedDate, final int version, final WorkspaceUser savedBy, final ResolvedWorkspaceID workspaceID, final String chksum, final long size, final UncheckedUserMetadata meta) { if (id < 1) { throw new IllegalArgumentException("id must be > 0"); } if (version < 1) { throw new IllegalArgumentException("version must be > 0"); } if (size < 1) { throw new IllegalArgumentException("size must be > 0"); } if (name == null || name.isEmpty()) { throw new IllegalArgumentException("name is null or empty"); } if (typeString == null || typeString.isEmpty()) { throw new IllegalArgumentException("typeString is null or empty"); } if (chksum == null|| chksum.isEmpty()) { throw new IllegalArgumentException("chksum is null or empty"); } if (savedDate == null) { throw new NullPointerException("savedDate"); } if (savedBy == null) { throw new NullPointerException("savedBy"); } if (workspaceID == null) { throw new NullPointerException("workspaceID"); } this.id = id; this.name = name; this.type = typeString; this.savedDate = savedDate.getTime(); this.version = version; this.savedBy = savedBy; this.workspaceID = workspaceID.getID(); this.workspaceName = workspaceID.getName(); this.chksum = chksum; this.size = size; this.meta = meta; final List<Reference> refs = new LinkedList<>(); refs.add(new Reference(workspaceID.getID(), id, version)); this.refpath = Collections.unmodifiableList(refs); }
Source:
public String getDisplayName() { return "Abort and restart the build"; }

Target:
public String getDisplayName() { return Messages.AbortAndRestartOperation_DisplayName(); }
Source:
private boolean tooManyPacks() { int autopacklimit = repo.getConfig().getInt( ConfigConstants.CONFIG_GC_SECTION, ConfigConstants.CONFIG_KEY_AUTOPACKLIMIT, 50); if (autopacklimit <= 0) { return false; } return repo.getObjectDatabase().getPacks().size() > autopacklimit; }

Target:
private boolean tooManyPacks() { int autopacklimit = repo.getConfig().getInt( ConfigConstants.CONFIG_GC_SECTION, ConfigConstants.CONFIG_KEY_AUTOPACKLIMIT, DEFAULT_AUTOPACKLIMIT); if (autopacklimit <= 0) { return false; } return repo.getObjectDatabase().getPacks().size() > (autopacklimit + 1); }
Source:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null || config.isEmpty()) { logger.warn("Empty or null configuration. Ignoring."); return; } Set<String> names = getNames(config); for (String name : names) { String value = (String) config.get(name + ".serialPort"); String serialPort = value != null ? value : MeterDeviceConfig.DEFAULT_SERIAL_PORT; value = (String) config.get(name + ".baudRateChangeDelay"); int baudRateChangeDelay = value != null ? Integer.valueOf(value) : MeterDeviceConfig.DEFAULT_BAUD_RATE_CHANGE_DELAY; value = (String) config.get(name + ".echoHandling"); boolean echoHandling = value != null ? Boolean.valueOf(value) : MeterDeviceConfig.DEFAULT_ECHO_HANDLING; MeterReader reader = createIec6205621MeterReader(name, new MeterDeviceConfig(serialPort, baudRateChangeDelay, echoHandling)); if (meterDevices.put(reader.getName(), reader) != null) { logger.info("Recreated reader with {}!", reader.getName(), reader.getConfig()); } else { logger.info("Created reader with {}!", reader.getName(), reader.getConfig()); } } if (config != null) { if (StringUtils.isNotBlank((String) config.get("refresh"))) { refreshInterval = Long .parseLong((String) config.get("refresh")); } setProperlyConfigured(true); } }

Target:
public void updated(Dictionary<String, ?> config) throws ConfigurationException { if (config == null || config.isEmpty()) { logger.warn("Empty or null configuration. Ignoring."); return; } Set<String> names = getNames(config); for (String name : names) { String value = (String) config.get(name + ".serialPort"); String serialPort = value != null ? value : MeterConfig.DEFAULT_SERIAL_PORT; value = (String) config.get(name + ".baudRateChangeDelay"); int baudRateChangeDelay = value != null ? Integer.valueOf(value) : MeterConfig.DEFAULT_BAUD_RATE_CHANGE_DELAY; value = (String) config.get(name + ".echoHandling"); boolean echoHandling = value != null ? Boolean.valueOf(value) : MeterConfig.DEFAULT_ECHO_HANDLING; Meter meterConfig = createIec6205621MeterConfig(name, new MeterConfig(serialPort, baudRateChangeDelay, echoHandling)); if (meterDeviceConfigurtions.put(meterConfig.getName(), meterConfig) != null) { logger.info("Recreated reader with {}!", meterConfig.getName(), meterConfig.getConfig()); } else { logger.info("Created reader with {}!", meterConfig.getName(), meterConfig.getConfig()); } } if (config != null) { if (StringUtils.isNotBlank((String) config.get("refresh"))) { refreshInterval = Long .parseLong((String) config.get("refresh")); } setProperlyConfigured(true); } }
Source:
public List<Project> fillClearingStateSummaryIncludingSubprojects(List<Project> projects, User user) { final Map<String, Project> allProjectsIdMap = ThriftUtils.getIdMap(repository.getAll()); projects.stream().forEach(project -> { Set<String> releaseIdsOfProjectTree = getReleaseIdsOfProjectTree(project, Sets.newHashSet(), allProjectsIdMap, user, null); List<Release> releasesForClearingStateSummary = componentDatabaseHandler .getReleasesForClearingStateSummary(releaseIdsOfProjectTree); final ReleaseClearingStateSummary releaseClearingStateSummary = ReleaseClearingStateSummaryComputer .computeReleaseClearingStateSummary(releasesForClearingStateSummary, project.getClearingTeam()); project.setReleaseClearingStateSummary(releaseClearingStateSummary); }); return projects; }

Target:
public List<Project> fillClearingStateSummaryIncludingSubprojects(List<Project> projects, User user) { final Map<String, Project> allProjectsIdMap = getRefreshedAllProjectsIdMap(); projects.stream().forEach(project -> { Set<String> releaseIdsOfProjectTree = getReleaseIdsOfProjectTree(project, Sets.newHashSet(), allProjectsIdMap, user, null); List<Release> releasesForClearingStateSummary = componentDatabaseHandler .getReleasesForClearingStateSummary(releaseIdsOfProjectTree); final ReleaseClearingStateSummary releaseClearingStateSummary = ReleaseClearingStateSummaryComputer .computeReleaseClearingStateSummary(releasesForClearingStateSummary, project.getClearingTeam()); project.setReleaseClearingStateSummary(releaseClearingStateSummary); }); return projects; }
Source:
public void deleteSupplementaryResources(IResource[] resources) { for (int i = 0; i < resources.length; i++) { try { resources[i].delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError("Error deleting supplementary resource " + resources[i], e); } } }

Target:
public void deleteSupplementaryResources(IResource[] resources) { for (int i = 0; i < resources.length; i++) { try { resources[i].delete(true, new NullProgressMonitor()); } catch (CoreException e) { Activator.getDefault().logError(Messages.TmfCommonProjectElement_ErrorDeletingSR + resources[i], e); } } }
Source:
public Study getMockStudy() { Study study = new Study(); study.setOrderId(getMockOrder().getOrderId()); study.setModality(Modality.CT); study.setPriority(RequestedProcedurePriority.LOW); study.setMwlStatus(MwlStatus.DEFAULT); study.setScheduledStatus(ScheduledProcedureStepStatus.SCHEDULED); return study; }

Target:
public Study getMockStudy() { Study study = new Study(); study.setOrderId(orderService.getOrder(ORDER_ID_WITHOUT_STUDY).getOrderId()); study.setModality(Modality.CT); study.setPriority(RequestedProcedurePriority.LOW); study.setMwlStatus(MwlStatus.DEFAULT); study.setScheduledStatus(ScheduledProcedureStepStatus.SCHEDULED); return study; }
Source:
public void setJobOverrideProperty(Project project, Props prop, String jobName, User modifier) throws ProjectManagerException { prop.setSource(jobName + ".jor"); Props oldProps = projectLoader.fetchProjectProperty(project, prop.getSource()); if (oldProps == null) { oldProps = new Props(); projectLoader.uploadProjectProperty(project, prop); } else { projectLoader.updateProjectProperty(project, prop); } String diffMessage = PropsUtils.getPropertyDiff(oldProps, prop); projectLoader.postEvent(project, EventType.PROPERTY_OVERRIDE, modifier.getUserId(), diffMessage); return; }

Target:
public void setJobOverrideProperty(Project project, Props prop, String jobName, User modifier) throws ProjectManagerException { prop.setSource(jobName + ".jor"); Props oldProps = projectLoader.fetchProjectProperty(project, prop.getSource()); projectLoader.updateProjectProperty(project, prop); String diffMessage = PropsUtils.getPropertyDiff(oldProps, prop); projectLoader.postEvent(project, EventType.PROPERTY_OVERRIDE, modifier.getUserId(), diffMessage); return; }
Source:
static void buildTransformation(ModelVersion version, ResourceTransformationDescriptionBuilder parent) { ResourceTransformationDescriptionBuilder builder = ModClusterModel.VERSION_6_0_0.requiresTransformation(version) ? parent.addChildRedirection(PATH, LEGACY_PATH) : parent.addChildResource(PATH); if (ModClusterModel.VERSION_6_0_0.requiresTransformation(version)) { builder.getAttributeBuilder() .setValueConverter(new AttributeConverter.DefaultAttributeConverter() { @Override protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { if (attributeValue.isDefined() && attributeValue.getType() != EXPRESSION) { attributeValue.set((int) Math.ceil(attributeValue.asDouble())); } } }, Attribute.DECAY.getDefinition()) .end(); } if (ModClusterModel.VERSION_7_0_0.requiresTransformation(version)) { builder.getAttributeBuilder() .setDiscard(DiscardAttributeChecker.UNDEFINED, Attribute.INITIAL_LOAD.getDefinition()) .addRejectCheck(RejectAttributeChecker.DEFINED, Attribute.INITIAL_LOAD.getDefinition()) .end(); } LoadMetricResourceDefinition.buildTransformation(version, builder); CustomLoadMetricResourceDefinition.buildTransformation(version, builder); }

Target:
static void buildTransformation(ModelVersion version, ResourceTransformationDescriptionBuilder parent) { ResourceTransformationDescriptionBuilder builder = ModClusterModel.VERSION_6_0_0.requiresTransformation(version) ? parent.addChildRedirection(PATH, LEGACY_PATH) : parent.addChildResource(PATH); if (ModClusterModel.VERSION_6_0_0.requiresTransformation(version)) { builder.getAttributeBuilder() .setValueConverter(new AttributeConverter.DefaultAttributeConverter() { @Override protected void convertAttribute(PathAddress address, String attributeName, ModelNode attributeValue, TransformationContext context) { if (attributeValue.isDefined() && attributeValue.getType() != EXPRESSION) { attributeValue.set((int) Math.ceil(attributeValue.asDouble())); } } }, Attribute.DECAY.getDefinition()) .end(); } if (ModClusterModel.VERSION_7_0_0.requiresTransformation(version)) { ModelNode legacyInitialLoad = new ModelNode(-1); builder.getAttributeBuilder() .setDiscard(new DiscardAttributeChecker.DiscardAttributeValueChecker(legacyInitialLoad), Attribute.INITIAL_LOAD.getDefinition()) .addRejectCheck(new RejectAttributeChecker.SimpleAcceptAttributeChecker(legacyInitialLoad), Attribute.INITIAL_LOAD.getDefinition()) .end(); } LoadMetricResourceDefinition.buildTransformation(version, builder); CustomLoadMetricResourceDefinition.buildTransformation(version, builder); }
Source:
public void setWorkingSet(IWorkingSet workingSet) { TreeViewer treeViewer = getTreeViewer(); Object[] expanded = treeViewer.getExpandedElements(); ISelection selection = treeViewer.getStructuredSelection(); boolean refreshNeeded = internalSetWorkingSet(workingSet); workingSetFilter.setWorkingSet(emptyWorkingSet ? null : workingSet); if (workingSet != null) { settings.put(STORE_WORKING_SET, workingSet.getName()); } else { settings.put(STORE_WORKING_SET, ""); } updateTitle(); if(refreshNeeded) { treeViewer.refresh(); } treeViewer.setExpandedElements(expanded); if (selection.isEmpty() == false && selection instanceof IStructuredSelection) { IStructuredSelection structuredSelection = (IStructuredSelection) selection; treeViewer.reveal(structuredSelection.getFirstElement()); } }

Target:
public void setWorkingSet(IWorkingSet workingSet) { TreeViewer treeViewer = getTreeViewer(); Object[] expanded = treeViewer.getExpandedElements(); IStructuredSelection structuredSelection = treeViewer.getStructuredSelection(); boolean refreshNeeded = internalSetWorkingSet(workingSet); workingSetFilter.setWorkingSet(emptyWorkingSet ? null : workingSet); if (workingSet != null) { settings.put(STORE_WORKING_SET, workingSet.getName()); } else { settings.put(STORE_WORKING_SET, ""); } updateTitle(); if(refreshNeeded) { treeViewer.refresh(); } treeViewer.setExpandedElements(expanded); if (structuredSelection.isEmpty() == false) { treeViewer.reveal(structuredSelection.getFirstElement()); } }
Source:
public static int convertIp4Address(String ipAddress) throws KuraException { if (ipAddress == null) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } String[] splitIpAddress = ipAddress.split("\\."); if (splitIpAddress.length != 4) { throw new KuraException(KuraErrorCode.INVALID_PARAMETER); } short[] addressBytes = new short[4]; for (int i = 0; i < 4; i++) { String octet = splitIpAddress[i]; addressBytes[i] = Short.parseShort(octet); } return NetworkUtil.packIp4AddressBytes(addressBytes); }

Target:
public static int convertIp4Address(String ipAddress) { if (ipAddress == null) { throw new IllegalArgumentException("ipAddress is null"); } String[] splitIpAddress = ipAddress.split("\\."); if (splitIpAddress.length != 4) { throw new IllegalArgumentException("ipAddress is invalid: " + ipAddress); } short[] addressBytes = new short[4]; for (int i = 0; i < 4; i++) { String octet = splitIpAddress[i]; addressBytes[i] = Short.parseShort(octet); } return NetworkUtil.packIp4AddressBytes(addressBytes); }
Source:
protected Void run() throws Exception { FilePath workspace = getContext().get(FilePath.class); workspace.mkdirs(); Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); Launcher launcher = getContext().get(Launcher.class); FlowNode node = getContext().get(FlowNode.class); String nodeId = node.getId(); TestResultAction testResultAction = JUnitResultArchiver.parseAndAttach(step, nodeId, run, workspace, launcher, listener); if (testResultAction != null) { if (testResultAction.getResult().getFailCount() > 0) { getContext().setResult(Result.UNSTABLE); } TagsAction tagsAction = node.getAction(TagsAction.class); if (tagsAction != null) { tagsAction.addTag(JUnitResultsStep.HAS_TEST_RESULTS_TAG_NAME, "true"); node.save(); } else { tagsAction = new TagsAction(); tagsAction.addTag(JUnitResultsStep.HAS_TEST_RESULTS_TAG_NAME, "true"); node.addAction(tagsAction); } } return null; }

Target:
protected TestResultSummary run() throws Exception { FilePath workspace = getContext().get(FilePath.class); workspace.mkdirs(); Run<?,?> run = getContext().get(Run.class); TaskListener listener = getContext().get(TaskListener.class); Launcher launcher = getContext().get(Launcher.class); FlowNode node = getContext().get(FlowNode.class); String nodeId = node.getId(); TestResultAction testResultAction = JUnitResultArchiver.parseAndAttach(step, nodeId, getEnclosingStagesAndParallels(node), run, workspace, launcher, listener); if (testResultAction != null) { if (testResultAction.getResult().getFailCount() > 0) { getContext().setResult(Result.UNSTABLE); } return new TestResultSummary(testResultAction.getResult().getResultByRunAndNode(run.getExternalizableId(), nodeId)); } return new TestResultSummary(); }
Source:
public void shouldThrowExceptionWhenKVStoreWithPartitionDoesntExists() { storeProvider.getStore(StoreQueryParameters.fromNameAndType(keyValueStore, QueryableStoreTypes.keyValueStore()).withPartition(numStateStorePartitions + 1)); }

Target:
public void shouldThrowExceptionWhenKVStoreWithPartitionDoesntExists() { final int partition = numStateStorePartitions + 1; final InvalidStateStoreException thrown = assertThrows(InvalidStateStoreException.class, () -> storeProvider.getStore( StoreQueryParameters .fromNameAndType(keyValueStore, QueryableStoreTypes.keyValueStore()) .withPartition(partition)) ); assertThat(thrown.getMessage(), equalTo(String.format("The specified partition %d for store %s does not exist.", partition, keyValueStore))); }
Source:
public Response getFieldTypes(@Context final HttpServletRequest req) { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); final ImmutableList<Map<String, Object>> fieldTypesMap = fieldTypeAPI.getFieldTypes(user).stream() .map(fieldType -> fieldType.toMap()) .collect(toImmutableList()); return Response.ok( new ResponseEntityView( fieldTypesMap ) ).build(); }

Target:
public Response getFieldTypes(@Context final HttpServletRequest req) { final InitDataObject initData = this.webResource.init(null, true, req, true, null); final User user = initData.getUser(); final ImmutableList<Map<String, Object>> fieldTypesMap = fieldTypeAPI.getFieldTypes(user).stream() .map(FieldType::toMap) .collect(toImmutableList()); return Response.ok( new ResponseEntityView( fieldTypesMap ) ).build(); }
Source:
public void getReplicasTest() throws Exception { List<? extends PartitionId> partitionIds = CLUSTER_MAP.getWritablePartitionIds(); for (PartitionId partitionId : partitionIds) { String originalReplicaStr = partitionId.getReplicaIds().toString().replace(", ", ","); BlobId blobId = new BlobId(BlobId.DEFAULT_FLAG, ClusterMapUtils.LEGACY_DATACENTER_ID, Account.LEGACY_ACCOUNT_ID, Container.LEGACY_CONTAINER_ID, partitionId); RestRequest restRequest = AdminTestUtils.createRestRequest(RestMethod.GET, blobId.getID() + "/" + RestUtils.SubResource.Replicas, null, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); JSONObject response = new JSONObject(new String(restResponseChannel.getResponseBody())); String returnedReplicasStr = response.getString(GetReplicasHandler.REPLICAS_KEY).replace("\"", ""); assertEquals("Replica IDs returned for the BlobId do no match with the replicas IDs of partition", originalReplicaStr, returnedReplicasStr); } }

Target:
public void getReplicasTest() throws Exception { List<? extends PartitionId> partitionIds = CLUSTER_MAP.getWritablePartitionIds(); for (PartitionId partitionId : partitionIds) { String originalReplicaStr = partitionId.getReplicaIds().toString().replace(", ", ","); BlobId blobId = new BlobId(BlobId.DEFAULT_FLAG, ClusterMapUtils.UNKNOWN_DATACENTER_ID, Account.UNKNOWN_ACCOUNT_ID, Container.UNKNOWN_CONTAINER_ID, partitionId); RestRequest restRequest = AdminTestUtils.createRestRequest(RestMethod.GET, blobId.getID() + "/" + RestUtils.SubResource.Replicas, null, null); MockRestResponseChannel restResponseChannel = new MockRestResponseChannel(); doOperation(restRequest, restResponseChannel); JSONObject response = new JSONObject(new String(restResponseChannel.getResponseBody())); String returnedReplicasStr = response.getString(GetReplicasHandler.REPLICAS_KEY).replace("\"", ""); assertEquals("Replica IDs returned for the BlobId do no match with the replicas IDs of partition", originalReplicaStr, returnedReplicasStr); } }
Source:
private void configVpnNetwork() { final Network network = new Network(mNetwork); final Network[] networks = new Network[] {network}; doReturn(networks).when(sMockConnectivityManager).getAllNetworks(); final NetworkCapabilities vpnCapabilities = new NetworkCapabilities(); vpnCapabilities.addTransportType(NetworkCapabilities.TRANSPORT_VPN); doReturn(vpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities(network); }

Target:
private void configVpnNetwork() { final Network network1 = new Network(TEST_NETID + 1); final Network network2 = new Network(TEST_NETID + 2); final Network[] networks = new Network[] {network1, network2}; doReturn(networks).when(sMockConnectivityManager).getAllNetworks(); final NetworkCapabilities underlyingCapabilities = new NetworkCapabilities() .addTransportType(NetworkCapabilities.TRANSPORT_WIFI); final NetworkCapabilities vpnCapabilities = new NetworkCapabilities(underlyingCapabilities) .addTransportType(NetworkCapabilities.TRANSPORT_VPN); doReturn(underlyingCapabilities).when(sMockConnectivityManager).getNetworkCapabilities( network1); doReturn(vpnCapabilities).when(sMockConnectivityManager).getNetworkCapabilities(network2); }
Source:
private Container newContainer( RuntimeIdentity runtimeId, List<EnvVar> envVars, String image, @Nullable String brokerVolumeName) { Matcher matcher = IMAGE_PATTERN.matcher(image); String containerName; if (matcher.matches()) { containerName = String.format("%s/%s", matcher.group("org"), matcher.group("image")); } else { containerName = image; } containerName = containerName.toLowerCase().replaceAll("[^\\d\\w-]", "-"); final ContainerBuilder cb = new ContainerBuilder() .withName(containerName) .withImage(image) .withArgs( "-push-endpoint", cheWebsocketEndpoint, "-runtime-id", String.format( "%s:%s:%s", runtimeId.getWorkspaceId(), MoreObjects.firstNonNull(runtimeId.getEnvName(), ""), runtimeId.getOwnerId()), "-cacert", certProvisioner.isConfigured() ? certProvisioner.getCertPath() : "", "--registry-address", Strings.nullToEmpty(pluginRegistryUrl)) .withImagePullPolicy(brokerPullPolicy) .withEnv(envVars); if (brokerVolumeName != null) { cb.withVolumeMounts(new VolumeMount(CONF_FOLDER + "/", null, brokerVolumeName, true, null)); cb.addToArgs("-metas", CONF_FOLDER + "/" + CONFIG_FILE); } Container container = cb.build(); Containers.addRamLimit(container, "250Mi"); Containers.addRamRequest(container, "250Mi"); return container; }

Target:
private Container newContainer( RuntimeIdentity runtimeId, List<EnvVar> envVars, String image, @Nullable String brokerVolumeName) { String containerName = generateContainerNameFromImageRef(image); final ContainerBuilder cb = new ContainerBuilder() .withName(containerName) .withImage(image) .withArgs( "-push-endpoint", cheWebsocketEndpoint, "-runtime-id", String.format( "%s:%s:%s", runtimeId.getWorkspaceId(), MoreObjects.firstNonNull(runtimeId.getEnvName(), ""), runtimeId.getOwnerId()), "-cacert", certProvisioner.isConfigured() ? certProvisioner.getCertPath() : "", "--registry-address", Strings.nullToEmpty(pluginRegistryUrl)) .withImagePullPolicy(brokerPullPolicy) .withEnv(envVars); if (brokerVolumeName != null) { cb.withVolumeMounts(new VolumeMount(CONF_FOLDER + "/", null, brokerVolumeName, true, null)); cb.addToArgs("-metas", CONF_FOLDER + "/" + CONFIG_FILE); } Container container = cb.build(); Containers.addRamLimit(container, "250Mi"); Containers.addRamRequest(container, "250Mi"); return container; }
Source:
public StateModel createNewStateModel(String resourceName, String partitionName) { StateModel stateModelToReturn; switch (ambryStateModelDef) { case AmbryStateModelDefinition.AMBRY_LEADER_STANDBY_MODEL: stateModelToReturn = new AmbryPartitionStateModel(); break; default: stateModelToReturn = new AmbryDefaultStateModel(); } return stateModelToReturn; }

Target:
public StateModel createNewStateModel(String resourceName, String partitionName) { StateModel stateModelToReturn; switch (ambryStateModelDef) { case AmbryStateModelDefinition.AMBRY_LEADER_STANDBY_MODEL: stateModelToReturn = new AmbryPartitionStateModel(resourceName, partitionName); break; case LeaderStandbySMD.name: stateModelToReturn = new DefaultLeaderStandbyStateModel(); break; default: throw new IllegalArgumentException("Unsupported state model definition: " + ambryStateModelDef); } return stateModelToReturn; }