auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void moveMaterialTo(FileKeyMaterialStore keyMaterialStore) throws ParquetCryptoRuntimeException { HadoopFSKeyMaterialStore targetStore = (HadoopFSKeyMaterialStore) keyMaterialStore; Path targetKeyMaterialFile = targetStore.getStorageFilePath(); try { hadoopFileSystem.rename(keyMaterialFile, targetKeyMaterialFile); } catch (IOException e) { throw new ParquetCryptoRuntimeException("Failed to rename file " + keyMaterialFile, e); } }

Target:
public void moveMaterialTo(FileKeyMaterialStore keyMaterialStore) throws ParquetCryptoRuntimeException { HadoopFSKeyMaterialStore targetStore; try { targetStore = (HadoopFSKeyMaterialStore) keyMaterialStore; } catch (ClassCastException e) { throw new IllegalArgumentException("Currently supports only moving to HadoopFSKeyMaterialStore, not to " + keyMaterialStore.getClass(), e); } Path targetKeyMaterialFile = targetStore.getStorageFilePath(); try { hadoopFileSystem.rename(keyMaterialFile, targetKeyMaterialFile); } catch (IOException e) { throw new ParquetCryptoRuntimeException("Failed to rename file " + keyMaterialFile, e); } }
Source:
void doChangeUserName() { if (!canEditSshUserName()) { return; } String newName = userNameTxt.getText(); if ("".equals(newName)) { newName = null; } if (newName != null && !newName.matches(Account.SSH_USER_NAME_PATTERN)) { invalidUserName(); return; } userNameTxt.setEnabled(false); changeUserName.setEnabled(false); final String newSshUserName = newName; Util.ACCOUNT_SEC.changeSshUserName(newSshUserName, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { userNameTxt.setEnabled(true); changeUserName.setEnabled(false); if (Gerrit.isSignedIn()) { Gerrit.getUserAccount().setSshUserName(newSshUserName); } } @Override public void onFailure(final Throwable caught) { userNameTxt.setEnabled(true); changeUserName.setEnabled(true); if (InvalidSshUserNameException.MESSAGE.equals(caught)) { invalidUserName(); } else { super.onFailure(caught); } } }); }

Target:
void doChangeUserName() { if (!canEditSshUserName()) { return; } String newName = userNameTxt.getText(); if ("".equals(newName)) { newName = null; } if (newName != null && !newName.matches(Account.SSH_USER_NAME_PATTERN)) { invalidUserName(); return; } userNameTxt.setEnabled(false); changeUserName.setEnabled(false); final String newSshUserName = newName; Util.ACCOUNT_SEC.changeSshUserName(newSshUserName, new GerritCallback<VoidResult>() { public void onSuccess(final VoidResult result) { userNameTxt.setEnabled(true); changeUserName.setEnabled(false); if (Gerrit.isSignedIn()) { Gerrit.getUserAccount().setSshUserName(newSshUserName); } } @Override public void onFailure(final Throwable caught) { userNameTxt.setEnabled(true); changeUserName.setEnabled(true); if (InvalidSshUserNameException.MESSAGE.equals(caught.getMessage())) { invalidUserName(); } else { super.onFailure(caught); } } }); }
Source:
public void start() throws ServerConnectorException { if (listenerConfiguration.isBindOnStartup()) { return; } serverConnectorController.bindInterface(this); }

Target:
public void start() throws ServerConnectorException { if (listenerConfiguration.isBindOnStartup()) { return; } try { serverConnectorController.bindInterface(this); } catch (Exception e) { throw new ServerConnectorException("Cannot bind to " + this + " : " + e.getMessage(), e); } }
Source:
private StormTopology tryReadTopologyFromName(final String topoName) throws NotAliveException, AuthorizationException, IOException { IStormClusterState state = stormClusterState; String topoId = state.getTopoId(topoName) .orElseThrow(() -> new WrappedNotAliveException(topoName + " is not alive")); return tryReadTopology(topoId, topoCache); }

Target:
private StormTopology tryReadTopologyFromName(final String topoName) throws NotAliveException, AuthorizationException, IOException { return tryReadTopology(toTopoId(topoName), topoCache); }
Source:
protected QueryIterator nextStage(Binding binding) { QueryIterator iter = exec(binding, argSubject, predicate, argObject, super.getExecContext()) ; if ( iter == null ) iter = IterLib.noResults(execCxt) ; return iter ; }

Target:
protected QueryIterator nextStage(Binding binding) { QueryIterator iter = exec(binding, argSubject, predicate, argObject, getExecContext()) ; if ( iter == null ) iter = IterLib.noResults(getExecContext()) ; return iter ; }
Source:
public void shouldBeAbleToInstantiateEncryptionAlgorithms() { for (HashAlgorithm algorithm : HashAlgorithm.values()) { if (!HashAlgorithm.CUSTOM.equals(algorithm) && !HashAlgorithm.PLAINTEXT.equals(algorithm)) { if (HashAlgorithm.ARGON2.equals(algorithm)) { try { System.loadLibrary("argon2"); } catch (UnsatisfiedLinkError e) { System.out.println("[WARNING] Cannot find argon2 library, skipping test suite"); return; } } EncryptionMethod method = injector.createIfHasDependencies(algorithm.getClazz()); if (method == null) { fail("Could not create '" + algorithm.getClazz() + "' - forgot to provide some class?"); } HashedPassword hashedPassword = method.computeHash("pwd", "name"); assertThat("Salt should not be null if method.hasSeparateSalt(), and vice versa. Method: '" + method + "'", StringUtils.isEmpty(hashedPassword.getSalt()), equalTo(!method.hasSeparateSalt())); assertThat("Hash should not be empty for method '" + method + "'", StringUtils.isEmpty(hashedPassword.getHash()), equalTo(false)); } } }

Target:
public void shouldBeAbleToInstantiateEncryptionAlgorithms() { for (HashAlgorithm algorithm : HashAlgorithm.values()) { if (!HashAlgorithm.CUSTOM.equals(algorithm) && !HashAlgorithm.PLAINTEXT.equals(algorithm)) { if (HashAlgorithm.ARGON2.equals(algorithm) && !Argon2.isLibraryLoaded()) { System.out.println("[WARNING] Cannot find argon2 library, skipping integration test"); continue; } EncryptionMethod method = injector.createIfHasDependencies(algorithm.getClazz()); if (method == null) { fail("Could not create '" + algorithm.getClazz() + "' - forgot to provide some class?"); } HashedPassword hashedPassword = method.computeHash("pwd", "name"); assertThat("Salt should not be null if method.hasSeparateSalt(), and vice versa. Method: '" + method + "'", StringUtils.isEmpty(hashedPassword.getSalt()), equalTo(!method.hasSeparateSalt())); assertThat("Hash should not be empty for method '" + method + "'", StringUtils.isEmpty(hashedPassword.getHash()), equalTo(false)); } } }
Source:
public TransferObserver upload(String key, InputStream inputStream) throws IOException { File file = File.createTempFile(UUID.randomUUID().toString(), ".tmp"); if (inputStream != null) { try { OutputStream outStream = new FileOutputStream(file); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outStream.write(buffer, 0, bytesRead); outStream.flush(); } inputStream.close(); outStream.close(); } catch (Exception e) { file = null; } } return upload(key, file); }

Target:
public TransferObserver upload(String key, InputStream inputStream) throws IOException { return upload(key, inputStream, UploadOptions.builder().build()); }
Source:
public StorageServerConnectionParametersBase(StorageServerConnections connection, Guid vdsId, boolean force) { this(connection, vdsId); setForce(force); }

Target:
public StorageServerConnectionParametersBase(StorageServerConnections connection, Guid vdsId, boolean force) { setStorageServerConnection(connection); setVdsId(vdsId); setForce(force); }
Source:
public static void setGlobalStaticConstants(Configuration conf) throws IOException { Kmer.setGlobalKmerLength(Integer.parseInt(conf.get(KMER_LENGTH))); ExternalableTreeSet.setupManager(conf, new Path(conf.get("hadoop.tmp.dir", "/tmp"))); ExternalableTreeSet.setCountLimit(1000); if (conf.get(READ_LENGTHS) != null) { readLengths = new ArrayList<>(); for (String length : conf.get(READ_LENGTHS).split(",")) { readLengths.add(Integer.valueOf(length)); } } Byte libraryId = 0; if (conf.get(OUTER_DISTANCE_MEANS) != null) { outerDistanceMeans = new HashMap<>(); for (String mean : conf.get(OUTER_DISTANCE_MEANS).split(",")) { outerDistanceMeans.put(libraryId++, Integer.valueOf(mean)); } } libraryId = 0; if (conf.get(OUTER_DISTANCE_STD_DEVS) != null) { outerDistanceMeans = new HashMap<>(); for (String stddev : conf.get(OUTER_DISTANCE_STD_DEVS).split(",")) { outerDistanceStdDevs.put(libraryId++, Integer.valueOf(stddev)); } } debug = conf.get(GenomixJobConf.DEBUG_KMERS) != null; if (debugKmers == null) { debugKmers = new ArrayList<VKmer>(); if (conf.get(GenomixJobConf.DEBUG_KMERS) != null) { for (String kmer : conf.get(GenomixJobConf.DEBUG_KMERS).split(",")) { debugKmers.add(new VKmer(kmer)); } } } }

Target:
public static void setGlobalStaticConstants(Configuration conf) throws IOException { Kmer.setGlobalKmerLength(Integer.parseInt(conf.get(KMER_LENGTH))); ExternalableTreeSet.setupManager(conf, new Path("/user/tmp")); ExternalableTreeSet.setCountLimit(1000); if (conf.get(READ_LENGTHS) != null) { readLengths = new ArrayList<>(); for (String length : conf.get(READ_LENGTHS).split(",")) { readLengths.add(Integer.valueOf(length)); } } Byte libraryId = 0; if (conf.get(OUTER_DISTANCE_MEANS) != null) { outerDistanceMeans = new HashMap<>(); for (String mean : conf.get(OUTER_DISTANCE_MEANS).split(",")) { outerDistanceMeans.put(libraryId++, Integer.valueOf(mean)); } } libraryId = 0; if (conf.get(OUTER_DISTANCE_STD_DEVS) != null) { outerDistanceStdDevs = new HashMap<>(); for (String stddev : conf.get(OUTER_DISTANCE_STD_DEVS).split(",")) { outerDistanceStdDevs.put(libraryId++, Integer.valueOf(stddev)); } } debug = conf.get(GenomixJobConf.DEBUG_KMERS) != null; if (debugKmers == null) { debugKmers = new ArrayList<VKmer>(); if (conf.get(GenomixJobConf.DEBUG_KMERS) != null) { for (String kmer : conf.get(GenomixJobConf.DEBUG_KMERS).split(",")) { debugKmers.add(new VKmer(kmer)); } } } }
Source:
BlobOutputStream(final AppendBlobAsyncClient parentBlob, final AppendBlobAccessConditions accessCondition) throws StorageException { this(parentBlob, accessCondition != null ? new BlobAccessConditions().modifiedAccessConditions( accessCondition.modifiedAccessConditions()).leaseAccessConditions(accessCondition.leaseAccessConditions()) : new BlobAccessConditions(), accessCondition != null ? accessCondition.appendPositionAccessConditions() : null, null, null, accessCondition != null ? ( accessCondition.appendPositionAccessConditions().appendPosition() != null ? accessCondition.appendPositionAccessConditions().appendPosition() : parentBlob.getProperties().block().value().blobSize() ) : 0, BlobType.APPEND_BLOB, BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE); }

Target:
BlobOutputStream(final AppendBlobAsyncClient parentBlob, final AppendBlobAccessConditions accessCondition) throws StorageException { this((BlobAsyncClient) parentBlob); this.streamType = BlobType.APPEND_BLOB; this.accessCondition = new BlobAccessConditions(); if (accessCondition != null) { this.appendPositionAccessConditions = accessCondition.appendPositionAccessConditions(); this.accessCondition = new BlobAccessConditions().modifiedAccessConditions(accessCondition.modifiedAccessConditions()).leaseAccessConditions(accessCondition.leaseAccessConditions()); if (accessCondition.appendPositionAccessConditions().appendPosition() != null) { this.initialBlobOffset = accessCondition.appendPositionAccessConditions().appendPosition(); } else { this.initialBlobOffset = parentBlob.getProperties().block().blobSize(); } } this.internalWriteThreshold = (int) BlockBlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE; }
Source:
public List<String> lines() { return Arrays.asList(contents.split("\\r?\\n")); }

Target:
public List<String> lines() { return Arrays.asList(Utils.splitLines(contents)); }
Source:
public AppenderatorDriverAddResult add( InputRow row, String sequenceName ) throws IOException { return append(row, sequenceName, null, true, true); }

Target:
public AppenderatorDriverAddResult add( InputRow row, String sequenceName ) throws IOException { return append(row, sequenceName, null, false, true); }
Source:
protected void interruptQuery() { try { long interruptTimeInMillies = interruptTime * 60 * 1000; long differenceInMillies = interruptTimeInMillies - ((new Date()).getTime() - submittedOn.getTime()); if(differenceInMillies > 0) { log.debug("Sleeping for {}", differenceInMillies); Thread.sleep(differenceInMillies); } if(!task.isDone()) { log.debug("Interrupting the task"); task.cancel(true); updateAsyncQueryStatus(QueryStatus.TIMEDOUT, id); } } catch (InterruptedException e) { log.error("InterruptedException: {}", e.getMessage()); } }

Target:
protected void interruptQuery() { try { long interruptTimeMillies = calculateTimeOut(maxRunTimeMinutes, submittedOn); if (interruptTimeMillies > 0) { log.debug("Waiting on the future with the given timeout for {}", interruptTimeMillies); task.get(interruptTimeMillies, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { log.error("InterruptedException: {}", e); } catch (ExecutionException e) { log.error("ExecutionException: {}", e); } catch (TimeoutException e) { log.error("TimeoutException: {}", e); task.cancel(true); asyncQueryDao.updateStatus(asyncQuery, QueryStatus.TIMEDOUT); } }
Source:
public CdmaSubscriptionListPreference(Context context, AttributeSet attrs) { super(context, attrs); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new CdmaSubscriptionButtonHandler(); int cdmaSubscriptionMode = Secure.getInt(mPhone.getContext().getContentResolver(), android.provider.Settings.Secure.CDMA_SUBSCRIPTION_MODE, preferredSubscriptionMode); setValue(Integer.toString(cdmaSubscriptionMode)); }

Target:
public CdmaSubscriptionListPreference(Context context, AttributeSet attrs) { super(context, attrs); mPhone = PhoneFactory.getDefaultPhone(); mHandler = new CdmaSubscriptionButtonHandler(); setCurrentCdmaSubscriptionModeValue(); }
Source:
private void assertToStringContainsLuceneQueryInformation(String fullTextQueryToString) { String queryString = ContextHelper.getSearchIntegrator( fullTextSession ) .createHSQuery( luceneQuery, Foo.class ) .getQueryString(); assertThat( "Unexpected toString implementation. The string should contain Lucene query information", fullTextQueryToString, CoreMatchers.containsString( queryString ) ); }

Target:
private void assertToStringContainsLuceneQueryInformation(String fullTextQueryToString) { String queryString = ContextHelper.getSearchIntegrator( fullTextSession ) .createHSQuery( luceneQuery, Foo.class ) .getQueryString(); assertThat( "Unexpected toString implementation. The string should contain a string representation of the internal query.", fullTextQueryToString, CoreMatchers.containsString( queryString ) ); }
Source:
protected IndentLevel curlyIndent() { int offset = 0; final DetailAST lcurly = getLeftCurly(); if (isOnStartOfLine(lcurly) && !TokenUtil.isOfType(lcurly.getParent(), TokenTypes.ARRAY_INIT)) { offset = getBraceAdjustment(); } final IndentLevel level = new IndentLevel(getIndent(), offset); return IndentLevel.addAcceptable(level, level.getLastIndentLevel() + getLineWrappingIndentation()); }

Target:
protected IndentLevel curlyIndent() { int offset = 0; final DetailAST lcurly = getLeftCurly(); if (isOnStartOfLine(lcurly) && lcurly.getParent().getType() != TokenTypes.ARRAY_INIT) { offset = getBraceAdjustment(); } final IndentLevel level = new IndentLevel(getIndent(), offset); return IndentLevel.addAcceptable(level, level.getLastIndentLevel() + getLineWrappingIndentation()); }
Source:
public void updateShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.update("foobar", new HashMap<String, Object>(), new RetrofitPromise<Card>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards/%s", MOCK_URL, "foobar")); Assert.assertEquals(bodyRef.get().getMethod(), "PATCH"); }

Target:
public void updateShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserCardService userCardService = adapter.create(UserCardService.class); userCardService.update("foobar", new HashMap<String, Object>(), new RetrofitPromise<Card>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "PATCH"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/cards/%s", MOCK_URL, "foobar")); }
Source:
private static List<Entity> fillTransport(AtBScenario scenario, Entity transport, UnitGeneratorParameters params, int skill, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(scenario.getTransportLinkages().containsKey(transport.getExternalIdAsString())) { return transportedUnits; } for(Transporter bay : transport.getTransports()) { if(bay instanceof TroopSpace) { double bayCapacity = ((TroopSpace) bay).getUnused(); UnitGeneratorParameters newParams = params.clone(); newParams.clearMovementModes(); newParams.setUnitType(UnitType.INFANTRY); newParams.setWeightClass(AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED); if(bayCapacity <= IUnitGenerator.FOOT_PLATOON_INFANTRY_WEIGHT) { newParams.getMovementModes().add(EntityMovementMode.INF_LEG); newParams.setFilter(inf -> inf.getTons() <= IUnitGenerator.FOOT_PLATOON_INFANTRY_WEIGHT); } else { newParams.getMovementModes().addAll(IUnitGenerator.ALL_INFANTRY_MODES); newParams.setFilter(inf -> inf.getTons() <= bayCapacity); } MechSummary ms = campaign.getUnitGenerator().generate(newParams); if (ms == null) { continue; } Entity infantry = createEntityWithCrew(params.getFaction(), skill, campaign, ms); while(infantry.getWeight() > bayCapacity) { ((Infantry) infantry).setSquadN(((Infantry) infantry).getSquadN() - 1); infantry.autoSetInternal(); } infantry.setDeployRound(transport.getDeployRound()); scenario.addTransportRelationship(transport.getExternalIdAsString(), infantry.getExternalIdAsString()); transportedUnits.add(infantry); } } return transportedUnits; }

Target:
private static List<Entity> fillTransport(AtBScenario scenario, Entity transport, UnitGeneratorParameters params, int skill, Campaign campaign) { List<Entity> transportedUnits = new ArrayList<>(); if(scenario.getTransportLinkages().containsKey(transport.getExternalIdAsString())) { return transportedUnits; } for(Transporter bay : transport.getTransports()) { if(bay instanceof TroopSpace) { double bayCapacity = ((TroopSpace) bay).getUnused(); UnitGeneratorParameters newParams = params.clone(); newParams.clearMovementModes(); newParams.setUnitType(UnitType.INFANTRY); newParams.setWeightClass(AtBDynamicScenarioFactory.UNIT_WEIGHT_UNSPECIFIED); if(bayCapacity <= IUnitGenerator.FOOT_PLATOON_INFANTRY_WEIGHT) { newParams.getMovementModes().add(EntityMovementMode.INF_LEG); newParams.setFilter(inf -> inf.getTons() <= IUnitGenerator.FOOT_PLATOON_INFANTRY_WEIGHT); } else { newParams.getMovementModes().addAll(IUnitGenerator.ALL_INFANTRY_MODES); newParams.setFilter(inf -> inf.getTons() <= bayCapacity); } MechSummary ms = campaign.getUnitGenerator().generate(newParams); if (ms == null) { continue; } Entity infantry = createEntityWithCrew(params.getFaction(), skill, campaign, ms); while(infantry.getWeight() > bayCapacity) { ((Infantry) infantry).setSquadN(((Infantry) infantry).getSquadN() - 1); infantry.autoSetInternal(); } if(((Infantry) infantry).getSquadN() == 0) { continue; } infantry.setDeployRound(transport.getDeployRound()); scenario.addTransportRelationship(transport.getExternalIdAsString(), infantry.getExternalIdAsString()); transportedUnits.add(infantry); } } return transportedUnits; }
Source:
protected synchronized void allocateContainer(RMContainer rmContainer, boolean launchedOnNode) { super.allocateContainer(rmContainer, launchedOnNode); Resource allocated = rmContainer.getAllocatedResource(); if (!Resources.isNone(allocated)) { for (FSAppAttempt app: resourcesPreemptedPerApp.keySet()) { if (app.getApplicationAttemptId().equals( rmContainer.getApplicationAttemptId())) { Resource reserved = resourcesPreemptedPerApp.get(app); Resource fulfilled = Resources.componentwiseMin(reserved, allocated); Resources.subtractFrom(reserved, fulfilled); Resources.subtractFrom(totalResourcesPreempted, fulfilled); if (Resources.isNone(reserved)) { resourcesPreemptedPerApp.remove(app); } break; } } } }

Target:
protected synchronized void allocateContainer(RMContainer rmContainer, boolean launchedOnNode) { super.allocateContainer(rmContainer, launchedOnNode); Resource allocated = rmContainer.getAllocatedResource(); if (!Resources.isNone(allocated)) { FSAppAttempt app = appIdToAppMap.get(rmContainer.getApplicationAttemptId()); if (app != null) { Resource reserved = resourcesPreemptedForApp.get(app); Resource fulfilled = Resources.componentwiseMin(reserved, allocated); Resources.subtractFrom(reserved, fulfilled); Resources.subtractFrom(totalResourcesPreempted, fulfilled); if (Resources.isNone(reserved)) { resourcesPreemptedForApp.remove(app); appIdToAppMap.remove(rmContainer.getApplicationAttemptId()); } } } else { LOG.error("Allocated empty container" + rmContainer.getContainerId()); } }
Source:
private boolean migrate(GoPluginDescriptor pluginDescriptor) { String pluginId = pluginDescriptor.id(); boolean isElasticAgentPlugin = pluginManager.isPluginOfType(ELASTIC_AGENT_EXTENSION, pluginId); if (!isElasticAgentPlugin) { return true; } LOG.debug("Migrating elastic agent information for plugin", pluginId); Plugin plugin = pluginSqlMapDao.findPlugin(pluginId); String pluginConfiguration = plugin.getConfiguration(); HashMap<String, String> pluginSettings = (pluginConfiguration == null) ? new HashMap<>() : JsonHelper.fromJson(pluginConfiguration, HashMap.class); ReplaceElasticAgentInformationCommand command = new ReplaceElasticAgentInformationCommand(clusterProfilesService, elasticProfileService, elasticAgentExtension, pluginDescriptor, pluginSettings); boolean updated = update(command, pluginDescriptor); if (updated) { LOG.debug("Done Migrating elastic agent information for plugin", pluginId); if (!pluginManager.resolveExtensionVersion(pluginId, ELASTIC_AGENT_EXTENSION, ElasticAgentExtension.SUPPORTED_VERSIONS).equals(ElasticAgentExtensionV4.VERSION)) { LOG.debug("Deleting stale plugin settings for plugin, after successful plugin config migration", pluginId); pluginSqlMapDao.deletePluginIfExists(pluginId); } else { LOG.debug("Skip deleting plugin settings for plugin, as the plugin implements elastic agent v4 extension which uses plugin settings", pluginId); } } else { LOG.debug("Failed migrating elastic agent information for plugin", pluginId); } return updated; }

Target:
private boolean migrate(GoPluginDescriptor pluginDescriptor) { String pluginId = pluginDescriptor.id(); boolean isElasticAgentPlugin = pluginManager.isPluginOfType(ELASTIC_AGENT_EXTENSION, pluginId); if (!isElasticAgentPlugin) { return true; } LOG.debug("Migrating elastic agent configurations for plugin with id: '{}'", pluginId); Plugin plugin = pluginSqlMapDao.findPlugin(pluginId); String pluginConfiguration = plugin.getConfiguration(); HashMap<String, String> pluginSettings = (pluginConfiguration == null) ? new HashMap<>() : JsonHelper.fromJson(pluginConfiguration, HashMap.class); ReplaceElasticAgentInformationCommand command = new ReplaceElasticAgentInformationCommand(clusterProfilesService, elasticProfileService, elasticAgentExtension, pluginDescriptor, pluginSettings); boolean updated = update(command, pluginDescriptor); if (updated) { LOG.debug("Done migrating elastic agent configurations for plugin with id: '{}'", pluginId); if (!pluginManager.resolveExtensionVersion(pluginId, ELASTIC_AGENT_EXTENSION, ElasticAgentExtension.SUPPORTED_VERSIONS).equals(ElasticAgentExtensionV4.VERSION)) { LOG.debug("Deleting stale plugin settings for plugin with id '{}' after successfully migrating elastic agent configurations", pluginId); pluginSqlMapDao.deletePluginIfExists(pluginId); } else { LOG.debug("Skip deleting plugin settings for plugin with id '{}', as the plugin implements elastic agent v4 extension which uses plugin settings", pluginId); } } return updated; }
Source:
public byte[] getCacheKey() { final CacheKeyBuilder builder = new CacheKeyBuilder( AggregatorUtil.QUANTILES_DOUBLES_SKETCH_TO_QUANTILES_CACHE_TYPE_ID).appendCacheable(field); for (final double value : fractions) { builder.appendDouble(value); } return builder.build(); }

Target:
public byte[] getCacheKey() { final CacheKeyBuilder builder = new CacheKeyBuilder( PostAggregatorIds.MOMENTS_SKETCH_TO_QUANTILES_CACHE_TYPE_ID ) .appendCacheable(field) .appendDoubleArray(fractions); return builder.build(); }
Source:
protected boolean ConcreteCheckExistingStorageDomain(Pair<storage_domain_static, SANState> domainFromIrs) { boolean returnValue = false; if (!StringUtils.isEmpty(getStorageDomain().getStorageStaticData().getstorage()) && !StringUtils.isEmpty(domainFromIrs.getFirst().getstorage())) { returnValue = (StringUtils.equals(domainFromIrs.getFirst().getstorage(), getStorageDomain().getStorageStaticData() .getstorage())); } if (!returnValue) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ADD_EXISTING_STORAGE_DOMAIN_CONNECTION_DATA_ILLEGAL); } else if (domainFromIrs.getSecond() != null && SANState.OK != domainFromIrs.getSecond()) { returnValue = false; getReturnValue().getCanDoActionMessages().add( VdcBllMessages.ERROR_CANNOT_ADD_EXISTING_STORAGE_DOMAIN_LUNS_PROBLEM.toString()); } return returnValue; }

Target:
protected boolean ConcreteCheckExistingStorageDomain(Pair<storage_domain_static, SANState> domainFromIrs) { boolean returnValue = false; if (StringUtils.isNotEmpty(getStorageDomain().getStorageStaticData().getstorage()) && StringUtils.isNotEmpty(domainFromIrs.getFirst().getstorage())) { returnValue = (StringUtils.equals(domainFromIrs.getFirst().getstorage(), getStorageDomain().getStorageStaticData() .getstorage())); } if (!returnValue) { addCanDoActionMessage(VdcBllMessages.ERROR_CANNOT_ADD_EXISTING_STORAGE_DOMAIN_CONNECTION_DATA_ILLEGAL); } else if (domainFromIrs.getSecond() != null && SANState.OK != domainFromIrs.getSecond()) { returnValue = false; getReturnValue().getCanDoActionMessages().add( VdcBllMessages.ERROR_CANNOT_ADD_EXISTING_STORAGE_DOMAIN_LUNS_PROBLEM.toString()); } return returnValue; }
Source:
public final Message<?> transform(Message<?> message) { Object result = this.messageProcessor.processMessage(message); if (result == null) { return null; } if (result instanceof Message<?>) { return (Message<?>) result; } MessageHeaders requestHeaders = message.getHeaders(); AbstractIntegrationMessageBuilder<?> messageBuilder = getMessageBuilderFactory() .withPayload(result); if (this.selectiveHeaderPropagation) { Map<String, Object> headersToCopy = new HashMap<>(requestHeaders); headersToCopy.entrySet() .removeIf(entry -> PatternMatchUtils.simpleMatch(this.notPropagatedHeaders, entry.getKey())); messageBuilder.copyHeadersIfAbsent(headersToCopy); } else { messageBuilder.copyHeadersIfAbsent(requestHeaders); } return messageBuilder.build(); }

Target:
public final Message<?> transform(Message<?> message) { Object result = this.messageProcessor.processMessage(message); if (result == null) { return null; } if (result instanceof Message<?>) { return (Message<?>) result; } MessageHeaders requestHeaders = message.getHeaders(); return getMessageBuilderFactory() .withPayload(result) .filterAndCopyHeadersIfAbsent(requestHeaders, this.selectiveHeaderPropagation ? this.notPropagatedHeaders : null) .build(); }
Source:
public boolean isAbstract() { return (declaringMapper != null && declaringMapper.getTypeElement().getKind().isInterface()) || executable.getModifiers().contains( Modifier.ABSTRACT ); }

Target:
public boolean isAbstract() { return executable.getModifiers().contains( Modifier.ABSTRACT ); }
Source:
public void start(BundleContext context) throws Exception { super.start(context); plugin = this; reviewManager = new ActiveReviewManager(); UIJob job = new UIJob(INITIALIZE_TASK_REVIEW_MAPPING_STORE_JOB) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { taskReviewsMappingStore = new TaskReviewsMappingsStore(TasksUiPlugin.getTaskDataManager(), TasksUiPlugin.getRepositoryManager()); TasksUiPlugin.getTaskList().addChangeListener(taskReviewsMappingStore); return ASYNC_FINISH; } }; job.schedule(0); }

Target:
public void start(BundleContext context) throws Exception { super.start(context); plugin = this; reviewManager = new ActiveReviewManager(); UIJob job = new UIJob(INITIALIZE_TASK_REVIEW_MAPPING_STORE_JOB) { @Override public IStatus runInUIThread(IProgressMonitor monitor) { taskReviewsMappingStore = new TaskReviewsMappingsStore(TasksUiPlugin.getTaskDataManager(), TasksUiPlugin.getRepositoryManager()); TasksUiPlugin.getTaskList().addChangeListener(taskReviewsMappingStore); return Status.OK_STATUS; } }; job.schedule(); }
Source:
private Query compileViewQuery(Session session, String sql, boolean literalsChecked, String viewName) { Prepared p; session.setParsingCreateView(true,viewName); try { p = session.prepare(sql, false, literalsChecked); } finally { session.setParsingCreateView(false,viewName); } if (!(p instanceof Query)) { throw DbException.getSyntaxError(sql, 0); } Query q = (Query) p; if(isTableExpression){ q.setNeverLazy(true); } return q; }

Target:
private Query compileViewQuery(Session session, String sql, boolean literalsChecked, String viewName) { Prepared p; session.setParsingCreateView(true, viewName); try { p = session.prepare(sql, false, literalsChecked); } finally { session.setParsingCreateView(false, viewName); } if (!(p instanceof Query)) { throw DbException.getSyntaxError(sql, 0); } Query q = (Query) p; if (isTableExpression && allowRecursive) { q.setNeverLazy(true); } return q; }
Source:
CompletableFuture<LedgerMetadata> closeRecovered() { long lac, len; synchronized (this) { lac = lastAddConfirmed; len = length; } LOG.info("Closing recovered ledger at entry {}", getId(), lac); CompletableFuture<LedgerMetadata> f = new MetadataUpdateLoop( clientCtx.getLedgerManager(), getId(), this::getLedgerMetadata, (metadata) -> metadata.isInRecovery(), (metadata) -> { LedgerMetadataBuilder builder = LedgerMetadataBuilder.from(metadata); Optional<Long> lastEnsembleKey = metadata.getLastEnsembleKey(); checkState(lastEnsembleKey.isPresent(), "Metadata shouldn't have been created without at least one ensemble"); newEnsemblesFromRecovery.entrySet().forEach( (e) -> { if (lastEnsembleKey.get().equals(e.getKey())) { builder.replaceEnsembleEntry(e.getKey(), e.getValue()); } else { builder.newEnsembleEntry(e.getKey(), e.getValue()); } }); return builder.closingAt(lac, len).build(); }, this::setLedgerMetadata).run(); f.thenRun(() -> newEnsemblesFromRecovery.clear()); return f; }

Target:
CompletableFuture<LedgerMetadata> closeRecovered() { long lac, len; synchronized (this) { lac = lastAddConfirmed; len = length; } LOG.info("Closing recovered ledger at entry {}", getId(), lac); CompletableFuture<LedgerMetadata> f = new MetadataUpdateLoop( clientCtx.getLedgerManager(), getId(), this::getLedgerMetadata, (metadata) -> metadata.isInRecovery(), (metadata) -> { LedgerMetadataBuilder builder = LedgerMetadataBuilder.from(metadata); Optional<Long> lastEnsembleKey = metadata.getLastEnsembleKey(); checkState(lastEnsembleKey.isPresent(), "Metadata shouldn't have been created without at least one ensemble"); synchronized (metadataLock) { newEnsemblesFromRecovery.entrySet().forEach( (e) -> { checkState(e.getKey() >= lastEnsembleKey.get(), "Once a ledger is in recovery, noone can add ensembles without closing"); if (lastEnsembleKey.get().equals(e.getKey())) { builder.replaceEnsembleEntry(e.getKey(), e.getValue()); } else { builder.newEnsembleEntry(e.getKey(), e.getValue()); } }); } return builder.closingAt(lac, len).build(); }, this::setLedgerMetadata).run(); f.thenRun(() -> { synchronized (metadataLock) { newEnsemblesFromRecovery.clear(); } }); return f; }
Source:
private void openRegion(MasterProcedureEnv env, RegionStateNode regionNode) throws IOException, ProcedureSuspendedException { ServerName loc = regionNode.getRegionLocation(); if (loc == null) { LOG.warn("No location specified for {}, jump back to state to get one", getRegion(), RegionStateTransitionState.REGION_STATE_TRANSITION_GET_ASSIGN_CANDIDATE); setNextState(RegionStateTransitionState.REGION_STATE_TRANSITION_GET_ASSIGN_CANDIDATE); return; } final boolean isMeta = regionNode.getRegionInfo().isMetaRegion(); final boolean isMetaAvailable = !env.getAssignmentManager().isMetaRegionInTransition(); if (!isMeta && !isMetaAvailable) { throw new ProcedureSuspendedException(); } env.getAssignmentManager().regionOpening(regionNode); addChildProcedure(new OpenRegionProcedure(this, getRegion(), loc)); setNextState(RegionStateTransitionState.REGION_STATE_TRANSITION_CONFIRM_OPENED); }

Target:
private void openRegion(MasterProcedureEnv env, RegionStateNode regionNode) throws IOException, ProcedureSuspendedException { ServerName loc = regionNode.getRegionLocation(); if (loc == null) { LOG.warn("No location specified for {}, jump back to state to get one", getRegion(), RegionStateTransitionState.REGION_STATE_TRANSITION_GET_ASSIGN_CANDIDATE); setNextState(RegionStateTransitionState.REGION_STATE_TRANSITION_GET_ASSIGN_CANDIDATE); return; } final boolean isMeta = regionNode.getRegionInfo().isMetaRegion(); final boolean isMetaAvailable = env.getMasterServices() .isRegionOnline(RegionInfoBuilder.FIRST_META_REGIONINFO); if (!isMeta && !isMetaAvailable) { throw new ProcedureSuspendedException(); } env.getAssignmentManager().regionOpening(regionNode); addChildProcedure(new OpenRegionProcedure(this, getRegion(), loc)); setNextState(RegionStateTransitionState.REGION_STATE_TRANSITION_CONFIRM_OPENED); }
Source:
private TriggerEventRequest buildTriggerForForm(Config config, CommcareApplicationJson application, FormSchemaJson form) { String applicationName = application.getApplicationName(); String formName = form.getFormName(); String displayName = DisplayNameHelper.buildDisplayName(RECEIVED_FORM, formName, applicationName, config.getName()); if (application.getCommcareAppId() != null) { return new TriggerEventRequest(displayName, FORMS_EVENT + "." + config.getName() + "." + form.getXmlns() + application.getCommcareAppId(), null, buildTriggerParameters(form), FORMS_EVENT); } else { return new TriggerEventRequest(displayName, FORMS_EVENT + "." + config.getName() + "." + form.getXmlns(), null, buildTriggerParameters(form), FORMS_EVENT); } }

Target:
private TriggerEventRequest buildTriggerForForm(Config config, CommcareApplicationJson application, FormSchemaJson form) { String applicationName = application.getApplicationName(); String formName = form.getFormName(); String displayName = DisplayNameHelper.buildDisplayName(RECEIVED_FORM, formName, applicationName, config.getName()); String appId = (application.getCommcareAppId() != null) ? application.getCommcareAppId() : ""; return new TriggerEventRequest(displayName, FORMS_EVENT + "." + config.getName() + "." + form.getXmlns() + appId, null, buildTriggerParameters(form), FORMS_EVENT); }
Source:
private void loadIndex() { File storeFolder = folders.getBase(); File index = new File(storeFolder, INDEX_FILE_NAME); if (index.exists() && index.length() > 0) { try { InputStream stream = new FileInputStream(index); ObjectInputStream ois = new ObjectInputStream(stream); try { diskDatas.clear(); for (DiskData diskData : (List<DiskData>)ois.readObject()) { diskData.pageStore = this; diskDatas.put(diskData.sessionIdentifier, diskData); } } finally { stream.close(); ois.close(); } } catch (Exception e) { log.error("Couldn't load DiskPageStore index from file " + index + ".", e); } } Files.remove(index); }

Target:
private void loadIndex() { File storeFolder = folders.getBase(); File index = new File(storeFolder, INDEX_FILE_NAME); if (index.exists() && index.length() > 0) { try (InputStream stream = new FileInputStream(index)) { ObjectInputStream ois = new ObjectInputStream(stream); diskDatas.clear(); for (DiskData diskData : (List<DiskData>)ois.readObject()) { diskData.pageStore = this; diskDatas.put(diskData.sessionIdentifier, diskData); } } catch (Exception e) { log.error("Couldn't load DiskPageStore index from file " + index + ".", e); } } Files.remove(index); }
Source:
public Container(final ContainerHeader containerHeader, final long containerByteOffset) { this.containerHeader = containerHeader; this.containerByteOffset = containerByteOffset; compressionHeader = null; slices = Collections.EMPTY_LIST; }

Target:
public Container(final ContainerHeader containerHeader, final long containerByteOffset) { this.containerHeader = containerHeader; this.containerByteOffset = containerByteOffset; compressionHeader = null; slices = Collections.emptyList(); }
Source:
public boolean hasNext() { if (numInflight == parallelism) { return false; } else { return replicaIterator.hasNext(); } }

Target:
public boolean hasNext() { return inflightCount < parallelism && replicaIterator.hasNext(); }
Source:
private void learnIdentifierConstraints(IdentifierTree tree, SymbolicValue sv) { if (THIS_SUPER.contains(tree.name())) { programState = programState.addConstraint(sv, ObjectConstraint.NOT_NULL); return; } Tree declaration = tree.symbol().declaration(); if (!isFinalField(tree.symbol()) || declaration == null) { return; } ExpressionTree initializer = ((VariableTree) declaration).initializer(); if (initializer == null) { return; } initializer = ExpressionUtils.skipParentheses(initializer); if (initializer.is(Tree.Kind.NULL_LITERAL)) { programState = programState.addConstraint(sv, ObjectConstraint.NULL); } else if (initializer.is(Tree.Kind.NEW_CLASS, Tree.Kind.NEW_ARRAY, Tree.Kind.STRING_LITERAL) || isNonNullMethodInvocation(initializer) || isNonBooleanPrimitiveTypeExpression(initializer)) { programState = programState.addConstraint(sv, ObjectConstraint.NOT_NULL); } else if (initializer.is(Tree.Kind.BOOLEAN_LITERAL)) { boolean boleanValue = Boolean.parseBoolean(((LiteralTree) initializer).value()); programState = programState .addConstraint(sv, ObjectConstraint.NOT_NULL) .addConstraint(sv, boleanValue ? BooleanConstraint.TRUE : BooleanConstraint.FALSE); } }

Target:
private void learnIdentifierConstraints(IdentifierTree tree, SymbolicValue sv) { if (THIS_SUPER.contains(tree.name())) { programState = programState.addConstraint(sv, ObjectConstraint.NOT_NULL); return; } Tree declaration = tree.symbol().declaration(); if (!isFinalField(tree.symbol()) || declaration == null) { return; } ExpressionTree initializer = ((VariableTree) declaration).initializer(); if (initializer == null) { return; } initializer = ExpressionUtils.skipParentheses(initializer); if (initializer.is(Tree.Kind.NULL_LITERAL)) { programState = programState.addConstraint(sv, ObjectConstraint.NULL); } else if (initializer.is(Tree.Kind.NEW_CLASS, Tree.Kind.NEW_ARRAY, Tree.Kind.STRING_LITERAL) || isNonNullMethodInvocation(initializer) || isNonBooleanPrimitiveTypeExpression(initializer)) { programState = programState.addConstraint(sv, ObjectConstraint.NOT_NULL); } else if (initializer.is(Tree.Kind.BOOLEAN_LITERAL)) { boolean booleanValue = Boolean.parseBoolean(((LiteralTree) initializer).value()); programState = programState .addConstraint(sv, ObjectConstraint.NOT_NULL) .addConstraint(sv, booleanValue ? BooleanConstraint.TRUE : BooleanConstraint.FALSE); } }
Source:
public void shouldCollectUnlimitedNumberOfBadEntries() throws Exception { List<String> nodeIds = new ArrayList<>(); for ( int i = 0; i < 10_000; i++ ) { nodeIds.add( "A" ); } importTool( "--into", dbRule.getStoreDirAbsolutePath(), "--nodes", nodeData( true, Configuration.COMMAS, nodeIds, TRUE ).getAbsolutePath(), "--skip-duplicate-nodes", "--bad-tolerance", "-" ); }

Target:
public void shouldCollectUnlimitedNumberOfBadEntries() throws Exception { List<String> nodeIds = Collections.nCopies( 10_000, "A" ); importTool( "--into", dbRule.getStoreDirAbsolutePath(), "--nodes", nodeData( true, Configuration.COMMAS, nodeIds, TRUE ).getAbsolutePath(), "--skip-duplicate-nodes", "--bad-tolerance", "true" ); }
Source:
public static Map<AnelCommandType, State> parseData(byte[] data, AnelState state) throws Exception { final String string = new String(data); final String[] arr = string.split(":"); if (arr.length < 26 && arr.length != 16) { throw new IllegalArgumentException( "Data with 16 or at least 26 values expected but " + arr.length + " received: " + string); } if (!arr[0].equals("NET-PwrCtrl")) { throw new IllegalArgumentException("Data must start with 'NET-PwrCtrl' but it didn't: " + arr[0]); } if (!state.host.equals(arr[2]) && !state.host.equalsIgnoreCase(arr[1].trim())) { return Collections.emptyMap(); } final Map<AnelCommandType, State> result = new LinkedHashMap<AnelCommandType, State>(); checkForNameChange(arr, state, result); if (arr.length >= 15) { checkForStateChanges(arr, state, result); } if (arr.length >= 24) { checkForIOChanges(arr, state, result); } if (arr.length >= 25) { checkForTemperatureChange(arr, state, result); } final int sensorDataIndex = findSensorDataIndex(arr, 26); if (sensorDataIndex > 0) { checkForSensorChanges(arr, state, result, sensorDataIndex); } final int powerDataIndex = findPowerDataIndex(arr, 26); if (powerDataIndex > 0) { } return result; }

Target:
public static Map<AnelCommandType, State> parseData(byte[] data, AnelState state) throws Exception { final String string = new String(data); final String[] arr = string.split(":"); if (arr.length < 26 && arr.length != 16) { throw new IllegalArgumentException( "Data with 16 or at least 26 values expected but " + arr.length + " received: " + string); } if (!arr[0].equals("NET-PwrCtrl")) { throw new IllegalArgumentException("Data must start with 'NET-PwrCtrl' but it didn't: " + arr[0]); } if (!state.host.equals(arr[2]) && !state.host.equalsIgnoreCase(arr[1].trim())) { return Collections.emptyMap(); } final Map<AnelCommandType, State> result = new LinkedHashMap<AnelCommandType, State>(); checkForNameChange(arr, state, result); if (arr.length >= 15) { checkForStateChanges(arr, state, result); } if (arr.length >= 24) { checkForIOChanges(arr, state, result); } if (arr.length >= 25) { checkForTemperatureChange(arr, state, result); } final int sensorDataIndex = findNameAndNumberPatternIndex(arr, 26, "s", 3); if (sensorDataIndex > 0) { checkForSensorChanges(arr, state, result, sensorDataIndex); } return result; }
Source:
public void updateMembers(IEntityGroup group) throws GroupsException { String groupName = group.getLocalKey(); GcAddMember gcAddMember = new GcAddMember().assignGroupName(groupName); Iterator<IGroupMember> membersIterator = group.getChildren().iterator(); while (membersIterator != null && membersIterator.hasNext()) { IGroupMember iGroupMember = membersIterator.next(); EntityIdentifier entityIdentifier = iGroupMember .getEntityIdentifier(); String identifier = entityIdentifier.getKey(); gcAddMember.addSubjectIdentifier(identifier); } gcAddMember.execute(); }

Target:
public void updateMembers(IEntityGroup group) throws GroupsException { String groupName = group.getLocalKey(); GcAddMember gcAddMember = new GcAddMember().assignGroupName(groupName); for (IGroupMember iGroupMember : group.getChildren()) { EntityIdentifier entityIdentifier = iGroupMember.getEntityIdentifier(); String identifier = entityIdentifier.getKey(); gcAddMember.addSubjectIdentifier(identifier); } gcAddMember.execute(); }
Source:
public static Configuration getCfg() { return new ConfigurationCreator().getInstance(); }

Target:
public static Configuration getCfg() throws IOException { return new CustomConfigurationCreator(new DefaultEnvironment(environmentType)).getInstance(); }
Source:
public int onStartCommand(Intent intent, int flags, int startId) { Log.i("LocalService", "setting the location from service"); String longitude = intent.getStringExtra("longitude"); String latitude = intent.getStringExtra("latitude"); mock = new MockLocationProvider(LocationManager.GPS_PROVIDER, this); mock.pushLocation(Double.valueOf(latitude), Double.valueOf(longitude)); return START_NOT_STICKY; }

Target:
public int onStartCommand(Intent intent, int flags, int startId) { String longitude = intent.getStringExtra("longitude"); String latitude = intent.getStringExtra("latitude"); Log.i("LocationService", "setting the location from service with longitude: "+longitude+" latitude: "+latitude); mock = new MockLocationProvider(LocationManager.GPS_PROVIDER, this); mock.pushLocation(Double.valueOf(latitude), Double.valueOf(longitude)); return START_NOT_STICKY; }
Source:
public void wrongKeyTypeThrowsException() throws IllegalAccessException, InstantiationException, LegalSPITesterException { kvStore2 = factory.newStore(); V value = factory.createValue(1); try { if (this.factory.getKeyType() == String.class) { kvStore2.putIfAbsent(1.0f, value); } else { kvStore2.putIfAbsent("key", value); } throw new AssertionError("Expected ClassCastException because the key is of the wrong type"); } catch (CacheAccessException cae) { assertThat(cae.getCause(), instanceOf(ClassCastException.class)); throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }

Target:
public void wrongKeyTypeThrowsException() throws IllegalAccessException, InstantiationException, LegalSPITesterException { kvStore2 = factory.newStore(); V value = factory.createValue(1); try { if (this.factory.getKeyType() == String.class) { kvStore2.putIfAbsent(1.0f, value); } else { kvStore2.putIfAbsent("key", value); } throw new AssertionError("Expected ClassCastException because the key is of the wrong type"); } catch (ClassCastException e) { } catch (CacheAccessException e) { throw new LegalSPITesterException("Warning, an exception is thrown due to the SPI test"); } }
Source:
public static TimestampIncrementingOffset fromMap(Map<String, ?> map) { TimestampIncrementingOffset offset = new TimestampIncrementingOffset(); if (map == null || map.isEmpty()) return offset; Object incr = map.get(INCREMENTING_FIELD); if (incr != null) offset.setIncrementingOffset((Long) incr); Object millis = map.get(TIMESTAMP_MILLIS_FIELD); if (millis != null) { Timestamp ts = new Timestamp((Long) millis); ts.setNanos((Integer) map.get(TIMESTAMP_NANOS_FIELD)); offset.setTimestampOffset(ts); } return offset; }

Target:
public static TimestampIncrementingOffset fromMap(Map<String, ?> map) { if (map == null || map.isEmpty()) return new TimestampIncrementingOffset(null, null); Long incr = (Long) map.get(INCREMENTING_FIELD); Long millis = (Long) map.get(TIMESTAMP_FIELD); Timestamp ts = null; if (millis != null) { ts = new Timestamp(millis); Integer nanos = (Integer) map.get(TIMESTAMP_NANOS_FIELD); if (nanos != null) ts.setNanos(nanos); } return new TimestampIncrementingOffset(ts, incr); }
Source:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptyTopEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, CANCELLING, ""); }

Target:
public void testUnmarshallTopLevelEmptyEventProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptyTopEvent = getCatchingIntermediateNodeById(diagram, EMPTY_TOP_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptyTopEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptyTopEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, CANCELLING, EMPTY_VALUE); }