auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testDebugContextRsAllocationCopy1D_Byte_BadCount() { setupAllocationCopyTests AC = new setupAllocationCopyTests(this, 1, 512, (RenderScript rs)-> new Type.Builder(rs, Element.I8(rs))); int Offset = AC.RN.nextInt(AC.Width); Soob.set_dstXOff(Offset); Soob.set_srcXOff(Offset); Soob.set_xCount(AC.ArrLen - Offset + 1); Soob.set_srcMip(0); Soob.set_dstMip(0); Soob.invoke_test1D(); AC.finishAllocationCopyTests(); assertTrue(mRanErrorHandler); RenderScript.releaseAllContexts(); }

Target:
public void testDebugContextRsAllocationCopy1D_Byte_BadCount() { SetupAllocationCopyTests AC = new SetupAllocationCopyTests(1, 512, (RenderScript rs)-> new Type.Builder(rs, Element.I8(rs)), 0x172d8abd); int Offset = AC.RN.nextInt(AC.Width); Soob.set_dstXOff(Offset); Soob.set_srcXOff(Offset); Soob.set_xCount(AC.Width - Offset + 1); Soob.set_srcMip(0); Soob.set_dstMip(0); Soob.invoke_test1D(); AC.finishAllocationCopyTests(); assertTrue(mRanErrorHandler); RenderScript.releaseAllContexts(); }
Source:
static Context mockPackageResourceContext() { Context context = mock(Context.class); PackageManager pm = mock(PackageManager.class); Resources res = mock(Resources.class); doReturn(pm).when(context).getPackageManager(); try { doReturn(res).when(pm).getResourcesForApplication(RESOURCE_PACKAGE); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException(e); } doReturn(RESOURCE_ID_1).when(res).getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE); System.out.println(RESOURCE_ID_URI); System.out.println(RESOURCE_TYPE_URI); return context; }

Target:
static Context mockPackageResourceContext() { Context context = mock(Context.class); PackageManager pm = mock(PackageManager.class); Resources res = mock(Resources.class); doReturn(pm).when(context).getPackageManager(); try { doReturn(res).when(pm).getResourcesForApplication(RESOURCE_PACKAGE); } catch (PackageManager.NameNotFoundException e) { throw new RuntimeException(e); } doReturn(RESOURCE_ID_1).when(res).getIdentifier(RESOURCE_NAME, RESOURCE_TYPE, RESOURCE_PACKAGE); return context; }
Source:
public static Class<?> getFieldClass(FieldDescriptor field) { final FieldDescriptor.JavaType javaType = field.getJavaType(); switch (javaType) { case INT: return Integer.class; case LONG: return Long.class; case FLOAT: return Float.class; case DOUBLE: return Double.class; case BOOLEAN: return Boolean.class; case STRING: return String.class; case BYTE_STRING: return ByteString.class; case ENUM: final String enumTypeNameStr = field.getEnumType().getFullName(); final TypeName enumTypeName = TypeName.of(enumTypeNameStr); return tryConvertToClass(enumTypeName); case MESSAGE: final Descriptor messageType = field.getMessageType(); final TypeName typeName = TypeName.of(messageType); return tryConvertToClass(typeName); } throw new IllegalStateException("Unknown field type discovered: " + field.getFullName()); }

Target:
public static Class<?> getFieldClass(FieldDescriptor field) { final FieldDescriptor.JavaType javaType = field.getJavaType(); switch (javaType) { case INT: return Integer.class; case LONG: return Long.class; case FLOAT: return Float.class; case DOUBLE: return Double.class; case BOOLEAN: return Boolean.class; case STRING: return String.class; case BYTE_STRING: return ByteString.class; case ENUM: final String enumTypeName = field.getEnumType().getFullName(); final Class<? extends Message> enumClass = toMessageClass(TypeName.of(enumTypeName)); return enumClass; case MESSAGE: final TypeName typeName = TypeName.of(field.getMessageType()); final Class<? extends Message> msgClass = toMessageClass(typeName); return msgClass; } throw new IllegalArgumentException("Unknown field type discovered: " + field.getFullName()); }
Source:
public void testAddSingleStitchPoint() { final int expectedInvocations = 1; testSprite1.getActionFactory().createStitchAction(testSprite1).act(1f); Mockito.verify(StageActivity.stageListener.embroideryList, Mockito.times(expectedInvocations)).add(new StitchPoint(spriteCoords1, StitchPoint.NORMALSTITCH, testSprite1)); }

Target:
public void testAddSingleStitchPoint() { ActionFactory.createStitchAction(testSprite1).act(1f); Mockito.verify(StageActivity.stageListener.embroideryPatternManager, Mockito.times(1)).addStitchCommand( Mockito.eq(new DSTStitchCommand(spriteCoords1.x, spriteCoords1.y, testSprite1.look.getZIndex(), testSprite1))); }
Source:
private DateTime getLatest(DateTime date1, DateTime date2) { return date1.isAfter(date2) ? date1 : date2; }

Target:
private DateTime getLatest(DateTime date1, DateTime date2) { if (date1 == null) { return date2; } else if (date2 == null) { return date1; } else { return date1.isAfter(date2) ? date1 : date2; } }
Source:
private Object removeObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("REPLACE must not include data argument"); } if(!context.ids.isPresent()) { throw new BadRequestException("REPLACE must include ids argument"); } Set<PersistentResource> toRemove = (Set<PersistentResource>) fetchObjects(context); if(!context.isRoot()) { toRemove.forEach(item -> context.parentResource.removeRelation(context.field.getName(), item)); } else { return deleteObjects(toRemove); } return toRemove; }

Target:
private Object removeObjects(Environment context) { if(context.data.isPresent()) { throw new BadRequestException("REPLACE must not include data argument"); } if(!context.ids.isPresent()) { throw new BadRequestException("REPLACE must include ids argument"); } Set<PersistentResource> toRemove = (Set<PersistentResource>) fetchObjects(context); if(!context.isRoot()) { toRemove.forEach(item -> context.parentResource.removeRelation(context.field.getName(), item)); } else { toRemove.forEach(PersistentResource::deleteResource); } return toRemove; }
Source:
protected void doExecute() { if (canExecute()) { if (isSource) { DirectedRelationshipPropertyPath directedRelationshipPropertyPath = UMLUtil.getStereotypeApplication(directedRelationShipPropertyPath, DirectedRelationshipPropertyPath.class); directedRelationshipPropertyPath.getSourcePropertyPath().clear(); directedRelationshipPropertyPath.getSourcePropertyPath().addAll(PropertyPath.getPropertyPath(sourceView)); directedRelationshipPropertyPath.setSourceContext(PropertyPath.getCompositeContext(sourceView)); } else { DirectedRelationshipPropertyPath directedRelationshipPropertyPath = UMLUtil.getStereotypeApplication(directedRelationShipPropertyPath, DirectedRelationshipPropertyPath.class); directedRelationshipPropertyPath.getTargetPropertyPath().clear(); directedRelationshipPropertyPath.getTargetPropertyPath().addAll(PropertyPath.getPropertyPath(sourceView)); directedRelationshipPropertyPath.setTargetContext(PropertyPath.getCompositeContext(sourceView)); } } }

Target:
protected void doExecute() { if (canExecute()) { if (isSource) { DirectedRelationshipPropertyPath stereotypeApplication = UMLUtil.getStereotypeApplication(directedRelationShipPropertyPath, DirectedRelationshipPropertyPath.class); stereotypeApplication.getSourcePropertyPath().clear(); stereotypeApplication.getSourcePropertyPath().addAll(PropertyPathUtil.getPropertyPath(sourceView)); stereotypeApplication.setSourceContext(PropertyPathUtil.getCompositeContext(sourceView)); } else { DirectedRelationshipPropertyPath stereotypeApplication = UMLUtil.getStereotypeApplication(directedRelationShipPropertyPath, DirectedRelationshipPropertyPath.class); stereotypeApplication.getTargetPropertyPath().clear(); stereotypeApplication.getTargetPropertyPath().addAll(PropertyPathUtil.getPropertyPath(sourceView)); stereotypeApplication.setTargetContext(PropertyPathUtil.getCompositeContext(sourceView)); } } }
Source:
public void write(Object source, Document sink) { Assert.notNull(source, "source to map must not be null"); source = maybeCallbackBeforeConvert(source); if (source instanceof Map) { sink.putAll((Map<String, Object>) source); return; } Class<?> entityType = ClassUtils.getUserClass(source.getClass()); TypeInformation<?> type = ClassTypeInformation.from(entityType); if (requiresTypeHint(type, source.getClass(), null)) { typeMapper.writeType(source.getClass(), sink); } Optional<Class<?>> customTarget = conversions.getCustomWriteTarget(entityType, Map.class); if (customTarget.isPresent()) { sink.putAll(conversionService.convert(source, Map.class)); return; } ElasticsearchPersistentEntity<?> entity = type.getType().equals(entityType) ? mappingContext.getRequiredPersistentEntity(type) : mappingContext.getRequiredPersistentEntity(entityType); writeEntity(entity, source, sink, null); }

Target:
public void write(Object source, Document sink) { Assert.notNull(source, "source to map must not be null"); if (source instanceof Map) { sink.putAll((Map<String, Object>) source); return; } Class<?> entityType = ClassUtils.getUserClass(source.getClass()); TypeInformation<?> type = ClassTypeInformation.from(entityType); if (requiresTypeHint(type, source.getClass(), null)) { typeMapper.writeType(source.getClass(), sink); } Optional<Class<?>> customTarget = conversions.getCustomWriteTarget(entityType, Map.class); if (customTarget.isPresent()) { sink.putAll(conversionService.convert(source, Map.class)); return; } ElasticsearchPersistentEntity<?> entity = type.getType().equals(entityType) ? mappingContext.getRequiredPersistentEntity(type) : mappingContext.getRequiredPersistentEntity(entityType); writeEntity(entity, source, sink, null); }
Source:
private void handleAnyChildSPMTaskCompletion(boolean succeeded) { if (getParameters().getCommandStep() != RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { return; } syncChildCommandList(); Guid currentChildId = getCurrentChildId(); if (!Guid.isNullOrEmpty(currentChildId)) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(currentChildId); CommandEntity cmdEntity = CommandCoordinatorUtil.getCommandEntity(currentChildId); if (command != null && cmdEntity != null && !cmdEntity.isCallbackNotified()) { if (!succeeded) { command.getParameters().setTaskGroupSuccess(false); } Backend.getInstance().endAction(VdcActionType.DestroyImage, command.getParameters(), cloneContextAndDetachFromParent()); if (succeeded && CommandCoordinatorUtil.getCommandEntity(currentChildId) != null) { CommandCoordinatorUtil.getCommandEntity(currentChildId).setCallbackNotified(true); } } } }

Target:
private void handleAnyChildSPMTaskCompletion(boolean succeeded) { if (getParameters().getCommandStep() != RemoveSnapshotSingleDiskLiveStep.DESTROY_IMAGE) { return; } syncChildCommandList(); Guid currentChildId = getCurrentChildId(); if (!Guid.isNullOrEmpty(currentChildId)) { CommandBase<?> command = CommandCoordinatorUtil.retrieveCommand(currentChildId); CommandEntity cmdEntity = CommandCoordinatorUtil.getCommandEntity(currentChildId); if (command != null && cmdEntity != null && !cmdEntity.isCallbackNotified()) { if (!succeeded) { command.getParameters().setTaskGroupSuccess(false); } Backend.getInstance().endAction(VdcActionType.DestroyImage, command.getParameters(), cloneContextAndDetachFromParent()); if (succeeded && cmdEntity != null) { cmdEntity.setCallbackNotified(true); } } } }
Source:
public void configureRequest(final IEditCommandRequest request) { super.configureRequest(request); if (false == request instanceof ConfigureRequest) { return; } StereotypeToApply namingStereotype = null; final List<StereotypeToApply> stereotypes = this.configuration.getStereotypesToApply(); for (int i = stereotypes.size() - 1; i >= 0; i--) { final StereotypeToApply current = stereotypes.get(i); if (current.isUpdateName()) { namingStereotype = current; break; } } if (null != namingStereotype) { request.setParameter(RequestParameterConstants.BASE_NAME_TO_SET, NamedElementUtil.getNameFromQualifiedName(namingStereotype.getStereotypeQualifiedName())); } }

Target:
public void configureRequest(final IEditCommandRequest request) { super.configureRequest(request); if (false == request instanceof ConfigureRequest) { return; } final List<StereotypeToApply> stereotypes = this.configuration.getStereotypesToApply(); for (int i = stereotypes.size() - 1; i >= 0; i--) { final StereotypeToApply current = stereotypes.get(i); if (current.isUpdateName()) { request.setParameter(RequestParameterConstants.BASE_NAME_TO_SET, NamedElementUtil.getNameFromQualifiedName(current.getStereotypeQualifiedName())); break; } } }
Source:
public void testExecuteQueryCommand() { when(params.getNetworkId()).thenReturn(networkId); setupVdsDao(); setupVdsNetworkInterfaceDao(); Pair<VdsNetworkInterface, VDS> VdsInterfaceVdsPair = new Pair(vdsNetworkInterface, vds); List<Pair<VdsNetworkInterface, VDS>> expected = Collections.singletonList(VdsInterfaceVdsPair); GetVdsAndNetworkInterfacesByNetworkIdQuery<NetworkIdParameters> query = getQuery(); query.executeQueryCommand(); assertEquals("Wrong result returned", expected, getQuery().getQueryReturnValue().getReturnValue()); }

Target:
public void testExecuteQueryCommand() { when(params.getNetworkId()).thenReturn(networkId); setupVdsDao(); setupVdsNetworkInterfaceDao(); Pair<VdsNetworkInterface, VDS> vdsInterfaceVdsPair = new Pair(vdsNetworkInterface, vds); List<Pair<VdsNetworkInterface, VDS>> expected = Collections.singletonList(vdsInterfaceVdsPair); GetVdsAndNetworkInterfacesByNetworkIdQuery<NetworkIdParameters> query = getQuery(); query.executeQueryCommand(); assertEquals("Wrong result returned", expected, getQuery().getQueryReturnValue().getReturnValue()); }
Source:
private MetricDatum toMetric(Result result) { ImmutableList<String> typeNames = getTypeNames(); Map<String, String> typeNameValues = result.getTypeNameMap(); ImmutableList<Dimension> dimensions = FluentIterable.from(this.dimensions) .append(toDimensions(typeNames, typeNameValues)) .toList(); return new MetricDatum() .withDimensions(dimensions) .withMetricName(result.getAttributeName()) .withTimestamp(new Date(result.getEpoch())) .withValue(toDouble(result.getValue())); }

Target:
private MetricDatum toMetric(Result result) { ImmutableList<String> typeNames = getTypeNames(); Map<String, String> typeNameValues = result.getTypeNameMap(); ImmutableList<Dimension> dimensions = FluentIterable.from(this.dimensions) .append(toDimensions(typeNames, typeNameValues)) .toList(); String metricName = result.getValuePath().isEmpty() ? result.getAttributeName() : result.getAttributeName() + "_" + KeyUtils.getValuePathString(result); return new MetricDatum() .withDimensions(dimensions) .withMetricName(metricName) .withTimestamp(new Date(result.getEpoch())) .withValue(toDouble(result.getValue())); }
Source:
static String extractMsi(String msiFile) { Process process = null; try { process = Runtime.getRuntime().exec( new String[] { "msiexec", "/a", msiFile, "/qn", "TARGETDIR=" + SeLionConstants.SELION_HOME_DIR }); process.waitFor(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not find file " + msiFile, e); } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Exception waiting for msiexec to be finished", e); } finally { process.destroy(); } moveExeFileToSeLionHomeAndDeleteExtras(); String exeFilePath = FileUtils.getFile(SeLionConstants.SELION_HOME_DIR + "MicrosoftWebDriver.exe") .getAbsolutePath(); LOGGER.exiting(exeFilePath); return exeFilePath; }

Target:
static String extractMsi(String msiFile) { Process process = null; String exeFilePath = null; boolean isMsiExtracted = true; try { process = Runtime.getRuntime().exec( new String[] { "msiexec", "/a", msiFile, "/qn", "TARGETDIR=" + SeLionConstants.SELION_HOME_DIR }); process.waitFor(); } catch (IOException e) { LOGGER.log(Level.SEVERE, "Could not find file " + msiFile, e); isMsiExtracted = false; } catch (InterruptedException e) { LOGGER.log(Level.SEVERE, "Exception waiting for msiexec to be finished", e); isMsiExtracted = false; } finally { process.destroy(); } if (isMsiExtracted) { moveExeFileToSeLionHomeAndDeleteExtras(); exeFilePath = FileUtils.getFile(SeLionConstants.SELION_HOME_DIR + SeLionConstants.EDGE_DRIVER) .getAbsolutePath(); } LOGGER.exiting(exeFilePath); return exeFilePath; }
Source:
public void shouldSubstituteCorrectly() throws IOException { StrLookup<?> dummyLookup = new StrLookup<Object>() { @Override public String lookup(String key) { return "baz"; } }; DummySourceProvider dummyProvider = new DummySourceProvider(); SubstitutingSourceProvider provider = new SubstitutingSourceProvider(dummyProvider, new StrSubstitutor(dummyLookup)); String results = new String(ByteStreams.toByteArray(provider.open("foo: ${bar}")), StandardCharsets.UTF_8); assertThat(results).isEqualTo("foo: baz"); try { dummyProvider.lastStream.read(); fail("IOException expected; stream should be closed"); } catch (IOException e) { assertThat(e).hasMessage("Stream closed"); } }

Target:
public void shouldSubstituteCorrectly() throws IOException { StrLookup<?> dummyLookup = new StrLookup<Object>() { @Override public String lookup(String key) { return "baz"; } }; DummySourceProvider dummyProvider = new DummySourceProvider(); SubstitutingSourceProvider provider = new SubstitutingSourceProvider(dummyProvider, new StrSubstitutor(dummyLookup)); String results = new String(ByteStreams.toByteArray(provider.open("foo: ${bar}")), StandardCharsets.UTF_8); assertThat(results).isEqualTo("foo: baz"); try { dummyProvider.lastStream.read(); failBecauseExceptionWasNotThrown(IOException.class); } catch (IOException e) { assertThat(e).hasMessage("Stream closed"); } }
Source:
public void init(Map<SystemStreamPartition, String> checkpointedChangelogSSPOffsets) { cleanBaseDirsAndReadOffsetFiles(new StorageConfig(config).getCleanLoggedStoreDirsOnInit()); setupBaseDirs(); validateChangelogStreams(); getOldestChangeLogOffsets(); registerStartingOffsets(); }

Target:
public void init(Map<SystemStreamPartition, String> checkpointedChangelogSSPOffsets) { cleanBaseDirsAndReadOffsetFiles(); setupBaseDirs(); validateChangelogStreams(); getOldestChangeLogOffsets(); registerStartingOffsets(); }
Source:
private void sendConstructionStartEvent(Vector3i centerBlock, BuildingType buildingType, EntityRef building, EntityRef playerEntity) { SpawnBlockRegionsComponent blockRegionsComponent = buildingTemplate.getComponent(SpawnBlockRegionsComponent.class); List<SpawnBlockRegionsComponent.RegionToFill> relativeRegions = blockRegionsComponent.regionsToFill; List<BlockRegion> absoluteRegions = new ArrayList<>(); for (SpawnBlockRegionsComponent.RegionToFill regionToFill : relativeRegions) { BlockRegion relativeRegion = regionToFill.region; BlockRegion absoluteRegion = relativeRegion.translate(centerBlock, new BlockRegion(BlockRegion.INVALID)); absoluteRegions.add(absoluteRegion); } long delay = buildingTemplate.getComponent(CompletionTimeComponent.class).completionDelay; playerEntity.send(new BuildingConstructionStartedEvent(absoluteRegions, buildingType, centerBlock, building, delay)); }

Target:
private void sendConstructionStartEvent(Vector3i centerBlock, BuildingType buildingType, EntityRef building, EntityRef playerEntity) { playerEntity.send(getBuildingConstructionStartedEvent(centerBlock, buildingType, building)); }
Source:
public static IContentManager getInstance(Context context) { if(Instance == null) Instance = new ContentManager(context); return Instance; }

Target:
public static IContentManager getInstance(Context context) { if(Instance == null){ Instance = new ContentManager(context); } return Instance; }
Source:
@Override protected FileMonitoringController doLaunch(FilePath ws, Launcher launcher, TaskListener listener, EnvVars envVars) throws IOException, InterruptedException { if (launcher.isUnix()) { throw new IOException("Batch scripts can only be run on Windows nodes"); } BatchController c = new BatchController(ws); String cmd; if (capturingOutput) { cmd = String.format("@echo off \r\ncmd /c \"\"%s\"\" > \"%s\" 2> \"%s\"\r\necho %%ERRORLEVEL%% > \"%s\"\r\n", quote(c.getBatchFile2(ws)), quote(c.getOutputFile(ws)), quote(c.getLogFile(ws)), quote(c.getResultFile(ws))); } else { cmd = String.format("@echo off \r\ncmd /c \"\"%s\"\" > \"%s\" 2>&1\r\necho %%ERRORLEVEL%% > \"%s\"\r\n", quote(c.getBatchFile2(ws)), quote(c.getLogFile(ws)), quote(c.getResultFile(ws))); } c.getBatchFile1(ws).write(cmd, "UTF-8"); c.getBatchFile2(ws).write(script, "UTF-8"); Launcher.ProcStarter ps = launcher.launch().cmds("cmd", "/c", "\"\"" + c.getBatchFile1(ws) + "\"\"").envs(escape(envVars)).pwd(ws).quiet(true); ps.readStdout().readStderr(); ps.start(); Proc p = ps.start(); c.registerForCleanup(p.getStdout()); c.registerForCleanup(p.getStderr()); return c; }

Target:
@Override protected FileMonitoringController doLaunch(FilePath ws, Launcher launcher, TaskListener listener, EnvVars envVars) throws IOException, InterruptedException { if (launcher.isUnix()) { throw new IOException("Batch scripts can only be run on Windows nodes"); } BatchController c = new BatchController(ws); String cmd; if (capturingOutput) { cmd = String.format("@echo off \r\ncmd /c \"\"%s\"\" > \"%s\" 2> \"%s\"\r\necho %%ERRORLEVEL%% > \"%s\"\r\n", quote(c.getBatchFile2(ws)), quote(c.getOutputFile(ws)), quote(c.getLogFile(ws)), quote(c.getResultFile(ws))); } else { cmd = String.format("@echo off \r\ncmd /c \"\"%s\"\" > \"%s\" 2>&1\r\necho %%ERRORLEVEL%% > \"%s\"\r\n", quote(c.getBatchFile2(ws)), quote(c.getLogFile(ws)), quote(c.getResultFile(ws))); } c.getBatchFile1(ws).write(cmd, "UTF-8"); c.getBatchFile2(ws).write(script, "UTF-8"); Launcher.ProcStarter ps = launcher.launch().cmds("cmd", "/c", "\"\"" + c.getBatchFile1(ws) + "\"\"").envs(escape(envVars)).pwd(ws).quiet(true); ps.readStdout().readStderr(); Proc p = ps.start(); c.registerForCleanup(p.getStdout()); c.registerForCleanup(p.getStderr()); return c; }
Source:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append('^'); builder.append(commit.abbreviate(7).name()); builder.append(' ').append('('); PersonIdent author = commit.getAuthorIdent(); builder.append(author.getName()); builder.append(' '); final SimpleDateFormat format; format = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy Z", Locale.US); format.setTimeZone(author.getTimeZone()); builder.append(format.format(author.getWhen())); builder.append(' '); builder.append(number + 1); builder.append(')'); return builder.toString(); }

Target:
public String toString() { StringBuilder builder = new StringBuilder(); builder.append('^'); builder.append(commit.abbreviate(7).name()); builder.append(' ').append('('); PersonIdent author = commit.getAuthorIdent(); if (author != null) { builder.append(author.getName()); builder.append(' '); final SimpleDateFormat format; format = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy Z", Locale.US); format.setTimeZone(author.getTimeZone()); builder.append(format.format(author.getWhen())); builder.append(' '); } builder.append(number + 1); builder.append(')'); return builder.toString(); }
Source:
public void test_retrieve_segment_information() { execute("create table t1 (id INTEGER, name STRING) clustered into 1 shards with (number_of_replicas = 1)"); ensureYellow(); execute("insert into t1 values (1, 'test')"); refresh(); execute("select table_name, shard_id, segment_name, generation, num_docs, deleted_docs, size, memory, " + "committed, search, compound, version, node, attributes, primary from sys.segments order by primary desc"); assertThat(response.rowCount(), greaterThan(0L)); Arrays.stream(response.rows()).forEach(this::validateResponse); }

Target:
public void test_retrieve_segment_information() { execute("create table t1 (id INTEGER, name STRING) clustered into 1 shards with (number_of_replicas = 1)"); execute("insert into t1 values (1, 'test')"); refresh(); ensureGreen(); execute("select table_name, shard_id, segment_name, generation, num_docs, deleted_docs, size, memory, " + "committed, search, compound, version, node, node['id'], node['name'], attributes, primary from sys.segments order by primary desc"); assertThat(response.rowCount(), is(2L)); validateResponse(response.rows()[0], true); validateResponse(response.rows()[1],false); }
Source:
public void testPushTimeTwoWeeksFromNow() { ParsePush.State.Builder builder = new ParsePush.State.Builder(); ParsePush.State state = builder .pushTime(System.currentTimeMillis() + 60*60*24*7*3) .data(new JSONObject()) .build(); }

Target:
public void testPushTimeTwoWeeksFromNow() { ParsePush.State.Builder builder = new ParsePush.State.Builder(); ParsePush.State state = builder .pushTime(System.currentTimeMillis() / 1000 + 60*60*24*7*3) .data(new JSONObject()) .build(); }
Source:
public String getParentId(String testId){ return (String)getHibernateTemplate().find("select distinct w.parentId from WorkloadData w where w.taskId=?", testId).get(0); }

Target:
private String getParentId(String testId) { return (String) getHibernateTemplate().find("select distinct w.parentId from WorkloadData w where w.taskId=? and w.sessionId=?", testId, sessionId).get(0); }
Source:
public Api getAPIForSite(Site site) { if (!sentMccMnc) { String mccMnc = Utils.getMccMnc(this); if (mccMnc != null) { HashMap<String,String> customHeaders = new HashMap<String,String>(); customHeaders.put("X-MCCMNC", mccMnc); if (!apis.containsKey(site.getDomain() + customHeaders.hashCode())) { apis.put(site.getDomain() + customHeaders.hashCode(), new Api(site.getApiDomain(), getUserAgent(), customHeaders)); } sentMccMnc = true; return apis.get(site.getDomain() + customHeaders.hashCode()); } } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }

Target:
public Api getAPIForSite(Site site) { if (!MccMncStateHandler.hasMccMncBeenSent()) { Api api = MccMncStateHandler.makeApiWithMccMncHeaderEnrichment(this, site, getUserAgent()); if (api != null) { return api; } } if (!apis.containsKey(site.getDomain())) { apis.put(site.getDomain(), new Api(site.getApiDomain(), getUserAgent())); } return apis.get(site.getDomain()); }
Source:
public void writeEntityToNBT(NBTTagCompound nbt) { super.writeEntityToNBT(nbt); nbt.setTag("spells", NBTExtras.listToNBT(getSpells(), spell -> new NBTTagString(spell.getRegistryName().toString()))); }

Target:
public void writeEntityToNBT(NBTTagCompound nbt) { super.writeEntityToNBT(nbt); nbt.setTag("spells", NBTHelper.getTagList(getSpells(), spell -> new NBTTagString(spell.getRegistryName().toString()))); }
Source:
public boolean selectDates(Collection<Date> selectedDates, boolean smoothScroll) { boolean wasSelected = false; int monthIndex = 1; if (selectedDates != null) { for (Date date : selectedDates) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); monthIndex = monthCellWithMonthIndex != null ? monthCellWithMonthIndex.monthIndex : 1; if (monthCellWithMonthIndex == null || !isDateSelectable(date)) { return false; } wasSelected = doSelectDate(date, monthCellWithMonthIndex.cell); } } if (wasSelected) { scrollToSelectedMonth(monthIndex, smoothScroll); } return wasSelected; }

Target:
public boolean selectDates(Collection<Date> selectedDates, boolean smoothScroll) { boolean firstDateThatWasSelected = false; int firstMonthIndex = 1; int monthIndex = 1; if (selectedDates != null) { for (Date date : selectedDates) { validateDate(date); MonthCellWithMonthIndex monthCellWithMonthIndex = getMonthCellWithIndexByDate(date); if (monthCellWithMonthIndex == null || !isDateSelectable(date)) { return false; } monthIndex = monthCellWithMonthIndex.monthIndex; if (!firstDateThatWasSelected) { firstDateThatWasSelected = doSelectDate(date, monthCellWithMonthIndex.cell); firstMonthIndex = monthIndex; } } } if (firstDateThatWasSelected) { scrollToSelectedMonth(firstMonthIndex, smoothScroll); } return firstDateThatWasSelected; }
Source:
public void userCanBeTestForBeingCollaborator() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_NO_CONTENT, Json.createArrayBuilder() .add(json("octocat2")) .add(json("dummy")) .build().toString() ) ).start(); final Collaborators users = new RtCollaborators( new JdkRequest(container.home()), repo() ); MatcherAssert.assertThat( users.isCollaborator("octocat2"), Matchers.equalTo(true) ); container.stop(); }

Target:
public void userCanBeTestForBeingCollaborator() throws Exception { final MkContainer container = new MkGrizzlyContainer().next( new MkAnswer.Simple( HttpURLConnection.HTTP_NO_CONTENT, Json.createArrayBuilder() .add(json("octocat2")) .add(json("dummy")) .build().toString() ) ).start(); final Collaborators users = new RtCollaborators( new JdkRequest(container.home()), repo() ); try { MatcherAssert.assertThat( users.isCollaborator("octocat2"), Matchers.equalTo(true) ); } finally { container.stop(); } }
Source:
public CaseChangeMenu(final StringProperty text) { super(Localization.lang("Change case")); Objects.requireNonNull(text); List<Formatter> caseChangers = new ArrayList<>(Formatters.getCaseChangers()); caseChangers.add(new ProtectTermsFormatter(Globals.protectedTermsLoader)); for (final Formatter caseChanger : caseChangers) { CustomMenuItem menuItem = new CustomMenuItem(new Label(caseChanger.getName())); Tooltip toolTip = new Tooltip(caseChanger.getDescription()); Tooltip.install(menuItem.getContent(), toolTip); menuItem.setOnAction(event -> text.set(caseChanger.format(text.get()))); this.getItems().add(menuItem); } }

Target:
public CaseChangeMenu(final StringProperty text) { super(Localization.lang("Change case")); Objects.requireNonNull(text); List<Formatter> caseChangers = new ArrayList<>(); caseChangers.addAll(Formatters.getCaseChangers()); caseChangers.add(new ProtectTermsFormatter(Globals.protectedTermsLoader)); for (final Formatter caseChanger : caseChangers) { CustomMenuItem menuItem = new CustomMenuItem(new Label(caseChanger.getName())); Tooltip toolTip = new Tooltip(caseChanger.getDescription()); Tooltip.install(menuItem.getContent(), toolTip); menuItem.setOnAction(event -> text.set(caseChanger.format(text.get()))); this.getItems().add(menuItem); } }
Source:
Map<String, Symbol> membersByName() { if (membersByName == null) { membersByName = declaredMembers().stream().collect(Collectors.toMap(Symbol::name, m -> m, (s1, s2) -> s1)); } return membersByName; }

Target:
private Map<String, Symbol> membersByName() { if (membersByName == null) { membersByName = declaredMembers().stream().collect(Collectors.toMap(Symbol::name, m -> m, (s1, s2) -> s1)); } return membersByName; }
Source:
public ImmutableOptionalValue<UUID> owner() { return ImmutableDataCachingUtil.getValue(ImmutableSpongeOptionalValue.class, Keys.TAMED_OWNER, Optional.fromNullable(this.owner), Optional.<UUID>absent()); }

Target:
public ImmutableOptionalValue<UUID> owner() { return createValue(owner); }
Source:
public void testBasicScriptFailure() { RuntimeEngine runtime1 = manager.getRuntimeEngine(ProcessInstanceIdContext.get()); KieSession ksession1 = runtime1.getKieSession(); assertNotNull(ksession1); try { ksession1.startProcess("BrokenScriptTask"); fail("Start process should fail due to broken script"); } catch (Throwable e) { } manager.disposeRuntimeEngine(runtime1); ExecutionErrorManager errorManager = ((AbstractRuntimeManager) manager).getExecutionErrorManager(); ExecutionErrorStorage storage = errorManager.getStorage(); List<ExecutionError> errors = storage.list(0, 10); assertNotNull(errors); assertEquals(1, errors.size()); assertExecutionError(errors.get(0), "Process", "BrokenScriptTask", "Hello"); manager.close(); }

Target:
public void testBasicScriptFailure() { RuntimeEngine runtime1 = manager.getRuntimeEngine(ProcessInstanceIdContext.get()); KieSession ksession1 = runtime1.getKieSession(); assertNotNull(ksession1); try { ksession1.startProcess("BrokenScriptTask"); fail("Start process should fail due to broken script"); } catch (Throwable e) { } manager.disposeRuntimeEngine(runtime1); ExecutionErrorManager errorManager = ((AbstractRuntimeManager) manager).getExecutionErrorManager(); ExecutionErrorStorage storage = errorManager.getStorage(); List<ExecutionError> errors = storage.list(0, 10); assertNotNull(errors); assertEquals(1, errors.size()); assertExecutionError(errors.get(0), "Process", "BrokenScriptTask", "Hello"); }
Source:
private void generateBaseContainerSource() { javaBuffer.addImport(Collections.class); javaBuffer.addImport(List.class); javaBuffer.addImport(ListWithHref.class); javaBuffer.addImport(UnmodifiableListWithHref.class); JavaClassName containerName = javaTypes.getBaseContainerName(); javaBuffer.addLine("public class %1$s {", containerName.getSimpleName()); javaBuffer.addLine( "protected static <E> List<E> makeUnmodifiableList(List<E> original) {"); javaBuffer.addLine( "if (original == null) {"); javaBuffer.addLine( "return Collections.emptyList();"); javaBuffer.addLine( "}"); javaBuffer.addLine( "else {"); javaBuffer.addLine( "if (original instanceof ListWithHref) {"); javaBuffer.addLine( "return new UnmodifiableListWithHref((ListWithHref)original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "return Collections.unmodifiableList(original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "}"); javaBuffer.addLine("}"); }

Target:
private void generateBaseContainerSource() { javaBuffer.addImport(ArrayList.class); javaBuffer.addImport(ArrayListWithHref.class); javaBuffer.addImport(Collections.class); javaBuffer.addImport(List.class); javaBuffer.addImport(ListWithHref.class); javaBuffer.addImport(UnmodifiableListWithHref.class); JavaClassName containerName = javaTypes.getBaseContainerName(); javaBuffer.addLine("public class %1$s {", containerName.getSimpleName()); javaBuffer.addLine( "protected static <E> List<E> makeUnmodifiableList(List<E> original) {"); javaBuffer.addLine( "if (original == null) {"); javaBuffer.addLine( "return Collections.emptyList();"); javaBuffer.addLine( "}"); javaBuffer.addLine( "else {"); javaBuffer.addLine( "if (original instanceof ListWithHref) {"); javaBuffer.addLine( "return new UnmodifiableListWithHref((ListWithHref) original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "return Collections.unmodifiableList(original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "}"); javaBuffer.addLine(); javaBuffer.addLine( "protected static <E> List<E> makeArrayList(List<E> original) {"); javaBuffer.addLine( "if (original == null) {"); javaBuffer.addLine( "return Collections.emptyList();"); javaBuffer.addLine( "}"); javaBuffer.addLine( "else {"); javaBuffer.addLine( "if (original instanceof ListWithHref) {"); javaBuffer.addLine( "return new ArrayListWithHref<E>((ListWithHref) original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "return new ArrayList<E>(original);"); javaBuffer.addLine( "}"); javaBuffer.addLine( "}"); javaBuffer.addLine("}"); }
Source:
public boolean isResolvedStateDisplayed(double defaultVideoHeight, double resolvedVideoHeight) { int percentResult = (int)Math.round(100-(100/(defaultVideoHeight/resolvedVideoHeight))); if (percentResult == EXPECTED_PERCENTAGE_DIFFERENCE_IN_VIDEO_AD_HEIGHT) { return true; } return false; }

Target:
public boolean isResolvedStateDisplayed(double defaultVideoHeight, double resolvedVideoHeight) { return EXPECTED_PERCENTAGE_DIFFERENCE_IN_VIDEO_AD_HEIGHT == getStatesPercentageDifference(defaultVideoHeight, resolvedVideoHeight); }
Source:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setAvailableFormat(); waitingDialog = new ProgressDialog(getActivity()); TextView findBattle = (TextView) view.findViewById(R.id.find_battle); findBattle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getActivity()) .setMessage(R.string.still_in_development) .create().show(); } }); TextView watchBattle = (TextView) view.findViewById(R.id.watch_battle); watchBattle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApplication.getMyApplication().sendClientMessage("|/cmd roomlist"); waitingDialog.setMessage("Downloading list of matches"); waitingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); waitingDialog.setCancelable(true); getActivity().runOnUiThread(new Runnable() { @Override public void run() { waitingDialog.show(); } }); } }); pokemonTeamSpinner = (Spinner) view.findViewById(R.id.teams_spinner); }

Target:
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); setAvailableFormat(); mWaitingDialog = new ProgressDialog(getActivity()); TextView findBattle = (TextView) view.findViewById(R.id.find_battle); findBattle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(getActivity()) .setMessage(R.string.still_in_development) .create().show(); } }); TextView watchBattle = (TextView) view.findViewById(R.id.watch_battle); watchBattle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MyApplication.getMyApplication().sendClientMessage("|/cmd roomlist"); mWaitingDialog.setMessage("Downloading list of matches"); mWaitingDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); mWaitingDialog.setCancelable(true); getActivity().runOnUiThread(new Runnable() { @Override public void run() { mWaitingDialog.show(); } }); } }); mPokemonTeamSpinner = (Spinner) view.findViewById(R.id.teams_spinner); mNoTeamsAdapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.empty_team_list_filler)); mRandomTeamAdapter = new PokemonTeamListArrayAdapter(getActivity(), Arrays.asList(new PokemonTeam[]{new PokemonTeam("Random Team")})); }
Source:
public RpcClient(Channel channel, String exchange, String routingKey, int timeout) throws IOException { this(channel, exchange, routingKey, "amq.rabbitmq.reply-to", timeout) }

Target:
public RpcClient(Channel channel, String exchange, String routingKey, int timeout) throws IOException { this(channel, exchange, routingKey, "amq.rabbitmq.reply-to", timeout); }
Source:
public boolean setSilentMode(VeluxBridge bridge, int sceneNo, boolean silentMode) { logger.trace("setSilentMode({},{}) called.", sceneNo, silentMode); SetSilentMode bcp = bridge.bridgeAPI().setSilentMode(); bcp.setMode(sceneNo, silentMode); if ((bridge.bridgeCommunicate(bcp)) && (bcp.isCommunicationSuccessful())) { logger.info("setSilentMode() finished successfully."); return true; } logger.trace("setSilentMode() finished with failure."); return false; }

Target:
public boolean setSilentMode(VeluxBridge bridge, int sceneNo, boolean silentMode) { logger.trace("setSilentMode({},{}) called.", sceneNo, silentMode); SetSilentMode bcp = bridge.bridgeAPI().setSilentMode(); bcp.setMode(sceneNo, silentMode); if (bridge.bridgeCommunicate(bcp) && bcp.isCommunicationSuccessful()) { logger.info("setSilentMode() finished successfully."); return true; } logger.trace("setSilentMode() finished with failure."); return false; }
Source:
public void testOperationThrowsPaymentApiException() throws Exception { final CallbackTest callback = new CallbackTest(new PaymentApiException(ErrorCode.__UNKNOWN_ERROR_CODE)); final PaymentOperation pluginOperation = getPluginOperation(); try { pluginOperation.dispatchWithAccountLockAndTimeout("pluginIdentifier", callback); Assert.fail(); } catch (final OperationException e) { Assert.assertEquals(e.getOperationResult(), OperationResult.EXCEPTION); Assert.assertTrue(e.getCause() instanceof PaymentApiException); } }

Target:
public void testOperationThrowsPaymentApiException() throws Exception { final CallbackTest callback = new CallbackTest(new PaymentApiException(ErrorCode.__UNKNOWN_ERROR_CODE)); final PaymentOperation pluginOperation = getPluginOperation(); try { pluginOperation.dispatchWithAccountLockAndTimeout(PLUGIN_NAME_PLACEHOLDER, callback); Assert.fail(); } catch (final OperationException e) { Assert.assertEquals(e.getOperationResult(), OperationResult.EXCEPTION); Assert.assertTrue(e.getCause() instanceof PaymentApiException); } }
Source:
public synchronized void invokeCallbackMethods() { initCommandExecutor(); for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch(status) { case REJECTED: CommandEntity cmdEntity = coco.getCommandEntity(cmdId); executeAsyncCommand(cmdEntity.getCommandType(), cmdEntity.getActionParameters()); iterator.remove(); break; case FAILED: callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE: case ACTIVE_ASYNC: callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); break; default: break; } } }

Target:
public void invokeCallbackMethods() { initCommandExecutor(); for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE: case ACTIVE_ASYNC: callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); break; default: break; } } }
Source:
public boolean isValid(CruiseConfig preprocessedConfig, String repositoryId) { PackageRepositories packageRepositories = preprocessedConfig.getPackageRepositories(); PackageRepository repository = packageRepositories.find(repositoryId); Packages packages = repository.getPackages(); packageRepositories.validate(new ConfigSaveValidationContext(preprocessedConfig)); packages.validate(new ConfigSaveValidationContext(repository)); PackageDefinition nameValidatedPackage = packages.find(this.packageDefinition.getId()); nameValidatedPackage.validate(new ConfigSaveValidationContext(packages)); if(!isPackageIdPresent(nameValidatedPackage)){ result.unprocessableEntity(LocalizedMessage.string("PACKAGE_ID_NOT_PROVIDED")); } BasicCruiseConfig.copyErrors(nameValidatedPackage, packageDefinition); return com.thoughtworks.go.config.ErrorCollector.getAllErrors(nameValidatedPackage).isEmpty() && result.isSuccessful(); }

Target:
public boolean isValid(CruiseConfig preprocessedConfig, String repositoryId) { PackageRepositories packageRepositories = preprocessedConfig.getPackageRepositories(); PackageRepository repository = packageRepositories.find(repositoryId); Packages packages = repository.getPackages(); preprocessedPackageDefinition = packages.find(this.packageDefinition.getId()); preprocessedPackageDefinition.validate(null); if (preprocessedPackageDefinition.getAllErrors().isEmpty()) { packageRepositories.validate(null); packages.validate(null); packageDefinitionService.validatePackageConfiguration(preprocessedPackageDefinition); BasicCruiseConfig.copyErrors(preprocessedPackageDefinition, packageDefinition); return preprocessedPackageDefinition.getAllErrors().isEmpty() && result.isSuccessful(); } BasicCruiseConfig.copyErrors(preprocessedPackageDefinition, packageDefinition); return false; }
Source:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (fRejectedElements != null) { for (Object fRejectedElement : fRejectedElements) { if (element.equals(fRejectedElement)) { return false; } } } for (Class<?> fAcceptedType : fAcceptedTypes) { if (fAcceptedType.isInstance(element)) { return true; } } return false; }

Target:
public boolean select(Viewer viewer, Object parentElement, Object element) { if (fRejectedElements != null) { for (Object rejectedelement : fRejectedElements) { if (element.equals(rejectedelement)) { return false; } } } for (Class<?> type : fAcceptedTypes) { if (type.isInstance(element)) { return true; } } return false; }
Source:
private List<SignedCertificateTimestamp> getSCTsFromSCTList(byte[] data, SignedCertificateTimestamp.Origin origin) { List<SignedCertificateTimestamp> scts = new ArrayList(); byte[][] sctList; try { sctList = Serialization.readList(data, 2, 2); } catch (SerializationException e) { return null; } for (byte[] encodedSCT: sctList) { try { SignedCertificateTimestamp sct = SignedCertificateTimestamp.decode(encodedSCT, origin); scts.add(sct); } catch (SerializationException e) { } } return scts; }

Target:
private List<SignedCertificateTimestamp> getSCTsFromSCTList(byte[] data, SignedCertificateTimestamp.Origin origin) { if (data == null) { return Collections.EMPTY_LIST; } byte[][] sctList; try { sctList = Serialization.readList(data, 2, 2); } catch (SerializationException e) { return Collections.EMPTY_LIST; } List<SignedCertificateTimestamp> scts = new ArrayList(); for (byte[] encodedSCT: sctList) { try { SignedCertificateTimestamp sct = SignedCertificateTimestamp.decode(encodedSCT, origin); scts.add(sct); } catch (SerializationException e) { } } return scts; }
Source:
public void check(ConfigurationGenerator cg) throws ConfigurationException { File configFile = new File(cg.getConfigDir(), CONFIG_NAME); if (configFile.exists()) { MongoDBConnectionConfig config = getDescriptor(configFile, MongoDBConnectionConfig.class); try (MongoClient mongoClient = MongoDBConnectionHelper.newMongoClient(config, builder -> builder.serverSelectionTimeout((int) TimeUnit.SECONDS.toMillis(getCheckTimeoutInSeconds(cg))) .description("Nuxeo DB Check"))) { MongoDatabase database = mongoClient.getDatabase(config.dbname); Document ping = new Document("ping", "1"); database.runCommand(ping); } catch (MongoTimeoutException e) { throw new ConfigurationException(String.format( "Unable to connect to MongoDB at %s, please check your connection", config.server)); } } }

Target:
public void check(ConfigurationGenerator cg) throws ConfigurationException { File configFile = new File(cg.getConfigDir(), CONFIG_NAME); if (!configFile.exists()) { log.warn("Unable to find config file " + CONFIG_NAME); return; } MongoDBConnectionConfig config = getDescriptor(configFile, MongoDBConnectionConfig.class); try (MongoClient mongoClient = MongoDBConnectionHelper.newMongoClient(config, builder -> builder.serverSelectionTimeout( (int) TimeUnit.SECONDS.toMillis(getCheckTimeoutInSeconds(cg))) .description("Nuxeo DB Check"))) { MongoDatabase database = mongoClient.getDatabase(config.dbname); Document ping = new Document("ping", "1"); database.runCommand(ping); } catch (MongoTimeoutException e) { throw new ConfigurationException(String.format( "Unable to connect to MongoDB at %s, please check your connection", config.server)); } }
Source:
protected final MaterializedFrame determineContext(final Frame frame) { Object next = SArguments.rcvr(frame); int i = contextLevel - 1; while (i > 0) { if (next instanceof SBlock) { next = ((SBlock) next).getOuterSelf(); } else if (next instanceof SObjectWithClass) { next = SArguments.rcvr(((SObjectWithClass) next).getSOMClass().getContext()); } else if (next instanceof MaterializedFrame) { next = SArguments.rcvr((MaterializedFrame) next); } else { throw new RuntimeException("Cannot process " + next + " as contextual object"); } i--; } if (next instanceof SBlock) { return frameType.profile(((SBlock) next).getContext()); } else if (next instanceof SObjectWithClass) { SClass sClass = ((SObjectWithClass) next).getSOMClass(); return frameType.profile(sClass.getContext()); } else if (next instanceof MaterializedFrame) { return frameType.profile((MaterializedFrame) next); } else { throw new RuntimeException("Cannot process " + next + " as contextual object"); } }

Target:
protected final MaterializedFrame determineContext(final Frame frame) { SObjectWithContext self = (SObjectWithContext) SArguments.rcvr(frame); int i = contextLevel - 1; if (i > 0) { boolean doBuildChain = determineContext == null; if (doBuildChain) { determineContext = buildChain(self, i); } self = determineContext.getOuterSelf(self); } return frameType.profile(outerType.profile(self).getContext()); }