auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void fillPropertyMap(Map<String, Object> map, BlackboardArtifact artifact) { try { for (BlackboardAttribute attribute : artifact.getAttributes()) { final int attributeTypeID = attribute.getAttributeType().getTypeID(); if (attributeTypeID == ATTRIBUTE_TYPE.TSK_PATH_ID.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_TAGGED_ARTIFACT.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE.getTypeID() || attribute.getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.JSON) { } else if (artifact.getArtifactTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG.getTypeID()) { addEmailMsgProperty(map, attribute); } else if (attribute.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) { map.put(attribute.getAttributeType().getDisplayName(), ContentUtils.getStringTime(attribute.getValueLong(), associated)); } else if (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getTypeID() && attributeTypeID == ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()) { String value = attribute.getDisplayString(); if (value.length() > 512) { value = value.substring(0, 512); } map.put(attribute.getAttributeType().getDisplayName(), value); } else { map.put(attribute.getAttributeType().getDisplayName(), attribute.getDisplayString()); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Getting attributes failed", ex); } }

Target:
private void fillPropertyMap(Map<String, Object> map, BlackboardArtifact artifact) { try { for (BlackboardAttribute attribute : artifact.getAttributes()) { final int attributeTypeID = attribute.getAttributeType().getTypeID(); if (attributeTypeID == ATTRIBUTE_TYPE.TSK_PATH_ID.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_TAGGED_ARTIFACT.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_ASSOCIATED_ARTIFACT.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_SET_NAME.getTypeID() || attributeTypeID == ATTRIBUTE_TYPE.TSK_KEYWORD_SEARCH_TYPE.getTypeID() || attribute.getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.JSON) { continue; } else if (artifact.getArtifactTypeID() == BlackboardArtifact.ARTIFACT_TYPE.TSK_EMAIL_MSG.getTypeID()) { addEmailMsgProperty(map, attribute); } else if (attribute.getAttributeType().getValueType() == BlackboardAttribute.TSK_BLACKBOARD_ATTRIBUTE_VALUE_TYPE.DATETIME) { map.put(attribute.getAttributeType().getDisplayName(), ContentUtils.getStringTime(attribute.getValueLong(), associated)); } else if (artifact.getArtifactTypeID() == ARTIFACT_TYPE.TSK_TOOL_OUTPUT.getTypeID() && attributeTypeID == ATTRIBUTE_TYPE.TSK_TEXT.getTypeID()) { String value = attribute.getDisplayString(); if (value.length() > 512) { value = value.substring(0, 512); } map.put(attribute.getAttributeType().getDisplayName(), value); } else { map.put(attribute.getAttributeType().getDisplayName(), attribute.getDisplayString()); } } } catch (TskCoreException ex) { logger.log(Level.SEVERE, "Getting attributes failed", ex); } }
Source:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug("JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); SimpleDateFormat jdbcDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.format(filter.getBeginDate()) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.format(filter.getEndDate().getTime()) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC"; if (filter.getPageSize() != 0x7fffffff) { filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT " + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }

Target:
private String histItemFilterQueryProvider(FilterCriteria filter, int numberDecimalcount, String table, String simpleName) { logger.debug( "JDBC::getHistItemFilterQueryProvider filter = {}, numberDecimalcount = {}, table = {}, simpleName = {}", filter.toString(), numberDecimalcount, table, simpleName); String filterString = ""; if (filter.getBeginDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME>'" + jdbcDateFormat.print(new DateTime(filter.getBeginDate().getTime())) + "'"; } if (filter.getEndDate() != null) { filterString += filterString.isEmpty() ? " WHERE" : " AND"; filterString += " TIME<'" + jdbcDateFormat.print(new DateTime(filter.getEndDate().getTime())) + "'"; } filterString += (filter.getOrdering() == Ordering.ASCENDING) ? " ORDER BY time ASC" : " ORDER BY time DESC"; if (filter.getPageSize() != 0x7fffffff) { filterString += " OFFSET " + filter.getPageNumber() * filter.getPageSize() + " LIMIT " + filter.getPageSize(); } String queryString = "NUMBERITEM".equalsIgnoreCase(simpleName) && numberDecimalcount > -1 ? "SELECT time, ROUND(CAST (value AS numeric)," + numberDecimalcount + ") FROM " + table : "SELECT time, value FROM " + table; if (!filterString.isEmpty()) { queryString += filterString; } logger.debug("JDBC::query queryString = {}", queryString); return queryString; }
Source:
private String buildConnectorUri(Account account, String path) { return buildConnectorUri(account, path, Maps.newHashMap()); }

Target:
private String buildConnectorUri(Account account, String path) { return buildConnectorUri(account, path, Collections.emptyMap()); }
Source:
public void terminate(int count) throws IllegalStateException{ if (count > addresses.size()) { count = addresses.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, props.get("CLOUD_PROVIDER"))); echo("Current number of machines: " + addresses.size()); echo("Desired number of machines: " + (addresses.size() - count)); long startMs = System.currentTimeMillis(); ComputeService compute = new ComputeServiceBuilder(props).build(); int destroyedCount=0; for (int batchSize : calcBatches(count)) { final Map<String, AgentAddress> terminateMap = new HashMap<String, AgentAddress>(); for (AgentAddress address : addresses.subList(0, batchSize)) { terminateMap.put(address.publicAddress, address); } destroyedCount += destroyNodes(compute, terminateMap); } log.info("Updating " + agentsFile.getAbsolutePath()); AgentsFile.save(agentsFile, addresses); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Terminated %s of %s, remaining=%s", destroyedCount, count, addresses.size()); if(destroyedCount!=count){ throw new IllegalStateException("Terminated "+destroyedCount+" of "+count); } }

Target:
public void terminate(int count){ if (count > addresses.size()) { count = addresses.size(); } echoImportant(format("Terminating %s %s machines (can take some time)", count, props.get("CLOUD_PROVIDER"))); echo("Current number of machines: " + addresses.size()); echo("Desired number of machines: " + (addresses.size() - count)); long startMs = System.currentTimeMillis(); ComputeService compute = new ComputeServiceBuilder(props).build(); int destroyedCount=0; for (int batchSize : calcBatches(count)) { final Map<String, AgentAddress> terminateMap = new HashMap<String, AgentAddress>(); for (AgentAddress address : addresses.subList(0, batchSize)) { terminateMap.put(address.publicAddress, address); } destroyedCount += destroyNodes(compute, terminateMap); } log.info("Updating " + agentsFile.getAbsolutePath()); AgentsFile.save(agentsFile, addresses); long durationSeconds = TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis() - startMs); echo("Duration: " + secondsToHuman(durationSeconds)); echoImportant("Terminated %s of %s, remaining=%s", destroyedCount, count, addresses.size()); if(destroyedCount!=count){ throw new IllegalStateException("Terminated "+destroyedCount+" of "+count+ "\n1) You are trying to terminate physical hardware that you own (unsupported feature)"+ "\n2) if and only if you are using AWS, our Harakiri Monitor might have terminated them"+ "\n3) You have not payed you bill and your instances have been terminated by your provider"+ "\n4) You have terminated our own instances perhaps vai some console interface"+ "\n5) Someone else has terminated your instances"+ "\n5) elves ?"+ "\n5) try again"); } }
Source:
public <T> T data(LightblueRequest lightblueRequest, Class<T> type) throws IOException { try{ LightblueResponse response = data(lightblueRequest); JsonNode objectNode = response.getJson().path("processed"); try { return mapper.readValue(objectNode.traverse(), type); } catch (JsonMappingException e) { throw new RuntimeException("Error parsing lightblue response: " + response.getJson().toString(), e); } } catch(RuntimeException e){ throw new LightblueHttpClientException("Error sending lightblue request: " + lightblueRequest.getBody(), e); } }

Target:
public <T> T data(LightblueRequest lightblueRequest, Class<T> type) throws IOException { LightblueResponse response = null; try{ response = data(lightblueRequest); JsonNode objectNode = response.getJson().path("processed"); return mapper.readValue(objectNode.traverse(), type); } catch(RuntimeException | JsonMappingException e) { StringBuilder buff = new StringBuilder(); if (e instanceof JsonMappingException) { buff.append("Error parsing lightblue response: " + ((response == null) ? "null" : response.getJson().toString() + "\n")); } buff.append("Error sending lightblue request: " + lightblueRequest.getBody()); throw new LightblueHttpClientException(buff.toString(), e); } }
Source:
public List<ResourceState> getResourcesState(PerunSession session, Vo vo) throws PrivilegeException, VoNotExistsException, InternalErrorException { TaskManager taskManager = new TaskManagerImpl(); List<Resource> resources = perun.getResourcesManager().getResources(session, vo); List<ResourceState> resourceStateList = new ArrayList<ResourceState>(); for (Resource resource : resources) { List<Task> taskList = taskManager.listAllTasksForFacility(resource.getFacilityId()); END tasks Iterator<Task> iterator = taskList.iterator(); while (iterator.hasNext()) { if ( !(iterator.next().getExecService().getExecServiceType().name().equals("SEND")) ) { iterator.remove(); } } ResourceState resourceState = new ResourceState(); resourceState.setResource(resource); resourceState.setTaskList(taskList); resourceStateList.add(resourceState); } return resourceStateList; }

Target:
public List<ResourceState> getResourcesState(PerunSession session, Vo vo) throws PrivilegeException, VoNotExistsException, InternalErrorException { List<Resource> resources = perun.getResourcesManager().getResources(session, vo); List<ResourceState> resourceStateList = new ArrayList<ResourceState>(); for (Resource resource : resources) { List<Task> taskList = taskManager.listAllTasksForFacility(resource.getFacilityId()); END tasks Iterator<Task> iterator = taskList.iterator(); while (iterator.hasNext()) { if ( !(iterator.next().getExecService().getExecServiceType().equals(ExecService.ExecServiceType.SEND)) ) { iterator.remove(); } } ResourceState resourceState = new ResourceState(); resourceState.setResource(resource); resourceState.setTaskList(taskList); resourceStateList.add(resourceState); } return resourceStateList; }
Source:
public synchronized double getDuration() { return (fEndTime - fStartTime) / 1000000000.0; }

Target:
public synchronized double getDuration() { return (fEndTime - fStartTime) / SECOND_TO_NANOSECOND; }
Source:
public Object get(String key) throws JSONException { if (key == null) { } Object object = this.opt(key); if (object == null) { } return object; }

Target:
public Object get(String key) throws JSONException { if (key == null) { throw new JSONException("Null key."); } Object object = this.opt(key); if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); } return object; }
Source:
public static void closeIfNeeded(Handle handle) { if (UNMANAGED_HANDLES.contains(handle)) { handle.close(); } }

Target:
public static void closeIfNeeded(Handle handle) { if (UNMANAGED_HANDLES.contains(handle)) { try { handle.close(); } finally { UNMANAGED_HANDLES.remove(handle); } } }
Source:
public ServerEndpointMetadata getServerEndpointMetadata(final Class<?> endpoint, final ServerEndpointConfig config) throws DeploymentException { try { ServerEndpointMetadata metadata; ServerEndpoint anno = endpoint.getAnnotation(ServerEndpoint.class); if (anno != null) { AnnotatedServerEndpointMetadata ametadata = new AnnotatedServerEndpointMetadata(this, endpoint, config); AnnotatedEndpointScanner<ServerEndpoint, ServerEndpointConfig> scanner = new AnnotatedEndpointScanner<>(ametadata); metadata = ametadata; scanner.scan(); } else if (Endpoint.class.isAssignableFrom(endpoint)) { @SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>)endpoint; metadata = new SimpleServerEndpointMetadata(eendpoint, config); } else { throw new DeploymentException("Unable to identify as valid Endpoint: " + endpoint); } return metadata; } catch (RuntimeException e) { throw new DeploymentException(e.getMessage(), e); } }

Target:
public ServerEndpointMetadata getServerEndpointMetadata(final Class<?> endpoint, final ServerEndpointConfig config) throws DeploymentException { try { ServerEndpointMetadata metadata; ServerEndpoint anno = endpoint.getAnnotation(ServerEndpoint.class); if (anno != null) { AnnotatedServerEndpointMetadata ametadata = new AnnotatedServerEndpointMetadata(this, endpoint, config); AnnotatedEndpointScanner<ServerEndpoint, ServerEndpointConfig> scanner = new AnnotatedEndpointScanner<>(ametadata); metadata = ametadata; scanner.scan(); } else if (Endpoint.class.isAssignableFrom(endpoint)) { @SuppressWarnings("unchecked") Class<? extends Endpoint> eendpoint = (Class<? extends Endpoint>)endpoint; metadata = new SimpleServerEndpointMetadata(eendpoint, config); } else { String err = "Not a recognized websocket [" + endpoint.getName() + "] does not extend @" + ServerEndpoint.class.getName() + " or extend from " + Endpoint.class.getName(); throw new DeploymentException(err); } return metadata; } catch (DeploymentException e) { throw e; } catch (Throwable t) { throw new DeploymentException(t.getMessage(), t); } }
Source:
public Container and(BitmapContainer x) { int card = this.getCardinality(); if (card <= ArrayContainer.DEFAULT_MAX_SIZE) { if (card > x.cardinality) { card = x.cardinality; } ArrayContainer answer = new ArrayContainer(card); answer.cardinality = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int runStart = Util.toIntUnsigned(this.getValue(rlepos)); int runEnd = runStart + Util.toIntUnsigned(this.getLength(rlepos)); for (int runValue = runStart; runValue <= runEnd; ++runValue) { if (x.contains((short) runValue)) { answer.content[answer.cardinality++] = (short) runValue; } } } return answer; } BitmapContainer answer = x.clone(); int start = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int end = Util.toIntUnsigned(this.getValue(rlepos)); int prevOnes = Util.cardinalityInBitmapRange(answer.bitmap, start, end); Util.resetBitmapRange(answer.bitmap, start, end); answer.updateCardinality(prevOnes, 0); start = end + Util.toIntUnsigned(this.getLength(rlepos)) + 1; } int ones = Util.cardinalityInBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); Util.resetBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); answer.updateCardinality(ones, 0); if (answer.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return answer; } else { return answer.toArrayContainer(); } }

Target:
public Container and(BitmapContainer x) { int card = this.getCardinality(); if (card <= ArrayContainer.DEFAULT_MAX_SIZE) { if (card > x.cardinality) { card = x.cardinality; } ArrayContainer answer = new ArrayContainer(card); answer.cardinality = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int runStart = Util.toIntUnsigned(this.getValue(rlepos)); int runEnd = runStart + Util.toIntUnsigned(this.getLength(rlepos)); for (int runValue = runStart; runValue <= runEnd; ++runValue) { if (x.contains((short) runValue)) { answer.content[answer.cardinality++] = (short) runValue; } } } return answer; } BitmapContainer answer = x.clone(); int start = 0; for (int rlepos = 0; rlepos < this.nbrruns; ++rlepos) { int end = Util.toIntUnsigned(this.getValue(rlepos)); int prevOnes = answer.cardinalityInRange(start, end); Util.resetBitmapRange(answer.bitmap, start, end); answer.updateCardinality(prevOnes, 0); start = end + Util.toIntUnsigned(this.getLength(rlepos)) + 1; } int ones = answer.cardinalityInRange(start, BitmapContainer.MAX_CAPACITY); Util.resetBitmapRange(answer.bitmap, start, BitmapContainer.MAX_CAPACITY); answer.updateCardinality(ones, 0); if (answer.getCardinality() > ArrayContainer.DEFAULT_MAX_SIZE) { return answer; } else { return answer.toArrayContainer(); } }
Source:
public void deleteHybridRole(String roleName) throws UserStoreException { if (UserCoreUtil.isEveryoneRole(roleName, realmConfig)) { throw new UserStoreException("Invalid operation"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.ON_DELETE_ROLE_REMOVE_USER_ROLE_SQL, roleName, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.DELETE_ROLE_SQL, roleName, tenantId); dbConnection.commit(); } catch (SQLException e) { String errorMessage = "Error occurred while deleting Hybrid role :"+roleName; throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } userRealm.getAuthorizationManager().clearRoleAuthorization(roleName); }

Target:
public void deleteHybridRole(String roleName) throws UserStoreException { if (UserCoreUtil.isEveryoneRole(roleName, realmConfig)) { throw new UserStoreException("Invalid operation"); } Connection dbConnection = null; try { dbConnection = getDBConnection(); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.ON_DELETE_ROLE_REMOVE_USER_ROLE_SQL, roleName, tenantId, tenantId); DatabaseUtil.updateDatabase(dbConnection, HybridJDBCConstants.DELETE_ROLE_SQL, roleName, tenantId); dbConnection.commit(); } catch (SQLException e) { String errorMessage = "Error occurred while deleting Hybrid role : " + roleName; if (log.isDebugEnabled()) { log.debug(errorMessage, e); } throw new UserStoreException(errorMessage, e); } finally { DatabaseUtil.closeAllConnections(dbConnection); } userRealm.getAuthorizationManager().clearRoleAuthorization(roleName); }
Source:
public void testForceRefreshWithAutoRefresh() throws Exception { genericSetUp(SEMANTIC_MODEL_PATH_FOR_NULL_VALUE, MODELER_DESCRIPTION_PATH_FOR_NULL_VALUE, SESSION_PATH_FOR_NULL_VALUE); changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); Iterator<DRepresentation> iterator = getRepresentations("PackageDiag").iterator(); DDiagram firstDiag = (DDiagram) iterator.next(); DiagramEditor diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, firstDiag, new NullProgressMonitor()); DDiagram secondDiag = (DDiagram) iterator.next(); diagramEditor = (DiagramEditor) DialectUIManager.INSTANCE.openEditor(session, secondDiag, new NullProgressMonitor()); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); try { applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Diagram should not be empty", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Diagram should not be empty", 1, firstDiag.getOwnedDiagramElements().size()); } catch (NullPointerException exception) { Assert.fail("No expcetion should have been raised during Node creation. This is a regression."); } }

Target:
public void testForceRefreshWithAutoRefresh() throws Exception { changeSiriusPreference(SiriusPreferencesKeys.PREF_AUTO_REFRESH.name(), true); assertTrue("Diagram should be empty", firstDiag.getOwnedDiagramElements().isEmpty()); assertTrue("Diagram should be empty", secondDiag.getOwnedDiagramElements().isEmpty()); applyNodeCreationTool("createPackageWithRefresh", secondDiag, secondDiag); assertEquals("Force refresh diagram has not been refreshed", 1, secondDiag.getOwnedDiagramElements().size()); assertEquals("Non 'Force refresh' diagram has not been refreshed.", 1, firstDiag.getOwnedDiagramElements().size()); }
Source:
protected XBeeMode determineConnectionMode() { dataReader = new DataReader(connectionInterface); dataReader.start(); try { operatingMode = XBeeMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null) { if (response.getResponse()[0] == 0x01) return XBeeMode.API; else return XBeeMode.API_ESCAPE; } } catch (XBeeException e) { e.printStackTrace(); return XBeeMode.UNKNOWN; } catch (InvalidOperatingModeException e) { return XBeeMode.UNKNOWN; } return XBeeMode.UNKNOWN; }

Target:
protected OperatingMode determineConnectionMode() { try { operatingMode = OperatingMode.API; dataReader.setXBeeReaderMode(operatingMode); ATCommandResponse response = sendATCommand(new ATCommand("AP")); if (response.getResponse() != null) { if (response.getResponse()[0] == OperatingMode.API.getID()) return OperatingMode.API; else return OperatingMode.API_ESCAPE; } } catch (XBeeException e) { e.printStackTrace(); return OperatingMode.UNKNOWN; } catch (InvalidOperatingModeException e) { return OperatingMode.UNKNOWN; } return OperatingMode.UNKNOWN; }
Source:
public int getMaxConcurrency() throws IOException { return Integer.parseInt( this.client.getConfig().get(LuaConfigParameter.MAX_CONCURRENCY.toString()) .toString()); }

Target:
public int getMaxConcurrency() throws IOException { return Integer.parseInt( this.client.getConfig().get(LuaConfigParameter.MAX_CONCURRENCY) .toString()); }
Source:
private void compareCompiledPlans(CompiledPlan calcitePlan, CompiledPlan voltdbPlan) { assertEquals(voltdbPlan.hasLimitOrOffset(), calcitePlan.hasLimitOrOffset()); assertEquals(voltdbPlan.hasDeterministicStatement(), calcitePlan.hasDeterministicStatement()); ParameterValueExpression[] voltdbParams = voltdbPlan.getParameters(); ParameterValueExpression[] calciteParams = calcitePlan.getParameters(); assertEquals(voltdbParams.length, calciteParams.length); for (int i = 0; i < voltdbParams.length; ++i) { assertEquals(voltdbParams[i].getParameterIndex(), calciteParams[i].getParameterIndex()); } }

Target:
private void compareCompiledPlans(CompiledPlan calcitePlan, CompiledPlan voltdbPlan) { assertEquals("Plans with different limit or offset", voltdbPlan.hasLimitOrOffset(), calcitePlan.hasLimitOrOffset()); assertEquals("Plans with different determinism", voltdbPlan.hasDeterministicStatement(), calcitePlan.hasDeterministicStatement()); ParameterValueExpression[] voltdbParams = voltdbPlan.getParameters(); ParameterValueExpression[] calciteParams = calcitePlan.getParameters(); assertEquals("Plans with different parameter number", voltdbParams.length, calciteParams.length); for (int i = 0; i < voltdbParams.length; ++i) { assertEquals("The " + i + "-th parameter differ", voltdbParams[i].getParameterIndex(), calciteParams[i].getParameterIndex()); } }
Source:
public HeaderViewHolder(View itemView) { super(itemView); instructionbutton = (Button) itemView.findViewById(R.id.instruction_button); dismissImageButton = (ImageButton) itemView.findViewById(R.id.dismiss_image_button); viewPager = (ViewPager) itemView.findViewById(R.id.view_pager); viewPager.setAdapter(new BannerOnboardingAdapter()); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { if(!isRunning) { startSlidingViewPager(); } } @Override public void onPageScrollStateChanged(int i) { if(isRunning && i == ViewPager.SCROLL_STATE_DRAGGING) { stopSlidingViewPager(); } } }); pageIndicator = (BannerOnboardingPageIndicator) itemView.findViewById(R.id.page_indicator); pageIndicator.setViewPager(viewPager); handler = new Handler(); slideRunnable = new Runnable() { @Override public void run() { int nextItem = viewPager.getCurrentItem() + 1; if(nextItem == viewPager.getAdapter().getCount()) nextItem = 0; viewPager.setCurrentItem(nextItem, true); handler.postDelayed(this, SLIDE_TIME); } }; }

Target:
public HeaderViewHolder(View itemView) { super(itemView); instructionbutton = (Button) itemView.findViewById(R.id.instruction_button); dismissImageButton = (ImageButton) itemView.findViewById(R.id.dismiss_image_button); viewPager = (ViewPager) itemView.findViewById(R.id.view_pager); viewPager.setAdapter(new OnboardingBannerAdapter()); viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int i, float v, int i1) { } @Override public void onPageSelected(int i) { if(!isRunning) { startSlidingViewPager(); } } @Override public void onPageScrollStateChanged(int i) { if(isRunning && i == ViewPager.SCROLL_STATE_DRAGGING) { stopSlidingViewPager(); } } }); pageIndicator = (BannerOnboardingPageIndicator) itemView.findViewById(R.id.page_indicator); pageIndicator.setViewPager(viewPager); handler = new Handler(); slideRunnable = new Runnable() { @Override public void run() { int nextItem = viewPager.getCurrentItem() + 1; if(nextItem == viewPager.getAdapter().getCount()) nextItem = 0; viewPager.setCurrentItem(nextItem, true); handler.postDelayed(this, SLIDE_TIME); } }; }
Source:
public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); thumbnailLoadToggleKey = getString(R.string.download_thumbnail_key); youtubeRestrictedModeEnabledKey = getString(R.string.youtube_restricted_mode_enabled); initialSelectedLocalization = org.schabi.newpipe.util.Localization .getPreferredLocalization(requireContext()); initialSelectedContentCountry = org.schabi.newpipe.util.Localization .getPreferredContentCountry(requireContext()); initialLanguage = PreferenceManager .getDefaultSharedPreferences(requireContext()).getString("app_language_key", "en"); findPreference(getString(R.string.clear_cookie_key)) .setOnPreferenceClickListener(preference -> { defaultPreferences.edit() .putString(getString(R.string.recaptcha_cookies_key), "").apply(); Toast.makeText(getActivity(), R.string.recaptcha_cookies_cleared, Toast.LENGTH_SHORT).show(); return true; }); }

Target:
public void onCreate(@Nullable final Bundle savedInstanceState) { super.onCreate(savedInstanceState); thumbnailLoadToggleKey = getString(R.string.download_thumbnail_key); youtubeRestrictedModeEnabledKey = getString(R.string.youtube_restricted_mode_enabled); initialSelectedLocalization = org.schabi.newpipe.util.Localization .getPreferredLocalization(requireContext()); initialSelectedContentCountry = org.schabi.newpipe.util.Localization .getPreferredContentCountry(requireContext()); initialLanguage = PreferenceManager .getDefaultSharedPreferences(requireContext()).getString("app_language_key", "en"); final Preference clearCookiePref = findPreference(getString(R.string.clear_cookie_key)); clearCookiePref.setOnPreferenceClickListener(preference -> { defaultPreferences.edit() .putString(getString(R.string.recaptcha_cookies_key), "").apply(); DownloaderImpl.getInstance().setCookie(ReCaptchaActivity.RECAPTCHA_COOKIES_KEY, ""); Toast.makeText(getActivity(), R.string.recaptcha_cookies_cleared, Toast.LENGTH_SHORT).show(); clearCookiePref.setVisible(false); return true; }); if (defaultPreferences.getString(getString(R.string.recaptcha_cookies_key), "").isEmpty()) { clearCookiePref.setVisible(false); } }
Source:
public MsgpackGZFileBuilder(MessagePack msgpack, File file) throws IOException { this.log = Exec.getLogger(getClass()); this.file = checkNotNull(file); this.out = new DataSizeFilter(new BufferedOutputStream(new FileOutputStream(file))); this.gzout = new GZIPOutputStream(this.out); this.packer = msgpack.createPacker(this.gzout); this.recordCount = 0; }

Target:
public MsgpackGZFileBuilder(MessagePack msgpack, File file) throws IOException { this.file = checkNotNull(file); this.out = new DataSizeFilter(new BufferedOutputStream(new FileOutputStream(file))); this.gzout = new GZIPOutputStream(this.out); this.packer = msgpack.createPacker(this.gzout); this.recordCount = 0; }
Source:
public InfoPanel(SearchBox searchBox) { setId(ID); addStyleName(ID); addStyleName("v-scrollable"); toggleButton = new CssLayout(); toggleButton.setStyleName("toggle-button"); toggleButton.setDescription(HIDE_TOOLTIP); toggleButton.addLayoutClickListener((event) -> { expanded = !expanded; if (expanded) { toggleButton.removeStyleName("info-panel-collapsed"); toggleButton.setDescription(HIDE_TOOLTIP); } else { toggleButton.addStyleName("info-panel-collapsed"); toggleButton.setDescription(SHOW_TOOLTIP); } refreshInfoArea(); }); staticComponents.add(searchBox); staticComponents.add(toggleButton); graphRenderContainer = new InlineGraphContainer(); staticComponents.add(graphRenderContainer); }

Target:
public InfoPanel(SearchBox searchBox) { setId(ID); addStyleName(ID); addStyleName("v-scrollable"); toggleButton = new CssLayout(); toggleButton.setStyleName("toggle-button"); toggleButton.setDescription(HIDE_TOOLTIP); toggleButton.addLayoutClickListener((event) -> { expanded = !expanded; if (expanded) { toggleButton.removeStyleName("info-panel-collapsed"); toggleButton.setDescription(HIDE_TOOLTIP); } else { toggleButton.addStyleName("info-panel-collapsed"); toggleButton.setDescription(SHOW_TOOLTIP); } refreshInfoArea(); }); staticComponents.add(searchBox); staticComponents.add(toggleButton); staticComponents.add(new InlineGraphContainer()); }
Source:
public void equalsAndHashCodeTest() { Offset o1 = new Offset("test", 2); Offset o2 = new Offset("test", 2); Offset o3 = new Offset("test", 3); Offset o4 = new Offset("test_more", 2); assertTrue("Offset should be equal to itself", o1.equals(o1)); assertFalse("Offset should not be equal to null", o1.equals(null)); assertFalse("Offset should not be equal to random Object", o1.equals(new Object())); assertTrue("Offsets should be declared equal", o1.equals(o2)); assertEquals("Hashcode mismatch", o1.hashCode(), o2.hashCode()); assertFalse("Offsets should be declared unequal", o1.equals(o3)); assertFalse("Hashcode should be declared unequal", o1.equals(o3)); assertFalse("Offsets should be declared unequal", o1.equals(o4)); assertFalse("Hashcode should be declared unequal", o1.equals(o4)); }

Target:
public void equalsAndHashCodeTest() { Offset o1 = new Offset("test", 2); Offset o2 = new Offset("test", 2); Offset o3 = new Offset("test", 3); Offset o4 = new Offset("test_more", 2); assertTrue("Offset should be equal to itself", o1.equals(o1)); assertFalse("Offset should not be equal to null", o1.equals(null)); assertFalse("Offset should not be equal to random Object", o1.equals(new Object())); assertTrue("Offsets should be declared equal", o1.equals(o2)); assertEquals("Hashcode mismatch", o1.hashCode(), o2.hashCode()); assertFalse("Offsets should be declared unequal", o1.equals(o3)); }
Source:
public void setup() { when(mockKvs.getMetadataForTable(TABLE_REF)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE)); when(mockKvs.getMetadataForTable(TABLE_REF2)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.THOROUGH)); partitioner = new WriteInfoPartitioner(mockKvs); writer = new SweepableTimestampsWriter(kvs, partitioner); reader = new SweepableTimestampsReader(kvs, provider); progress = new KvsSweepQueueProgress(kvs); provider = new SweepTimestampProvider(() -> unreadableTs, () -> immutableTs); shard = writeTs(writer, TS, true); shard2 = writeTs(writer, TS2, false); immutableTs = 10 * TS; unreadableTs = 10 * TS; }

Target:
public void setup() { when(mockKvs.getMetadataForTable(TABLE_REF)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.CONSERVATIVE)); when(mockKvs.getMetadataForTable(TABLE_REF2)) .thenReturn(SweepQueueTestUtils.metadataBytes(TableMetadataPersistence.SweepStrategy.THOROUGH)); partitioner = new WriteInfoPartitioner(mockKvs); provider = new SweepTimestampProvider(() -> unreadableTs, () -> immutableTs); writer = new SweepableTimestampsWriter(kvs, partitioner); reader = new SweepableTimestampsReader(kvs, provider); progress = new KvsSweepQueueProgress(kvs); shard = writeTs(writer, TS, true); shard2 = writeTs(writer, TS2, false); immutableTs = 10 * TS; unreadableTs = 10 * TS; }
Source:
private List<ConsumedEvent> extractTimespan(final long batchWindowEndTimestamp) { int count = 1; while (count < nakadiEvents.size() && nakadiEvents.get(count).getTimestamp() < batchWindowEndTimestamp) { count++; } return extract(count); }

Target:
private List<ConsumedEvent> extractTimespan(final long batchWindowEndTimestamp) { batchWindowStartTimestamp = batchWindowEndTimestamp; return extract((i) -> nakadiEvents.get(0).getTimestamp() < batchWindowEndTimestamp); }
Source:
public static void writeIndex(final Index idx, final File idxFile) throws IOException { LittleEndianOutputStream stream = null; try { final OutputStream underlyingStream = (idx instanceof TabixIndex) ? new BlockCompressedOutputStream(idxFile) : new FileOutputStream(idxFile); stream = new LittleEndianOutputStream(new BufferedOutputStream(underlyingStream)); idx.write(stream); } finally { if(stream != null) { stream.close(); } } }

Target:
public static void writeIndex(final Index idx, final File idxFile) throws IOException { idx.write(idxFile); }
Source:
private static CompletableFuture<Boolean> copyAllChunks(boolean includeFirst, AbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash targetSigner, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap.getLocation()) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } return (includeFirst ? network.uploadChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), targetSigner, tid) : CompletableFuture.completedFuture(true)) .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); Optional<byte[]> nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); if (! nextChunkMapKey.isPresent()) return CompletableFuture.completedFuture(true); return copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey.get()), targetSigner, tid, network); }) .thenCompose(b -> { if (! (mOpt.get() instanceof DirAccess)) return CompletableFuture.completedFuture(true); Set<AbsoluteCapability> childCaps = ((DirAccess) mOpt.get()).getChildrenCapabilities(currentCap); return Futures.reduceAll(childCaps, true, (x, cap) -> copyAllChunks(true, cap, targetSigner, tid, network), (x, y) -> x && y); }); }); }

Target:
private static CompletableFuture<Boolean> copyAllChunks(boolean includeFirst, AbsoluteCapability currentCap, SigningPrivateKeyAndPublicHash targetSigner, TransactionId tid, NetworkAccess network) { return network.getMetadata(currentCap.getLocation()) .thenCompose(mOpt -> { if (! mOpt.isPresent()) { return CompletableFuture.completedFuture(true); } return (includeFirst ? network.addPreexistingChunk(mOpt.get(), currentCap.owner, currentCap.getMapKey(), targetSigner, tid) : CompletableFuture.completedFuture(true)) .thenCompose(b -> { CryptreeNode chunk = mOpt.get(); Optional<byte[]> nextChunkMapKey = chunk.getNextChunkLocation(currentCap.rBaseKey); if (! nextChunkMapKey.isPresent()) return CompletableFuture.completedFuture(true); return copyAllChunks(true, currentCap.withMapKey(nextChunkMapKey.get()), targetSigner, tid, network); }) .thenCompose(b -> { if (! (mOpt.get() instanceof DirAccess)) return CompletableFuture.completedFuture(true); Set<AbsoluteCapability> childCaps = ((DirAccess) mOpt.get()).getChildrenCapabilities(currentCap); return Futures.reduceAll(childCaps, true, (x, cap) -> copyAllChunks(true, cap, targetSigner, tid, network), (x, y) -> x && y); }); }); }
Source:
public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); data.write(frameID); try { if (sourceAddress64 != null) data.write(sourceAddress64.getValue()); if (sourceAddress16 != null) data.write(sourceAddress16.getValue()); if (command != null) data.write(ByteUtils.stringToByteArray(command)); if (status != null) data.write(status.getId()); if (commandValue != null) data.write(commandValue); } catch (IOException e) { logger.error(e.getMessage(), e); } return data.toByteArray(); }

Target:
public byte[] getAPIData() { ByteArrayOutputStream data = new ByteArrayOutputStream(); data.write(frameID); try { data.write(sourceAddress64.getValue()); data.write(sourceAddress16.getValue()); data.write(ByteUtils.stringToByteArray(command)); data.write(status.getId()); if (commandValue != null) data.write(commandValue); } catch (IOException e) { logger.error(e.getMessage(), e); } return data.toByteArray(); }
Source:
@Override public SecurityContext authenticate( AuthenticationContext authCtx) throws IgniteCheckedException { SecurityCredentials credentials = authCtx.credentials(); if(credentials != null && user.equals(credentials.getLogin())) { if(credentials.getPassword().toString().equals(password)) { log.info("Admin access granted by " + authCtx.subjectType() + " from " + authCtx.address()); return new AllowAll(); } else { log.warning("Admin password error by " + authCtx.subjectType() + " from " + authCtx.address()); } } UUID uuid = authCtx.subjectId(); SecuritySubjectType securitySubjectType = authCtx.subjectType(); return new AllowSome( new Subject( uuid, securitySubjectType, credentials != null ? credentials.getLogin() : null, authCtx.address() ) ); }

Target:
@Override public SecurityContext authenticate(AuthenticationContext authCtx) { SecurityCredentials credentials = authCtx.credentials(); if (credentials != null && user.equals(credentials.getLogin())) { if (credentials.getPassword().toString().equals(password)) { log.info("Admin access granted by " + authCtx.subjectType() + " from " + authCtx.address()); return new AllowAll(); } else { log.warning("Admin password error by " + authCtx.subjectType() + " from " + authCtx.address()); } } UUID uuid = authCtx.subjectId(); SecuritySubjectType securitySubjectType = authCtx.subjectType(); return new AllowSome( new Subject(uuid, securitySubjectType, credentials != null ? credentials.getLogin() : null, authCtx.address()) ); }
Source:
public String format(@Nullable String pattern) { String formatPattern = pattern; if (formatPattern == null || "%s".equals(formatPattern)) { formatPattern = "%2$s°N %3$s°E %1$sm"; } return String.format(formatPattern, getConstituents().values().toArray()); }

Target:
public String format(@Nullable String pattern) { String formatPattern = pattern; if (formatPattern == null || "%s".equals(formatPattern)) { formatPattern = LOCATION_PATTERN; } return String.format(formatPattern, getConstituents().values().toArray()); }
Source:
public void shouldCallImporterMethodsWithCorrectArguments() { Range<DateTime> range = new Range<>(DATES.get(0), DATES.get(1)); importer = Mockito.mock(CommcareFormImporterImpl.class); when(importer.countForImport(eq(range), eq(CONFIG_NAME))).thenReturn(0); doNothing().when(importer).startImport(eq(range), eq(CONFIG_NAME)); eventHandler.setImporter(importer); MotechEvent event = prepareEvent(true); eventHandler.handleEvent(event); }

Target:
public void shouldCallImporterMethodsWithCorrectArguments() { Range<DateTime> range = new Range<>(DATES.get(0), DATES.get(1)); MotechEvent event = prepareEvent(true); when(importerFactory.getCommcareFormImporter()).thenReturn(importer); when(importer.countForImport(range, CONFIG_NAME)).thenReturn(0); doNothing().when(importer).startImport(range, CONFIG_NAME); eventHandler.handleEvent(event); verify(importer).countForImport(eq(range), eq(CONFIG_NAME)); verify(importer).startImport(eq(range), eq(CONFIG_NAME)); }
Source:
public Collection<Partition<T>> definePartitions(Collection<Partition<T>> partitions, PartitioningContext context) { final int newPartitionCount = DefaultPartition.getRequiredPartitionCount(context, this.partitionCount); logger.debug("define partitions, partitionCount current requested {}", partitions.size(), newPartitionCount); DefaultPartition<T> partition = (DefaultPartition<T>)partitions.iterator().next(); ArrayList<Partition<T>> newPartitions; newPartitions = Lists.newArrayList(); Set partSet = Sets.newHashSet(); for (int partitionCounter = 0; partitionCounter < newPartitionCount; partitionCounter++) { DefaultPartition<T> partitionToAdd = new DefaultPartition<T>(partition.getPartitionedInstance()); newPartitions.add(partitionToAdd); partSet.add(partitionCounter); } List<InputPort<?>> inputPortList = context.getInputPorts(); if (inputPortList != null) { for (InputPort<?> port : inputPortList) { for (int i = 0; i < newPartitions.size(); i++) { newPartitions.get(i).getPartitionKeys().put(port, new PartitionKeys(i, partSet)); } } } logger.debug("new partition size {}", newPartitions.size()); return newPartitions; }

Target:
public Collection<Partition<T>> definePartitions(Collection<Partition<T>> partitions, PartitioningContext context) { final int newPartitionCount = DefaultPartition.getRequiredPartitionCount(context, this.partitionCount); logger.debug("define partitions, partitionCount current requested {}", partitions.size(), newPartitionCount); DefaultPartition<T> partition = (DefaultPartition<T>)partitions.iterator().next(); ArrayList<Partition<T>> newPartitions = Lists.newArrayList(); Set partSet = Sets.newHashSet(); for (int partitionCounter = 0; partitionCounter < newPartitionCount; partitionCounter++) { newPartitions.add(new DefaultPartition<T>(partition.getPartitionedInstance())); partSet.add(partitionCounter); } List<InputPort<?>> inputPortList = context.getInputPorts(); if (inputPortList != null) { for (InputPort<?> port : inputPortList) { for (int i = 0; i < newPartitions.size(); i++) { newPartitions.get(i).getPartitionKeys().put(port, new PartitionKeys(i, partSet)); } } } logger.debug("new partition size {}", newPartitions.size()); return newPartitions; }
Source:
public boolean hasValue(Path desiredPath) { for (AbstractConfigNode node : children) { if (node instanceof ConfigNodeField) { Path key = ((ConfigNodeField) node).path().value(); if (key.equals(desiredPath) || key.startsWith(desiredPath)) { return true; } else if (desiredPath.startsWith(key)) { if (((ConfigNodeField) node).value() instanceof ConfigNodeObject) { Path remainingPath = desiredPath.subPath(key.length()); if (((ConfigNodeObject) ((ConfigNodeField) node).value()).hasValue(remainingPath)) { return true; } } } } } return false; }

Target:
public boolean hasValue(Path desiredPath) { for (AbstractConfigNode node : children) { if (node instanceof ConfigNodeField) { ConfigNodeField field = (ConfigNodeField) node; Path key = field.path().value(); if (key.equals(desiredPath) || key.startsWith(desiredPath)) { return true; } else if (desiredPath.startsWith(key)) { if (field.value() instanceof ConfigNodeObject) { ConfigNodeObject obj = (ConfigNodeObject) field.value(); Path remainingPath = desiredPath.subPath(key.length()); if (obj.hasValue(remainingPath)) { return true; } } } } } return false; }
Source:
private static void skipGeneratedFiles(JavaContext context) { PsiClass[] classes = context.getJavaFile().getClasses(); if (classes.length > 0 && classes[0].getName() != null) { String qualifiedName = classes[0].getName(); if (qualifiedName.contains("PermissionsDispatcher") || qualifiedName .contains("PermissionsDispatcher")) { return; } } }

Target:
private static void skipGeneratedFiles(JavaContext context) { PsiClass[] classes = context.getJavaFile().getClasses(); if (classes.length > 0 && classes[0].getName() != null) { String qualifiedName = classes[0].getName(); if (qualifiedName.contains("PermissionsDispatcher")) { return; } } }
Source:
protected void connectAllHostsToStorage(List<String> connectionIds) { List<Callable<Void>> tasks = new ArrayList<>(); final List<StorageServerConnections> connections = getDbFacade().getStorageServerConnectionDao().getByIds(connectionIds); List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getIscsiBond().getStoragePoolId(), VDSStatus.Up); for (final VDS host : hosts) { tasks.add(new Callable<Void>() { @Override public Void call() throws Exception { try { final List<StorageServerConnections> conns = ISCSIStorageHelper.updateIfaces(connections, host.getId()); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters(host.getId(), Guid.Empty, StorageType.ISCSI, conns) ); final Map<String, String> iscsiMap = (Map<String, String>) returnValue.getReturnValue(); List<String> failedConnectionsList = LinqUtils.filter(iscsiMap.keySet(), new Predicate<String>() { @Override public boolean eval(String a) { return !"0".equals(iscsiMap.get(a)); } }); if (!failedConnectionsList.isEmpty()) { log.errorFormat("Host {0} - {1} encounter problems to connect to the Iscsi Storage Server. The following connections were problematic (connectionid=vdsm result): {2}", host.getName(), host.getId(), iscsiMap.toString()); encounterConnectionProblems = true; } } catch (VdcBLLException e) { log.errorFormat("Could not connect Host {0} - {1} to Iscsi Storage Server. The exception is: {2}", host.getName(), host.getId(), e); encounterConnectionProblems = true; } return null; } }); } ThreadPoolUtil.invokeAll(tasks); }

Target:
protected void connectAllHostsToStorage(List<String> connectionIds) { List<Callable<Void>> tasks = new ArrayList<>(); final List<StorageServerConnections> connections = getDbFacade().getStorageServerConnectionDao().getByIds(connectionIds); List<VDS> hosts = getVdsDAO().getAllForStoragePoolAndStatus(getIscsiBond().getStoragePoolId(), VDSStatus.Up); for (final VDS host : hosts) { tasks.add(new Callable<Void>() { @Override public Void call() throws Exception { try { final List<StorageServerConnections> conns = ISCSIStorageHelper.updateIfaces(connections, host.getId()); VDSReturnValue returnValue = runVdsCommand(VDSCommandType.ConnectStorageServer, new StorageServerConnectionManagementVDSParameters(host.getId(), Guid.Empty, StorageType.ISCSI, conns) ); final Map<String, String> iscsiMap = (Map<String, String>) returnValue.getReturnValue(); List<String> failedConnectionsList = LinqUtils.filter(iscsiMap.keySet(), new Predicate<String>() { @Override public boolean eval(String a) { return !"0".equals(iscsiMap.get(a)); } }); if (!failedConnectionsList.isEmpty()) { log.errorFormat("Host {0} - {1} encounter problems to connect to the iSCSI Storage Server. The following connections were problematic (connectionid=vdsm result): {2}", host.getName(), host.getId(), iscsiMap.toString()); encounterConnectionProblems = true; } } catch (VdcBLLException e) { log.errorFormat("Could not connect Host {0} - {1} to Iscsi Storage Server. The exception is: {2}", host.getName(), host.getId(), e); encounterConnectionProblems = true; } return null; } }); } ThreadPoolUtil.invokeAll(tasks); }