auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void remove(String regName) { MetricRegistry mreg = registries.remove(regName); if (mreg != null) notifyListeners(mreg, metricRegRemoveLsnrs, log); metaLock.writeLock().lock(); try { for (Metric m : mreg) { if (m instanceof HitRateMetric) metastorage.remove(metricName(HITRATE_CFG_PREFIX, m.name())); else if (m instanceof HistogramMetric) metastorage.remove(metricName(HISTOGRAM_CFG_PREFIX, m.name())); } } catch (IgniteCheckedException e) { throw new IgniteException(e); } finally { metaLock.writeLock().unlock(); } }

Target:
public void remove(String regName) { MetricRegistry mreg = registries.remove(regName); if (mreg == null) return; notifyListeners(mreg, metricRegRemoveLsnrs, log); try { GridCompoundFuture opsFut = new GridCompoundFuture<>(); for (Metric m : mreg) { if (m instanceof HitRateMetric) opsFut.add(metastorage.removeAsync(metricName(HITRATE_CFG_PREFIX, m.name()))); else if (m instanceof HistogramMetric) opsFut.add(metastorage.removeAsync(metricName(HISTOGRAM_CFG_PREFIX, m.name()))); } opsFut.markInitialized(); opsFut.get(); } catch (IgniteCheckedException e) { throw new IgniteException(e); } }
Source:
public SocketAddress localAddress() { SocketAddress address = localAddress; if (address == null) { java.net.SocketAddress addr = chctx.channel().hasAttr(LOCAL_ADDRESS_OVERRIDE) ? chctx.channel().attr(LOCAL_ADDRESS_OVERRIDE).getAndSet(null) : chctx.channel().localAddress(); if (addr != null) { address = vertx.transport().convert(addr); localAddress = address; } } return address; }

Target:
public SocketAddress localAddress() { SocketAddress address = localAddress; if (address == null) { if (chctx.channel().hasAttr(LOCAL_ADDRESS_OVERRIDE)) { address = chctx.channel().attr(LOCAL_ADDRESS_OVERRIDE).getAndSet(null); } else { java.net.SocketAddress addr = chctx.channel().localAddress(); if (addr != null) { address = vertx.transport().convert(addr); } } if (address != null) localAddress = address; } return address; }
Source:
public PostMessageField(String title, String value) { this.title = title; this.value = value; }

Target:
public PostMessageField(String title, String value) { this(title, value, false); }
Source:
public void onPartitionsAssigned(Collection<TopicPartition> partitions) { _consumerMetrics.updateRebalanceRate(1); _logger.info("Partition ownership assigned for {}.", partitions); _consumerAssignment = Sets.newHashSet(partitions); _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }

Target:
public void onPartitionsAssigned(Collection<TopicPartition> partitions) { _consumerMetrics.updateRebalanceRate(1); _logger.info("Partition ownership assigned for {}.", partitions); _consumerAssignment = Sets.newHashSet(partitions); _logger.info("Current assignment is {}", _consumerAssignment); _taskUpdates.add(DatastreamConstants.UpdateType.PAUSE_RESUME_PARTITIONS); }
Source:
@Override public V remove(int key) { lock.writeLock().lock(); try { if (entries.length != INITIAL_CAPACITY && (int)(COMPACT_LOAD_FACTOR * (entries.length >> 1)) > size) resize(false); int idx = find(key); if (idx < 0) return null; size--; V tmp = entries[idx].val; for (int i = 0; i < entries.length; i++) { int curIdx = (idx + i) & (entries.length - 1); int nextIdx = (idx + i + 1) & (entries.length - 1); Entry<V> nextEntry = entries[nextIdx]; if (nextEntry == null || distance(nextIdx, nextEntry.key) == 0) { entries[curIdx] = null; return tmp; } entries[curIdx] = entries[nextIdx]; } throw new IllegalStateException("Unreachable state exception. Backward shift has a problem. " + "Removing key: " + key + " map state: " + toString()); } finally { lock.writeLock().unlock(); } }

Target:
@Override public V remove(int key) { if (entries.length != INITIAL_CAPACITY && compactThreshold > size) resize(false); int idx = find(key); if (idx < 0) return null; size--; V tmp = entries[idx].val; for (int i = 0; i < entries.length; i++) { int curIdx = (idx + i) & (entries.length - 1); int nextIdx = (idx + i + 1) & (entries.length - 1); Entry<V> nextEntry = entries[nextIdx]; if (nextEntry == null || distance(nextIdx, nextEntry.key) == 0) { entries[curIdx] = null; return tmp; } entries[curIdx] = nextEntry; } throw new IllegalStateException("Unreachable state exception. Backward shift has a problem. " + "Removing key: " + key + " map state: " + toString()); }
Source:
private String generateDeclarations(List<SourceFile> sourceFiles, List<SourceFile> externs) throws AssertionError { Compiler compiler = new Compiler(); compiler.disableThreads(); CompilerOptions compilerOptions = opts.getCompilerOptions(); compiler.setPassConfig(new DefaultPassConfig(compilerOptions)); compiler.setErrorManager(new BasicErrorManager() { @Override public void println(CheckLevel level, JSError error) @Override protected void printSummary() }); if (externs.isEmpty()) { externs = opts.skipParseExterns ? Collections.<SourceFile>emptyList() : getDefaultExterns(); } Result compilationResult = compiler.compile(externs, sourceFiles, compilerOptions); if (compiler.hasErrors()) { throw new AssertionError("Compile failed: " + Arrays.toString(compilationResult.errors)); } return produceDts(compiler); }

Target:
private String generateDeclarations(List<SourceFile> sourceFiles, List<SourceFile> externs) throws AssertionError { Compiler compiler = new Compiler(); compiler.disableThreads(); CompilerOptions compilerOptions = opts.getCompilerOptions(); compiler.setPassConfig(new DefaultPassConfig(compilerOptions)); compiler.setErrorManager(new BasicErrorManager() { @Override public void println(CheckLevel level, JSError error) @Override protected void printSummary() }); if (externs.isEmpty()) { externs = opts.skipParseExterns ? Collections.<SourceFile>emptyList() : getDefaultExterns(); } else { Preconditions.checkArgument(!opts.skipParseExterns); } Result compilationResult = compiler.compile(externs, sourceFiles, compilerOptions); if (compiler.hasErrors()) { throw new AssertionError("Compile failed: " + Arrays.toString(compilationResult.errors)); } return produceDts(compiler); }
Source:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); this.potentialProjects = Collections.emptyMap(); this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }

Target:
public SmartImportRootWizardPage(SmartImportWizard wizard, File initialSelection, Set<IWorkingSet> initialWorkingSets) { super(SmartImportRootWizardPage.class.getName()); this.selection = initialSelection; this.workingSets = initialWorkingSets; if (this.workingSets == null) { this.workingSets = new HashSet<>(); } setWizard(wizard); }
Source:
protected void addField(String fieldName, String value) { output.append("\"").append(value).append("\","); }

Target:
protected void addField(String fieldName, String value) { output .append(StringEscapeUtils.escapeCsv(value)) .append(","); }
Source:
protected TerracottaServer createNode(int stripeId, int nodesId) { String uniqueId = combine(stripeId, nodesId); TerracottaServer terracottaServer = server("node-" + uniqueId, "localhost") .tsaPort(getNodePort(stripeId, nodesId)) .tsaGroupPort(getNodeGroupPort(stripeId, nodesId)) .configRepo("terracotta" + uniqueId + "/repository") .logs("terracotta" + uniqueId + "/logs") .dataDir("main:terracotta" + uniqueId + "/data-dir") .offheap("main:512MB,foo:1GB") .metaData("terracotta" + uniqueId + "/metadata"); if (mode) { if (voters > 0) { terracottaServer.failoverPriority("consistency:" + voters); } else if (voters == 0) { terracottaServer.failoverPriority("consistency"); } else { throw new IllegalArgumentException("voters can't be negative " + voters); } } return terracottaServer; }

Target:
protected TerracottaServer createNode(int stripeId, int nodesId) { String uniqueId = combine(stripeId, nodesId); return server("node-" + uniqueId, "localhost") .tsaPort(getNodePort(stripeId, nodesId)) .tsaGroupPort(getNodeGroupPort(stripeId, nodesId)) .configRepo("terracotta" + uniqueId + "/repository") .logs("terracotta" + uniqueId + "/logs") .dataDir("main:terracotta" + uniqueId + "/data-dir") .offheap("main:512MB,foo:1GB") .metaData("terracotta" + uniqueId + "/metadata") .failoverPriority(failoverPriority.toString()); }
Source:
public ActionDescriptor[] getExtendedActions() { ArrayList<ActionDescriptor> results = new ArrayList<>(); for (Object element : cache) { EditorContribution ec = (EditorContribution) element; if (ec.actions != null) { results.addAll(ec.actions); } } return results.toArray(new ActionDescriptor[results.size()]); }

Target:
public ActionDescriptor[] getExtendedActions() { ArrayList<ActionDescriptor> results = new ArrayList<>(); for (Object contribution : cache) { EditorContribution ec = (EditorContribution) contribution; if (ec.actions != null) { results.addAll(ec.actions); } } return results.toArray(new ActionDescriptor[results.size()]); }
Source:
public Object get(Object thiz) { try { return getter.invoke( thiz ); } catch (Error e) { throw e; } catch (Throwable e) { if ( e instanceof InterruptedException ) { Thread.currentThread().interrupt(); } throw log.errorInvokingMember( member.getName(), thiz.toString(), e ); } }

Target:
public Object get(Object thiz) { try { return getter.invoke( thiz ); } catch (Error e) { throw e; } catch (Throwable e) { if ( e instanceof InterruptedException ) { Thread.currentThread().interrupt(); } throw log.errorInvokingMember( member, thiz, e ); } }
Source:
public void pull_filterDocIdsFromAnimalDb_twoDocShouldBePulled() throws Exception { org.junit.Assume.assumeTrue(ClientTestUtils.isCouchDBV2(remoteDb.couchClient.getRootUri())); List<String> docIds = Arrays.asList("snipe","kookaburra"); PullStrategy replicator = super.getPullStrategy(docIds); Assert.assertEquals(0, datastore.getDocumentCount()); AnimalDb.populate(remoteDb.couchClient); this.pull(replicator, 2); Assert.assertEquals(2, datastore.getDocumentCount()); String[] birds = {"snipe", "kookaburra"}; for (String bird : birds) { Assert.assertTrue(datastore.contains(bird)); } }

Target:
public void pull_filterDocIdsFromAnimalDb_twoDocShouldBePulled() throws Exception { org.junit.Assume.assumeTrue(ClientTestUtils.isCouchDBV2(remoteDb.couchClient.getRootUri())); List<String> docIds = Arrays.asList("snipe","kookaburra"); PullStrategy replicator = super.getPullStrategy(docIds); Assert.assertEquals(0, datastore.getDocumentCount()); AnimalDb.populate(remoteDb.couchClient); this.pull(replicator, 2); Assert.assertEquals(2, datastore.getDocumentCount()); for (String bird : docIds) { Assert.assertTrue(datastore.contains(bird)); } }
Source:
public DataWord negate() { if (this.isZero()) return zero(); byte[] newData = this.getData(); for (int i = 0; i < this.data.length; ++i) { newData[i] = (byte) ~this.data[i]; } for (int i = this.data.length - 1; i >= 0; --i) { newData[i] = (byte) (1 + this.data[i] & 0xFF); if (newData[i] != 0) break; } return new DataWord(newData); }

Target:
public DataWord negate() { if (this.isZero()) return ZERO; byte[] newData = this.copyData(); for (int i = 0; i < this.data.length; ++i) { newData[i] = (byte) ~this.data[i]; } for (int i = this.data.length - 1; i >= 0; --i) { newData[i] = (byte) (1 + this.data[i] & 0xFF); if (newData[i] != 0) break; } return new DataWord(newData); }
Source:
public void generate(ActivationClassBuilder acb, MethodBuilder mb) throws StandardException { dataSetProcessorType= CompilerContext.DataSetProcessorType.FORCED_SPARK; acb.setDataSetProcessorType(dataSetProcessorType); assignResultSetNumber(); costEstimate = childResult.getFinalCostEstimate(); if (SanityManager.DEBUG) { SanityManager.ASSERT(windowInfoList != null, "windowInfoList not set up as expected"); } int aggInfoItemIndex = acb.addItem(windowInfoList); acb.pushGetResultSetFactoryExpression(mb); childResult.generate(acb, mb); mb.push(isInSortedOrder); mb.push(aggInfoItemIndex); resultColumns.generateHolder(acb, mb); mb.push(resultColumns.getTotalColumnSize()); mb.push(resultSetNumber); mb.push(costEstimate.rowCount()); mb.push(costEstimate.getEstimatedCost()); mb.push(printExplainInformationForActivation()); mb.callMethod(VMOpcode.INVOKEINTERFACE, null, "getWindowResultSet", ClassName.NoPutResultSet, 9); }

Target:
public void generate(ActivationClassBuilder acb, MethodBuilder mb) throws StandardException { assignResultSetNumber(); costEstimate = childResult.getFinalCostEstimate(); if (SanityManager.DEBUG) { SanityManager.ASSERT(windowInfoList != null, "windowInfoList not set up as expected"); } int aggInfoItemIndex = acb.addItem(windowInfoList); acb.pushGetResultSetFactoryExpression(mb); childResult.generate(acb, mb); mb.push(isInSortedOrder); mb.push(aggInfoItemIndex); resultColumns.generateHolder(acb, mb); mb.push(resultColumns.getTotalColumnSize()); mb.push(resultSetNumber); mb.push(costEstimate.rowCount()); mb.push(costEstimate.getEstimatedCost()); mb.push(printExplainInformationForActivation()); mb.callMethod(VMOpcode.INVOKEINTERFACE, null, "getWindowResultSet", ClassName.NoPutResultSet, 9); }
Source:
private LogReplicationEntry processReceivedMessage(LogReplicationEntry message) { if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { LogReplicationEntry ack = snapshotSinkBufferManager.processMsgAndBuffer(message); if (ack.getMetadata().getMessageMetadataType() == MessageType.SNAPSHOT_REPLICATED) { long lastStartedSnapshotSync = logReplicationMetadataManager.getLastSnapStartTimestamp(); if (ack.getMetadata().getSnapshotTimestamp() == lastStartedSnapshotSync) { snapshotSyncPlugin.onSnapshotSyncEnd(runtime); } else { log.warn("SNAPSHOT_SYNC has completed for {}, but new ongoing SNAPSHOT_SYNC is {}", ack.getMetadata().getSnapshotTimestamp(), lastStartedSnapshotSync); } } return ack; } }

Target:
private LogReplicationEntry processReceivedMessage(LogReplicationEntry message) { if (rxState.equals(RxState.LOG_ENTRY_SYNC)) { return logEntrySinkBufferManager.processMsgAndBuffer(message); } else { LogReplicationEntry ack = snapshotSinkBufferManager.processMsgAndBuffer(message); if (ack.getMetadata().getMessageMetadataType() == MessageType.SNAPSHOT_REPLICATED) { long lastAppliedBaseSnapshotTimestamp = logReplicationMetadataManager.getLastAppliedBaseSnapshotTimestamp(); long latestSnapshotSyncCycleId = logReplicationMetadataManager.getCurrentSnapshotSyncCycleId(); long ackSnapshotSyncCycleId = ack.getMetadata().getSyncRequestId().getMostSignificantBits() & Long.MAX_VALUE; if ((ackSnapshotSyncCycleId == latestSnapshotSyncCycleId) && (ack.getMetadata().getSnapshotTimestamp() == lastAppliedBaseSnapshotTimestamp)) { snapshotSyncPlugin.onSnapshotSyncEnd(runtime); } else { log.warn("SNAPSHOT_SYNC has completed for {}, but new ongoing SNAPSHOT_SYNC is {}", ack.getMetadata().getSnapshotTimestamp(), lastAppliedBaseSnapshotTimestamp); } } return ack; } }
Source:
default Stream<T> removeLast(Predicate<T> predicate) { if(findFirst(predicate).isDefined()) { return reverse().removeFirst(predicate).reverse(); } else { return this; } }

Target:
default Stream<T> removeLast(Predicate<T> predicate) { final Stream<T> removed = reverse().removeFirst(predicate); return removed.length() == length() ? this : removed.reverse(); }
Source:
private void reconnectPending() { synchronized (mPendingReconnect) { for (WeakReference<TerminalBridge> ref : mPendingReconnect) { TerminalBridge bridge = ref.get(); if (bridge == null) { continue; } int sleepVal = 500; int retryLimit = getRetries(); int retryCount = 0; try { Thread.sleep(sleepVal); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } while ( ( retryLimit == 0 || retryCount <= retryLimit ) && bridge.isDisconnected() ){ bridge.startConnection(); if ( retryCount < 8 ) { sleepVal = sleepVal * 2; } try { Thread.sleep(sleepVal); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } retryCount++; Log.d(TAG, String.format("Retries %s session stat: %s", retryCount, bridge.isSessionOpen() )); while(bridge.isConnecting()){ try { Thread.sleep(500); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } Log.d(TAG, String.format("Sleeping while wait on connecting")); } } } mPendingReconnect.clear(); } }

Target:
private void reconnectPending() { synchronized (mPendingReconnect) { for (WeakReference<TerminalBridge> ref : mPendingReconnect) { TerminalBridge bridge = ref.get(); if (bridge == null) { continue; } int sleepVal = MINIMUM_RETRY_INTERVAL; int retryLimit = getRetries(); int retryCount = 0; try { Thread.sleep(sleepVal); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } while ((retryLimit == 0 || retryCount <= retryLimit) && bridge.isDisconnected()){ bridge.startConnection(); if (retryCount < MAXIMUM_RETRY_MULTIPLIER) { sleepVal = sleepVal * RETRY_SLEEP_MULTIPLIER; } try { Thread.sleep(sleepVal); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } retryCount++; Log.d(TAG, String.format("Retries %s session stat: %s", retryCount, bridge.isSessionOpen() )); int connectingCount = 0; while(bridge.isConnecting() && connectingCount<=MAXIMUM_CONNECTING_WAIT){ try { Thread.sleep(MINIMUM_RETRY_INTERVAL); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } connectingCount++; Log.d(TAG, String.format("Sleeping while wait on connecting")); } } } mPendingReconnect.clear(); } }
Source:
public void initTable() { AbstractTextColumn<GuestContainer> idColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if(row != null) { return row.getId(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> namesColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null && row.getNames() != null) { return StringUtils.join(row.getNames(), ", "); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> imageColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getImage(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> commandColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getCommand(); } return constants.empty(); } }; AbstractTextColumn<GuestContainer> statusColumn = new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getStatus(); } return constants.empty(); } }; getTable().addColumn(idColumn, constants.idContainer()); getTable().addColumn(namesColumn, constants.namesContainer()); getTable().addColumn(imageColumn, constants.imageContainer()); getTable().addColumn(commandColumn, constants.commandContainer()); getTable().addColumn(statusColumn, constants.statusContainer()); }

Target:
public void initTable() { getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { if (row != null) { return row.getId(); } return constants.empty(); } }, constants.idContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return StringUtils.join(row.getNames(), ", "); } }, constants.namesContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getImage(); } }, constants.imageContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getCommand(); } }, constants.commandContainer()); getTable().addColumn(new AbstractTextColumn<GuestContainer>() { @Override public String getValue(GuestContainer row) { return row.getStatus(); } }, constants.statusContainer()); }
Source:
byte[] receive(int code) throws IOException { try { int len = din.readInt(); int get_code = din.read(); byte[] data = null; if (len > 1) { data = new byte[len - 1]; din.readFully(data); } if (get_code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); throw new RiakError(err); } if (code != get_code) { throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); } return data; } catch (IOException e) { close(); throw e; } }

Target:
byte[] receive(int code) throws IOException { int len; int get_code; byte[] data = null; try { len = din.readInt(); get_code = din.read(); if (len > 1) { data = new byte[len - 1]; din.readFully(data); } } catch (IOException e) { close(); throw e; } if (get_code == RiakClient.MSG_ErrorResp) { RpbErrorResp err = com.basho.riak.pbc.RPB.RpbErrorResp.parseFrom(data); throw new RiakError(err); } if (code != get_code) { throw new IOException("bad message code. Expected: " + code + " actual: " + get_code); } return data; }
Source:
public void testShouldDumpMetaDataForNonNativeTableIfSetMeataDataOnly() throws Throwable { String createTableQuery = "CREATE TABLE custom_serdes( serde_id bigint COMMENT 'from deserializer', name string " + "COMMENT 'from deserializer', slib string COMMENT 'from deserializer') " + "ROW FORMAT SERDE 'org.apache.hive.storage.jdbc.JdbcSerDe' " + "STORED BY 'org.apache.hive.storage.jdbc.JdbcStorageHandler' " + "WITH SERDEPROPERTIES ('serialization.format'='1') " + "TBLPROPERTIES ( " + "'hive.sql.database.type'='METASTORE', " + "'hive.sql.query'='SELECT \"SERDE_ID\", \"NAME\", \"SLIB\" FROM \"SERDES\"')"; WarehouseInstance.Tuple bootstrapTuple = primary .run("use " + primaryDbName) .run(createTableQuery) .dump(primaryDbName, null, Collections.singletonList("'hive.repl.dump.metadata.only'='true'")); Path cSerdesTableDumpLocation = new Path( new Path(bootstrapTuple.dumpLocation, primaryDbName), "custom_serdes"); FileSystem fs = cSerdesTableDumpLocation.getFileSystem(primary.hiveConf); assertTrue(fs.exists(cSerdesTableDumpLocation)); FileStatus[] fileInfoList = fs.listStatus(cSerdesTableDumpLocation); assertFalse(fileInfoList.length == 0); }

Target:
public void testShouldDumpMetaDataForNonNativeTableIfSetMeataDataOnly() throws Throwable { String tableName = testName.getMethodName() + "_table"; String createTableQuery = "CREATE TABLE " + tableName + " ( serde_id bigint COMMENT 'from deserializer', name string " + "COMMENT 'from deserializer', slib string COMMENT 'from deserializer') " + "ROW FORMAT SERDE 'org.apache.hive.storage.jdbc.JdbcSerDe' " + "STORED BY 'org.apache.hive.storage.jdbc.JdbcStorageHandler' " + "WITH SERDEPROPERTIES ('serialization.format'='1') " + "TBLPROPERTIES ( " + "'hive.sql.database.type'='METASTORE', " + "'hive.sql.query'='SELECT \"SERDE_ID\", \"NAME\", \"SLIB\" FROM \"SERDES\"')"; WarehouseInstance.Tuple bootstrapTuple = primary .run("use " + primaryDbName) .run(createTableQuery) .dump(primaryDbName, null, Collections.singletonList("'hive.repl.dump.metadata.only'='true'")); replica.load(replicatedDbName, bootstrapTuple.dumpLocation) .status(replicatedDbName) .verifyResult(bootstrapTuple.lastReplicationId) .run("use " + replicatedDbName) .run("show tables") .verifyResult(tableName); }
Source:
public String toString() { return serverName; }

Target:
public String toString() { return format( "Server[%s]", serverName ); }
Source:
private void updateLabelList() { AsyncQuery getLabelsQuery = new AsyncQuery(); getLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { List<Label> allLabels = (List<Label>) result; if (getIsNew()) { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } else { List<Label> selectedLabels = new ArrayList<>(); for (Label label : allLabels) { if (label.getHosts().contains(getHostId())) { selectedLabels.add(label); } } labelList.setItems(allLabels); labelList.setSelectedItems(selectedLabels); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getLabelsQuery); }

Target:
private void updateLabelList() { final AsyncQuery getAllLabelsQuery = new AsyncQuery(); getAllLabelsQuery.asyncCallback = new INewAsyncCallback() { @SuppressWarnings("unchecked") @Override public void onSuccess(Object model, Object result) { final List<Label> allLabels = (List<Label>) result; if (getIsNew()) { labelList.setItems(allLabels); labelList.setSelectedItems(new ArrayList<Label>()); } else { AsyncQuery getLabelsByHostIdQuery = new AsyncQuery(); getLabelsByHostIdQuery.asyncCallback = new INewAsyncCallback() { @Override public void onSuccess(Object model, Object returnValue) { List<Label> hostLabelsList = (List<Label>) returnValue; labelList.setItems(allLabels); labelList.setSelectedItems(hostLabelsList); } }; AsyncDataProvider.getInstance().getLabelListByEntityId(getLabelsByHostIdQuery, getHostId()); } labelList.setIsChangeable(false); } }; AsyncDataProvider.getInstance().getLabelList(getAllLabelsQuery); }
Source:
public boolean isTerminationRequired(WorkloadExecutionStatus status) { if (stopTime != -1) { if (System.currentTimeMillis() >= stopTime) { log.info("Request to terminate work. Max duration reached"); return true; } } if (stopSampleCount != -1) { if (status.getTotalSamples() >= stopSampleCount) { log.info("Request to terminate work. Number of samples reached"); return true; } } boolean everyNodeHasEmptyTransactions = true; for (NodeId nodeId : status.getNodes()) { if (status.getEmptyTransactions(nodeId) == 0) { everyNodeHasEmptyTransactions = false; break; } } if (everyNodeHasEmptyTransactions) { log.info("Request to terminate work. Every node has empty transactions which means there are nothing to do any more"); return true; } return shutdown.get(); }

Target:
public boolean isTerminationRequired(WorkloadExecutionStatus status) { if (stopTime != -1) { if (System.currentTimeMillis() >= stopTime) { log.info("Request to terminate work. Max duration reached"); return true; } } if (stopSampleCount != -1) { if (status.getTotalSamples() >= stopSampleCount) { log.info("Request to terminate work. Number of samples reached"); return true; } } boolean everyNodeHasEmptyTransactions = true; for (NodeId nodeId : status.getNodes()) { if (status.getEmptyTransactions(nodeId) == 0) { everyNodeHasEmptyTransactions = false; break; } } if (everyNodeHasEmptyTransactions) { log.info("Request to terminate work. All planned invocations are finished"); return true; } return shutdown.get(); }
Source:
public Type getOutputType(final Schema schema, final Schema stateSchema) { final Type castFrom = getLeft().getOutputType(schema, stateSchema); final Type castTo = getRight().getOutputType(schema, stateSchema); if (isSimpleCast(castFrom, castTo)) { return castTo; } else { Preconditions.checkState(false, "Cannot cast from " + castFrom + " to " + castTo); return null; } }

Target:
public Type getOutputType(final Schema schema, final Schema stateSchema) { final Type castFrom = getLeft().getOutputType(schema, stateSchema); final Type castTo = getRight().getOutputType(schema, stateSchema); if (isSimpleCast(castFrom, castTo)) { return castTo; } else { throw new IllegalStateException(String.format("Cannot cast from %s to %s", castFrom, castTo)); } }
Source:
private void advanceLocation() { if (this.showParticles) { playAirbendingParticles(this.location, this.particles, 0.275F, 0.275F, 0.275F); } if (this.random.nextInt(4) == 0) { playAirbendingSound(this.location); } if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { this.remove(); return; } else if (this.location.distance(this.origin) > this.range) { this.remove(); return; } this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); }

Target:
private void advanceLocation() { if (this.showParticles) { playAirbendingParticles(this.location, this.particles, 0.275F, 0.275F, 0.275F); } if (this.random.nextInt(4) == 0) { playAirbendingSound(this.location); } if (GeneralMethods.checkDiagonalWall(this.location, this.direction)) { this.remove(); return; } this.location = this.location.add(this.direction.clone().multiply(this.speedFactor)); }
Source:
private void acquireWithinEventExecutor(final Promise<Channel> acquirePromise) { assert this.executor.inEventLoop(); if (!this.isClosed) { if (this.allChannels.size() + this.pendingCreateChannelFutures.size() < this.capacity) { final Future<Channel> createChannelFuture = this.channelFactory.create(executor.newPromise()); this.pendingCreateChannelFutures.add(createChannelFuture); createChannelFuture.addListener((GenericFutureListener<Future<Channel>>) future -> { ApnsChannelPool.this.pendingCreateChannelFutures.remove(createChannelFuture); if (future.isSuccess()) { final Channel channel = future.getNow(); ApnsChannelPool.this.allChannels.add(channel); ApnsChannelPool.this.metricsListener.handleConnectionAdded(); log.debug("Created channel {}", channel); acquirePromise.trySuccess(channel); } else { ApnsChannelPool.this.metricsListener.handleConnectionCreationFailed(); log.debug("Failed to create channel", future.cause()); acquirePromise.tryFailure(future.cause()); ApnsChannelPool.this.handleNextAcquisition(); } }); } else { final Channel channelFromIdlePool = ApnsChannelPool.this.idleChannels.poll(); if (channelFromIdlePool != null) { if (channelFromIdlePool.isActive()) { acquirePromise.trySuccess(channelFromIdlePool); } else { this.discardChannel(channelFromIdlePool); this.acquireWithinEventExecutor(acquirePromise); } } else { pendingAcquisitionPromises.add(acquirePromise); } } } else { acquirePromise.tryFailure(POOL_CLOSED_EXCEPTION); } }

Target:
private void acquireWithinEventExecutor(final Promise<Channel> acquirePromise) { assert this.executor.inEventLoop(); if (!this.isClosed) { if (this.allChannels.size() + this.pendingCreateChannelFutures.size() < this.capacity) { final Future<Channel> createChannelFuture = this.channelFactory.create(executor.newPromise()); this.pendingCreateChannelFutures.add(createChannelFuture); createChannelFuture.addListener((GenericFutureListener<Future<Channel>>) future -> { ApnsChannelPool.this.pendingCreateChannelFutures.remove(createChannelFuture); if (future.isSuccess()) { final Channel channel = future.getNow(); ApnsChannelPool.this.allChannels.add(channel); ApnsChannelPool.this.metricsListener.handleConnectionAdded(); log.debug("Created channel {}", channel); acquirePromise.trySuccess(channel); } else { ApnsChannelPool.this.metricsListener.handleConnectionCreationFailed(); log.warn("Failed to create channel", future.cause()); acquirePromise.tryFailure(future.cause()); ApnsChannelPool.this.handleNextAcquisition(); } }); } else { final Channel channelFromIdlePool = ApnsChannelPool.this.idleChannels.poll(); if (channelFromIdlePool != null) { if (channelFromIdlePool.isActive()) { acquirePromise.trySuccess(channelFromIdlePool); } else { this.discardChannel(channelFromIdlePool); this.acquireWithinEventExecutor(acquirePromise); } } else { pendingAcquisitionPromises.add(acquirePromise); } } } else { acquirePromise.tryFailure(POOL_CLOSED_EXCEPTION); } }
Source:
public boolean scmMaterialsHaveDestination() { for (MaterialConfig scmMaterial : getSCMAndPluggableSCMConfigs()) { String destination = (scmMaterial instanceof ScmMaterialConfig) ? ((ScmMaterialConfig) scmMaterial).getFolder() : ((PluggableSCMMaterialConfig) scmMaterial).getFolder(); if (StringUtil.isBlank(destination)) { return false; } } return true; }

Target:
public boolean scmMaterialsHaveDestination() { for (MaterialConfig scmMaterial : getSCMAndPluggableSCMConfigs()) { String destination = scmMaterial.getFolder(); if (StringUtil.isBlank(destination)) { return false; } } return true; }
Source:
private void buildTestableDeployments(DeploymentScenario scenario, TestClass testCase, ProtocolRegistry protoReg) { for (Deployment deployment : scenario.deployments()) { DeploymentDescription description = deployment.getDescription(); if (!description.testable() || !description.isArchiveDeployment()) { continue; } List<Archive<?>> auxiliaryArchives = loadAuxiliaryArchives(description); ProtocolDefinition protocolDefinition = protoReg.getProtocol(description.getProtocol()); if (protocolDefinition == null) { protocolDefinition = protoReg.getProtocol( containerRegistry.get() .getContainer(description.getTarget()) .getDeployableContainer() .getDefaultProtocol()); } Protocol<?> protocol = protocolDefinition.getProtocol(); DeploymentPackager packager = protocol.getPackager(); Archive<?> applicationArchive = description.getArchive(); applyApplicationProcessors(description.getArchive(), testCase); applyAuxiliaryProcessors(auxiliaryArchives); try { if (ClassContainer.class.isInstance(applicationArchive)) { ClassContainer<?> classContainer = ClassContainer.class.cast(applicationArchive); classContainer.addClass(testCase.getJavaClass()); addAdditionalObserverClass(classContainer, testCase.getJavaClass()); } } catch (UnsupportedOperationException e) { } description.setTestableArchive( packager.generateDeployment( new TestDeployment(deployment.getDescription(), applicationArchive, auxiliaryArchives), serviceLoader.get().all(ProtocolArchiveProcessor.class))); } }

Target:
private void buildTestableDeployments(DeploymentScenario scenario, TestClass testCase, ProtocolRegistry protoReg) { for (Deployment deployment : scenario.deployments()) { DeploymentDescription description = deployment.getDescription(); if (!description.testable() || !description.isArchiveDeployment()) { continue; } List<Archive<?>> auxiliaryArchives = loadAuxiliaryArchives(description); ProtocolDefinition protocolDefinition = protoReg.getProtocol(description.getProtocol()); if (protocolDefinition == null) { protocolDefinition = protoReg.getProtocol( containerRegistry.get() .getContainer(description.getTarget()) .getDeployableContainer() .getDefaultProtocol()); } Protocol<?> protocol = protocolDefinition.getProtocol(); DeploymentPackager packager = protocol.getPackager(); Archive<?> applicationArchive = description.getArchive(); applyApplicationProcessors(description.getArchive(), testCase); applyAuxiliaryProcessors(auxiliaryArchives); try { if (ClassContainer.class.isInstance(applicationArchive)) { ClassContainer<?> classContainer = ClassContainer.class.cast(applicationArchive); classContainer.addClass(testCase.getJavaClass()); addAdditionalObserverClassesIfPresent(classContainer, testCase.getJavaClass()); } } catch (UnsupportedOperationException e) { } description.setTestableArchive( packager.generateDeployment( new TestDeployment(deployment.getDescription(), applicationArchive, auxiliaryArchives), serviceLoader.get().all(ProtocolArchiveProcessor.class))); } }
Source:
public static void init(Class<?> caller) { if ( !init ) { objectNotFoundExceptions = new ArrayList<Class>( 2 ); try { objectNotFoundExceptions.add( ClassLoaderHelper.classForName( "org.hibernate.ObjectNotFoundException", caller ) ); } catch ( ClassNotFoundException e ) { } try { objectNotFoundExceptions.add( ClassLoaderHelper.classForName( "javax.persistence.EntityNotFoundException", caller ) ); } catch ( ClassNotFoundException e ) { } init = true; } }

Target:
public static void init(Class<?> caller) { if ( !init ) { objectNotFoundExceptions = new ArrayList<Class>( 2 ); try { objectNotFoundExceptions.add( ClassLoaderHelper.classForName( "org.hibernate.ObjectNotFoundException", caller.getClassLoader() ) ); } catch ( ClassNotFoundException e ) { } try { objectNotFoundExceptions.add( ClassLoaderHelper.classForName( "javax.persistence.EntityNotFoundException", caller.getClassLoader() ) ); } catch ( ClassNotFoundException e ) { } init = true; } }
Source:
public void onMessage(String message) { logger.debug("Message received from server: {}", message); final JsonObject json = parser.parse(message).getAsJsonObject(); if (json.has("id")) { logger.debug("Response received from server: {}", json); int messageId = json.get("id").getAsInt(); if (messageId == nextMessageId - 1) { commandResponse = json; commandLatch.countDown(); } } else { logger.debug("Event received from server: {}", json); try { if (eventHandler != null) { scheduler.submit(new Runnable() { @Override public void run() { try { eventHandler.handleEvent(json); } catch (Exception e) { logger.error("Error handling event player state change message: {}", json, e.getMessage(), e); } } }); } } catch (Exception e) { logger.error("Error handling player state change message", e); } } }

Target:
public void onMessage(String message) { logger.debug("Message received from server: {}", message); try { final JsonObject json = parser.parse(message).getAsJsonObject(); if (json.has("id")) { logger.debug("Response received from server: {}", json); int messageId = json.get("id").getAsInt(); if (messageId == nextMessageId - 1) { commandResponse = json; commandLatch.countDown(); } } else { logger.debug("Event received from server: {}", json); try { if (eventHandler != null) { scheduler.submit(() -> { try { eventHandler.handleEvent(json); } catch (Exception e) { logger.error("Error handling event player state change message: {}", json, e.getMessage(), e); } }); } } catch (Exception e) { logger.error("Error handling player state change message", e); } } } catch (JsonParseException e) { logger.debug("Not valid JSON message: {}", e.getMessage(), e); } }
Source:
public void setVisible(boolean visible) { parent.setVisible(visible); isVisible = visible; if (visible && handler != null && !isVisited()) { tv.setInput(CfgHolder.unique(getDefaultCfgs(handler))); tv.setAllChecked(true); StringBuilder s = new StringBuilder(EMPTY_STR); visitedTCs = handler.getSelectedToolChains(); for (int i=0; i < visitedTCs.length; i++) { s.append(((visitedTCs[i] == null) ? "" : visitedTCs[i].getUniqueRealName())); if (i < visitedTCs.length - 1) s.append("\n"); } l_chains.setText(s.toString()); l_projtype.setText(handler.getName()); setPageComplete(isCustomPageComplete()); l_chains.getParent().pack(); } if (visible) { parent.getParent().layout(true, true); update(); } }

Target:
public void setVisible(boolean visible) { parent.setVisible(visible); isVisible = visible; if (visible && handler != null && !isVisited()) { tv.setInput(CfgHolder.unique(getDefaultCfgs(handler))); tv.setAllChecked(true); StringBuilder s = new StringBuilder(); visitedTCs = handler.getSelectedToolChains(); for (int i=0; i < visitedTCs.length; i++) { s.append(((visitedTCs[i] == null) ? "" : visitedTCs[i].getUniqueRealName())); if (i < visitedTCs.length - 1) s.append('\n'); } l_chains.setText(s.toString()); l_projtype.setText(handler.getName()); setPageComplete(isCustomPageComplete()); l_chains.getParent().pack(); } if (visible) { parent.getParent().layout(true, true); update(); } }
Source:
public void testGetTaskFormWithoutPermissioneViaUIClientTest() throws Exception { changeUser(USER_YODA); long processInstanceId = processClient.startProcess(CONTAINER_ID, HIRING_PROCESS_ID); assertTrue(processInstanceId > 0); try { List<TaskSummary> tasks = taskClient.findTasksByStatusByProcessInstanceId(processInstanceId, null, 0, 10); assertNotNull(tasks); assertEquals(1, tasks.size()); Long taskId = tasks.get(0).getId(); changeUser(USER_JOHN); uiServicesClient.getTaskForm(CONTAINER_ID, taskId, "en"); fail(); } finally { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } }

Target:
public void testGetTaskFormWithoutPermissioneViaUIClientTest() throws Exception { long processInstanceId = processClient.startProcess(CONTAINER_ID, HIRING_PROCESS_ID); assertTrue(processInstanceId > 0); List<TaskSummary> tasks = taskClient.findTasksByStatusByProcessInstanceId(processInstanceId, null, 0, 10); assertNotNull(tasks); assertEquals(1, tasks.size()); Long taskId = tasks.get(0).getId(); try { assertClientException( () -> uiServicesClient.getTaskForm(CONTAINER_ID, taskId, "en"), 401, MessageFormat.format(TASK_PERMISSION_REST_ERROR, taskId), MessageFormat.format(TASK_PERMISSION_JMS_ERROR, USER_YODA, taskId)); } finally { processClient.abortProcessInstance(CONTAINER_ID, processInstanceId); } }
Source:
private Thread getStuckThread(Thread mainThread) { List<Thread> threadsInGroup = getThreadsInGroup(mainThread.getThreadGroup()); if (threadsInGroup.isEmpty()) { return null; } Thread stuckThread = null; long maxCpuTime = 0; for (Thread thread : threadsInGroup) { try { thread.join(); long threadCpuTime = cpuTime(thread); if (stuckThread == null || threadCpuTime > maxCpuTime) { stuckThread = thread; maxCpuTime = threadCpuTime; } } catch (InterruptedException e) { e.printStackTrace(); } } return (stuckThread == mainThread) ? null : stuckThread; }

Target:
private Thread getStuckThread(Thread mainThread) { List<Thread> threadsInGroup = getThreadsInGroup(mainThread.getThreadGroup()); if (threadsInGroup.isEmpty()) { return null; } Thread stuckThread = null; long maxCpuTime = 0; for (Thread thread : threadsInGroup) { if (thread.getState() == Thread.State.RUNNABLE) { long threadCpuTime = cpuTime(thread); if (stuckThread == null || threadCpuTime > maxCpuTime) { stuckThread = thread; maxCpuTime = threadCpuTime; } } } return (stuckThread == mainThread) ? null : stuckThread; }
Source:
public boolean getIsNamespaceEnabled() throws AzureBlobFileSystemException { if (!isNamespaceEnabledSet) { if (isNameSpaceEnabledSetFromConfig()) { return this.isNamespaceEnabled; } LOG.debug("Get root ACL status"); try (AbfsPerfInfo perfInfo = startTracking("getIsNamespaceEnabled", "getAclStatus")) { AbfsRestOperation op = client.getAclStatus(AbfsHttpConstants.FORWARD_SLASH + AbfsHttpConstants.ROOT_PATH); perfInfo.registerResult(op.getResult()); isNamespaceEnabled = true; perfInfo.registerSuccess(true); } catch (AbfsRestOperationException ex) { if (HttpURLConnection.HTTP_BAD_REQUEST != ex.getStatusCode()) { throw ex; } isNamespaceEnabled = false; } isNamespaceEnabledSet = true; } return isNamespaceEnabled; }

Target:
public boolean getIsNamespaceEnabled() throws AzureBlobFileSystemException { try { return this.isNamespaceEnabled.toBoolean(); } catch (TrileanConversionException e) { LOG.debug("isNamespaceEnabled is UNKNOWN; fall back and determine through" + " getAcl server call", e); } LOG.debug("Get root ACL status"); try (AbfsPerfInfo perfInfo = startTracking("getIsNamespaceEnabled", "getAclStatus")) { AbfsRestOperation op = client.getAclStatus( AbfsHttpConstants.FORWARD_SLASH + AbfsHttpConstants.ROOT_PATH); perfInfo.registerResult(op.getResult()); isNamespaceEnabled = Trilean.getTrilean(true); perfInfo.registerSuccess(true); } catch (AbfsRestOperationException ex) { if (HttpURLConnection.HTTP_BAD_REQUEST != ex.getStatusCode()) { throw ex; } isNamespaceEnabled = Trilean.getTrilean(false); } return isNamespaceEnabled.toBoolean(); }
Source:
public static Map<String, Set<String>> getParentChildMap(String hierarchyPath) { Map<String, Set<String>> parentChildMap = new HashMap<>(); try { BufferedReader reader = new BufferedReader(new FileReader(hierarchyPath)); reader.readLine(); String line; String[] nodes; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; String[] tokens = line.split("\t", 2); String parentID = tokens[0].trim(); String childIDs = tokens[1].trim(); Set<String> childIDSet = new HashSet<>(); nodes = childIDs.split("\t"); for (String node : nodes) { childIDSet.add(node); } parentChildMap.put(parentID, childIDSet); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return parentChildMap; }

Target:
static Map<String, Set<String>> getParentChildMap(String hierarchyPath) { Map<String, Set<String>> parentChildMap = new HashMap<>(); try(BufferedReader reader = new BufferedReader(new FileReader(hierarchyPath))) { reader.readLine(); String line; String[] nodes; while ((line = reader.readLine()) != null) { if (line.isEmpty()) continue; String[] tokens = line.split("\t", 2); String parentID = tokens[0].trim(); String childIDs = tokens[1].trim(); Set<String> childIDSet = new HashSet<>(); nodes = childIDs.split("\t"); childIDSet.addAll(Arrays.asList(nodes)); parentChildMap.put(parentID, childIDSet); } } catch (IOException e) { e.printStackTrace(); logger.error("IO Error while reading the file at " + hierarchyPath); throw new RuntimeException("IO Error while reading the file at " + hierarchyPath); } return parentChildMap; }
Source:
public void lockAcquiredByConjureLockServiceIsAlsoAcquiredInLegacy() throws InterruptedException { com.palantir.lock.LockRequest lockRequest = com.palantir.lock.LockRequest.builder( ImmutableSortedMap.<LockDescriptor, LockMode>naturalOrder() .put(StringLockDescriptor.of("lock"), LockMode.WRITE) .build()) .doNotBlock() .build(); String anonymousId = LockClient.ANONYMOUS.getClientId(); ConjureLockV1Request conjureLockRequest = ConjureLockV1Request.builder() .lockClient(anonymousId) .lockRequest(lockRequest) .build(); HeldLocksToken token = client.conjureLegacyLockService().lockAndGetHeldLocks( AuthHeader.valueOf("Bearer unused"), client.namespace(), conjureLockRequest) .orElseThrow(() -> new RuntimeException("We should have been able to get the lock")); assertThat(client.legacyLockService().lockAndGetHeldLocks(anonymousId, lockRequest)) .as("if the conjure impl has taken a lock, the legacy impl mustn't be able to take it") .isNull(); assertThat(client.legacyLockService().unlock(token.getLockRefreshToken())).isTrue(); assertThat(client.legacyLockService().lockAndGetHeldLocks(anonymousId, lockRequest)) .as("a lock once unlocked by conjure impl can be acquired by legacy impl") .isNotNull(); assertThat(client.conjureLegacyLockService().lockAndGetHeldLocks( AuthHeader.valueOf("Bearer unused"), client.namespace(), conjureLockRequest)) .as("if the legacy impl has taken a lock, the conjure impl mustn't be able to take it") .isEmpty(); }

Target:
public void lockAcquiredByConjureLockServiceIsAlsoAcquiredInLegacy() throws InterruptedException { com.palantir.lock.LockRequest lockRequest = com.palantir.lock.LockRequest.builder( ImmutableSortedMap.<LockDescriptor, LockMode>naturalOrder() .put(StringLockDescriptor.of("lock"), LockMode.WRITE) .build()) .doNotBlock() .build(); String anonymousId = LockClient.ANONYMOUS.getClientId(); ConjureLockV1Request conjureLockRequest = ConjureLockV1Request.builder() .lockClient(anonymousId) .lockRequest(lockRequest) .build(); HeldLocksToken token = client.conjureLegacyLockService().lockAndGetHeldLocks( AuthHeader.valueOf("Bearer unused"), client.namespace(), conjureLockRequest) .orElseThrow(() -> new RuntimeException("We should have been able to get the lock")); assertThat(client.legacyLockService().lockAndGetHeldLocks(anonymousId, lockRequest)) .as("if the conjure impl has taken a lock, the legacy impl mustn't be able to take it") .isNull(); assertThat(client.legacyLockService().unlock(token.getLockRefreshToken())) .as("legacy impl can unlock a lock taken by conjure impl") .isTrue(); assertThat(client.legacyLockService().lockAndGetHeldLocks(anonymousId, lockRequest)) .as("lock taken by conjure impl that was unlocked can now be acquired by legacy impl") .isNotNull(); assertThat(client.conjureLegacyLockService().lockAndGetHeldLocks( AuthHeader.valueOf("Bearer unused"), client.namespace(), conjureLockRequest)) .as("if the legacy impl has taken a lock, the conjure impl mustn't be able to take it") .isEmpty(); }
Source:
protected boolean isLBSystemService(Service service) { Map<String, Object> data = DataAccessor.fields(service) .withKey("launchConfig").withDefault(Collections.EMPTY_MAP) .as(Map.class); Object imageObj = data.get(InstanceConstants.FIELD_IMAGE_UUID); if (imageObj == null) { return false; } String defaultImageUuid = LB_IMAGE_UUID.get().toLowerCase(); String[] splitted = defaultImageUuid.split(":"); String formattedDefault = String.format("%s:%s", splitted[0], splitted[1]); logger.info("Image is " + imageObj.toString()); logger.info("formatted default is " + formattedDefault); return imageObj.toString().startsWith(formattedDefault); }

Target:
protected boolean isLBSystemService(Service service) { Map<String, Object> data = DataAccessor.fields(service) .withKey("launchConfig").withDefault(Collections.EMPTY_MAP) .as(Map.class); Object imageObj = data.get(InstanceConstants.FIELD_IMAGE_UUID); if (imageObj == null) { return false; } String defaultImageUuid = LB_IMAGE_UUID.get().toLowerCase(); String[] splitted = defaultImageUuid.split(":"); String formattedDefault = String.format("%s:%s", splitted[0], splitted[1]); return imageObj.toString().startsWith(formattedDefault); }