auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); final Collection<Locator> locators = new ArrayList<Locator>(); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); ColumnList<Locator> columns = query.execute().getResult(); for (Column<Locator> column: columns) { locators.add(column.getName().withLastUpdatedTimestamp(column.getTimestamp() / 1000)); } if (locators.size() == 0) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + " )", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } return locators; }

Target:
public Collection<Locator> getLocators(long shard) throws IOException { Timer.Context ctx = Instrumentation.getReadTimerContext(CassandraModel.CF_METRICS_LOCATOR_NAME); final Collection<Locator> locators = new ArrayList<Locator>(); try { RowQuery<Long, Locator> query = AstyanaxIO.getKeyspace() .prepareQuery(CassandraModel.CF_METRICS_LOCATOR) .getKey(shard); ColumnList<Locator> columns = query.execute().getResult(); for (Column<Locator> column: columns) { locators.add(column.getName() .withLastUpdatedTimestamp(TimeUnit.MILLISECONDS.convert(column.getTimestamp(), TimeUnit.MICROSECONDS))); } if (locators.size() == 0) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } } catch (NotFoundException e) { Instrumentation.markNotFound(CassandraModel.CF_METRICS_LOCATOR_NAME); return Collections.emptySet(); } catch (ConnectionException ex) { Instrumentation.markReadError(ex); LOG.error("Connection exception during getLocators(" + Long.toString(shard) + " )", ex); throw new IOException("Error reading locators", ex); } finally { ctx.stop(); } return locators; }
Source:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } String bootStr = str.toString(); if (!bootStr.equals("")) { return BootSequence.valueOf(bootStr); } return null; }

Target:
public BootSequence getSequence() { StringBuilder str = new StringBuilder(); for (EntityModel a : getItems()) { if (a.getIsChangable()) { BootSequence bs = (BootSequence) a.getEntity(); str.append(bs.toString()); } } return !str.toString().equals("") ? BootSequence.valueOf(str.toString()) : null; }
Source:
public boolean add(TileEntity te) { ChunkPos pos = getChunkPos(te); List<TileEntity> list = getChunkTEList(pos); if(list == null) { list = new ArrayList<>(); list.add(te); content.put(pos, list); return true; } else return list.add(te); }

Target:
public boolean add(TileEntity te) { ChunkPos pos = getChunkPos(te); List<TileEntity> list = content.get(pos); totalCount++; modCount++; if (list == null) { list = new ArrayList<>(); list.add(te); content.put(pos, list); return true; } else return list.add(te); }
Source:
public FlowLoader createFlowLoader(final File projectDir) throws ProjectManagerException { final File[] projectFileList = projectDir.listFiles(new SuffixFilter(Constants .PROJECT_FILE_SUFFIX)); if (projectFileList != null && projectFileList.length > 0) { if (projectFileList.length > 1) { throw new ProjectManagerException("Duplicate project YAML files found in the project " + "directory. Only one is allowed."); } final Map<String, Object> projectYamlParser; try { projectYamlParser = (Map<String, Object>) new Yaml() .load(new FileInputStream(projectFileList[0])); } catch (final FileNotFoundException e) { throw new ProjectManagerException("Error reading project YAML file.", e); } if (!projectYamlParser.containsKey(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION)) { throw new ProjectManagerException("Azkaban-Flow-Version is not specified in the project " + "YAML file."); } if (projectYamlParser.get(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION).equals (Constants.VERSION_2_0)) { return new DirectoryYamlFlowLoader(this.props); } else { throw new ProjectManagerException("Invalid Azkaban-Flow-Version in the project YAML file."); } } else { return new DirectoryFlowLoader(this.props); } }

Target:
public FlowLoader createFlowLoader(final File projectDir) throws ProjectManagerException { final File[] projectFileList = projectDir.listFiles(new SuffixFilter(Constants .PROJECT_FILE_SUFFIX)); if (projectFileList == null) { throw new ProjectManagerException("Error reading project directory. Input is not a " + "directory or IO error happens."); } if (ArrayUtils.isNotEmpty(projectFileList)) { if (projectFileList.length > 1) { throw new ProjectManagerException("Duplicate project YAML files found in the project " + "directory. Only one is allowed."); } final Map<String, Object> azkabanProject; try (FileInputStream fis = new FileInputStream(projectFileList[0])) { azkabanProject = (Map<String, Object>) new Yaml().load(fis); } catch (final IOException e) { throw new ProjectManagerException("Error reading project YAML file.", e); } if (azkabanProject == null || !azkabanProject .containsKey(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION)) { throw new ProjectManagerException("azkaban-flow-version is not specified in the project " + "YAML file."); } if (azkabanProject.get(Constants.ConfigurationKeys.AZKABAN_FLOW_VERSION).equals (Constants.AZKABAN_FLOW_VERSION_2_0)) { return new DirectoryYamlFlowLoader(this.props); } else { throw new ProjectManagerException("Invalid azkaban-flow-version in the project YAML file."); } } else { return new DirectoryFlowLoader(this.props); } }
Source:
public void validate() { super.validate(); if (!this.containsMacro("filesystemURI")) { if (!filesystemURI.startsWith("s3a://")) { throw new IllegalArgumentException("URI for S3 source must start with s3a://"); } } }

Target:
public void validate() { super.validate(); if (!this.containsMacro("filesystemURI")) { URI fsUri = URI.create(filesystemURI); if (!fsUri.getScheme().equals("s3a") && !fsUri.getScheme().equals("s3n")) { throw new IllegalArgumentException("URI scheme for S3 source must be s3a or s3n"); } } }
Source:
protected String startServerCommand(String name, int port, int connectedLocatorPort) { String command = "start server --name=" + name + " --server-port=" + port + " --locators=localhost[" + connectedLocatorPort + "]"; return command; }

Target:
private String startServerCommand(String name, int port, int connectedLocatorPort) { String command = "start server --name=" + name + " --server-port=" + port + " --locators=localhost[" + connectedLocatorPort + "]"; return command; }
Source:
protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslFactory == null) { throw new IllegalArgumentException("ssl factory shouldn't be null"); } SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT)); pipeline.addLast(sslHandler); pipeline.addLast(Http2FrameCodecBuilder.forClient().build()); pipeline.addLast(new Http2MultiplexHandler(new DummyChildHandler())); }

Target:
protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (sslFactory == null) { throw new IllegalArgumentException("ssl factory shouldn't be null"); } SslHandler sslHandler = new SslHandler(sslFactory.createSSLEngine(host, port, SSLFactory.Mode.CLIENT)); pipeline.addLast(sslHandler); pipeline.addLast(Http2FrameCodecBuilder.forClient().build()); pipeline.addLast(new Http2MultiplexHandler(new ChannelInboundHandlerAdapter())); }
Source:
static StatsSnapshot reduceByPartitionClass(StatsSnapshot statsSnapshot) { StatsSnapshot returnSnapshot = new StatsSnapshot(statsSnapshot.getValue(), new HashMap<>()); Map<String, StatsSnapshot> partitionClassSnapshots = statsSnapshot.getSubMap(); if (partitionClassSnapshots != null) { for (Map.Entry<String, StatsSnapshot> partitionClassToSnapshot : partitionClassSnapshots.entrySet()) { StatsSnapshot partitionClassSnapshot = partitionClassToSnapshot.getValue(); StatsSnapshot reducedPartitionClassSnapshot = new StatsSnapshot(0L, null); Map<String, StatsSnapshot> partitionToSnapshot = partitionClassSnapshot.getSubMap(); if (partitionToSnapshot != null) { for (StatsSnapshot snapshot : partitionToSnapshot.values()) { StatsSnapshot.aggregate(reducedPartitionClassSnapshot, snapshot); } returnSnapshot.getSubMap().put(partitionClassToSnapshot.getKey(), reducedPartitionClassSnapshot); } } } return returnSnapshot; }

Target:
static StatsSnapshot reduceByPartitionClass(StatsSnapshot statsSnapshot) { StatsSnapshot returnSnapshot = new StatsSnapshot(statsSnapshot.getValue(), new HashMap<>()); Map<String, StatsSnapshot> partitionClassSnapshots = statsSnapshot.getSubMap(); if (!partitionClassSnapshots.isEmpty()) { for (Map.Entry<String, StatsSnapshot> partitionClassToSnapshot : partitionClassSnapshots.entrySet()) { StatsSnapshot partitionClassSnapshot = partitionClassToSnapshot.getValue(); StatsSnapshot reducedPartitionClassSnapshot = new StatsSnapshot(0L, null); Map<String, StatsSnapshot> partitionToSnapshot = partitionClassSnapshot.getSubMap(); for (StatsSnapshot snapshot : partitionToSnapshot.values()) { StatsSnapshot.aggregate(reducedPartitionClassSnapshot, snapshot); } returnSnapshot.getSubMap().put(partitionClassToSnapshot.getKey(), reducedPartitionClassSnapshot); } } return returnSnapshot; }
Source:
public synchronized int read(byte[] buffer, int offset, int length) { requireNonNull(buffer, "buffer is null"); checkArgument(offset >= 0, "offset should equal to or greater than 0"); checkArgument(length >= 0, "length should equal to or greater than 0"); int totalReadBytes = 0; while (totalReadBytes < length && remainingBytes > 0 && (currentArray != null || arrays.hasNext())) { if (currentArray == null) { currentArray = arrays.next(); nextByte = 0; } int readBytes = min(remainingBytes, min(length - totalReadBytes, currentArray.length - nextByte)); arraycopy(currentArray, nextByte, buffer, offset + totalReadBytes, readBytes); totalReadBytes += readBytes; nextByte += readBytes; remainingBytes -= readBytes; if (nextByte >= currentArray.length || remainingBytes <= 0) { currentArray = null; } } return totalReadBytes > 0 ? totalReadBytes : -1; }

Target:
public synchronized int read(byte[] buffer, int offset, int length) { requireNonNull(buffer, "buffer is null"); checkPositionIndexes(offset, offset + length, buffer.length); if (remainingBytes == 0) { return -1; } int totalReadBytes = (int) min(length, remainingBytes); length = totalReadBytes; while (length > 0) { if (currentBufferPosition >= currentBuffer.length) { advanceCurrentBuffer(); } int readBytes = min(length, currentBuffer.length - currentBufferPosition); arraycopy(currentBuffer, currentBufferPosition, buffer, offset, readBytes); offset += readBytes; length -= readBytes; currentBufferPosition += readBytes; } remainingBytes -= totalReadBytes; return totalReadBytes; }
Source:
private Set<String> getEvalGroupsForNodeSectionAware( String nodeID ) { Set<String> groups = new HashSet<>(); try { List<HierarchyNodeRule> rules = this.getRulesByNodeID( Long.parseLong( nodeID ) ); for( HierarchyNodeRule rule : rules ) { if( EvalConstants.HIERARCHY_RULE_SECTION.equals( rule.getOption() ) ) { groups.addAll( dao.getAllSiteIDsMatchingSectionTitle( rule.getRule() ) ); } else { groups.addAll( dao.getAllSiteIDsMatchingSiteTitle( rule.getRule() ) ); } } } catch( NumberFormatException ex ) { log.warn( ex ); } return groups; }

Target:
private Set<String> getEvalGroupsForNodeSectionAware( String nodeID ) { Set<String> groups = new HashSet<>(); try { List<HierarchyNodeRule> rules = getRulesByNodeID( Long.parseLong( nodeID ) ); for( HierarchyNodeRule rule : rules ) { if( EvalConstants.HIERARCHY_RULE_SECTION.equals( rule.getOption() ) ) { groups.addAll( dao.getAllSiteIDsMatchingSectionTitle( rule.getRule() ) ); } else { groups.addAll( dao.getAllSiteIDsMatchingSiteTitle( rule.getRule() ) ); } } } catch( NumberFormatException ex ) { LOG.warn( ex ); } return groups; }
Source:
public int compareTo(ServerDescription o) { if (this.getServerName().equalsIgnoreCase(o.getServerName())) return 1; return this.getServerName().compareTo(o.getServerName()); }

Target:
public int compareTo(ServerDescription o) { if (this.getServerName().equalsIgnoreCase(o.getServerName())) { return 1; } return this.getServerName().compareTo(o.getServerName()); }
Source:
public TexParserResult parse(Path texFile) { return parseTexFiles(new ArrayList<>(Collections.singletonList(texFile))); }

Target:
public TexParserResult parse(Path texFile) { return parse(Collections.singletonList(texFile)); }
Source:
public AcceleoProjectState getLastBuiltState(IProject project, IProgressMonitor monitor) { try { if (project.isAccessible() && project.hasNature(IAcceleoConstants.ACCELEO_NATURE_ID)) { AcceleoProjectInfo info = this.getAcceleoProjectInfo(project, true); if (!info.hasBeenRead()) { info.markAsRead(); info.setSavedState(this.readBuiltState(project)); } return info.getSavedState(); } } catch (CoreException e) { AcceleoCommonPlugin.log(e, true); } return null; }

Target:
public AcceleoProjectState getLastBuiltState(IProject project, IProgressMonitor monitor) { try { if (project.isAccessible() && project.hasNature(IAcceleoConstants.ACCELEO_NATURE_ID)) { AcceleoProjectInfo info = this.getAcceleoProjectInfo(project, true); if (!info.hasBeenRead()) { info.markAsRead(); info.setSavedState(this.readBuiltState(project)); } return info.getSavedState(); } } catch (CoreException e) { AcceleoLogger.log(e, true); } return null; }
Source:
private JavadocNodeImpl createJavadocNode(ParseTree parseTree, DetailNode parent, int index) { final JavadocNodeImpl node = new JavadocNodeImpl(); node.setText(parseTree.getText()); final int parseTreeLine = getLine(parseTree); node.setColumnNumber(getColumn(parseTree)); node.setLineNumber(parseTreeLine + blockCommentLineNumber); node.setIndex(index); node.setType(getTokenType(parseTree)); node.setParent(parent); node.setChildren((DetailNode[]) new JavadocNodeImpl[parseTree.getChildCount()]); return node; }

Target:
private JavadocNodeImpl createJavadocNode(ParseTree parseTree, DetailNode parent, int index) { final JavadocNodeImpl node = new JavadocNodeImpl(); node.setText(parseTree.getText()); node.setColumnNumber(getColumn(parseTree)); node.setLineNumber(getLine(parseTree) + blockCommentLineNumber); node.setIndex(index); node.setType(getTokenType(parseTree)); node.setParent(parent); node.setChildren((DetailNode[]) new JavadocNodeImpl[parseTree.getChildCount()]); return node; }
Source:
private void upgrade() { if (getWindow() != null) { return; } final VDS host = getEntity(); Model model; if (host.getVdsType() == VDSType.oVirtNode) { model = new UpgradeModel(host); } else { model = new UpgradeConfirmationModel(host); } model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); setWindow(model); }

Target:
private void upgrade() { if (getWindow() != null) { return; } final VDS host = getEntity(); Model model = createUpgradeModel(host); model.initialize(); model.getCommands().add(UICommand.createCancelUiCommand("Cancel", this)); setWindow(model); }
Source:
public void onDetach() { super.onDetach(); mLoginListener = null; if (mGoogleApiClient.isConnected()) { mGoogleApiClient.stopAutoManage(getActivity()); mGoogleApiClient.disconnect(); } ActivityUtils.showKeyboard(getActivity().getCurrentFocus()); }

Target:
public void onDetach() { super.onDetach(); mLoginListener = null; if (mGoogleApiClient.isConnected()) { mGoogleApiClient.stopAutoManage(getActivity()); mGoogleApiClient.disconnect(); } }
Source:
public List<PredefinedCalendarConfiguration> getAvailablePredefinedCalendarConfigurations(PortletRequest request) { final String username = getUsername(request); if (username != null) { return calendarStore.getPredefinedCalendarConfigurations(username, false); } else { return new ArrayList<PredefinedCalendarConfiguration>(); } }

Target:
public List<PredefinedCalendarConfiguration> getAvailablePredefinedCalendarConfigurations(PortletRequest request) { final String username = getUsername(request); if (username != null) { return calendarStore.getPredefinedCalendarConfigurations(username, false); } else { log.warn("username is null -- returning empty calendar configuration list"); return new ArrayList<PredefinedCalendarConfiguration>(); } }
Source:
public void shouldNotContinueWithConfigSaveIfUserIsUnauthorized() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(false); when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false); SCM updatedScm = new SCM("id", new PluginConfiguration("plugin-id", "1"), new Configuration(new ConfigurationProperty(new ConfigurationKey("key1"),new ConfigurationValue("value1")))); UpdateSCMConfigCommand command = new UpdateSCMConfigCommand(updatedScm, pluggableScmService, goConfigService, currentUser, result, "md5", entityHashingService); assertThat(command.canContinue(cruiseConfig), is(false)); }

Target:
public void shouldNotContinueWithConfigSaveIfUserIsUnauthorized() { when(goConfigService.isUserAdmin(currentUser)).thenReturn(false); when(goConfigService.isGroupAdministrator(currentUser.getUsername())).thenReturn(false); SCM updatedScm = new SCM("id", new PluginConfiguration("plugin-id", "1"), new Configuration(new ConfigurationProperty(new ConfigurationKey("key1"),new ConfigurationValue("value1")))); UpdateSCMConfigCommand command = new UpdateSCMConfigCommand(updatedScm, pluggableScmService, goConfigService, currentUser, result, "md5", entityHashingService); assertThat(command.canContinue(cruiseConfig), is(false)); assertThat(result.toString(), containsString("UNAUTHORIZED_TO_EDIT")); }
Source:
public void removeCustomizedView(List<String> resourceNames) { for (String resourceName : resourceNames) { _customizedViewCache.remove(resourceName); } }

Target:
public synchronized void removeCustomizedView(List<String> resourceNames) { for (String resourceName : resourceNames) { _customizedViewCache.remove(resourceName); } }
Source:
public void createApplicationContextFrom_validBuilderContext_shouldCreateAnApplicationContext() { KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), Maps.<Platform.ExtraComponentKey, Object>newHashMap() ); ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(platformConfiguration.configuration(), applicationContext.getBean(Config.class)); assertEquals(platformConfiguration.eventBus(), applicationContext.getBean(EventBus.class)); assertEquals(platformConfiguration.commandGateway(), applicationContext.getBean(CommandGateway.class)); assertEquals(platformConfiguration.queryGateway(), applicationContext.getBean(QueryGateway.class)); assertEquals(platformConfiguration.metricRegistry(), applicationContext.getBean(MetricRegistry.class)); }

Target:
public void createApplicationContextFrom_validBuilderContext_shouldCreateAnApplicationContext() { final KasperPlatformConfiguration platformConfiguration = new KasperPlatformConfiguration(); final Platform.BuilderContext builderContext = new Platform.BuilderContext( platformConfiguration.configuration(), platformConfiguration.eventBus(), platformConfiguration.commandGateway(), platformConfiguration.queryGateway(), platformConfiguration.metricRegistry(), Maps.<Platform.ExtraComponentKey, Object>newHashMap() ); final ApplicationContext applicationContext = BuilderContextHelper.createApplicationContextFrom(builderContext); assertNotNull(applicationContext); assertEquals(platformConfiguration.configuration(), applicationContext.getBean(Config.class)); assertEquals(platformConfiguration.eventBus(), applicationContext.getBean(EventBus.class)); assertEquals(platformConfiguration.commandGateway(), applicationContext.getBean(CommandGateway.class)); assertEquals(platformConfiguration.queryGateway(), applicationContext.getBean(QueryGateway.class)); assertEquals(platformConfiguration.metricRegistry(), applicationContext.getBean(MetricRegistry.class)); }
Source:
private static boolean isHtmlTag(TagNode node) { return "HTML".equalsIgnoreCase(node.getLocalName()); }

Target:
private static boolean isHtmlTag(TagNode node) { return "HTML".equalsIgnoreCase(node.getNodeName()); }
Source:
private void init() { this.parent = getParent(); list.add(new PhantomReference(this, referenceQueue)); INSTANCE_COUNT.set(INSTANCE_COUNT.get() + 1); system = this.getClass().getClassLoader(); END SJSAS 6317864 securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } addOverridablePackage("com.sun.faces.extensions"); permissionsHolder = new PermsHolder(); }

Target:
private void init() { this.parent = getParent(); system = this.getClass().getClassLoader(); END SJSAS 6317864 securityManager = System.getSecurityManager(); if (securityManager != null) { refreshPolicy(); } addOverridablePackage("com.sun.faces.extensions"); permissionsHolder = new PermsHolder(); }
Source:
synchronized static public void init(){ if( map == null ) { map = new HashMap<CtfTmfTrace, CtfIteratorViceManager>(); } }

Target:
public static synchronized void init() { if (map == null) { map = new HashMap<CtfTmfTrace, CtfTraceManager>(); } }
Source:
public ListenableFuture<Response> request(final HeliosRequest request) { final HeliosRequest req; final String authHeader = authProvider.currentAuthorization(); if (authHeader != null) { req = request.toBuilder().header(HttpHeaders.AUTHORIZATION, authHeader).build(); } else { req = request; } return Futures.transform(delegate.request(req), new AsyncFunction<Response, Response>() { @Override public ListenableFuture<Response> apply(final Response response) throws Exception { if (response != null && response.status() == HTTP_UNAUTHORIZED && response.header(HttpHeaders.WWW_AUTHENTICATE) != null) { return authenticateAndRetry(req, response); } else { return immediateFuture(response); } } }); }

Target:
public ListenableFuture<Response> request(final HeliosRequest request) { final HeliosRequest req; final String authHeader = authProvider.currentAuthorizationHeader(); if (authHeader != null) { req = request.toBuilder().header(HttpHeaders.AUTHORIZATION, authHeader).build(); } else { req = request; } return Futures.transform(delegate.request(req), new AsyncFunction<Response, Response>() { @Override public ListenableFuture<Response> apply(final Response response) throws Exception { if (response != null && response.status() == HTTP_UNAUTHORIZED && response.header(HttpHeaders.WWW_AUTHENTICATE) != null) { return authenticateAndRetry(req, response); } else { return immediateFuture(response); } } }); }
Source:
private boolean canVmNumaPinnedToVds(VM vm, List<VmNumaNode> nodes, VDS vds) { List<VdsNumaNode> pNodes = DbFacade.getInstance().getVdsNumaNodeDAO().getAllVdsNumaNodeByVdsId(vds.getId()); if (pNodes == null || pNodes.isEmpty()) { return false; } Map<Integer, VdsNumaNode> indexMap = toMap(pNodes); for (VmNumaNode vNode : nodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vNode.getVdsNumaNodeList()) { if (pair.getSecond() != null && pair.getSecond().getFirst()) { if (vNode.getMemTotal() > indexMap.get(vNode.getIndex()).getNumaNodeStatistics().getMemFree()) { return false; } } } } return true; }

Target:
private boolean canVmNumaPinnedToVds(VM vm, List<VmNumaNode> nodes, VDS vds) { List<VdsNumaNode> pNodes = DbFacade.getInstance().getVdsNumaNodeDAO().getAllVdsNumaNodeByVdsId(vds.getId()); if (pNodes == null || pNodes.isEmpty()) { return false; } Map<Integer, VdsNumaNode> indexMap = toMap(pNodes); for (VmNumaNode vNode : nodes) { for (Pair<Guid, Pair<Boolean, Integer>> pair : vNode.getVdsNumaNodeList()) { if (pair.getSecond() != null && pair.getSecond().getFirst()) { if (vNode.getMemTotal() > indexMap.get(pair.getSecond().getSecond()) .getNumaNodeStatistics() .getMemFree()) { return false; } } } } return true; }
Source:
private static AbstractHandleClient getHandleServiceClient( final URL handleServiceUrl, final AuthToken handleMgrToken, final InitReporter rep) { final AbstractHandleClient cli; try { cli = new AbstractHandleClient( handleServiceUrl, handleMgrToken); if (handleServiceUrl.getProtocol().equals("http")) { rep.reportInfo("Warning - the Handle Service url uses insecure http. " + "https is recommended."); cli.setIsInsecureHttpConnectionAllowed(true); } cli.isOwner(Arrays.asList("KBH_-100")); } catch (Exception e) { rep.reportFail("Could not establish a connection to the Handle Service at " + handleServiceUrl + ": " + e.getMessage()); return null; } return cli; }

Target:
private static AbstractHandleClient getHandleServiceClient( final URL handleServiceUrl, final AuthToken handleMgrToken, final InitReporter rep) { final AbstractHandleClient cli; try { cli = new AbstractHandleClient( handleServiceUrl, handleMgrToken); if (handleServiceUrl.getProtocol().equals("http")) { rep.reportInfo("Warning - the Handle Service url uses insecure http. " + "https is recommended."); cli.setIsInsecureHttpConnectionAllowed(true); } cli.isOwner(Arrays.asList("FAKEHANDLE_-100")); } catch (Exception e) { rep.reportFail("Could not establish a connection to the Handle Service at " + handleServiceUrl + ": " + e.getMessage()); return null; } return cli; }
Source:
public Page getOutput() { if (split == null) { return null; } if (source == null) { source = pageSourceProvider.createPageSource(operatorContext.getSession(), split, table, columns); } Page page = source.getNextPage(); if (page != null) { page = page.getLoadedPage(); long endCompletedBytes = source.getCompletedBytes(); long endCompletedPositions = source.getCompletedPositions(); if (endCompletedPositions < 0) { endCompletedPositions = completedPositions + page.getPositionCount(); } long endReadTimeNanos = source.getReadTimeNanos(); operatorContext.recordRawInputWithTiming(endCompletedBytes - completedBytes, endReadTimeNanos - readTimeNanos); operatorContext.recordProcessedInput(endCompletedBytes - completedBytes, endCompletedPositions - completedPositions); completedBytes = endCompletedBytes; completedPositions = endCompletedPositions; readTimeNanos = endReadTimeNanos; } systemMemoryContext.setBytes(source.getSystemMemoryUsage()); return page; }

Target:
public Page getOutput() { if (split == null) { return null; } if (source == null) { source = pageSourceProvider.createPageSource(operatorContext.getSession(), split, table, columns); } Page page = source.getNextPage(); if (page != null) { page = page.getLoadedPage(); long endCompletedBytes = source.getCompletedBytes(); long endCompletedPositions = source.getCompletedPositions(); long endReadTimeNanos = source.getReadTimeNanos(); operatorContext.recordRawInputWithTiming(endCompletedBytes - completedBytes, endCompletedPositions - completedPositions, endReadTimeNanos - readTimeNanos); operatorContext.recordProcessedInput(page.getSizeInBytes(), page.getPositionCount()); completedBytes = endCompletedBytes; completedPositions = endCompletedPositions; readTimeNanos = endReadTimeNanos; } systemMemoryContext.setBytes(source.getSystemMemoryUsage()); return page; }
Source:
public String getUuidProperty() { return getObject().getIdentifierType().getUuid(); }

Target:
public String getUuidProperty() { return getObject().getUuid(); }
Source:
public void shouldReturnAllFoundTags() throws Exception { Tag foundTag = TestTagBuilder.aTag().build(); when(tagServiceMock.findAll()).thenReturn(asList(foundTag)); mockMvc.perform(get("/api/v1/tags") .accept(APPLICATION_JSON_UTF8)).andDo(print()) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$[0]." + ID).value(is(((int) foundTag.getId())))) .andExpect(jsonPath("$[0].name").value(is(foundTag.getName()))) .andExpect(jsonPath("$[0].links", hasSize(0))); verify(tagServiceMock, times(1)).findAll(); verifyNoMoreInteractions(tagServiceMock); }

Target:
public void shouldReturnAllFoundTags() throws Exception { Tag foundTag = TestTagBuilder.aTag().build(); when(tagServiceMock.findAll()).thenReturn(asList(foundTag)); mockMvc.perform(get("/api/v1/tags") .accept(APPLICATION_JSON_UTF8)) .andExpect(status().isOk()) .andExpect(content().contentType(APPLICATION_JSON_UTF8)) .andExpect(jsonPath("$[0]." + ID).value(is(((int) foundTag.getId())))) .andExpect(jsonPath("$[0].name").value(is(foundTag.getName()))) .andExpect(jsonPath("$[0].links", hasSize(2))) .andExpect(jsonPath("$[0].links[0].rel").value(is(Link.REL_SELF))) .andExpect(jsonPath("$[0].links[0].href").value(containsString("/api/v1/tags/" + foundTag.getId()))) .andExpect(jsonPath("$[0].links[1].rel").value(is(TagResourceAsm.IDEAS_REL))) .andExpect(jsonPath("$[0].links[1].href").value(containsString("/api/v1/tags/" + foundTag.getId() + "/ideas"))); verify(tagServiceMock, times(1)).findAll(); verifyNoMoreInteractions(tagServiceMock); }
Source:
public String toString() { return "SubscriptionCalculator{" + "price=" + price + ", subscriptions=" + subscriptions + "} " + super.toString(); }

Target:
public String toString() { return "SubscriptionCalculator{" + "price=" + price + ", subscriptions=" + subscriptions + "}"; }
Source:
public Operation exec(Prolog engine) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); PrologEnvironment env = (PrologEnvironment) engine.control; ChangeControl cControl = StoredValues.CHANGE_CONTROL.get(engine); CurrentUser curUser = cControl.getCurrentUser(); Term resultTerm; if (curUser instanceof IdentifiedUser) { Account.Id id = ((IdentifiedUser)curUser).getAccountId(); resultTerm = new IntegerTerm(id.get()); } else if (curUser instanceof AnonymousUser) { resultTerm = anonymous; } else if (curUser instanceof PeerDaemonUser) { resultTerm = peerDaemon; } else if (curUser instanceof ReplicationUser) { resultTerm = SymbolTerm.intern("replication"); } else { throw new EvaluationException("Unknown user type"); } if (!a1.unify(new StructureTerm(user, resultTerm), engine.trail)) { return engine.fail(); } return cont; }

Target:
public Operation exec(Prolog engine) throws PrologException { engine.setB0(); Term a1 = arg1.dereference(); PrologEnvironment env = (PrologEnvironment) engine.control; ChangeControl cControl = StoredValues.CHANGE_CONTROL.get(engine); CurrentUser curUser = cControl.getCurrentUser(); Term resultTerm; if (curUser instanceof IdentifiedUser) { Account.Id id = ((IdentifiedUser)curUser).getAccountId(); resultTerm = new IntegerTerm(id.get()); } else if (curUser instanceof AnonymousUser) { resultTerm = anonymous; } else if (curUser instanceof PeerDaemonUser) { resultTerm = peerDaemon; } else if (curUser instanceof ReplicationUser) { resultTerm = replication; } else { throw new EvaluationException("Unknown user type"); } if (!a1.unify(new StructureTerm(user, resultTerm), engine.trail)) { return engine.fail(); } return cont; }
Source:
public Direction calculateDirection(Entity entity) { if (provider instanceof Block) { Optional<RayTracer.RayTraceBlockResult> hit = new RayTracer(entity) .setDistance(7) .rayTraceBlocks(entity.world()) .filter(res -> res.block != provider) .findFirst(); if (hit.isPresent()) { Direction dir = (isFlip) ? hit.get().side.opposite() : hit.get().side; return rotationMask.test(dir) ? dir : calculateDirectionFromEntity(entity); } } return Direction.UNKNOWN; }

Target:
public Direction calculateDirection(Entity entity) { if (provider instanceof Block) { return new RayTracer(entity) .setDistance(7) .rayTraceBlocks(entity.world()) .filter(res -> res.block != provider) .findFirst() .map(hit -> isFlip ? hit.side.opposite() : hit.side) .map(dir -> rotationFilter.test(dir) ? dir : calculateDirectionFromEntity(entity)) .orElse(Direction.UNKNOWN); } else { return Direction.UNKNOWN; } }
Source:
public String getId() { return RestoreRedundancyFunction.ID; }

Target:
public String getId() { return ID; }
Source:
private void insertReferencesToYears(HashMap<Integer, String> years, int ownYear, DigitalDocumentInterface act, PrefsInterface ruleSet) throws TypeNotAllowedForParentException, MetadataTypeNotAllowedException, TypeNotAllowedAsChildException { for (Map.Entry<Integer, String> year : years.entrySet()) { if (year.getKey() != ownYear) { DocStructInterface child = getOrCreateChild(act.getLogicalDocStruct(), yearLevelName, MetsModsImportExportInterface.CREATE_LABEL_ATTRIBUTE_TYPE, year.getKey().toString(), MetsModsImportExportInterface.CREATE_ORDERLABEL_ATTRIBUTE_TYPE, act, ruleSet); child.addMetadata(MetsModsImportExportInterface.CREATE_MPTR_ELEMENT_TYPE, year.getValue()); } } }

Target:
private void insertReferencesToYears(HashMap<Integer, String> years, int ownYear, DigitalDocumentInterface act, PrefsInterface ruleSet) throws MetadataTypeNotAllowedException, TypeNotAllowedAsChildException { for (Map.Entry<Integer, String> year : years.entrySet()) { if (year.getKey() != ownYear) { DocStructInterface child = getOrCreateChild(act.getLogicalDocStruct(), yearLevelName, MetsModsImportExportInterface.CREATE_LABEL_ATTRIBUTE_TYPE, year.getKey().toString(), MetsModsImportExportInterface.CREATE_ORDERLABEL_ATTRIBUTE_TYPE, act, ruleSet); child.addMetadata(MetsModsImportExportInterface.CREATE_MPTR_ELEMENT_TYPE, year.getValue()); } } }
Source:
public View getView(int position, View convertView, ViewGroup parent){ if (convertView == null){ LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.item_snooze, parent, false); } TextView title = (TextView)convertView; if (position == 0){ title.setText("In an hour"); } else if (position == 1){ title.setText("This time tomorrow"); } else if (position == 2){ title.setText("Pick a date and time"); } return convertView; }

Target:
public View getView(int position, View convertView, ViewGroup parent){ if (convertView == null){ LayoutInflater inflater = LayoutInflater.from(mContext); convertView = inflater.inflate(R.layout.item_snooze, parent, false); } TextView title = (TextView)convertView; if (position == 0){ title.setText(R.string.later_in_an_hour); } else if (position == 1){ title.setText(R.string.later_tomorrow); } else if (position == 2){ title.setText(R.string.later_pick); } return convertView; }
Source:
public void shouldNotAlertIfResponseIsJsonOrXml(String contentType) throws Exception { nano.addHandler(new MiscOkResponse(" HttpMessage message = getHttpMessage(URL); rule.init(message, parent); rule.scan(); assertThat(alertsRaised, hasSize(0)); }

Target:
public void shouldNotAlertIfResponseIsJsonOrXml(String contentType) throws Exception { nano.addHandler(new MiscOkResponse(URL, contentType)); HttpMessage message = getHttpMessage(URL); rule.init(message, parent); rule.scan(); assertThat(alertsRaised, hasSize(0)); }
Source:
protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) { Application application = (Application) request.getAttribute(Application.class.getName()); String email = form.getFieldValue("email"); Map<String, Object> model = new HashMap<String, Object>(); try { request.setAttribute("form", form); AccountStore accountStore = accountStoreResolver.getAccountStore(request, response); if (accountStore != null) { application.sendPasswordResetEmail(email, accountStore); } else { application.sendPasswordResetEmail(email); } } catch (ResourceException e) { if (e.getCode() != 404) { if (UserAgents.get(request).isJsonPreferred()) { model.put("status", 200); model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } throw e; } } if (UserAgents.get(request).isJsonPreferred()) { model.put("status", 200); model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } return new DefaultViewModel(nextUri).setRedirect(true); }

Target:
protected ViewModel onValidSubmit(HttpServletRequest request, HttpServletResponse response, Form form) { Application application = (Application) request.getAttribute(Application.class.getName()); String email = form.getFieldValue("email"); Map<String, Object> model = new HashMap<String, Object>(); try { request.setAttribute("form", form); AccountStore accountStore = accountStoreResolver.getAccountStore(request, response); if (accountStore != null) { application.sendPasswordResetEmail(email, accountStore); } else { application.sendPasswordResetEmail(email); } } catch (ResourceException e) { if (isJsonPreferred(request, response)) { model.put("status", 200); model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } } if (isJsonPreferred(request, response)) { model.put("status", 200); model.put("message", "OK"); return new DefaultViewModel("stormpathJsonView", model); } return new DefaultViewModel(nextUri).setRedirect(true); }
Source:
public void setEndUserCreatedAt(long createdAt) { if (createdAt > 9999999999L) { Log.d(TAG, "WARNING: The created date exceeds the maximum 10 characters allowed. " + "If you are using System.currentTimeMillis() divide it by 1000."); } endUser.setCreatedAt(createdAt); }

Target:
public void setEndUserCreatedAt(long createdAt) { Utils.checkDate(createdAt); endUser.setCreatedAt(createdAt); }
Source:
public void testActivateAppUnknownApp() throws Exception { App app = when(mock(App.class).isActive()).thenReturn(false).getMock(); MvcResult result = mockMvc.perform(post(AppsController.URI + "/id/activate")).andReturn(); assertEquals(result.getResolvedException().getMessage(), "Unknown app 'id'"); }

Target:
public void testActivateAppUnknownApp() throws Exception { App app = when(mock(App.class).isActive()).thenReturn(false).getMock(); MvcResult result = mockMvc.perform(post(AppsController.URI + "/id/activate")).andReturn(); throw result.getResolvedException(); }
Source:
protected static String buildAggregatesClause(PageProvider provider) { try { Properties namedParameters = (Properties) provider.getSearchDocumentModel() .getContextData(NAMED_PARAMETERS); Map<String, Aggregate<? extends Bucket>> aggregates = provider.getAggregates(); if (namedParameters == null) { return null; } String aggregatesClause = ""; for (Aggregate<? extends Bucket> aggregate : aggregates.values()) { if (namedParameters.containsKey(aggregate.getId())) { JsonNode node = OBJECT_MAPPER.readTree(namedParameters.get(aggregate.getId())); List<String> keys = StreamSupport.stream(node.spliterator(), false) .map(value -> value.asText().replaceAll("^\"|\"$", "")) .collect(Collectors.toList()); String aggClause = aggregate.getBuckets() .stream() .filter(bucket -> keys.contains(bucket.getKey())) .map(bucket -> getClauseFromBucket(bucket, aggregate.getXPathField())) .collect(Collectors.joining(" OR ")); if (StringUtils.isNotEmpty(aggClause)) { aggClause = "(" + aggClause + ")"; aggregatesClause = StringUtils.isEmpty(aggregatesClause) ? aggClause : NXQLQueryBuilder.appendClause(aggregatesClause, aggClause); } } } return aggregatesClause; } catch (IOException e) { throw new NuxeoException(e); } }

Target:
protected static String buildAggregatesClause(PageProvider provider) { try { Properties namedParameters = (Properties) provider.getSearchDocumentModel() .getContextData(NAMED_PARAMETERS); if (namedParameters == null) { return ""; } Map<String, Aggregate<? extends Bucket>> aggregates = provider.getAggregates(); String aggregatesClause = ""; for (Aggregate<? extends Bucket> aggregate : aggregates.values()) { if (namedParameters.containsKey(aggregate.getId())) { JsonNode node = OBJECT_MAPPER.readTree(namedParameters.get(aggregate.getId())); List<String> keys = StreamSupport.stream(node.spliterator(), false) .map(value -> value.asText().replaceAll("^\"|\"$", "")) .collect(Collectors.toList()); String aggClause = aggregate.getBuckets() .stream() .filter(bucket -> keys.contains(bucket.getKey())) .map(bucket -> getClauseFromBucket(bucket, aggregate.getXPathField())) .collect(Collectors.joining(" OR ")); if (StringUtils.isNotEmpty(aggClause)) { aggClause = "(" + aggClause + ")"; aggregatesClause = StringUtils.isEmpty(aggregatesClause) ? aggClause : NXQLQueryBuilder.appendClause(aggregatesClause, aggClause); } } } return aggregatesClause; } catch (IOException e) { throw new NuxeoException(e); } }
Source:
private void writeRewrittenHashes() throws RevisionSyntaxException, IOException, RefNotFoundException { File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT); if (!currentCommitFile.exists()) return; ObjectId headId = repo.resolve(Constants.HEAD); if (headId == null) { headId = getHead().getObjectId(); } String head = headId.getName(); String currentCommits = rebaseState.readFile(CURRENT_COMMIT); for (String current : currentCommits.split("\n")) RebaseState .createFile(rebaseState.getRewrittenDir(), current, head); FileUtils.delete(currentCommitFile); }

Target:
private void writeRewrittenHashes() throws RevisionSyntaxException, IOException, RefNotFoundException { File currentCommitFile = rebaseState.getFile(CURRENT_COMMIT); if (!currentCommitFile.exists()) return; ObjectId headId = getHead().getObjectId(); String head = headId.getName(); String currentCommits = rebaseState.readFile(CURRENT_COMMIT); for (String current : currentCommits.split("\n")) RebaseState .createFile(rebaseState.getRewrittenDir(), current, head); FileUtils.delete(currentCommitFile); }
Source:
public JSONObject changePoolIdBarcode(HttpSession session, JSONObject json) { Long poolId = json.getLong("poolId"); String idBarcode = json.getString("identificationBarcode"); try { if (!"".equals(idBarcode)) { Pool pool = requestManager.getPoolById(poolId); pool.setIdentificationBarcode(idBarcode); requestManager.savePool(pool); } else { return JSONUtils.SimpleJSONError("New identification barcode not recognized"); } } catch (IOException e) { e.printStackTrace(); return JSONUtils.SimpleJSONError(e.getMessage()); } return JSONUtils.SimpleJSONResponse("New identification barcode successfully assigned."); }

Target:
public JSONObject changePoolIdBarcode(HttpSession session, JSONObject json) { Long poolId = json.getLong("poolId"); String idBarcode = json.getString("identificationBarcode"); try { if (!isStringEmptyOrNull(idBarcode)) { Pool<? extends Poolable> pool = requestManager.getPoolById(poolId); pool.setIdentificationBarcode(idBarcode); requestManager.savePool(pool); } else { return JSONUtils.SimpleJSONError("New identification barcode not recognized"); } } catch (IOException e) { log.debug("Could not change Pool identificationBarcode: " + e.getMessage()); e.printStackTrace(); return JSONUtils.SimpleJSONError(e.getMessage()); } return JSONUtils.SimpleJSONResponse("New identification barcode successfully assigned."); }
Source:
public final int doPhase2Commit () { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerTransaction::doPhase2Commit ( " + get_uid() + " )"); } org.omg.CosTransactions.Status s = get_status(); if (s == org.omg.CosTransactions.Status.StatusCommitting || s == org.omg.CosTransactions.Status.StatusCommitted) { TransactionCache.ReplayPhaseReturnStatus replayStatus = TransactionCache.replayPhase2(get_uid(), type()); if(replayStatus == TransactionCache.ReplayPhaseReturnStatus.NONE) { return ActionStatus.COMMITTING; } } if (s != org.omg.CosTransactions.Status.StatusPrepared) { jtsLogger.i18NLogger.warn_orbspecific_interposition_coordinator_txnotprepared("ServerTransaction.doPhase2Commit", Utility.stringStatus(s)); return finalStatus(); } super.phase2Commit(true); if (super.failedList != null && super.failedList.size() > 0) { return ActionStatus.COMMITTING; } try { doAfterCompletion(get_status()); } catch (Exception e) { } if (parentTransaction != null) parentTransaction.removeChildAction(this); super.destroyAction(); ActionManager.manager().remove(get_uid()); return finalStatus(); }

Target:
public final int doPhase2Commit () { if (jtsLogger.logger.isTraceEnabled()) { jtsLogger.logger.trace("ServerTransaction::doPhase2Commit ( " + get_uid() + " )"); } org.omg.CosTransactions.Status s = get_status(); if (s != org.omg.CosTransactions.Status.StatusPrepared) { jtsLogger.i18NLogger.warn_orbspecific_interposition_coordinator_txnotprepared("ServerTransaction.doPhase2Commit", Utility.stringStatus(s)); return finalStatus(); } super.phase2Commit(true); if (super.failedList != null && super.failedList.size() > 0) { return ActionStatus.COMMITTING; } try { doAfterCompletion(get_status()); } catch (Exception e) { } if (parentTransaction != null) parentTransaction.removeChildAction(this); super.destroyAction(); ActionManager.manager().remove(get_uid()); return finalStatus(); }
Source:
protected List<SmackFuture<LookupConnectionEndpointsResult, Exception>> lookupConnectionEndpoints() { LOGGER.info("Looking up for endpoints"); assert discoveredWebsocketEndpoints == null; List<SmackFuture<LookupConnectionEndpointsResult, Exception>> futures = new ArrayList<>(2); InternalSmackFuture<LookupConnectionEndpointsResult, Exception> websocketEndpointsLookupFuture = new InternalSmackFuture<>(); connectionInternal.asyncGo(() -> { Result<WebsocketRemoteConnectionEndpoint> result = RemoteWebsocketConnectionEndpoints.lookup(connectionInternal); LookupConnectionEndpointsResult endpointsResult; if (result.discoveredRemoteConnectionEndpoints.isEmpty()) { endpointsResult = new WebsocketEndpointsDiscoveryFailed(result); } else { endpointsResult = new DiscoveredWebsocketEndpoints(result); } websocketEndpointsLookupFuture.setResult(endpointsResult); LOGGER.info("endpoint result is computed"); }); futures.add(websocketEndpointsLookupFuture); if (moduleDescriptor.isUsingHttps()) { throw new IllegalArgumentException("Cannot handle secure-http/https yet"); } return futures; }

Target:
protected List<SmackFuture<LookupConnectionEndpointsResult, Exception>> lookupConnectionEndpoints() { assert discoveredWebsocketEndpoints == null; InternalSmackFuture<LookupConnectionEndpointsResult, Exception> websocketEndpointsLookupFuture = new InternalSmackFuture<>(); connectionInternal.asyncGo(() -> { WebsocketRemoteConnectionEndpoint providedEndpoint = null; URI uri = moduleDescriptor.getExplicitlyProvidedUri(); if (uri != null) { providedEndpoint = new WebsocketRemoteConnectionEndpoint(uri); } if (!moduleDescriptor.isWebsocketEndpointDiscoveryEnabled()) { assert providedEndpoint != null; SecurityMode mode = connectionInternal.connection.getConfiguration().getSecurityMode(); if ((providedEndpoint.isSecureEndpoint() && mode.equals(SecurityMode.disabled)) || (!providedEndpoint.isSecureEndpoint() && mode.equals(SecurityMode.required))) { throw new IllegalStateException("Explicitly configured uri: " + providedEndpoint.getWebsocketEndpoint().toString() + " does not comply with the configured security mode: " + mode); } Result manualResult = new Result(Arrays.asList(providedEndpoint), null); LookupConnectionEndpointsResult endpointsResult = new DiscoveredWebsocketEndpoints(manualResult); websocketEndpointsLookupFuture.setResult(endpointsResult); } else { DomainBareJid host = connectionInternal.connection.getXMPPServiceDomain(); ModularXmppClientToServerConnectionConfiguration configuration = connectionInternal.connection.getConfiguration(); SecurityMode mode = configuration.getSecurityMode(); Result xep0156result = WebsocketRemoteConnectionEndpointLookup.lookup(host, mode); List<WebsocketRemoteConnectionEndpoint> discoveredEndpoints = xep0156result.discoveredRemoteConnectionEndpoints; Result finalResult = new Result(discoveredEndpoints, xep0156result.getLookupFailures()); LookupConnectionEndpointsResult endpointsResult = new DiscoveredWebsocketEndpoints(finalResult); websocketEndpointsLookupFuture.setResult(endpointsResult); } }); return Collections.singletonList(websocketEndpointsLookupFuture); }