auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void populateModelWithObjectStoreConfig(ModelNode operation, ModelNode objectStoreModel) throws OperationFailedException { TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.validateAndSet(operation, objectStoreModel); TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.validateAndSet(operation, objectStoreModel); ModelNode relativeVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.getName()); ModelNode pathVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getName()); if (!relativeVal.isDefined() && (!pathVal.isDefined() || pathVal.asString().equals(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getDefaultValue().asString()))) { relativeVal.set(new ModelNode().set("jboss.server.data.dir")); } }

Target:
private void populateModelWithObjectStoreConfig(ModelNode operation, ModelNode objectStoreModel) throws OperationFailedException { TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.validateAndSet(operation, objectStoreModel); TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.validateAndSet(operation, objectStoreModel); ModelNode relativeVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_RELATIVE_TO.getName()); ModelNode pathVal = objectStoreModel.get(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getName()); if (!relativeVal.isDefined() && (!pathVal.isDefined() || pathVal.asString().equals(TransactionSubsystemRootResourceDefinition.OBJECT_STORE_PATH.getDefaultValue().asString()))) { relativeVal.set(new ModelNode().set("jboss.server.data.dir")); TransactionLogger.ROOT_LOGGER.objectStoreRelativeToIsSetToDefault(); } }
Source:
void setUp() { factory = shouldHaveSizeLessThanOrEqualTo(newArrayList('a', 'b'), 4, 2); }

Target:
void setUp() { factory = shouldHaveSizeLessThanOrEqualTo("ab", 4, 2); }
Source:
public Response postExperiment(@FormParam("name") String name, @FormParam("traces") List<UUID> traceUUIDs) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath ipath = root.getLocation().append(EXPERIMENTS).append(name); IResource resource = root.findMember(ipath); if (Iterables.any(TmfTraceManager.getInstance().getOpenedTraces(), t -> t.getPath().equals(ipath.toOSString()))) { return Response.status(Status.CONFLICT).entity("There is already an experiment named: " + name).build(); } ITmfTrace[] array = new ITmfTrace[traceUUIDs.size()]; int i = 0; for (UUID uuid : traceUUIDs) { ITmfTrace trace = TraceManagerService.getTraceByUUID(uuid); if (trace == null) { return Response.noContent().build(); } array[i++] = trace; } TmfExperiment experiment = new TmfExperiment(ITmfEvent.class, ipath.toOSString(), array, TmfExperiment.DEFAULT_INDEX_PAGE_SIZE, resource); experiment.traceOpened(new TmfTraceOpenedSignal(this, experiment, null)); TmfTraceManager.getInstance().traceOpened(new TmfTraceOpenedSignal(this, experiment, null)); return Response.ok(experiment).build(); }

Target:
public Response postExperiment(@FormParam("name") String name, @FormParam("traces") List<UUID> traceUUIDs) { IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IPath ipath = root.getLocation().append(EXPERIMENTS).append(name); IResource resource = root.findMember(ipath); if (Iterables.any(TmfTraceManager.getInstance().getOpenedTraces(), t -> t.getPath().equals(ipath.toOSString()))) { return Response.status(Status.CONFLICT).entity("There is already an experiment named: " + name).build(); } ITmfTrace[] array = new ITmfTrace[traceUUIDs.size()]; int i = 0; for (UUID uuid : traceUUIDs) { ITmfTrace trace = TraceManagerService.getTraceByUUID(uuid); if (trace == null) { return Response.noContent().build(); } try { ITmfTrace clone = trace.getClass().newInstance(); clone.initTrace(trace.getResource(), trace.getPath(), ITmfEvent.class, trace.getName(), trace.getTraceTypeId()); array[i++] = clone; } catch (InstantiationException | IllegalAccessException | TmfTraceException e) { return Response.serverError().entity(e.getMessage()).build(); } } TmfExperiment experiment = new TmfExperiment(ITmfEvent.class, ipath.toOSString(), array, TmfExperiment.DEFAULT_INDEX_PAGE_SIZE, resource); TmfSignalManager.dispatchSignal(new TmfTraceOpenedSignal(this, experiment, null)); return Response.ok(experiment).build(); }
Source:
void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource) throws AuthenticationException { final List<String> keys; final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType(); switch (tokenEntryType) { case REGULAR_TOKEN_ENTRY : Logger.v(TAG, "Regular RT was used to get access token, remove entries " + "for regular RT entries."); keys = getKeyListToRemoveForRT(tokenCacheItem); break; case MRRT_TOKEN_ENTRY : Logger.v(TAG, "MRRT was used to get access token, remove entries for both " + "MRRT entries and regular RT entries."); keys = getKeyListToRemoveForMRRT(tokenCacheItem, resource); final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem); regularRTItem.setResource(resource); keys.addAll(getKeyListToRemoveForRT(regularRTItem)); break; case FRT_TOKEN_ENTRY : Logger.v(TAG, "FRT was used to get access token, remove entries for " + "FRT entries."); keys = getKeyListToRemoveForFRT(tokenCacheItem); break; default : throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM); } for (final String key : keys) { mTokenCacheStore.removeItem(key); } }

Target:
private void removeTokenCacheItem(final TokenCacheItem tokenCacheItem, final String resource) throws AuthenticationException { final List<String> keys; final TokenEntryType tokenEntryType = tokenCacheItem.getTokenEntryType(); switch (tokenEntryType) { case REGULAR_TOKEN_ENTRY : Logger.v(TAG, "Regular RT was used to get access token, remove entries " + "for regular RT entries."); keys = getKeyListToRemoveForRT(tokenCacheItem); break; case MRRT_TOKEN_ENTRY : Logger.v(TAG, "MRRT was used to get access token, remove entries for both " + "MRRT entries and regular RT entries."); keys = getKeyListToRemoveForMRRT(tokenCacheItem, resource); final TokenCacheItem regularRTItem = new TokenCacheItem(tokenCacheItem); regularRTItem.setResource(resource); keys.addAll(getKeyListToRemoveForRT(regularRTItem)); break; case FRT_TOKEN_ENTRY : Logger.v(TAG, "FRT was used to get access token, remove entries for " + "FRT entries."); keys = getKeyListToRemoveForFRT(tokenCacheItem); break; default : throw new AuthenticationException(ADALError.INVALID_TOKEN_CACHE_ITEM); } for (final String key : keys) { mTokenCacheStore.removeItem(key); } }
Source:
private File getBackupFile(int age) { List<Long> fileTimes = new ArrayList<Long>(); File folder = new File(file.getParent() + File.separator + "backup"); File[] files = folder.listFiles(); int count = files.length; for (int i = 0; i < count; i++) { if (files[i].isFile()) { String[] parts = files[i].getName().split(SEPARATOR); if (parts.length != 2 || !parts[1].equals(file.getName())) { continue; } long time = Long.parseLong(parts[0]); fileTimes.add(time); } } Collections.sort(fileTimes); if (fileTimes.size() < age) { return null; } return new File(file.getParent() + File.separator + "backup", fileTimes.get(fileTimes.size() - age) + SEPARATOR + file.getName()); }

Target:
private File getBackupFile(int age) { List<Long> fileTimes = new ArrayList<Long>(); File folder = new File(file.getParent() + File.separator + BACKUP_EXTENSION); File[] files = folder.listFiles(); int count = files.length; for (int i = 0; i < count; i++) { if (files[i].isFile()) { String[] parts = files[i].getName().split(SEPARATOR); if (parts.length != 2 || !parts[1].equals(file.getName())) { continue; } long time = Long.parseLong(parts[0]); fileTimes.add(time); } } Collections.sort(fileTimes); if (fileTimes.size() < age) { return null; } return new File(file.getParent() + File.separator + BACKUP_EXTENSION, fileTimes.get(fileTimes.size() - age) + SEPARATOR + file.getName()); }
Source:
public static Long determineTotalImageInitialSize(DiskImage sourceImage, VolumeFormat destFormat, Guid srcDomain, Guid dstDomain) { if (isInitialSizeSupportedForFormat(destFormat, dstDomain)) { double totalSizeForClonedDisk = getTotalActualSizeOfDisk(sourceImage, DbFacade.getInstance().getStorageDomainDao().get(srcDomain).getStorageStaticData()); return computeCowImageNeededSize(sourceImage.getVolumeFormat(), Double.valueOf(totalSizeForClonedDisk).longValue()); } return null; }

Target:
public Long determineTotalImageInitialSize(DiskImage sourceImage, VolumeFormat destFormat, Guid srcDomain, Guid dstDomain) { if (isInitialSizeSupportedForFormat(destFormat, dstDomain)) { double totalSizeForClonedDisk = getTotalActualSizeOfDisk(sourceImage, storageDomainDao.get(srcDomain).getStorageStaticData()); return computeCowImageNeededSize(sourceImage.getVolumeFormat(), Double.valueOf(totalSizeForClonedDisk).longValue()); } return null; }
Source:
public String toString() { return MoreObjects.toStringHelper(this) .add("table", table) .add("name", name) .toString(); }

Target:
public String toString() { return "DropCheckConstraint{" + "table=" + table + ", name='" + name + '\'' + '}'; }
Source:
public int parseRetryInterval() throws ConfigurationException { verifyNotEmpty("retry interval", _retryInterval); int retryInterval; try { retryInterval = Integer.parseInt(_retryInterval); } catch (NumberFormatException ex) { throw new ConfigurationException("Number of retries has to be between 1 and 10"); } if ((retryInterval < 0) || (retryInterval > 10000)) { throw new ConfigurationException("Number of retries has to be between 1 and 10"); } return retryInterval; }

Target:
public int parseRetryInterval() throws ConfigurationException { return verifyInRange("Retry interval", _retryInterval, 1, 10000); }
Source:
private void downloadLocal() { File workerHome = newFile(getSimulatorHome(), WORKERS_HOME_NAME); File targetDirectory = ensureExistingDirectory(newFile(".", WORKERS_HOME_NAME), testSuite.getId()); String workerPath = workerHome.getAbsolutePath(); String targetPath = targetDirectory.getAbsolutePath(); execute(format("mv %s/%s/* %s || true", workerPath, testSuite.getId(), targetPath)); execute(format("rmdir %s/%s || true", workerPath, testSuite.getId())); execute(format("rmdir %s || true", workerPath)); execute(format("mv ./agent.err %s/ || true", targetPath)); execute(format("mv ./agent.out %s/ || true", targetPath)); execute(format("mv ./failures-%s.txt %s/ || true", testSuite.getId(), targetPath)); }

Target:
private void downloadLocal() { echoLocal("Retrieving artifacts of local machine"); File workerHome = newFile(getSimulatorHome(), WORKERS_HOME_NAME); String workerPath = workerHome.getAbsolutePath(); execute(format("mv %s/%s/* %s || true", workerPath, testSuite.getId(), outputDirectory.getAbsolutePath())); execute(format("rmdir %s/%s || true", workerPath, testSuite.getId())); execute(format("rmdir %s || true", workerPath)); execute(format("mv ./agent.err %s/ || true", outputDirectory.getAbsolutePath())); execute(format("mv ./agent.out %s/ || true", outputDirectory.getAbsolutePath())); }
Source:
public Comparable score(QueryPlan qp) { LOGGER.debug("score begin"); QueryPlanNode[] nodes = qp.getAllNodes(); QueryPlanNode[] sources = qp.getSources(); QueryPlanNode root = null; int numNodeQueries=0; for (QueryPlanNode node : nodes) { if (node.getMetadata().getParent() == null) { root = node; } if(getData(node).hasQueries()) numNodeQueries++; } if (null == root) { throw new IllegalStateException("Unable to find root metadata"); } if(numNodeQueries==0) { if(qp.isPlanMatchesMetadata()) return BigInteger.ZERO; else return new BigInteger("999999999"); } BigInteger penalty=BigInteger.ONE; if(sources.length>1) penalty=BigInteger.TEN; for(QueryPlanNode node:sources) if(!getData(node).hasQueries()) penalty=penalty.multiply(new BigInteger("100")); for(QueryPlanNode node:nodes) { if(!getData(node).hasQueries()) { if(aboveRoot(node,root)) { QueryPlanNode[] s=node.getSources(); if(s!=null&&s.length>0) { penalty=penalty.multiply(new BigInteger("5")); } } } } LOGGER.debug("penalty={}",penalty); BigInteger finalCost; if (sources.length == 1 && sources[0] == root) { if (getData(root).isIdentitySearch()) { finalCost = BigInteger.ZERO; } else { finalCost = computeRetrievalCost(root); } } else { CostAndSize cs = computeQueryCost(root, qp); finalCost = cs.cost.add(cs.size); } LOGGER.debug("Final cost w/o penalty:{}", finalCost); finalCost=finalCost.multiply(penalty); LOGGER.debug("Final cost:{}", finalCost); return finalCost; }

Target:
public Comparable score(QueryPlan qp) { LOGGER.debug("score begin"); QueryPlanNode[] nodes = qp.getAllNodes(); QueryPlanNode[] sources = qp.getSources(); QueryPlanNode root = null; int numNodeQueries=0; for (QueryPlanNode node : nodes) { if (node.getMetadata().getParent() == null) { root = node; } if(getData(node).hasQueries()) numNodeQueries++; } if (null == root) { throw new IllegalStateException("Unable to find root metadata"); } if(numNodeQueries==0) { if(qp.isPlanMatchesMetadata()) return BigInteger.ZERO; else return new BigInteger(Integer.toString(Integer.MAX_VALUE)); } BigInteger penalty=BigInteger.ONE; if(sources.length>1) penalty=BigInteger.TEN; for(QueryPlanNode node:sources) if(!getData(node).hasQueries()) penalty=penalty.multiply(new BigInteger("100")); for(QueryPlanNode node:nodes) { if(!getData(node).hasQueries()) { if(aboveRoot(node,root)) { QueryPlanNode[] s=node.getSources(); if(s!=null&&s.length>0) { penalty=penalty.multiply(new BigInteger("5")); } } } } LOGGER.debug("penalty={}",penalty); BigInteger finalCost; if (sources.length == 1 && sources[0] == root) { if (getData(root).isIdentitySearch()) { finalCost = BigInteger.ZERO; } else { finalCost = computeRetrievalCost(root); } } else { CostAndSize cs = computeQueryCost(root, qp); finalCost = cs.cost.add(cs.size); } LOGGER.debug("Final cost w/o penalty:{}", finalCost); finalCost=finalCost.multiply(penalty); LOGGER.debug("Final cost:{}", finalCost); return finalCost; }
Source:
public void onUpdateRecord(Data key, Record record, Object newValue) { eventJournal.writeUpdateEvent(mapContainer.getEventJournalConfig(), mapContainer.getObjectNamespace(), partitionId, record.getKey(), record.getValue(), newValue); }

Target:
public void onUpdateRecord(Data key, Record record, Object newValue) { eventJournal.writeUpdateEvent(eventJournalConfig, objectNamespace, partitionId, record.getKey(), record.getValue(), newValue); }
Source:
public BufferedMultipleNodeCallField toBuffered() { if(!(paramValues instanceof BufferableHandle)) throw new IllegalArgumentException("Default parameter must implement BufferableHandle."); BytesHandle bytesHandle = new BytesHandle((BufferableHandle) paramValues); return new BufferedMultipleNodeCallField(super.paramName, Stream.of(bytesHandle)); }

Target:
public BufferedMultipleNodeCallField toBuffered() { Stream<BytesHandle> bytesHandleStream = paramValues.map(handle ->{ if(!(handle instanceof BufferableHandle)) throw new IllegalArgumentException("Default parameter must implement BufferableHandle."); return new BytesHandle((BufferableHandle) handle); }); return new BufferedMultipleNodeCallField(super.getParamName(), bytesHandleStream); }
Source:
public static GoFunctionDeclaration createFunctionDeclarationFromText(@NotNull Project project, @NotNull String name, @NotNull String text, @Nullable String expectedType) { if (expectedType == null) { expectedType = ""; } else { expectedType += " "; } GoFile file = createFileFromText(project, "package a; func " + name + "(" + text + ") " + expectedType + "{\n}"); return ContainerUtil.getFirstItem(file.getFunctions()); }

Target:
public static GoFunctionDeclaration createFunctionDeclarationFromText(@NotNull Project project, @NotNull String name, @NotNull String text, @Nullable String expectedType) { expectedType = expectedType == null ? "" : expectedType + " "; GoFile file = createFileFromText(project, "package a; func " + name + "(" + text + ") " + expectedType + "{\n}"); return ContainerUtil.getFirstItem(file.getFunctions()); }
Source:
AuthenticationAuthority(final URL authorityUrl, final boolean validateAuthority) { this.authorityUrl = authorityUrl; this.authorityType = detectAuthorityType(); this.validateAuthority = validateAuthority; proxy = Proxy.NO_PROXY; validateAuthorityUrl(); setupAuthorityProperties(); }

Target:
AuthenticationAuthority(final URL authorityUrl, final boolean validateAuthority) { this.authorityUrl = authorityUrl; this.authorityType = detectAuthorityType(); this.validateAuthority = validateAuthority; validateAuthorityUrl(); setupAuthorityProperties(); }
Source:
public QueueModel updateQueue(ArrayList<Subscriber> subscribersList, ArrayList<Alert> alertsList, String pushType, String errorQueue, int retries, int retriesDelay) throws IOException { String url = "queues/" + name; UpdateQueue updateQueue = new UpdateQueue(subscribersList, alertsList, pushType, errorQueue, retries, retriesDelay); Gson gson = new Gson(); String jsonMessages = gson.toJson(updateQueue); Reader reader = client.patch(url, jsonMessages); QueueModel message = gson.fromJson(reader, QueueModel.class); reader.close(); return message; }

Target:
public QueueModel updateQueue(ArrayList<Subscriber> subscribersList, ArrayList<Alert> alertsList, String pushType, String errorQueue, int retries, int retriesDelay) throws IOException { QueueModel model = new QueueModel(); model.setPushInfo(new QueuePushModel(subscribersList, retries, retriesDelay, errorQueue)); model.setAlerts(alertsList); model.setType(pushType); return update(model); }
Source:
public void testPopulatedNewRequisitionAccount() { final String accountType = "REQS"; final Class<TestableRequisitionAccount> accountClass = TestableRequisitionAccount.class; validateAccount(accountType, accountClass); }

Target:
public void testPopulatedNewRequisitionAccount() { final String accountType = PurapConstants.REQUISITION_DOCUMENT_TYPE; final Class<TestableRequisitionAccount> accountClass = TestableRequisitionAccount.class; validateAccount(accountType, accountClass); }
Source:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); throw new IllegalArgumentException(member.getName() + " is not a member of " + getName()); } }

Target:
public int getVisibility(IBinding member) { try { PDOMCPPMemberBlock members = new PDOMCPPMemberBlock(getLinkage(), record + MEMBERLIST); return members.getVisibility(member); } catch (CoreException e) { CCorePlugin.log(e); return v_public; } }
Source:
private static boolean isGetMessageReferencedByIdentifiers(MethodInvocationTree mit) { Set<IdentifierTree> identifiersChildren = new HashSet<>(); BaseTreeVisitor visitor = new BaseTreeVisitor() { @Override public void visitIdentifier(IdentifierTree tree) { identifiersChildren.add(tree); } }; mit.accept(visitor); boolean invocationInInitializer = identifiersChildren.stream().anyMatch(identifierTree -> hasGetMessageMethodInvocation(getVariableInitializer(identifierTree))); return invocationInInitializer || identifiersChildren.stream() .map(IdentifierTree::symbol) .map(Symbol::usages) .flatMap(usagesList -> getAssignments(usagesList).stream()) .anyMatch(assignment -> hasGetMessageMethodInvocation(assignment.expression())); }

Target:
private static boolean isGetMessageReferencedByIdentifiers(MethodInvocationTree mit) { ChildrenIdentifierCollector visitor = new ChildrenIdentifierCollector(); mit.accept(visitor); boolean invocationInInitializer = visitor.identifiersChildren.stream() .map(UsageStatus::getVariableInitializer) .distinct() .anyMatch(UsageStatus::hasGetMessageMethodInvocation); return invocationInInitializer || visitor.identifiersChildren.stream() .map(IdentifierTree::symbol) .map(Symbol::usages) .flatMap(usagesList -> getAssignments(usagesList).stream()) .anyMatch(assignment -> hasGetMessageMethodInvocation(assignment.expression())); }
Source:
public List<Mounted> checkCriticalSlotsForEquipment(Entity entity) { List<Mounted> unallocated = new ArrayList<>(); for (Mounted m : entity.getEquipment()) { if ((m.getLocation() == Entity.LOC_NONE) && !m.isOneShotAmmo() && m.getCriticals() > 0) { unallocated.add(m); } } return unallocated; }

Target:
public List<Mounted> checkCriticalSlotsForEquipment(Entity entity) { List<Mounted> unallocated = new ArrayList<>(); for (Mounted m : entity.getEquipment()) { if ((m.getLocation() == Entity.LOC_NONE) && !m.isOneShotAmmo() && (m.getCriticals() > 0)) { unallocated.add(m); } } return unallocated; }
Source:
protected boolean isPathInContentEntry(@NotNull File path, @NotNull ContentEntry contentEntry) { VirtualFile rootFile = contentEntry.getFile(); if (rootFile == null) { return false; } File rootFilePath = new File(FileUtil.toSystemDependentName(rootFile.getPath())); return FileUtil.isAncestor(rootFilePath, path, false); }

Target:
protected boolean isPathInContentEntry(@NotNull File path, @NotNull ContentEntry contentEntry) { VirtualFile rootFile = contentEntry.getFile(); if (rootFile == null) { return false; } File rootFilePath = VfsUtilCore.virtualToIoFile(rootFile); return FileUtil.isAncestor(rootFilePath, path, false); }
Source:
public PrologJar (Config config, SitePaths site, Repository git) { this.git = git; String s = config.getString("cache", null, "directory"); cacheDir = site.resolve(config.getString("cache", null, "directory")); }

Target:
public PrologJar (Config config, SitePaths site, Repository git) { this.git = git; cacheDir = site.resolve(config.getString("cache", null, "directory")); }
Source:
public OrcStruct parseOrcSchema(Schema inputSchema) { StringBuilder builder = new StringBuilder(); try { HiveSchemaConverter.appendType(builder, inputSchema); } catch (UnsupportedTypeException e) { LOG.debug("Not a valid Schema {}", inputSchema.toString(), e); } TypeDescription schema = TypeDescription.fromString(builder.toString()); OrcStruct pair = (OrcStruct) OrcStruct.createValue(schema); return pair; }

Target:
private OrcStruct parseOrcSchema(Schema inputSchema) { OrcStruct orcRecord; if (schemaCache.containsKey(inputSchema)) { TypeDescription schema = schemaCache.get(inputSchema); orcRecord = (OrcStruct) OrcStruct.createValue(schema); } else { StringBuilder builder = new StringBuilder(); try { HiveSchemaConverter.appendType(builder, inputSchema); } catch (UnsupportedTypeException e) { throw new IllegalArgumentException(String.format("Not a valid Schema {}", inputSchema.toString()), e); } TypeDescription schema = TypeDescription.fromString(builder.toString()); orcRecord = (OrcStruct) OrcStruct.createValue(schema); schemaCache.put(inputSchema, schema); } return orcRecord; }
Source:
public static void setItemEnchantments(ItemStack itemStack, List<ItemEnchantment> value) { final NBTTagCompound compound; if (itemStack.getTagCompound() == null) { compound = new NBTTagCompound(); itemStack.setTagCompound(compound); } else { compound = itemStack.getTagCompound(); } final Map<Enchantment, Integer> valueMap = Maps.newLinkedHashMap(); for (ItemEnchantment enchantment : value) { valueMap.put(enchantment.getEnchantment(), enchantment.getLevel()); } final NBTTagList newList = new NBTTagList(); for (Map.Entry<Enchantment, Integer> entry : valueMap.entrySet()) { final NBTTagCompound enchantmentCompound = new NBTTagCompound(); enchantmentCompound.setShort(NbtDataUtil.ITEM_ENCHANTMENT_ID, (short) net.minecraft.enchantment.Enchantment.getEnchantmentID((net.minecraft.enchantment.Enchantment) entry.getKey())); enchantmentCompound.setShort(NbtDataUtil.ITEM_ENCHANTMENT_LEVEL, entry.getValue().shortValue()); newList.appendTag(enchantmentCompound); } if (valueMap.isEmpty()) { compound.removeTag(NbtDataUtil.ITEM_ENCHANTMENT_LIST); } else { compound.setTag(NbtDataUtil.ITEM_ENCHANTMENT_LIST, newList); } }

Target:
public static void setItemEnchantments(ItemStack itemStack, List<ItemEnchantment> value) { final NBTTagCompound compound; if (itemStack.getTagCompound() == null) { compound = new NBTTagCompound(); itemStack.setTagCompound(compound); } else { compound = itemStack.getTagCompound(); } if (value.isEmpty()) { compound.removeTag(NbtDataUtil.ITEM_ENCHANTMENT_LIST); return; } final Map<Enchantment, Integer> valueMap = Maps.newLinkedHashMap(); for (ItemEnchantment enchantment : value) { valueMap.put(enchantment.getEnchantment(), enchantment.getLevel()); } final NBTTagList newList = new NBTTagList(); for (Map.Entry<Enchantment, Integer> entry : valueMap.entrySet()) { final NBTTagCompound enchantmentCompound = new NBTTagCompound(); enchantmentCompound.setShort(NbtDataUtil.ITEM_ENCHANTMENT_ID, (short) net.minecraft.enchantment.Enchantment.getEnchantmentID((net.minecraft.enchantment.Enchantment) entry.getKey())); enchantmentCompound.setShort(NbtDataUtil.ITEM_ENCHANTMENT_LEVEL, entry.getValue().shortValue()); newList.appendTag(enchantmentCompound); } compound.setTag(NbtDataUtil.ITEM_ENCHANTMENT_LIST, newList); }
Source:
private boolean isUIThread() { return PlatformUI.getWorkbench().getDisplay().getThread() == Thread .currentThread(); }

Target:
private static boolean isUIThread() { return Display.getCurrent() != null; }
Source:
public ICPPEvaluation computeForFunctionCall(ActivationRecord record, ConstexprEvaluationContext context) { ICPPEvaluation[] args = fArguments; for (int i = 0; i < fArguments.length; i++) { ICPPEvaluation arg = fArguments[i].computeForFunctionCall(record, context.recordStep()); if (arg != fArguments[i]) { if (args == fArguments) { args = new ICPPEvaluation[fArguments.length]; System.arraycopy(fArguments, 0, args, 0, fArguments.length); } args[i] = arg; } } ICPPFunction constructor = getConstructor(null); if (constructor != null && constructor instanceof ICPPConstructor) { return new EvalConstructor(fInputType, (ICPPConstructor) constructor, fArguments, getTemplateDefinition()).computeForFunctionCall(record, context); } if (args == fArguments) { return this; } EvalTypeId evalTypeId = new EvalTypeId(fInputType, getTemplateDefinition(), fRepresentsNewExpression, args); return evalTypeId; }

Target:
public ICPPEvaluation computeForFunctionCall(ActivationRecord record, ConstexprEvaluationContext context) { ICPPEvaluation[] args = fArguments; for (int i = 0; i < fArguments.length; i++) { ICPPEvaluation arg = fArguments[i].computeForFunctionCall(record, context.recordStep()); if (arg != fArguments[i]) { if (args == fArguments) { args = new ICPPEvaluation[fArguments.length]; System.arraycopy(fArguments, 0, args, 0, fArguments.length); } args[i] = arg; } } ICPPFunction constructor = getConstructor(null); if (constructor != null && constructor instanceof ICPPConstructor) { return new EvalConstructor(fInputType, (ICPPConstructor) constructor, fArguments, getTemplateDefinition()).computeForFunctionCall(record, context); } if (args == fArguments) { return this; } EvalTypeId evalTypeId = new EvalTypeId(fInputType, getTemplateDefinition(), fRepresentsNewExpression, fUsesBracedInitList, args); return evalTypeId; }
Source:
public void writeTo(Appendable appendable) throws IOException { try (JsonOutput json = new Json().newOutput(appendable)) { json.beginObject(); Map<String, Object> first = getOss(); if (first == null) { first = (Map<String, Object>) stream().findFirst() .orElse(new ImmutableCapabilities()) .asMap(); } json.name(DESIRED_CAPABILITIES); json.write(first); json.name(CAPABILITIES); json.beginObject(); json.name(ALWAYS_MATCH); json.write(first); json.name(FIRST_MATCH); json.beginArray(); getW3C().forEach(json::write); json.endArray(); json.endObject(); writeMetaData(json); json.endObject(); } }

Target:
public void writeTo(Appendable appendable) throws IOException { try (JsonOutput json = new Json().newOutput(appendable)) { json.beginObject(); Map<String, Object> first = getOss(); if (first == null) { first = (Map<String, Object>) stream().findFirst() .orElse(new ImmutableCapabilities()) .asMap(); } json.name(DESIRED_CAPABILITIES); json.write(first); json.name(CAPABILITIES); json.beginObject(); json.name(ALWAYS_MATCH); getW3C().forEach(json::write); json.name(FIRST_MATCH); json.beginArray(); json.beginObject(); json.endObject(); json.endArray(); json.endObject(); writeMetaData(json); json.endObject(); } }
Source:
public boolean hasResponseInCache() { return mResponses.size() != 0; }

Target:
public boolean hasResponseInCache() { return mResponses.size() > 0; }
Source:
private InputStream openStream(String url) throws IOException { return new URL(url).openStream(); }

Target:
private static InputStream openStream(String url) throws IOException { return new URL(url).openStream(); }
Source:
protected EventBus getEventBus() { return eventBus; }

Target:
protected final EventBus getEventBus() { return eventBus; }
Source:
public static void configureStaticResources(String folder) { if (!isStaticResourcesSet()) { if (folder != null) { try { ClassPathResource resource = new ClassPathResource(folder); if (resource.getFile().isDirectory()) { if (staticResourceHandlers == null) { staticResourceHandlers = new ArrayList<>(); } staticResourceHandlers.add(new ClassPathResourceHandler(folder, "index.html")); LOG.info("StaticResourceHandler configured with folder = " + folder); } else { LOG.error("Static resource location must be a folder"); } } catch (IOException e) { LOG.error("Error when creating StaticResourceHandler", e); } } staticResourcesSet = true; } }

Target:
public static void configureStaticResources(String folder) { Assert.notNull(folder, "'folder' must not be null"); if (!isStaticResourcesSet()) { try { ClassPathResource resource = new ClassPathResource(folder); if (!resource.getFile().isDirectory()) { LOG.error("Static resource location must be a folder"); return; } if (staticResourceHandlers == null) { staticResourceHandlers = new ArrayList<>(); } staticResourceHandlers.add(new ClassPathResourceHandler(folder, "index.html")); LOG.info("StaticResourceHandler configured with folder = " + folder); } catch (IOException e) { LOG.error("Error when creating StaticResourceHandler", e); } staticResourcesSet = true; } }
Source:
public static Table getHTableSystemChildLink (RegionCoprocessorEnvironment env) throws IOException { if (coprocessorScanWorks(env)) { try { return env.getConnection().getTable(SchemaUtil.getPhysicalTableName(SYSTEM_CHILD_LINK_NAME_BYTES, env.getConfiguration())); } catch (Exception e){ return env.getConnection().getTable(SchemaUtil.getPhysicalTableName(SYSTEM_CATALOG_NAME_BYTES, env.getConfiguration())); } } try { return getTableFromSingletonPool(env, SchemaUtil.getPhysicalTableName(SYSTEM_CHILD_LINK_NAME_BYTES, env.getConfiguration())); } catch (Exception e){ return getTableFromSingletonPool(env, SchemaUtil.getPhysicalTableName(SYSTEM_CATALOG_NAME_BYTES, env.getConfiguration())); } }

Target:
public static Table getHTableSystemChildLink (RegionCoprocessorEnvironment env) throws IOException { try { return env.getConnection().getTable(SchemaUtil.getPhysicalTableName(SYSTEM_CHILD_LINK_NAME_BYTES, env.getConfiguration())); } catch (Exception e){ return env.getConnection().getTable(SchemaUtil.getPhysicalTableName(SYSTEM_CATALOG_NAME_BYTES, env.getConfiguration())); } }
Source:
public void testLazyTransformSet() { Set<String> original = Sets.newSet("John", "Jane", "Adam", "Tom"); Function<String, String> function = new Function<String, String>() { @Override public String apply(String input) { return input+"HI"; } }; Set<String> output = Transformers.transformSetLazily(original, function); Set<String> transformedSetOutput = Transformers.transformSet(original, function); Iterator<String> it1 = output.iterator(); Iterator<String> it2 = transformedSetOutput.iterator(); while(it1.hasNext() && it2.hasNext()) { assertTrue(it1.next().equals(it2.next())); } }

Target:
public void testLazyTransformSet() { Set<String> original = Sets.newSet("John", "Jane", "Adam", "Tom"); Function<String, String> function = new Function<String, String>() { @Override public String apply(String input) { return input+"HI"; } }; Set<String> output = Transformers.transformSetLazily(original, function); Set<String> transformedSetOutput = Transformers.transformSet(original, function); Iterator<String> it1 = output.iterator(); Iterator<String> it2 = transformedSetOutput.iterator(); while(it1.hasNext() && it2.hasNext()) { assertEquals(it1.next(), it2.next()); } }
Source:
public static Page mergePages(List<Type> types, List<Page> pages) { PageBuilder pageBuilder = new PageBuilder(types); int totalPositionCount = 0; for (Page page : pages) { verify(page.getChannelCount() == types.size()); for (int i = 0; i < types.size(); i++) { BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i); Block block = page.getBlock(i); for (int position = 0; position < page.getPositionCount(); position++) { if (block.isNull(position)) { blockBuilder.appendNull(); } else { block.writePositionTo(position, blockBuilder); } } } totalPositionCount += page.getPositionCount(); } pageBuilder.declarePositions(totalPositionCount); return pageBuilder.build(); }

Target:
public static Page mergePages(List<Type> types, List<Page> pages) { PageBuilder pageBuilder = new PageBuilder(types); int totalPositionCount = 0; for (Page page : pages) { verify(page.getChannelCount() == types.size(), format("Number of channels in page %d is not equal to number of types %d", page.getChannelCount(), types.size())); for (int i = 0; i < types.size(); i++) { BlockBuilder blockBuilder = pageBuilder.getBlockBuilder(i); Block block = page.getBlock(i); for (int position = 0; position < page.getPositionCount(); position++) { if (block.isNull(position)) { blockBuilder.appendNull(); } else { block.writePositionTo(position, blockBuilder); } } } totalPositionCount += page.getPositionCount(); } pageBuilder.declarePositions(totalPositionCount); return pageBuilder.build(); }
Source:
public static boolean isRestfulWmtsRequest(MutableHttpServletRequest mutableRequest) { String url = mutableRequest.getRequestURL().toString(); String service = mutableRequest.getParameterIgnoreCase("service"); if (!StringUtils.isEmpty(service) && service.equalsIgnoreCase("wmts")) { return false; } return Pattern.compile(".*/geoserver.action/.*/wmts/\\d+/(.*)").matcher(url).matches(); }

Target:
public static boolean isRestfulWmtsRequest(MutableHttpServletRequest mutableRequest) { String url = mutableRequest.getRequestURL().toString(); boolean defaultRestfulRequest = Pattern.compile("[^\\/]*\\/[^\\/]*[^\\/]\\/\\d+\\/\\d+").matcher(url).find(); boolean isWmtsUrl = Pattern.compile(".*/geoserver.action/.*/wmts/\\d+/(.*)").matcher(url).matches(); return defaultRestfulRequest && isWmtsUrl; }
Source:
public Set<String> getIndexCollections() { return IndexCentralizerUtil.indexCollectionMap.keySet(); }

Target:
public List<String> getIndexCollections() { return collections; }
Source:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present").toString(), checkNotNull(postParams.get("imageRef"), "imageRef parameter not present").toString(), checkNotNull(postParams.get("flavorRef"), "flavorRef parameter not present").toString()); if (metadata.size() > 0) server.metadata = metadata; if (personality.size() > 0) server.personality = personality; if (keyName != null) server.key_name = keyName; if (userData != null) server.user_data = base64().encode(userData); if (securityGroupNames.size() > 0) { server.securityGroupNames = Sets.newLinkedHashSet(); for (String groupName : securityGroupNames) { server.securityGroupNames.add(new NamedThingy(groupName)); } } if (adminPass != null) { server.adminPass = adminPass; } if (networks.size() > 0) { server.networks = Sets.<ImmutableMap<String, String>>newLinkedHashSet(); for (String network : networks) { server.networks.add(ImmutableMap.of("uuid", network)); } } return bindToRequest(request, ImmutableMap.of("server", server)); }

Target:
public <R extends HttpRequest> R bindToRequest(R request, Map<String, Object> postParams) { ServerRequest server = new ServerRequest(checkNotNull(postParams.get("name"), "name parameter not present").toString(), checkNotNull(postParams.get("imageRef"), "imageRef parameter not present").toString(), checkNotNull(postParams.get("flavorRef"), "flavorRef parameter not present").toString()); if (metadata.size() > 0) server.metadata = metadata; if (personality.size() > 0) server.personality = personality; if (keyName != null) server.key_name = keyName; if (userData != null) server.user_data = base64().encode(userData); if (securityGroupNames.size() > 0) { server.securityGroupNames = Sets.newLinkedHashSet(); for (String groupName : securityGroupNames) { server.securityGroupNames.add(new NamedThingy(groupName)); } } if (adminPass != null) { server.adminPass = adminPass; } if (diskConfig != null) { server.diskConfig = diskConfig; } if (!networks.isEmpty()) { server.networks = Sets.newLinkedHashSet(); for (String network : networks) { server.networks.add(ImmutableMap.of("uuid", network)); } } return bindToRequest(request, ImmutableMap.of("server", server)); }
Source:
public Map<ColumnHandle, ColumnHandle> pushdownSubfieldPruning( ConnectorSession session, ConnectorTableHandle table, Map<ColumnHandle, List<SubfieldPath>> desiredSubfields) { if (!isSubfieldPushdownEnabled(session)) { return Collections.emptyMap(); } return desiredSubfields.keySet().stream() .map(column -> (TpchColumnHandle) column) .collect(toImmutableMap(Function.identity(), column -> new TpchColumnHandle(column.getColumnName(), column.getType(), Optional.of(desiredSubfields.get(column))))); }

Target:
public Map<ColumnHandle, ColumnHandle> pushdownSubfieldPruning( ConnectorSession session, ConnectorTableHandle table, Map<ColumnHandle, List<SubfieldPath>> desiredSubfields) { if (!isSubfieldPushdownEnabled(session)) { return ImmutableMap.of(); } return desiredSubfields.keySet().stream() .map(column -> (TpchColumnHandle) column) .collect(toImmutableMap(Function.identity(), column -> new TpchColumnHandle(column.getColumnName(), column.getType(), desiredSubfields.get(column)))); }
Source:
public Set<Integer> addContainers(Integer count) { List<String> auroraCmd = new ArrayList<>(Arrays.asList( "aurora", "job", "add", "--wait-until", "RUNNING", jobSpec + "/0", count.toString(), "--verbose")); LOG.info(String.format("Requesting %s new aurora containers %s", count, auroraCmd)); StringBuilder stderr = new StringBuilder(); if (!runProcess(auroraCmd, null, stderr)) { throw new RuntimeException("Failed to create " + count + " new aurora instances"); } String stdoutStr = stderr.toString(); String pattern = "Querying instance statuses: ["; int idx1 = stdoutStr.indexOf(pattern) + pattern.length(); int idx2 = stdoutStr.indexOf("]", idx1); String containerIdStr = stdoutStr.substring(idx1, idx2); LOG.info("container IDs returned by Aurora " + containerIdStr); return Arrays.asList(containerIdStr.split(", ")) .stream().map(x->Integer.valueOf(x)).collect(Collectors.toSet()); }

Target:
public Set<Integer> addContainers(Integer count) { List<String> auroraCmd = new ArrayList<>(Arrays.asList( "aurora", "job", "add", "--wait-until", "RUNNING", jobSpec + "/0", count.toString(), "--verbose")); LOG.info(String.format("Requesting %s new aurora containers %s", count, auroraCmd)); StringBuilder stderr = new StringBuilder(); if (!runProcess(auroraCmd, null, stderr)) { throw new RuntimeException("Failed to create " + count + " new aurora instances"); } if (stderr.length() <= 0) { throw new RuntimeException("empty output by Aurora"); } return extractContainerIds(stderr.toString()); }
Source:
public ExtensionScript getExtensionScript() { return this.extensionScript; }

Target:
protected ExtensionScript getExtensionScript() { return this.extensionScript; }
Source:
public void save() { activate(); log.info("Save editor"); try { new ShellMenuItem(new WorkbenchShell(), "File", "Save").select(); } catch (CoreLayerException coreExc) { if (coreExc.getMessage().contains("Menu item is not enabled")) { throw new WorkbenchLayerException("Menu item 'Save' is not enabled"); } throw coreExc; } new WaitWhile(new EditorIsDirty(this)); activate(); }

Target:
public void save() { activate(); log.info("Save editor"); ShellMenuItem saveItem = new ShellMenuItem(new WorkbenchShell(), "File", "Save"); if (saveItem.isEnabled()) { saveItem.select(); } else { throw new WorkbenchLayerException("Menu item 'Save' is not enabled"); } new WaitWhile(new EditorIsDirty(this)); activate(); }
Source:
public void testGoBackToDiscardXChanges() { onBrickAtPosition(brickPosition).checkShowsText(R.string.brick_place_at); onBrickAtPosition(brickPosition).onFormulaTextField(R.id.brick_place_at_edit_text_x) .perform(click()); onFormulaEditor() .performEnterFormula("1234"); pressBack(); onView(withText(R.string.formula_editor_discard_changes_dialog_title)) .check(matches(isDisplayed())); onView(withText(no)) .perform(click()); onToast(withText(R.string.formula_editor_changes_discarded)) .check(matches(isDisplayed())); onBrickAtPosition(brickPosition).onFormulaTextField(R.id.brick_place_at_edit_text_x) .checkShowsNumber(0); }

Target:
public void testGoBackToDiscardXChanges() { onBrickAtPosition(brickPosition).checkShowsText(R.string.brick_place_at); onBrickAtPosition(brickPosition).onFormulaTextField(R.id.brick_place_at_edit_text_x) .perform(click()); onFormulaEditor() .performEnterFormula("1234"); pressBack(); onView(withText(R.string.formula_editor_save_changes_dialog_title)) .check(matches(isDisplayed())); onView(withText(no)) .perform(click()); onToast(withText(R.string.formula_editor_changes_discarded)) .check(matches(isDisplayed())); onBrickAtPosition(brickPosition).onFormulaTextField(R.id.brick_place_at_edit_text_x) .checkShowsNumber(0); }
Source:
public void dockerMachineTestFileScanner(){ DumbSlave dockerSlave = (DumbSlave) getDockerSlave(dockerContainer.get()); FreeStyleJob job = prepairDockerSlave(dockerSlave); job.configure(); job.copyResource(resource("/warnings_plugin/out.txt")); job.addPublisher(WarningsPublisher.class).addWorkspaceFileScanner(JAVA_ID, "out.txt"); job.save(); Build build = job.startBuild().shouldSucceed(); assertThatActionExists(job, build, "Java Warnings"); }

Target:
public void dockerMachineTestFileScanner(){ DumbSlave dockerSlave = getDockerSlave(dockerContainer.get()); FreeStyleJob job = prepareDockerSlave(dockerSlave); job.configure(); job.copyResource(resource("/warnings_plugin/out.txt")); job.addPublisher(WarningsPublisher.class).addWorkspaceFileScanner(JAVA_ID, "out.txt"); job.save(); Build build = job.startBuild().shouldSucceed(); assertThatActionExists(job, build, "Java Warnings"); build.open(); assertThat(driver, hasContent("Java Warnings: " + 2)); }
Source:
private static WorkloadClockConfiguration generateTps(JLoadProfileTps jLoadProfile) { TpsClockConfiguration tpsClockConfiguration = new TpsClockConfiguration(); tpsClockConfiguration.setValue(jLoadProfile.getTransactionsPerSecond()); tpsClockConfiguration.setWarmUpTime(jLoadProfile.getWarmUpTimeInSeconds()); tpsClockConfiguration.setMaxThreadNumber((int) jLoadProfile.getMaxLoadThreads()); tpsClockConfiguration.setTickInterval(jLoadProfile.getTickInterval()); return tpsClockConfiguration; }

Target:
private static WorkloadClockConfiguration generateTps(JLoadProfileTps jLoadProfile) { TpsClockConfiguration tpsClockConfiguration = new TpsClockConfiguration(); tpsClockConfiguration.setValue(jLoadProfile.getTransactionsPerSecond()); tpsClockConfiguration.setWarmUpTime(jLoadProfile.getWarmUpTimeInMilliseconds()); tpsClockConfiguration.setMaxThreadNumber((int) jLoadProfile.getMaxLoadThreads()); tpsClockConfiguration.setTickInterval(jLoadProfile.getTickInterval()); return tpsClockConfiguration; }
Source:
public void delete(String id) { CuratorFramework client = zkConnection.getClient(); try { client.setData().forPath( Paths.build(Paths.JOB_DEPLOYMENTS, id, Paths.STATUS), ZooKeeperUtils.mapToBytes(new DeploymentUnitStatus( DeploymentUnitStatus.State.undeploying).toMap())); } catch (Exception e) { logger.warn("Exception while transitioning job state to " + DeploymentUnitStatus.State.undeploying, e); } try { client.delete().deletingChildrenIfNeeded() .forPath(Paths.build(Paths.JOB_DEPLOYMENTS, id)); } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, KeeperException.NoNodeException.class); } }

Target:
public void delete(String id) { CuratorFramework client = zkConnection.getClient(); try { client.setData().forPath( Paths.build(Paths.JOB_DEPLOYMENTS, id, Paths.STATUS), ZooKeeperUtils.mapToBytes(new DeploymentUnitStatus( DeploymentUnitStatus.State.undeploying).toMap())); } catch (Exception e) { logger.warn("Exception while transitioning job '{}' state to {}", id, DeploymentUnitStatus.State.undeploying, e); } try { client.delete().deletingChildrenIfNeeded() .forPath(Paths.build(Paths.JOB_DEPLOYMENTS, id)); } catch (Exception e) { ZooKeeperUtils.wrapAndThrowIgnoring(e, KeeperException.NoNodeException.class); } }
Source:
Result process(Path localPath, Path absolutePath, ParseResult<CompilationUnit> result) throws IOException; } private final Path root; private final Map<Path, ParseResult<CompilationUnit>> content = new HashMap<>(); private JavaParser javaParser = new JavaParser(); public SourceRoot(Path root) { if (Files.isRegularFile(root)) { throw new IllegalArgumentException("Only directories are allowed as root path!"); } this.root = root.normalize(); Log.info("New source root at \"%s\"", this.root); }

Target:
Result process(Path localPath, Path absolutePath, ParseResult<CompilationUnit> result) throws IOException; } private final Path root; private final Map<Path, ParseResult<CompilationUnit>> content = new HashMap<>(); private JavaParser javaParser = new JavaParser(); public SourceRoot(Path root) { if (!Files.isDirectory(root)) { throw new IllegalArgumentException("Only directories are allowed as root path!"); } this.root = root.normalize(); Log.info("New source root at \"%s\"", this.root); }
Source:
public void setupNewValue(Message message) { if (message.getContent() == null) { return; } Map<String, Map<String,String>> dataMap = ((Map<String, Map<String, String>>) message.getContent().get(DATA)); if (dataMap != null && !dataMap.isEmpty()) { Map<String, String> stateMap = dataMap.get(STATE); if (stateMap != null && !stateMap.isEmpty()) { Object newValue = null; if (stateMap.containsKey("value")) { newValue = stateMap.get("value"); } else if (stateMap.containsKey("index")) { newValue = stateMap.get("index"); } widget.setValue(newValue); } } }

Target:
private void setupNewValue(Message message) { if (message.getContent() == null) { return; } Map<String, Map<String,String>> dataMap = ((Map<String, Map<String, String>>) message.getContent().get(DATA)); if (dataMap != null && !dataMap.isEmpty()) { Map<String, String> stateMap = dataMap.get(STATE); if (stateMap != null && !stateMap.isEmpty()) { getNewValue(stateMap).ifPresent(newValue -> widget.setValue(newValue)); } } }