auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private int executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { ArrayList<String> immutableList = new ArrayList<>(); LOGGER.info("Executing " + operation); for (Map.Entry<String, HashSet<String>> entry :tablesAndIndexes.entrySet()) { String dataTableFullName = entry.getKey(); HashSet<String> indexes = entry.getValue(); try (Admin admin = queryServices.getAdmin()) { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); if (dataTable.isImmutableRows()) { immutableList.add(dataTableFullName); continue; } LOGGER.info("Executing " + operation + " of " + dataTableFullName); disableTable(admin, dataTableFullName, indexes); modifyTable(admin, dataTableFullName, indexes); enableTable(admin, dataTableFullName, indexes); LOGGER.info("Completed " + operation + " of " + dataTableFullName); } catch (IOException | SQLException e) { LOGGER.severe("Something went wrong while executing " + operation + " steps " + e); return -1; } } executeToolForImmutableTables(queryServices, immutableList); if (upgrade) { for (String dataTableFullName : tablesAndIndexes.keySet()) { rebuildIndexes(conn, conf, dataTableFullName); LOGGER.info("Started index rebuild post " + operation + " of " + dataTableFullName); } } return 0; }

Target:
private int executeTool(Connection conn, ConnectionQueryServices queryServices, Configuration conf) { ArrayList<String> immutableList = new ArrayList<>(); ArrayList<String> mutableList = new ArrayList<>(); for (Map.Entry<String, HashSet<String>> entry :tablesAndIndexes.entrySet()) { String dataTableFullName = entry.getKey(); try { PTable dataTable = PhoenixRuntime.getTableNoCache(conn, dataTableFullName); if (dataTable.isImmutableRows()) { immutableList.add(dataTableFullName); } else { mutableList.add(dataTableFullName); } } catch (SQLException e) { LOGGER.severe("Something went wrong while getting the PTable " + dataTableFullName + " "+e); return -1; } } long startWaitTime = executeToolForImmutableTables(queryServices, immutableList); executeToolForMutableTables(conn, queryServices, conf, mutableList); enableImmutableTables(queryServices, immutableList, startWaitTime); rebuildIndexes(conn, conf, immutableList); return 0; }
Source:
public void renderPath(Map<String, String> _params, UrlBuilder url) { String target = request.url(); Preconditions.checkState( target.startsWith(baseUrl), "Request URL must start with base url", UnsafeArg.of("baseUrl", baseUrl)); String trailing = target.substring(baseUrl.length()); int queryParamsStart = trailing.indexOf('?'); String queryPortion = queryParamsStart == -1 ? trailing : trailing.substring(0, queryParamsStart); for (String pathSegment : pathSplitter.split(queryPortion)) { url.pathSegment(urlDecode(pathSegment)); } if (queryParamsStart != -1) { String querySegments = trailing.substring(queryParamsStart + 1); querySplitter .split(querySegments) .forEach((name, value) -> url.queryParam(urlDecode(name), urlDecode(value))); } }

Target:
public void renderPath(Map<String, String> _params, UrlBuilder url) { String target = request.url(); Preconditions.checkState( target.startsWith(baseUrl), "Request URL must start with base url", UnsafeArg.of("requestUrl", target), UnsafeArg.of("baseUrl", baseUrl)); String trailing = target.substring(baseUrl.length()); int queryParamsStart = trailing.indexOf('?'); String queryPortion = queryParamsStart == -1 ? trailing : trailing.substring(0, queryParamsStart); for (String pathSegment : pathSplitter.split(queryPortion)) { url.pathSegment(urlDecode(pathSegment)); } if (queryParamsStart != -1) { String querySegments = trailing.substring(queryParamsStart + 1); querySplitter .split(querySegments) .forEach((name, value) -> url.queryParam(urlDecode(name), urlDecode(value))); } }
Source:
private void sendDeliveryComplete(IMqttDeliveryToken token) { if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent( new MqttMessageDeliveredEvent(MqttPahoMessageHandler.this, token.getMessageId())); } }

Target:
private void sendDeliveryComplete(IMqttDeliveryToken token) { if (this.async && this.asyncEvents && this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent( new MqttMessageDeliveredEvent(this, token.getMessageId(), getClientId(), getClientInstance())); } }
Source:
public String print(Node node) { final PrettyPrintVisitor visitor = new PrettyPrintVisitor(configuration); node.accept(visitor, null); return visitor.getSource(); }

Target:
public String print(Node node) { final PrettyPrintVisitor visitor = configuration.getVisitorFactory().apply(configuration); node.accept(visitor, null); return visitor.getSource(); }
Source:
public void testHealth() { EtcdHealthResponse health = etcd.getHealth(); assertNotNull(health); }

Target:
public void testHealth() { EtcdHealthResponse health = etcd.getHealth(); assertNotNull(health); assertTrue(health.getHealth().equals("true")); }
Source:
public PropertiesConfig(final String configTemplate, final Path localConfig, final String delimiterRegex) throws IOException { checkNotNull(configTemplate); checkNotNull(delimiterRegex); Resource resource = new ClassPathResource(configTemplate); Properties properties = PropertiesLoaderUtils.loadProperties(resource); if (Files.exists(localConfig)) { properties.load(Files.newBufferedReader(localConfig, StandardCharsets.UTF_8)); } user = readUser(properties); environment = readEnvironment(properties); this.properties = new Properties(collapse(properties, environment.name().toLowerCase())); delimiter = Pattern.compile(delimiterRegex); }

Target:
public PropertiesConfig(final String configTemplate, final Path localConfig, final String delimiterRegex) throws IOException { this(setupPropertiesFromString(configTemplate), localConfig, delimiterRegex); }
Source:
public void shouldPurgeAnAutoGenerationOption() throws Exception { MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); }

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(service.getAutoGenerationOption(Integer.parseInt(getUuid()))); }
Source:
public String getUsername() { return "dleed"; }

Target:
public String getUsername() { return ""; }
Source:
public void testXYFactory() { ITmfTrace trace = getTrace(); assertNotNull(trace); try { runModule(trace); Element viewElement = TmfXmlUtils.getElementInFile(TmfXmlTestFiles.DATA_PROVIDER_SIMPLE_FILE.getPath().toOSString(), TmfXmlStrings.XY_VIEW, XY_VIEW_ID_FACTORY); assertNotNull(viewElement); TmfXmlXYViewCu tgViewCu = TmfXmlXYViewCu.compile(new AnalysisCompilationData(), viewElement); assertNotNull(tgViewCu); DataDrivenXYProviderFactory XYFactory = tgViewCu.generate(); ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = XYFactory.create(trace); assertNotNull(provider); assertEquals(DataDrivenXYDataProvider.ID, provider.getId()); ITmfAnalysisModuleWithStateSystems module = TmfTraceUtils.getAnalysisModuleOfClass(trace, ITmfAnalysisModuleWithStateSystems.class, ANALYSIS_ID); assertNotNull(module); Iterable<@NonNull ITmfStateSystem> stateSystems = module.getStateSystems(); assertNotNull(stateSystems); provider = XYFactory.create(trace, Objects.requireNonNull(Lists.newArrayList(stateSystems)), ANALYSIS_ID); assertNotNull(provider); assertEquals(ANALYSIS_ID, provider.getId()); } finally { trace.dispose(); TmfTraceManager.getInstance().traceClosed(new TmfTraceClosedSignal(this, trace)); } }

Target:
public void testXYFactory() { ITmfTrace trace = getTrace(); assertNotNull(trace); try { runModule(trace); Element viewElement = TmfXmlUtils.getElementInFile(TmfXmlTestFiles.DATA_PROVIDER_SIMPLE_FILE.getPath().toOSString(), TmfXmlStrings.XY_VIEW, XY_VIEW_ID_DELTA); assertNotNull(viewElement); TmfXmlXYViewCu tgViewCu = TmfXmlXYViewCu.compile(new AnalysisCompilationData(), viewElement); assertNotNull(tgViewCu); DataDrivenXYProviderFactory XYFactory = tgViewCu.generate(); ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> provider = XYFactory.create(trace); assertNotNull(provider); assertEquals(DataDrivenXYDataProvider.ID, provider.getId()); ITmfAnalysisModuleWithStateSystems module = TmfTraceUtils.getAnalysisModuleOfClass(trace, ITmfAnalysisModuleWithStateSystems.class, ANALYSIS_ID); assertNotNull(module); Iterable<@NonNull ITmfStateSystem> stateSystems = module.getStateSystems(); assertNotNull(stateSystems); provider = XYFactory.create(trace, Objects.requireNonNull(Lists.newArrayList(stateSystems)), ANALYSIS_ID); assertNotNull(provider); assertEquals(ANALYSIS_ID, provider.getId()); } finally { trace.dispose(); TmfTraceManager.getInstance().traceClosed(new TmfTraceClosedSignal(this, trace)); } }
Source:
private List<LoadHolder> findBestServers( Map<?, LoadHolder> groupServers, Set<ServerLocation> excludedServers, int count) { TreeSet<LoadHolder> bestEntries = new TreeSet<>((l1, l2) -> { int difference = Float.compare(l1.getLoad(), l2.getLoad()); if (difference != 0) { return difference; } ServerLocation sl1 = l1.getLocation(); ServerLocation sl2 = l2.getLocation(); return sl1.compareTo(sl2); }); boolean retainAll = (count < 0); float lastBestLoad = Float.MAX_VALUE; for (Map.Entry<?, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location; Object key = loadEntry.getKey(); if (key instanceof ServerLocationAndMemberId) { location = ((ServerLocationAndMemberId) key).getServerLocation(); } else if (key instanceof ServerLocation) { location = ((ServerLocation) key); } else { throw new InternalGemFireException( "findBestServers method was called with incorrect type parameters."); } if (excludedServers.contains(location)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if ((bestEntries.size() < count) || retainAll || (nextLoad < lastBestLoad)) { bestEntries.add(nextLoadReference); if (!retainAll && (bestEntries.size() > count)) { bestEntries.remove(bestEntries.last()); } LoadHolder lastBestHolder = bestEntries.last(); lastBestLoad = lastBestHolder.getLoad(); } } return new ArrayList<>(bestEntries); }

Target:
List<LoadHolder> findBestServers( Map<?, LoadHolder> groupServers, Set<ServerLocation> excludedServers, int count) { if (count == 0) { return new ArrayList<>(); } TreeSet<LoadHolder> bestEntries = new TreeSet<>((l1, l2) -> { int difference = Float.compare(l1.getLoad(), l2.getLoad()); if (difference != 0) { return difference; } ServerLocation sl1 = l1.getLocation(); ServerLocation sl2 = l2.getLocation(); return sl1.compareTo(sl2); }); boolean retainAll = (count < 0); float lastBestLoad = Float.MAX_VALUE; for (Map.Entry<?, LoadHolder> loadEntry : groupServers.entrySet()) { ServerLocation location; Object key = loadEntry.getKey(); if (key instanceof ServerLocationAndMemberId) { location = ((ServerLocationAndMemberId) key).getServerLocation(); } else if (key instanceof ServerLocation) { location = ((ServerLocation) key); } else { throw new InternalGemFireException( "findBestServers method was called with incorrect type parameters."); } if (excludedServers.contains(location)) { continue; } LoadHolder nextLoadReference = loadEntry.getValue(); float nextLoad = nextLoadReference.getLoad(); if ((bestEntries.size() < count) || retainAll || (nextLoad < lastBestLoad)) { bestEntries.add(nextLoadReference); if (!retainAll && (bestEntries.size() > count)) { bestEntries.remove(bestEntries.last()); } LoadHolder lastBestHolder = bestEntries.last(); lastBestLoad = lastBestHolder.getLoad(); } } return new ArrayList<>(bestEntries); }
Source:
public void logSystemInformation() { if ( getLogger().isInfoEnabled() ) { getLogger().info( getOtherProperties() ); } else { getOtherProperties(); } }

Target:
public void logSystemInformation() { if ( logger.isInfoEnabled() ) { logger.info( getSystemInformation() ); } else { getOtherProperties(); } }
Source:
public static void copyResourcesTo(String targetDirectory) throws IOException { Class<ResourceHandler> c = ResourceHandler.class; for (String file : FILES) { InputStream istream = c.getResourceAsStream("res/" + file); Path target = Paths.get(targetDirectory, file); if (!Files.exists(target)) { Files.createDirectories(target); } Files.copy(istream, Paths.get(targetDirectory, file), StandardCopyOption.REPLACE_EXISTING); } }

Target:
public static void copyResourcesTo(String targetDirectory) throws IOException { Class<ResourceHandler> c = ResourceHandler.class; for (String file : FILES) { InputStream istream = c.getResourceAsStream(Paths.get(RESOURCE_FOLDER, file).toString()); Path target = Paths.get(targetDirectory, file); if (!Files.exists(target)) { Files.createDirectories(target); } Files.copy(istream, Paths.get(targetDirectory, file), StandardCopyOption.REPLACE_EXISTING); } }
Source:
public ValidationResult checkRequiredAccountInfo(String chartOfAccountsCode, String accountNumber, String objectCode) { ValidationResult validationResult = new ValidationResult(true, new ArrayList<String>()); if (chartOfAccountsCode == null || chartOfAccountsCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_CHART_OF_ACCTS_REQUIRED); return validationResult; } else if (accountNumber == null || accountNumber.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_ACCT_NBR_REQUIRED); return validationResult; } else if (objectCode == null || objectCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(ConcurConstants.AccountingStringValidationErrorMessages.ERROR_OBJ_CD_REQUIRED); return validationResult; } return validationResult; }

Target:
public ValidationResult checkRequiredAccountInfo(String chartOfAccountsCode, String accountNumber, String objectCode) { ValidationResult validationResult = new ValidationResult(true, new ArrayList<String>()); if (chartOfAccountsCode == null || chartOfAccountsCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.CHART)); } if (accountNumber == null || accountNumber.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.ACCOUNT_NUMBER)); } if (objectCode == null || objectCode.isEmpty()) { validationResult.setValid(false); validationResult.addMessage(MessageFormat.format(configurationService.getPropertyValueAsString(KFSKeyConstants.ERROR_REQUIRED), ConcurConstants.AccountingStringFieldNames.OBJECT_CODE)); } return validationResult; }
Source:
public SenseUploadConfiguration getSenseUploadConfiguration() { return new SenseUploadConfiguration(); }

Target:
public SenseUploadConfiguration getSenseUploadConfiguration() { return this.senseUploadConfiguration; }
Source:
public void onPartitionBecomeStandbyFromBootstrap(String partitionName) { PartitionStateChangeListener replicationManagerListener = partitionStateChangeListeners.get(StateModelListenerType.ReplicationManagerListener); if (replicationManagerListener != null) { try { replicationManagerListener.onPartitionBecomeStandbyFromBootstrap(partitionName); replicaSyncUpManager.waitBootstrapCompleted(partitionName); } catch (InterruptedException e) { logger.error("Bootstrap was interrupted on partition {}", partitionName); participantMetrics.bootstrapCount.addAndGet(-1); participantMetrics.errorStateCount.addAndGet(1); throw new StateTransitionException("Bootstrap failed or was interrupted", BootstrapFailure); } catch (StateTransitionException e) { logger.error("Bootstrap didn't complete on partition {}", partitionName, e); participantMetrics.bootstrapCount.addAndGet(-1); participantMetrics.errorStateCount.addAndGet(1); throw e; } } participantMetrics.bootstrapCount.addAndGet(-1); participantMetrics.standbyCount.addAndGet(1); }

Target:
public void onPartitionBecomeStandbyFromBootstrap(String partitionName) { PartitionStateChangeListener replicationManagerListener = partitionStateChangeListeners.get(StateModelListenerType.ReplicationManagerListener); try { if (replicationManagerListener != null) { replicationManagerListener.onPartitionBecomeStandbyFromBootstrap(partitionName); replicaSyncUpManager.waitBootstrapCompleted(partitionName); } } catch (InterruptedException e) { logger.error("Bootstrap was interrupted on partition {}", partitionName); participantMetrics.errorStateCount.addAndGet(1); throw new StateTransitionException("Bootstrap failed or was interrupted", BootstrapFailure); } catch (StateTransitionException e) { logger.error("Bootstrap didn't complete on partition {}", partitionName, e); participantMetrics.errorStateCount.addAndGet(1); throw e; } finally { participantMetrics.bootstrapCount.addAndGet(-1); } participantMetrics.standbyCount.addAndGet(1); }
Source:
public void addTransformation(TransformationDescription description) { checkTransformationDescriptionId(description); ODocument source = getOrCreateModel(description.getSourceModel().toString()); ODocument target = getOrCreateModel(description.getTargetModel().toString()); ODocument edge = graph.createEdge(source, target); setIdFieldValue(edge, description.getId()); if (description.getFileName() != null) { setFilenameFieldValue(edge, description.getFileName()); } Map<String, Set<String>> connections = description.getPropertyConnections(); if (connections != null) { for (Map.Entry<String, Set<String>> entry : connections.entrySet()) { StringBuilder builder = new StringBuilder(); for (String property : entry.getValue()) { if (builder.length() != 0) { builder.append(","); } builder.append(property); } edge.field(entry.getKey(), builder.toString()); } } edge.save(); descriptions.put(description.getId(), description); LOGGER.debug("Added transformation description to the graph database", description); }

Target:
public void addTransformation(TransformationDescription description) { checkTransformationDescriptionId(description); ODocument source = getOrCreateModel(description.getSourceModel().toString()); ODocument target = getOrCreateModel(description.getTargetModel().toString()); ODocument edge = graph.createEdge(source, target); OrientModelGraphUtils.setIdFieldValue(edge, description.getId()); if (description.getFileName() != null) { OrientModelGraphUtils.setFilenameFieldValue(edge, description.getFileName()); } OrientModelGraphUtils.fillEdgeWithPropertyConnections(edge, description); edge.save(); descriptions.put(description.getId(), description); LOGGER.debug("Added transformation description to the graph database", description); }
Source:
protected void handleComparePair(S3GuardFsck.ComparePair comparePair, StringBuilder sB, HandleMode handleMode) throws IOException { for (S3GuardFsck.Violation violation : comparePair.getViolations()) { try { ViolationHandler handler = violation.getHandler() .getDeclaredConstructor(S3GuardFsck.ComparePair.class) .newInstance(comparePair); if (handleMode == HandleMode.LOG) { final String errorStr = handler.getError(); sB.append(errorStr); } if (handleMode == HandleMode.FIX) { final String fixStr = handler.fixViolation(rawFs, metadataStore); sB.append(fixStr); } } catch (NoSuchMethodException e) { LOG.error("Can not find declared constructor for handler: {}", violation.getHandler()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.error("Can not instantiate handler: {}", violation.getHandler()); } sB.append(newLine); } }

Target:
protected void handleComparePair(S3GuardFsck.ComparePair comparePair, StringBuilder sB, HandleMode handleMode) throws IOException { for (S3GuardFsck.Violation violation : comparePair.getViolations()) { try { ViolationHandler handler = violation.getHandler() .getDeclaredConstructor(S3GuardFsck.ComparePair.class) .newInstance(comparePair); switch (handleMode) { case FIX: final String errorStr = handler.getError(); sB.append(errorStr); break; case LOG: final String fixStr = handler.fixViolation(rawFs, metadataStore); sB.append(fixStr); break; default: throw new UnsupportedOperationException("Unknown handleMode: " + handleMode); } } catch (NoSuchMethodException e) { LOG.error("Can not find declared constructor for handler: {}", violation.getHandler()); } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) { LOG.error("Can not instantiate handler: {}", violation.getHandler()); } sB.append(newLine); } }
Source:
public static BuildData calculateBuildData( String parentName, String parentFullName, List<BuildData> buildDataList) { if (buildDataList != null && buildDataList.size() == 1) { return buildDataList.get(0); } String projectName = parentFullName.replace(parentName, ""); if (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.lastIndexOf('/')); } if (buildDataList == null) { return null; } for (BuildData buildData : buildDataList) { Set<String> remoteUrls = buildData.getRemoteUrls(); for (String remoteUrl : remoteUrls) { if (remoteUrl.contains(projectName)) { return buildData; } } } return null; }

Target:
public static BuildData calculateBuildData( String parentName, String parentFullName, List<BuildData> buildDataList ) { if (buildDataList == null) { return null; } if (buildDataList.size() == 1) { return buildDataList.get(0); } String projectName = parentFullName.replace(parentName, ""); if (projectName.endsWith("/")) { projectName = projectName.substring(0, projectName.lastIndexOf('/')); } for (BuildData buildData : buildDataList) { Set<String> remoteUrls = buildData.getRemoteUrls(); for (String remoteUrl : remoteUrls) { if (remoteUrl.contains(projectName)) { return buildData; } } } return null; }
Source:
public boolean canMorph(final QualifiedName elementName) { if (readOnly) { return false; } final IValidator validator = document.getValidator(); if (validator == null) { return true; } final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (currentElement == document.getRootElement()) { return false; } if (!validator.isValidSequence(elementName, Node.getNodeNames(currentElement.children()), true)) { return false; } final IElement parent = currentElement.getParentElement(); final int startOffset = currentElement.getStartOffset(); final int endOffset = currentElement.getEndOffset(); final List<QualifiedName> seq1 = Node.getNodeNames(parent.children().before(startOffset)); final List<QualifiedName> seq2 = Arrays.asList(elementName); final List<QualifiedName> seq3 = Node.getNodeNames(parent.children().after(endOffset)); return validator.isValidSequence(parent.getQualifiedName(), seq1, seq2, seq3, true); }

Target:
public boolean canMorph(final QualifiedName elementName) { final IElement currentElement = document.getElementForInsertionAt(getCaretOffset()); if (!canMorphElement(currentElement)) { return false; } final IValidator validator = document.getValidator(); if (!canContainContent(validator, elementName, Node.getNodeNames(currentElement.children()))) { return false; } final IElement parent = currentElement.getParentElement(); final List<QualifiedName> nodesBefore = Node.getNodeNames(parent.children().before(currentElement.getStartOffset())); final List<QualifiedName> nodesAfter = Node.getNodeNames(parent.children().after(currentElement.getEndOffset())); return isValidChild(validator, parent.getQualifiedName(), elementName, nodesBefore, nodesAfter); }
Source:
protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { final Response response = request.send(); final TokenExtractor<OAuth2AccessToken> extractor = api.getAccessTokenExtractor(); if (response.getCode() != 200) { if (extractor instanceof OAuth2AccessTokenJsonExtractor) { final OAuth2AccessTokenJsonExtractor jsonExtractor = (OAuth2AccessTokenJsonExtractor) extractor; throw new OAuthRequestException("Get Access token error", jsonExtractor.extractError(response.getBody())); } else { throw new OAuthException("Get Access token error: " + response.getBody()); } } return extractor.extract(response.getBody()); }

Target:
protected OAuth2AccessToken sendAccessTokenRequestSync(OAuthRequest request) throws IOException { return api.getAccessTokenExtractor().extract(request.send()); }
Source:
public void show() { getElement().getClassList().add("open"); }

Target:
public void show() { getElement().getClassList().add(OPEN); }
Source:
protected IntersectingLatencyTableViewer createTableViewer(@Nullable Composite parent) { SashForm sf = new SashForm(parent, SWT.NONE); TableViewer innerViewer = new TableViewer(sf, SWT.FULL_SELECTION | SWT.VIRTUAL); return new IntersectingLatencyTableViewer(innerViewer); }

Target:
protected LatencyTableViewer createTableViewer(@Nullable Composite parent) { TableViewer innerViewer = new TableViewer(parent, SWT.FULL_SELECTION | SWT.VIRTUAL); return new LatencyTableViewer(innerViewer, true); }
Source:
private void alterMssqlTextColumns() { executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN state VARCHAR(MAX)"); executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN changed_properties VARCHAR(MAX)"); }

Target:
private void alterMssqlTextColumns() { ColumnType stateColType = getTypeOf(getSnapshotTableNameWithSchema(), "state"); ColumnType changedPropertiesColType = getTypeOf(getSnapshotTableNameWithSchema(), "state"); if(stateColType.typeName.equals("text")) { executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN state VARCHAR(MAX)"); } if(changedPropertiesColType.typeName.equals("text")) { executeSQL("ALTER TABLE " + getSnapshotTableNameWithSchema() + " ALTER COLUMN changed_properties VARCHAR(MAX)"); } }
Source:
private ContainerHeartbeatResponse getHeartbeatResponse(StreamingContainerAgent sca) { ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse(); if (this.deployChangeInProgress.get() || sca.deployCnt != this.deployChangeCnt) { LOG.debug("{} deferred requests due to concurrent plan change.", sca.container.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } if (!sca.undeployOpers.isEmpty()) { rsp.undeployRequest = Lists.newArrayList(sca.undeployOpers); rsp.hasPendingRequests = (!sca.deployOpers.isEmpty()); return rsp; } Set<PTOperator> deployOperators = sca.deployOpers.keySet(); if (!deployOperators.isEmpty()) { for (PTContainer c : getPhysicalPlan().getContainers()) { if (c.getState() != PTContainer.State.ACTIVE) { LOG.debug("{} waiting for container activation {}", sca.container.toIdStateString(), c.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } for (PTOperator oper : c.getOperators()) { if (oper.getState() == PTOperator.State.PENDING_UNDEPLOY) { LOG.debug("{} waiting for undeploy {}", sca.container.toIdStateString(), c.toIdStateString(), oper); rsp.hasPendingRequests = true; return rsp; } } } LOG.debug("{} deployable operators: {}", sca.container.toIdStateString(), deployOperators); List<OperatorDeployInfo> deployList = sca.getDeployInfoList(deployOperators); if (deployList != null && !deployList.isEmpty()) { rsp.deployRequest = deployList; rsp.nodeRequests = Lists.newArrayList(); for (PTOperator o : deployOperators) { rsp.nodeRequests.addAll(o.deployRequests); } } rsp.hasPendingRequests = false; return rsp; } return rsp; }

Target:
private ContainerHeartbeatResponse getHeartbeatResponse(StreamingContainerAgent sca) { ContainerHeartbeatResponse rsp = new ContainerHeartbeatResponse(); if (this.deployChangeInProgress.get() || sca.deployCnt != this.deployChangeCnt) { LOG.debug("{} deferred requests due to concurrent plan change.", sca.container.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } if (!sca.undeployOpers.isEmpty()) { rsp.undeployRequest = Lists.newArrayList(sca.undeployOpers); rsp.hasPendingRequests = (!sca.deployOpers.isEmpty()); return rsp; } Set<PTOperator> deployOperators = sca.deployOpers; if (!deployOperators.isEmpty()) { for (PTContainer c : getPhysicalPlan().getContainers()) { if (c.getState() != PTContainer.State.ACTIVE) { LOG.debug("{} waiting for container activation {}", sca.container.toIdStateString(), c.toIdStateString()); rsp.hasPendingRequests = true; return rsp; } for (PTOperator oper : c.getOperators()) { if (oper.getState() == PTOperator.State.PENDING_UNDEPLOY) { LOG.debug("{} waiting for undeploy {}", sca.container.toIdStateString(), c.toIdStateString(), oper); rsp.hasPendingRequests = true; return rsp; } } } LOG.debug("{} deployable operators: {}", sca.container.toIdStateString(), deployOperators); List<OperatorDeployInfo> deployList = sca.getDeployInfoList(deployOperators); if (deployList != null && !deployList.isEmpty()) { rsp.deployRequest = deployList; rsp.nodeRequests = Lists.newArrayList(); for (PTOperator o : deployOperators) { rsp.nodeRequests.addAll(o.deployRequests); } } rsp.hasPendingRequests = false; return rsp; } return rsp; }
Source:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + "spm_status = {3}, non-responsive_timeout = {4}, error = {5}", vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }

Target:
public boolean handleNetworkException(VDSNetworkException ex, VDS vds) { if (vds.getStatus() != VDSStatus.Down) { long timeoutToFence = calcTimeoutToFence(vds.getVmCount(), vds.getSpmStatus()); if (mUnrespondedAttempts.get() < Config.<Integer> GetValue(ConfigValues.VDSAttemptsToResetCount) || (lastUpdate + timeoutToFence) > System.currentTimeMillis()) { boolean result = false; if (vds.getStatus() != VDSStatus.Connecting && vds.getStatus() != VDSStatus.PreparingForMaintenance && vds.getStatus() != VDSStatus.NonResponsive) { setStatus(VDSStatus.Connecting, vds); result = true; } mUnrespondedAttempts.incrementAndGet(); return result; } if (vds.getStatus() == VDSStatus.NonResponsive || vds.getStatus() == VDSStatus.Maintenance) { setStatus(VDSStatus.NonResponsive, vds); return true; } setStatus(VDSStatus.NonResponsive, vds); log.infoFormat( "Server failed to respond, vds_id = {0}, vds_name = {1}, vm_count = {2}, " + "spm_status = {3}, non-responsive_seconds = {4}, error = {5}", vds.getId(), vds.getName(), vds.getVmCount(), vds.getSpmStatus(), TimeUnit.MILLISECONDS.toSeconds(timeoutToFence), ex.getMessage()); AuditLogableBase logable = new AuditLogableBase(vds.getId()); AuditLogDirector.log(logable, AuditLogType.VDS_FAILURE); ResourceManager.getInstance().getEventListener().vdsNotResponding(vds); } return true; }
Source:
public void testAddWithParameterUpdate() throws Exception { assertTrue(new File(db.getWorkTree(), "sub").mkdir()); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); git.commit().setMessage("commit").call(); File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); writer = new PrintWriter(file3); writer.print("content c"); writer.close(); writer = new PrintWriter(file); writer.print("modified content"); writer.close(); FileUtils.delete(file2); git.add().addFilepattern("sub").setUpdate(true).call(); assertEquals( "[sub/a.txt, mode:100644, content:modified content]", indexState(CONTENT)); }

Target:
public void testAddWithParameterUpdate() throws Exception { FileUtils.mkdir(new File(db.getWorkTree(), "sub")); File file = new File(db.getWorkTree(), "sub/a.txt"); FileUtils.createNewFile(file); PrintWriter writer = new PrintWriter(file); writer.print("content"); writer.close(); File file2 = new File(db.getWorkTree(), "sub/b.txt"); FileUtils.createNewFile(file2); writer = new PrintWriter(file2); writer.print("content b"); writer.close(); Git git = new Git(db); git.add().addFilepattern("sub").call(); assertEquals( "[sub/a.txt, mode:100644, content:content]" + "[sub/b.txt, mode:100644, content:content b]", indexState(CONTENT)); git.commit().setMessage("commit").call(); File file3 = new File(db.getWorkTree(), "sub/c.txt"); FileUtils.createNewFile(file3); writer = new PrintWriter(file3); writer.print("content c"); writer.close(); writer = new PrintWriter(file); writer.print("modified content"); writer.close(); FileUtils.delete(file2); git.add().addFilepattern("sub").setUpdate(true).call(); assertEquals( "[sub/a.txt, mode:100644, content:modified content]", indexState(CONTENT)); }
Source:
public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = null; Object hostIdObject = DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).get(); if ( hostIdObject != null) { hostID = Long.parseLong(hostIdObject.toString()); } Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } if (hostID != null) { constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), v.getName(), hardConstraint)); } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }

Target:
public void appendConstraints(AllocationAttempt attempt, AllocationLog log, List<Constraint> constraints) { for (Instance instance : attempt.getInstances()) { List<Volume> volumes = InstanceHelpers.extractVolumesFromMounts(instance, objectManager); for (Volume v : volumes) { if (VolumeConstants.ACCESS_MODE_SINGLE_HOST_RW.equals(v.getAccessMode())) { Long hostID = null; Object hostIdObject = DataAccessor.fromDataFieldOf(v).withKey(VolumeConstants.FIELD_LAST_ALLOCATED_HOST_ID).get(); if ( hostIdObject != null) { hostID = Long.parseLong(hostIdObject.toString()); } Set<Long> hostIds = allocatorDao.findHostsWithVolumeInUse(v.getId()); boolean hardConstraint = false; if (hostIds.size() == 0) { hardConstraint = false; } else if (hostIds.size() == 1) { hardConstraint = true; for(Long id: hostIds) { hostID = id; } } else { throw new FailedToAllocate("SingleHostRW volume is used by mutiple hosts"); } if (hostID != null) { Host host = objectManager.loadResource(Host.class, hostID); String hostName = DataAccessor.fieldString(host, HostConstants.FIELD_HOSTNAME); constraints.add(new VolumeAccessModeSingleHostConstraint(hostID, v.getId(), v.getName(), hostName, hardConstraint)); } } else if (VolumeConstants.ACCESS_MODE_SINGLE_INSTANCE_RW.equals(v.getAccessMode())) { List<Long> currentlyUsedBy = allocatorDao.getInstancesWithVolumeMounted(v.getId(), instance.getId()); if (currentlyUsedBy.size() > 0) { constraints.add(new VolumeAccessModeSingleInstanceConstraint(v.getId(), v.getAccessMode(), currentlyUsedBy)); } } } } }
Source:
default Function<KeyType, Integer> hashFunction() { return Groupers::hash; }

Target:
default ToIntFunction<KeyType> hashFunction() { return Groupers::hash; }
Source:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { final String workspaceId = identity.getWorkspaceId(); if (EphemeralWorkspaceAdapter.isEphemeral(k8sEnv.getAttributes())) { ephemeralWorkspaceAdapter.provision(k8sEnv, identity); return; } final Set<String> subPaths = new HashSet<>(); final PersistentVolumeClaim pvc = newPVC(pvcName, pvcAccessMode, pvcQuantity); k8sEnv.getPersistentVolumeClaims().put(pvcName, pvc); for (Pod pod : k8sEnv.getPods().values()) { PodSpec podSpec = pod.getSpec(); List<Container> containers = new ArrayList<>(); containers.addAll(podSpec.getContainers()); containers.addAll(podSpec.getInitContainers()); for (Container container : podSpec.getContainers()) { String machineName = Names.machineName(pod, container); InternalMachineConfig machineConfig = k8sEnv.getMachines().get(machineName); addMachineVolumes(workspaceId, subPaths, pod, container, machineConfig.getVolumes()); } } if (preCreateDirs && !subPaths.isEmpty()) { pvc.setAdditionalProperty( format(SUBPATHS_PROPERTY_FMT, workspaceId), subPaths.toArray(new String[subPaths.size()])); } }

Target:
public void provision(KubernetesEnvironment k8sEnv, RuntimeIdentity identity) throws InfrastructureException { final String workspaceId = identity.getWorkspaceId(); if (EphemeralWorkspaceUtility.isEphemeral(k8sEnv.getAttributes())) { ephemeralWorkspaceAdapter.provision(k8sEnv, identity); return; } LOG.debug("Provisioning PVC strategy for workspace '{}'", workspaceId); final Set<String> subPaths = new HashSet<>(); final PersistentVolumeClaim pvc = newPVC(pvcName, pvcAccessMode, pvcQuantity); k8sEnv.getPersistentVolumeClaims().put(pvcName, pvc); for (Pod pod : k8sEnv.getPods().values()) { PodSpec podSpec = pod.getSpec(); List<Container> containers = new ArrayList<>(); containers.addAll(podSpec.getContainers()); containers.addAll(podSpec.getInitContainers()); for (Container container : containers) { String machineName = Names.machineName(pod, container); InternalMachineConfig machineConfig = k8sEnv.getMachines().get(machineName); addMachineVolumes(workspaceId, subPaths, pod, container, machineConfig.getVolumes()); } } if (preCreateDirs && !subPaths.isEmpty()) { pvc.setAdditionalProperty( format(SUBPATHS_PROPERTY_FMT, workspaceId), subPaths.toArray(new String[subPaths.size()])); } LOG.debug("PVC strategy provisioning done for workspace '{}'", workspaceId); }
Source:
public DiagnosticsPlugin(int diagnosticsPort, int httpPort, String projectName, String workingDirectory) throws IOException { try { serverSocket = new ServerSocket(diagnosticsPort, SERVER_SOCKET_BACKLOG, InetAddress.getLoopbackAddress()); } catch (IOException | IllegalArgumentException | SecurityException ex) { Logger.sys.error("Problem creating server socket: " + ex); throw ex; } modelMapper = new ModelMapper(projectName); instanceRegister = new InstanceRegister(); animator = new Animator(instanceRegister, modelMapper); server = new DiagnosticsServer(this); try { server.start(httpPort); } catch (IOException e) { Logger.sys.error("Couldn't start HTTP server on port " + httpPort + " in service instance 0x", e); return; } Logger.sys.info("txtUML diagnostics connection is set on HTTP port " + httpPort ); thread = new Thread(this, "txtUMLDiagnosticsPlugin"); thread.start(); }

Target:
public DiagnosticsPlugin(int diagnosticsPort, int httpPort, String projectName, String workingDirectory) throws IOException { try { serverSocket = new ServerSocket(diagnosticsPort, SERVER_SOCKET_BACKLOG, InetAddress.getLoopbackAddress()); } catch (IOException | IllegalArgumentException | SecurityException ex) { Logger.sys.error("Problem creating server socket: " + ex); throw ex; } modelMapper = new ModelMapper(projectName); instanceRegister = new InstanceRegister(); animator = new Animator(instanceRegister, modelMapper); server = new DiagnosticsServer(this); try { server.start(httpPort); } catch (IOException e) { Logger.sys.error("Couldn't start HTTP server on port " + httpPort + " in service instance 0x", e); return; } thread = new Thread(this, "txtUMLDiagnosticsPlugin"); thread.start(); }
Source:
public void eventOccured(String message) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; int i = 0; while (strTok.hasMoreTokens()) { String s = strTok.nextToken(); if (s.contains(SHCMessage.DATA_FLAG)) { data = s; logger.debug("<BaseStation data>[" + (i) + "]: " + data); } } if (data != null) { SHCMessage shcMessage = new SHCMessage(data, packet); SHCHeader shcHeader = shcMessage.getHeader(); logger.debug("BaseStation SenderID: " + shcHeader.getSenderID() + " MsgType: " + shcHeader.getMessageType() + " MsgGroupID:" + shcHeader.getMessageGroupID() + " MsgID: " + shcHeader.getMessageID() + " MsgData: " + shcHeader.getMessageData()); SHCData info = shcMessage.getData(); if (info != null) { logger.debug(info.toString()); } for (SmarthomaticBindingProvider provider : this.providers) { for (String itemName : provider.getItemNames()) { if (shcHeader.getSenderID() == provider.getDeviceId(itemName) && shcHeader.getMessageGroupID() == provider.getMessageGroupId(itemName) && shcHeader.getMessageID() == provider.getMessageId(itemName)) { Type type = shcMessage.openHABStateFromSHCMessage(provider.getItem(itemName)) .get(provider.getMessagePartId(itemName)); String transformed = processTransformation(provider.getConfigParam(itemName, "transformation"), type.toString()); if (type instanceof DecimalType) { type = DecimalType.valueOf(transformed); } if (isDataTypeSupported(provider.getItem(itemName), type)) { eventPublisher.postUpdate(itemName, (State) type); } } } } } }

Target:
public void eventOccured(String message) { StringTokenizer strTok = new StringTokenizer(message, "\n"); String data = null; int i = 0; while (strTok.hasMoreTokens()) { String s = strTok.nextToken(); if (s.contains(SHCMessage.DATA_FLAG)) { data = s; logger.debug("<BaseStation data>[{}]: {}", i, data); } } if (data != null) { SHCMessage shcMessage = new SHCMessage(data, packet); SHCHeader shcHeader = shcMessage.getHeader(); logger.debug("BaseStation SenderID: MsgType: MsgGroupID: MsgID: MsgData: {}", shcHeader.getSenderID(), shcHeader.getMessageType(), shcHeader.getMessageGroupID(), shcHeader.getMessageID(), shcHeader.getMessageData()); SHCData info = shcMessage.getData(); if (info != null) { logger.debug(info.toString()); } for (SmarthomaticBindingProvider provider : this.providers) { for (String itemName : provider.getItemNames()) { if (shcHeader.getSenderID() == provider.getDeviceId(itemName) && shcHeader.getMessageGroupID() == provider.getMessageGroupId(itemName) && shcHeader.getMessageID() == provider.getMessageId(itemName)) { Type type = shcMessage.openHABStateFromSHCMessage(provider.getItem(itemName)) .get(provider.getMessagePartId(itemName)); String transformed = processTransformation(provider.getConfigParam(itemName, "transformation"), type.toString()); if (type instanceof DecimalType) { type = DecimalType.valueOf(transformed); } if (isDataTypeSupported(provider.getItem(itemName), type)) { eventPublisher.postUpdate(itemName, (State) type); } } } } } }
Source:
public MiniEditorComponentObject triggerEditCommentArea() { jsActions.scrollToElement(allCommentsArea); WebElement mostRecentComment = articleComments.get(0); PageObjectLogging.log("First check",mostRecentComment.getText(), true); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement editButton = mostRecentComment.findElement(By.cssSelector(EDIT_BUTTON_SELECTOR)); Actions actions = new Actions(driver); actions.moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }

Target:
public MiniEditorComponentObject triggerEditCommentArea() { jsActions.scrollToElement(allCommentsArea); WebElement mostRecentComment = articleComments.get(0); PageObjectLogging.log("First check",mostRecentComment.getText(), true); JavascriptExecutor js = (JavascriptExecutor) driver; WebElement editButton = mostRecentComment.findElement(By.cssSelector(EDIT_BUTTON_SELECTOR)); new Actions(driver).moveToElement(editButton).perform(); js.executeScript("arguments[0].querySelector(arguments[1]).click()", mostRecentComment, EDIT_BUTTON_SELECTOR); return new MiniEditorComponentObject(driver); }
Source:
private URI createURI(String query, Collection<? extends NameValuePair> origParams) { final List<NameValuePair> params = new ArrayList<>( origParams); if (apiAccessKey != null) { params.add(new BasicNameValuePair("key", apiAccessKey)); } try { final URIBuilder builder = new URIBuilder(baseURL.toURI()); builder.addParameters(new ArrayList<>(origParams)); if (apiAccessKey != null) { builder.addParameter("key", apiAccessKey); } if (!query.isEmpty()) { String builderPath = builder.getPath(); if (null == builderPath) { builderPath = ""; } builder.setPath(builderPath + "/" + query); } return builder.build(); } catch (URISyntaxException e) { throw new RedmineInternalError(e); } }

Target:
private URI createURI(String query, Collection<? extends NameValuePair> origParams) { final List<NameValuePair> params = new ArrayList<>( origParams); if (apiAccessKey != null) { params.add(new BasicNameValuePair("key", apiAccessKey)); } try { final URIBuilder builder = new URIBuilder(baseURL.toURI()); builder.addParameters(new ArrayList<>(origParams)); if (apiAccessKey != null) { builder.addParameter("key", apiAccessKey); } if (!query.isEmpty()) { builder.setPath((builder.getPath() == null? "" : builder.getPath()) + "/" + query); } return builder.build(); } catch (URISyntaxException e) { throw new RedmineInternalError(e); } }
Source:
private Set<GlusterServerInfo> fetchServers(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers; GlusterServersListVDSCommand<VdsIdVDSCommandParametersBase> serversListCommand = createServersListCommand(upServer); fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); if(fetchedServers.size() == 1 && existingServers.size() > 2) { GlusterServerInfo server = fetchedServers.iterator().next(); if(server.getHostnameOrIp().equals(upServer.gethost_name()) || server.getHostnameOrIp().equals(upServer.getManagmentIp())) { upServer = getNewUpServer(existingServers, upServer); if (upServer == null) { log.warnFormat("The only UP server in cluster {0} seems to have been removed from it using gluster CLI. " + "Can't refresh it's data at this point.", cluster.getname()); return null; } fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); } } return fetchedServers; }

Target:
private Set<GlusterServerInfo> fetchServers(VDSGroup cluster, VDS upServer, List<VDS> existingServers) { Set<GlusterServerInfo> fetchedServers; GlusterServersListVDSCommand<VdsIdVDSCommandParametersBase> serversListCommand = createServersListCommand(upServer); fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); if (fetchedServers != null && fetchedServers.size() == 1 && existingServers.size() > 2) { GlusterServerInfo server = fetchedServers.iterator().next(); if(server.getHostnameOrIp().equals(upServer.gethost_name()) || server.getHostnameOrIp().equals(upServer.getManagmentIp())) { upServer = getNewUpServer(existingServers, upServer); if (upServer == null) { log.warnFormat("The only UP server in cluster {0} seems to have been removed from it using gluster CLI. " + "Can't refresh it's data at this point.", cluster.getname()); return null; } fetchedServers = (Set<GlusterServerInfo>)serversListCommand.ExecuteWithReturnValue(); } } return fetchedServers; }