auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void updateNotMatchingIDsInJSONAndURL() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat1 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 1") .build(); BitstreamFormat bitstreamFormat2 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 2") .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat1); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setId(bitstreamFormat2.getID()); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat1.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) <START> .andExpect(status().isBadRequest()); <END> }</code><technical_language>please check changes occur a separate GET request (please do in next calls)</technical_language>

Target:
public void updateNotMatchingIDsInJSONAndURL() throws Exception { ObjectMapper mapper = new ObjectMapper(); context.turnOffAuthorisationSystem(); BitstreamFormat bitstreamFormat1 = BitstreamFormatBuilder.createBitstreamFormat(context) .withShortDescription("Test short") .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 1") .build(); BitstreamFormat bitstreamFormat2 = BitstreamFormatBuilder.createBitstreamFormat(context) .withMimeType("application/octet-stream") .withDescription("Description - updateNotMatchingIDsInJSONAndURL 2") .build(); context.restoreAuthSystemState(); BitstreamFormatRest bitstreamFormatRest = converter.fromModel(bitstreamFormat1); String token = getAuthToken(admin.getEmail(), password); bitstreamFormatRest.setShortDescription("Test short UPDATED"); bitstreamFormatRest.setId(bitstreamFormat2.getID()); getClient(token).perform(put("/api/core/bitstreamformats/" + bitstreamFormat1.getID()) .content(mapper.writeValueAsBytes(bitstreamFormatRest)).contentType(contentType)) .andExpect(status().isBadRequest()); getClient().perform(get("/api/core/bitstreamformats/" + bitstreamFormat1.getID())) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$", Matchers.is( BitstreamFormatMatcher .matchBitstreamFormat(bitstreamFormat1.getID(), bitstreamFormat1.getMIMEType(), bitstreamFormat1.getDescription(), bitstreamFormat1.getShortDescription()) ))); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_save_page: <START> if (item.getTitle().equals(WikipediaApp.getInstance().getString(R.string.menu_refresh_saved_page))) { <END> refreshPage(true); } else { savePage(); app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); } return true; case R.id.menu_share_page: shareHandler.shareWithoutSelection(); return true; case R.id.menu_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_find_in_page: showFindInPage(); return true; case R.id.menu_themechooser: getPageActivity().showThemeChooser(); return true; case R.id.menu_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }</code><technical_language>Fragment.getString() instead</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.homeAsUp: return true; case R.id.menu_page_save: if (item.getTitle().equals(getString(R.string.menu_refresh_saved_page))) { refreshPage(true); } else { savePage(); app.getFunnelManager().getSavedPagesFunnel(model.getTitle().getSite()).logSaveNew(); } return true; case R.id.menu_page_share: shareHandler.shareWithoutSelection(); return true; case R.id.menu_page_other_languages: Intent langIntent = new Intent(); langIntent.setClass(getActivity(), LangLinksActivity.class); langIntent.setAction(LangLinksActivity.ACTION_LANGLINKS_FOR_TITLE); langIntent.putExtra(LangLinksActivity.EXTRA_PAGETITLE, model.getTitle()); getActivity().startActivityForResult(langIntent, PageActivity.ACTIVITY_REQUEST_LANGLINKS); return true; case R.id.menu_page_find_in_page: showFindInPage(); return true; case R.id.menu_page_font_and_theme: getPageActivity().showThemeChooser(); return true; case R.id.menu_page_show_tabs: tabsProvider.enterTabMode(); return true; default: return super.onOptionsItemSelected(item); } }
Source:
<code>public void testApplication() { try { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); XmlDataEmitterOperator input = dag.addOperator("data", new XmlDataEmitterOperator()); XmlParser parser = dag.addOperator("xmlparser", new XmlParser()); ResultCollector rc = dag.addOperator("rc", new ResultCollector()); dag.getMeta(parser).getMeta(parser.out).getAttributes().put(Context.PortContext.TUPLE_CLASS, com.datatorrent.lib.parser.XmlParserTest.EmployeeBean.class); ConsoleOutputOperator xmlObjectOp = dag.addOperator("xmlObjectOp", new ConsoleOutputOperator()); xmlObjectOp.setDebug(true); dag.addStream("input", input.output, parser.in); dag.addStream("output", parser.parsedOutput, xmlObjectOp.input); dag.addStream("pojo", parser.out,rc.input); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return TupleCount == 1; } }); <START> lc.run(30000); END> Assert.assertEquals(1,TupleCount); Assert.assertEquals("john", obj.getName()); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }</code><technical_language>nice rewrite test new embedded mode API. clear 30s expected result</technical_language>

Target:
public void testApplication() { try { LocalMode lma = LocalMode.newInstance(); DAG dag = lma.getDAG(); XmlDataEmitterOperator input = dag.addOperator("data", new XmlDataEmitterOperator()); XmlParser parser = dag.addOperator("xmlparser", new XmlParser()); ResultCollector rc = dag.addOperator("rc", new ResultCollector()); dag.getMeta(parser).getMeta(parser.out).getAttributes().put(Context.PortContext.TUPLE_CLASS, com.datatorrent.lib.parser.XmlParserTest.EmployeeBean.class); ConsoleOutputOperator xmlObjectOp = dag.addOperator("xmlObjectOp", new ConsoleOutputOperator()); xmlObjectOp.setDebug(true); dag.addStream("input", input.output, parser.in); dag.addStream("output", parser.parsedOutput, xmlObjectOp.input); dag.addStream("pojo", parser.out,rc.input); LocalMode.Controller lc = lma.getController(); lc.setHeartbeatMonitoringEnabled(false); ((StramLocalCluster)lc).setExitCondition(new Callable<Boolean>() { @Override public Boolean call() throws Exception { return TupleCount == 1; } }); lc.run(10000); Assert.assertEquals(1,TupleCount); Assert.assertEquals("john", obj.getName()); } catch (ConstraintViolationException e) { Assert.fail("constraint violations: " + e.getConstraintViolations()); } }
Source:
<code>public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { Repository repo = getRepository(); <START> try { <END> return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } finally { repo.close(); } }</code><technical_language>NIT: if repository is AutoCloseable try-with-resources is - if callable close fails initial error swallowed code is :-( (surely move parent 1.625 if is already?)</technical_language>

Target:
public <T> T withRepository(RepositoryCallback<T> callable) throws IOException, InterruptedException { try (Repository repo = getRepository()) { return callable.invoke(repo, Jenkins.MasterComputer.localChannel); } }
Source:
<code>public String getIdentifier() { return <START> "org.eclipse.ltk.core.refactoring.renameResourceProcessor"; <END> }</code><technical_language>a identifier RenameResourceProcessor</technical_language>

Target:
public String getIdentifier() { return "org.eclipse.ltk.core.refactoring.moveRenameResourceProcessor"; }
Source:
<code>public void testCompareWithChangedNewComponents() throws IOException { final String newConceptId = createNewConcept(branchPath); final ImmutableMap<String, Object> compareRequest = createCompareRequest(parentBranch, branchPath); <START> final InputStream responseInputStream = givenAuthenticatedRequest(SCT_API) <END> .contentType(ContentType.JSON) .accept(ContentType.JSON) .body(compareRequest) .post("/compare") .asInputStream(); final ObjectMapper mapper = new ObjectMapper(); final CompareResult compareResult = mapper.readValue(responseInputStream, CompareResult.class); final Set<ComponentIdentifier> newIds = prepareNewChanges(newConceptId, branchPath); assertThat(compareResult.getNewComponents()).containsAll(newIds); assertThat(compareResult.getChangedComponents()).doesNotContainAnyElementsOf(newIds); assertThat(compareResult.getDeletedComponents()).isEmpty(); }</code><technical_language>Extract common compare functionality helper methods tests more readable</technical_language>

Target:
public void testCompareWithChangedNewComponents() throws IOException { final String newConceptId = createNewConcept(branchPath); final CompareResult compareResult = getCompareResult(parentBranch.getPath(), branchPath.getPath()); final Set<ComponentIdentifier> newIds = prepareNewChanges(newConceptId, branchPath); assertThat(compareResult.getNewComponents()).containsAll(newIds); assertThat(compareResult.getChangedComponents()).doesNotContainAnyElementsOf(newIds); assertThat(compareResult.getDeletedComponents()).isEmpty(); }
Source:
<code>void handleExpiredRequest(String processorId, String preferredHost, SamzaResourceRequest request) { boolean resourceAvailableOnAnyHost = hasAllocatedResource(ResourceRequestState.ANY_HOST); <START> if (hostAffinityEnabled && standbyContainerManager.isPresent()) { <END> standbyContainerManager.get() .handleExpiredResourceRequest(processorId, request, Optional.ofNullable(peekAllocatedResource(ResourceRequestState.ANY_HOST)), this, resourceRequestState); } else if (resourceAvailableOnAnyHost) { LOG.info("Request for Processor ID: on host: has expired. Running on ANY_HOST", processorId, preferredHost); runStreamProcessor(request, ResourceRequestState.ANY_HOST); } else { LOG.info("Request for Processor ID: on host: has expired. Requesting additional resources on ANY_HOST.", processorId, preferredHost); resourceRequestState.cancelResourceRequest(request); requestResource(processorId, ResourceRequestState.ANY_HOST); } }</code><technical_language>need hostAffinityEnabled check here. assume standbyContainer is present host-affinity is enabled</technical_language>

Target:
void handleExpiredRequest(String processorId, String preferredHost, SamzaResourceRequest request) { boolean resourceAvailableOnAnyHost = hasAllocatedResource(ResourceRequestState.ANY_HOST); if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleExpiredResourceRequest(processorId, request, Optional.ofNullable(peekAllocatedResource(ResourceRequestState.ANY_HOST)), this, resourceRequestState); } else if (resourceAvailableOnAnyHost) { LOG.info("Request for Processor ID: on host: has expired. Running on ANY_HOST", processorId, preferredHost); runStreamProcessor(request, ResourceRequestState.ANY_HOST); } else { LOG.info("Request for Processor ID: on host: has expired. Requesting additional resources on ANY_HOST.", processorId, preferredHost); resourceRequestState.cancelResourceRequest(request); requestResource(processorId, ResourceRequestState.ANY_HOST); } }
Source:
<code>public static String format(String fmt, Object... objects) { List<String> strings = new ArrayList<String>(); for (Object object : objects) { strings.add(object.toString()); } String result = fmt; for (int i = 0; i < strings.size(); i += 2) { String pattern = "{" + strings.get(i) + "}"; String replacement = strings.get(i + 1); <START> result = result.replaceAll(pattern, replacement); <END> } return result; }</code><technical_language>Nit: This treats pattern a regex, shouldn't</technical_language>

Target:
public static String format(String fmt, Object... objects) { List<String> strings = new ArrayList<String>(); for (Object object : objects) { strings.add(object.toString()); } String result = fmt; for (int i = 0; i < strings.size(); i += 2) { String target = "{" + strings.get(i) + "}"; String replacement = strings.get(i + 1); result = result.replace(target, replacement); } return result; }
Source:
<code>public Stream<PojoPropertyModel<?>> getDeclaredProperties() { return Arrays.stream( declaredBeanInfo.getPropertyDescriptors() ) <START> .map( this::createProperty ); <END> }</code><technical_language>unnecessary? A property a setter getter, in case in Search. EDIT: I understand longer necessary switch HCANN in next commit. merge this change next commit</technical_language>

Target:
public Stream<PojoPropertyModel<?>> getDeclaredProperties() { return declaredProperties.values().stream() .map( this::createProperty ); }
Source:
<code>private boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); if (lun.getLunType() == StorageType.UNKNOWN) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); <START> return false; <END> } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); return false; } return true; }</code><technical_language>failCanDoAction(message)</technical_language>

Target:
private boolean checkIfLunDiskCanBeAdded() { LUNs lun = ((LunDisk) getParameters().getDiskInfo()).getLun(); switch (lun.getLunType()) { case UNKNOWN: return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); case ISCSI: if (lun.getLunConnections().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_HAS_NO_VALID_TYPE); } for (storage_server_connections conn : lun.getLunConnections()) { if (StringUtils.isEmpty(conn.getiqn()) || StringUtils.isEmpty(conn.getconnection()) || StringUtils.isEmpty(conn.getport())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_ISCSI_MISSING_CONNECTION_PARAMS); } } } if (getDiskLunMapDao().getDiskIdByLunId(lun.getLUN_id()) != null) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_DISK_LUN_IS_ALREADY_IN_USE); } return true; }
Source:
<code><START> private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { <END> assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); if (getMarshallerType() == Marshaller.NEW) { assertNotNull(executionSet.getCancelActivity()); assertEquals(isCancelling, executionSet.getCancelActivity().getValue()); assertNotNull(executionSet.getSlaDueDate()); assertEquals(slaDueDate, executionSet.getSlaDueDate().getValue()); } assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); }</code><technical_language>I wondering refactor this method methods below. do think</technical_language>

Target:
private void assertTimerEventMultiple(CancellingTimerEventExecutionSet executionSet, String timerValue, String timeCycleLanguage, boolean isCancelling, String slaDueDate) { assertNotNull(executionSet); assertNotNull(executionSet.getTimerSettings()); assertEquals(timerValue, executionSet.getTimerSettings().getValue().getTimeCycle()); assertEquals(timeCycleLanguage, executionSet.getTimerSettings().getValue().getTimeCycleLanguage()); assertNull(executionSet.getTimerSettings().getValue().getTimeDuration()); assertNull(executionSet.getTimerSettings().getValue().getTimeDate()); assertEventCancelActivity(executionSet, isCancelling); assertTimerEventSlaDueDate(executionSet, slaDueDate); }
Source:
<code>protected ESClient createRestClient(ElasticSearchClientConfig config) { String addressList = config.getOption("addressList", ""); if (addressList.isEmpty()) { throw new IllegalArgumentException("No addressList option provided cannot connect RestClient"); } String[] hosts = addressList.split(","); HttpHost[] httpHosts = new HttpHost[hosts.length]; int i = 0; for (String host : hosts) { try { int hostPort = DEFAULT_HOST_PORT; if (!host.startsWith("http")) { host = DEFAULT_SCHEMA_HTTP +host; } URL hostUrl = new URL(host); if (hostUrl.getPort() != -1) { hostPort = hostUrl.getPort(); } <START> httpHosts[i++] = new HttpHost(hostUrl.getHost(), hostPort, hostUrl.getProtocol()); <END> } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid host "+host+ " "+e.getMessage()); } } RestClientBuilder builder = RestClient.builder(httpHosts) .setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectTimeout( getConnectTimeoutMs(config)).setSocketTimeout( getSocketTimeoutMs(config))) .setMaxRetryTimeoutMillis(getConnectTimeoutMs(config)); if (StringUtils.isNotBlank(config.getOption(AUTH_USER_OPT)) || StringUtils.isNotBlank(config.getOption(KEYSTORE_PATH_OPT))) { addClientCallback(config, builder); } RestClient lowLevelRestClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient); return new ESRestClient(lowLevelRestClient, client); }</code><technical_language>Sound great. I change it</technical_language>

Target:
protected ESClient createRestClient(ElasticSearchClientConfig config) { String addressList = config.getOption("addressList", ""); if (addressList.isEmpty()) { throw new IllegalArgumentException("No addressList option provided cannot connect RestClient"); } String[] hosts = addressList.split(","); HttpHost[] httpHosts = new HttpHost[hosts.length]; int i = 0; for (String host : hosts) { httpHosts[i++] = HttpHost.create(host); } RestClientBuilder builder = RestClient.builder(httpHosts) .setRequestConfigCallback( requestConfigBuilder -> requestConfigBuilder.setConnectTimeout( getConnectTimeoutMs(config)).setSocketTimeout( getSocketTimeoutMs(config))) .setMaxRetryTimeoutMillis(getConnectTimeoutMs(config)); if (StringUtils.isNotBlank(config.getOption(AUTH_USER_OPT)) || StringUtils.isNotBlank(config.getOption(KEYSTORE_PATH_OPT))) { addClientCallback(config, builder); } RestClient lowLevelRestClient = builder.build(); RestHighLevelClient client = new RestHighLevelClient(lowLevelRestClient); return new ESRestClient(lowLevelRestClient, client); }
Source:
<code>protected boolean canDoAction() { <START> VDSGroup cluster = getDbFacade().getVdsGroupDao().get(getVds().getVdsGroupId()); <END> if (!cluster.supportsGlusterService() || !GlusterFeatureSupported.glusterDiskProvisioning(cluster.getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_PROVISIONING_NOT_SUPPORTED_BY_CLUSTER); } VdsValidator validator = new VdsValidator(getVds()); return validate(validator.isUp()); }</code><technical_language>call getVdsGroup()</technical_language>

Target:
protected boolean canDoAction() { VDSGroup cluster = getVdsGroup(); if (!cluster.supportsGlusterService() || !GlusterFeatureSupported.glusterBrickProvisioning(cluster.getCompatibilityVersion())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_PROVISIONING_NOT_SUPPORTED_BY_CLUSTER); } VdsValidator validator = new VdsValidator(getVds()); return validate(validator.isUp()); }
Source:
<code>static Optional<String> getFailureReason(ResponseInfo responseInfo) { Throwable failure = responseInfo.getFailureCause(); if (failure == null) { return Optional.empty(); } <START> String className = failure.getClass().getSimpleName().toUpperCase(); <END> if (className.endsWith("EXCEPTION")) { return Optional.of(className.substring(0, className.lastIndexOf("EXCEPTION"))); } return Optional.of(className); }</code><technical_language>set locale</technical_language>

Target:
static Optional<String> getFailureReason(ResponseInfo responseInfo) { Optional<Throwable> failure = responseInfo.getFailureCause(); if (!failure.isPresent()) { return Optional.empty(); } String className = failure.get().getClass().getSimpleName().toUpperCase(Locale.US); if (className.endsWith("EXCEPTION")) { return Optional.of(className.substring(0, className.lastIndexOf("EXCEPTION"))); } return Optional.of(className); }
Source:
<code>public @ResponseBody Map<String, Object> reviewJSON(@RequestBody RunEnhancementsRequest data, HttpServletRequest request, HttpServletResponse response) { Map<String, Object> result = new HashMap<>(); AccessGroupSet groups = GroupsThreadStore.getGroups(); for (String pid : data.getPids()) { if (!aclService.hasAccess(new PID(pid), groups, Permission.editAccessControl)) { result.put("error", "Insufficient permissions to perform operation"); return result; } } Job job = new Job(RunEnhancementsTreeJob.class.getName(), data.getPids(), data.isForce()); jesqueClient.enqueue(runEnhancementQueueName, job); <START> if (data.isForce()) { <END> result.put("message", "Forced enhancement of " + data.getPids().size() + " object(s) and their children has begun"); } else { result.put("message", "Enhancement of " + data.getPids().size() + " object(s) and their children has begun"); } result.put("success", true); return result; }</code><technical_language>I necessary differentiate cases in result message -- "enhancement ... begun" is sufficient</technical_language>

Target:
public @ResponseBody Map<String, Object> reviewJSON(@RequestBody RunEnhancementsRequest data, HttpServletRequest request, HttpServletResponse response) { Map<String, Object> result = new HashMap<>(); AccessGroupSet groups = GroupsThreadStore.getGroups(); for (String pid : data.getPids()) { if (!aclService.hasAccess(new PID(pid), groups, Permission.editAccessControl)) { result.put("error", "Insufficient permissions to perform operation"); return result; } } Job job = new Job(RunEnhancementsTreeJob.class.getName(), data.getPids(), data.isForce()); jesqueClient.enqueue(runEnhancementQueueName, job); result.put("message", "Enhancement of " + data.getPids().size() + " object(s) and their children has begun"); result.put("success", true); return result; }
Source:
<code>public void testExecute_addCsrfTokenCookies_shouldAddToResponseAccordingToExistingCsrfToken() { MockHttpServletRequest mockRequest = new MockHttpServletRequest(getRequestMethod(), Const.ResourceURIs.URI_PREFIX + getActionUri()); <START> String expectedCsrfToken = StringHelper.encrypt(mockRequest.getSession().getId()); <END> String[] emptyParams = new String[] {}; ______TS("No logged in user"); gaeSimulation.logoutUser(); GetAuthInfoAction a = getAction(emptyParams); JsonResult r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with fake csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); Cookie cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, "someFakeCsrfToken"); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with non existing csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); a = getAction(emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with matched CSRF token cookies"); loginAsInstructor("idOfInstructor1OfCourse1"); cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, StringHelper.encrypt(mockRequest.getSession().getId())); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(0, r.getCookies().size()); }</code><technical_language>hard-code session id 1234</technical_language>

Target:
public void testExecute_addCsrfTokenCookies_shouldAddToResponseAccordingToExistingCsrfToken() { String expectedCsrfToken = StringHelper.encrypt("1234"); String[] emptyParams = new String[] {}; ______TS("No logged in user"); gaeSimulation.logoutUser(); GetAuthInfoAction a = getAction(emptyParams); JsonResult r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with fake csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); Cookie cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, "someFakeCsrfToken"); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with non existing csrf token"); loginAsInstructor("idOfInstructor1OfCourse1"); a = getAction(emptyParams); r = getJsonResult(a); assertEquals(expectedCsrfToken, r.getCookies().get(0).getValue()); ______TS("User logged in with matched CSRF token cookies"); loginAsInstructor("idOfInstructor1OfCourse1"); cookieToAdd = new Cookie(Const.CsrfConfig.TOKEN_COOKIE_NAME, StringHelper.encrypt("1234")); a = getActionWithCookie(new ArrayList<>(Arrays.asList(cookieToAdd)), emptyParams); r = getJsonResult(a); assertEquals(0, r.getCookies().size()); }
Source:
<code><START> public void endSuccessfully() { <END> }</code><technical_language>setSucceeded(true) IIRC</technical_language>

Target:
public void endSuccessfully() { enclosingCommand.getReturnValue().setSucceeded(true); }
Source:
<code>Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException; default Entity createEntityNaturally(EntityType type, Vector3i position) throws IllegalArgumentException, IllegalStateException { <START> return createEntity(type, position.toDouble()); <END> }</code><technical_language>I assume meant call createEntityNaturally here</technical_language>

Target:
Entity createEntityNaturally(EntityType type, Vector3d position) throws IllegalArgumentException, IllegalStateException; default Entity createEntityNaturally(EntityType type, Vector3i position) throws IllegalArgumentException, IllegalStateException { checkNotNull(position, "position"); return createEntityNaturally(type, position.toDouble()); }
Source:
<code>public void run() { log.info("Starting git/repo artifact migration"); Predicate<Pipeline> hasExpectedGitRepoArtifact = p -> { List<Map> expectedArtifacts = (List<Map>) p.get("expectedArtifacts"); if (expectedArtifacts == null) { return false; } return expectedArtifacts.stream() .anyMatch( e -> { Map matchArtifact = (Map<String, Object>) e.get("matchArtifact"); Map defaultArtifact = (Map<String, Object>) e.get("defaultArtifact"); <START> return matchArtifact != null <END> && isGitRepoArtifact(matchArtifact) && hasSubpathInMetadata(matchArtifact) || defaultArtifact != null && isGitRepoArtifact(defaultArtifact) && hasSubpathInMetadata(defaultArtifact); }); }; pipelineDAO.all().stream() .filter(hasExpectedGitRepoArtifact) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }</code><technical_language>this easier read if a function: boolean shouldMigrateArtifact(@Nullable Map<String, Object> artifact) encapsulated checks in sequence 4 times in this migration</technical_language>

Target:
public void run() { log.info("Starting git/repo artifact migration"); Predicate<Pipeline> hasExpectedGitRepoArtifact = p -> { List<Map> expectedArtifacts = (List<Map>) p.get("expectedArtifacts"); if (expectedArtifacts == null) { return false; } return expectedArtifacts.stream() .anyMatch( e -> shouldMigrateArtifact((Map<String, Object>) e.get("matchArtifact")) || shouldMigrateArtifact((Map<String, Object>) e.get("defaultArtifact"))); }; pipelineDAO.all().stream() .filter(hasExpectedGitRepoArtifact) .forEach(pipeline -> migrate(pipelineDAO, pipeline)); }
Source:
<code>public void put(HttpHeader header, String value) { <START> Objects.requireNonNull(header, "header"); <END> if (value == null) remove(header); else put(new HttpField(header, value)); }</code><technical_language>"header null"</technical_language>

Target:
public void put(HttpHeader header, String value) { Objects.requireNonNull(header, "header must not be null"); if (value == null) remove(header); else put(new HttpField(header, value)); }
Source:
<code>public void test_unknown_locale() { Locale.setDefault(new Locale("en", "US")); <START> <END> JSONObject bundle = ResourceBundleUtil.getBundle("hudson.logging.Messages", new Locale("kok")); Assert.assertEquals("Initialing log recorders", bundle.getString("LogRecorderManager.init")); }</code><technical_language>more local? I mean, remove @BeforeClass @AfterClass put lines after. IIRC other tests concerned right</technical_language>

Target:
public void test_unknown_locale() { Locale defaultOSLocale = Locale.getDefault(); try { Locale.setDefault(new Locale("en", "US")); JSONObject bundle = ResourceBundleUtil.getBundle("hudson.logging.Messages", new Locale("kok")); Assert.assertEquals("Initialing log recorders", bundle.getString("LogRecorderManager.init")); }finally{ Locale.setDefault(defaultOSLocale); } }
Source:
<code>public ResultScanner<Row> readRows(ReadRowsRequest request) { final ResultScanner<FlatRow> delegate = readFlatRows(request); return new ResultScanner<Row>(){ @Override public void close() throws IOException { delegate.close(); } @Override public Row[] next(int count) throws IOException { FlatRow[] flatRows = delegate.next(count); <START> Row rows = new Row[flatRows.length]; <END> for (int i = 0; i < flatRows.length; i++) { rows[i] = FlatRowConverter.convert(flatRows[i]); } return rows; } @Override public Row next() throws IOException { return FlatRowConverter.convert(delegate.next()); } @Override public int available() { return delegate.available(); } }; }</code><technical_language>kill space brackets</technical_language>

Target:
public ResultScanner<Row> readRows(ReadRowsRequest request) { final ResultScanner<FlatRow> delegate = readFlatRows(request); return new ResultScanner<Row>() { @Override public void close() throws IOException { delegate.close(); } @Override public Row[] next(int count) throws IOException { FlatRow[] flatRows = delegate.next(count); Row[] rows = new Row[flatRows.length]; for (int i = 0; i < flatRows.length; i++) { rows[i] = FlatRowConverter.convert(flatRows[i]); } return rows; } @Override public Row next() throws IOException { return FlatRowConverter.convert(delegate.next()); } @Override public int available() { return delegate.available(); } }; }
Source:
<code><START> public void setPattern(String pattern) { <END> this.compiledPattern = Pattern.compile("(" + pattern + ")"); this.pattern = pattern; }</code><technical_language>this throws PatternSyntaxException</technical_language>

Target:
public void setPattern(String pattern) throws PatternSyntaxException { this.compiledPattern = Pattern.compile("(" + pattern + ")"); this.pattern = pattern; }
Source:
<code>private void postNicInit() { initSelectedType(); getName().setEntity(getNic().getName()); initMAC(); initLinked(); <START> <END> initNetworks(); initCustomPropertySheet(); getPlugged().setEntity(getNic().isPlugged()); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } getPlugged().setIsChangable(hotPlugSupported); initCommands(); }</code><technical_language>I understand remove initPortMirroring() here... a bug- port-mirroring is shown in EditTemplateVnic dialog</technical_language>

Target:
private void postNicInit() { initSelectedType(); getName().setEntity(getNic().getName()); initMAC(); initLinked(); initPortMirroring(); initNetworks(); initCustomPropertySheet(); getPlugged().setEntity(getNic().isPlugged()); if (!hotPlugSupported) { getPlugged().setChangeProhibitionReason(ConstantsManager.getInstance() .getMessages() .hotPlugNotSupported(getClusterCompatibilityVersion().toString())); } getPlugged().setIsChangable(hotPlugSupported); initCommands(); }
Source:
<code>public void updateSettings(List<String> errors) { MotdSettings motdSettings; try { motdSettings = mapper.readValue(new File(websiteLocation.concat(MOTD_SETTINGS)), MotdSettings.class); this.settings = motdSettings; } catch (IOException ex) { <START> errors.add(ex.getMessage()); <END> LOGGER.error(ex.getMessage(), ex); } }</code><technical_language>human readable message</technical_language>

Target:
public String updateSettings(List<String> errors) { MotdSettings motdSettings; String msg = "{\"status\": \"OK\", \"message\" : \"New configuration accepted.\"}"; try { motdSettings = mapper.readValue(new File(websiteLocation.concat(MOTD_SETTINGS)), MotdSettings.class); this.settings = motdSettings; } catch (IOException ex) { errors.add("motd_config.json is invalid."); msg = String.format("{\"status\": \"FAILED\", \"message\": \"%s\"}", ex.getMessage()); LOGGER.error(ex.getMessage(), ex); } return msg; }
Source:
<code>public TabletFile(String metadataEntry) { this.metadataEntry = Objects.requireNonNull(metadataEntry); String errorMsg = " is missing from tablet file metadata entry: " + metadataEntry; Path metaPath = new Path(metadataEntry); this.fileName = metaPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(fileName); Path tabletDirPath = Objects.requireNonNull(metaPath.getParent(), "Tablet dir" + errorMsg); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = Objects.requireNonNull(tabletDirPath.getParent(), "Table ID" + errorMsg); this.tableId = TableId.of(tableIdPath.getName()); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tableId.canonical()); <START> Path volumePath = Objects.requireNonNull( <END> TabletFileUtil.getVolumeFromFullPath(metaPath, "tables"), "Volume" + errorMsg); this.volume = volumePath.toString(); this.normalizedPath = volume + Constants.HDFS_TABLES_DIR + "/" + tableId.canonical() + "/" + tabletDir + "/" + fileName; }</code><technical_language>do avoid calling TabletFileUtil.getVolumeFromFullPath. This method converts a path a string internally a path. code exisitng path object. java Path tablePath = Objects.requireNonNull(tableIdPath.getParent(), "Table" + errorMsg); Preconditions.checkArgument(tablePath.getName().equals(Constants.HDFS_TABLES_DIR)); Path volumePath = Objects.requireNonNull(tablePath.getParent()); profiling in I Hadoop Path object show up. if easy avoid creating one, I try do that. This code pretty frequently</technical_language>

Target:
public TabletFile(String metadataEntry) { this.metadataEntry = Objects.requireNonNull(metadataEntry); String errorMsg = "Missing or invalid part of tablet file metadata entry: " + metadataEntry; this.metaPath = new Path(metadataEntry); this.fileName = metaPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(fileName); Path tabletDirPath = Objects.requireNonNull(metaPath.getParent(), errorMsg); this.tabletDir = tabletDirPath.getName(); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tabletDir); Path tableIdPath = Objects.requireNonNull(tabletDirPath.getParent(), errorMsg); this.tableId = TableId.of(tableIdPath.getName()); MetadataSchema.TabletsSection.ServerColumnFamily.validateDirCol(tableId.canonical()); Path tablePath = Objects.requireNonNull(tableIdPath.getParent(), errorMsg); String tpString = "/" + tablePath.getName(); Preconditions.checkArgument(tpString.equals(Constants.HDFS_TABLES_DIR), errorMsg); Path volumePath = Objects.requireNonNull(tablePath.getParent(), errorMsg); Preconditions.checkArgument(volumePath.toUri().getScheme() != null, errorMsg); this.volume = volumePath.toString(); this.normalizedPath = volume + Constants.HDFS_TABLES_DIR + "/" + tableId.canonical() + "/" + tabletDir + "/" + fileName; }
Source:
<code>public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> { if (rsp.isCommitted()) { LOGGER.log(isEOFException(e) ? Level.FINE : Level.WARNING, null, e); return; } req.setAttribute("javax.servlet.error.exception",e); try { reportMissingClassJava11Telemetry(e); WebApp.get(j.servletContext).getSomeStapler().invoke(req, rsp, j, "/oops"); } catch (ServletException | IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } }); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler."); } catch (SecurityException ex) { LOGGER.log(Level.SEVERE, "Failed to set the default UncaughtExceptionHandler. " + "If any threads die due to unhandled coding errors then there will be no logging of this information. " + "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins. " + <START> "It is highly recommended that you consult the documentation that comes with you servlet container on how to allow the " + <END> "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex); } }</code><technical_language>unrelated ws change IIUC</technical_language>

Target:
public static void init(final Jenkins j) throws IOException { CompressionFilter.setUncaughtExceptionHandler(j.servletContext, (e, context, req, rsp) -> { if (rsp.isCommitted()) { LOGGER.log(isEOFException(e) ? Level.FINE : Level.WARNING, null, e); return; } req.setAttribute("javax.servlet.error.exception",e); try { MissingClassTelemetry.reportExceptionInside(e); WebApp.get(j.servletContext).getSomeStapler().invoke(req, rsp, j, "/oops"); } catch (ServletException | IOException x) { if (!Stapler.isSocketException(x)) { throw x; } } }); try { Thread.setDefaultUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler()); LOGGER.log(Level.FINE, "Successfully installed a global UncaughtExceptionHandler."); } catch (SecurityException ex) { LOGGER.log(Level.SEVERE, "Failed to set the default UncaughtExceptionHandler. " + "If any threads die due to unhandled coding errors then there will be no logging of this information. " + "The lack of this diagnostic information will make it harder to track down issues which will reduce the supportability of Jenkins. " + "It is highly recommended that you consult the documentation that comes with you servlet container on how to allow the " + "`setDefaultUncaughtExceptionHandler` permission and enable it.", ex); } }
Source:
<code>public void ignoreInterfaces() throws MalformedURLException { ServletContext context = mock(ServletContext.class); when(context.getResource(any(String.class))).thenReturn(null); <START> IndexHtmlDispatcher.make(context, TestInterface.class); <END> }</code><technical_language>assertNull result too</technical_language>

Target:
public void ignoreInterfaces() throws MalformedURLException { ServletContext context = mock(ServletContext.class); when(context.getResource(any(String.class))).thenReturn(null); assertNull(IndexHtmlDispatcher.make(context, TestInterface.class)); }
Source:
<code>public EntityPermissions(EntityDictionary dictionary, Class<?> cls, Collection<AccessibleObject> fieldOrMethodList) { this.dictionary = dictionary; for (Class<? extends Annotation> annotationClass : PERMISSION_ANNOTATIONS) { final Map<String, ParseTree> fieldPermissions = new HashMap<>(); fieldOrMethodList.stream() .forEach(member -> bindMemberPermissions(fieldPermissions, member, annotationClass)); if (annotationClass == SharePermission.class && EntityDictionary.getFirstAnnotation(cls, Arrays.asList(annotationClass)) != null) { <START> bindings.put(SharePermission.class, new AnnotationBinding(null, fieldPermissions)); <END> } else { ParseTree classPermission = bindClassPermissions(cls, annotationClass); if (classPermission != null || !fieldPermissions.isEmpty()) { bindings.put(annotationClass, new AnnotationBinding(classPermission, fieldPermissions)); } } } }</code><technical_language>binding read permissions here</technical_language>

Target:
public EntityPermissions(EntityDictionary dictionary, Class<?> cls, Collection<AccessibleObject> fieldOrMethodList) { this.dictionary = dictionary; for (Class<? extends Annotation> annotationClass : PERMISSION_ANNOTATIONS) { final Map<String, ParseTree> fieldPermissions = new HashMap<>(); fieldOrMethodList.stream() .forEach(member -> bindMemberPermissions(fieldPermissions, member, annotationClass)); if (annotationClass != SharePermission.class) { ParseTree classPermission = bindClassPermissions(cls, annotationClass); if (classPermission != null || !fieldPermissions.isEmpty()) { bindings.put(annotationClass, new AnnotationBinding(classPermission, fieldPermissions)); } } } }
Source:
<code>public static boolean isTimeWithinPeriod(Date startTime, Date endTime, Date time, boolean isStartInclusive, boolean isEndInclusive) { if (startTime == null || endTime == null || time == null) { return false; } if (isStartInclusive && isEndInclusive) { return startTime.getTime() <= time.getTime() && time.getTime() <= endTime.getTime(); } else if (isStartInclusive && !isEndInclusive) { return startTime.getTime() <= time.getTime() && time.getTime() < endTime.getTime(); } else if (!isStartInclusive && isEndInclusive) { return startTime.getTime() < time.getTime() && time.getTime() <= endTime.getTime(); } else { return startTime.getTime() < time.getTime() && time.getTime() < endTime.getTime(); <START> } <END> }</code><technical_language>if simplify this</technical_language>

Target:
public static boolean isTimeWithinPeriod(Date startTime, Date endTime, Date time, boolean isStartInclusive, boolean isEndInclusive) { if (startTime == null || endTime == null || time == null) { return false; } boolean isAfterStartTime = time.after(startTime) || (isStartInclusive && time.equals(startTime)); boolean isBeforeEndTime = time.before(endTime) || (isEndInclusive && time.equals(endTime)); return isAfterStartTime && isBeforeEndTime; }
Source:
<code>private static ItemRequest createSubmissionRequest(final DBObject experiments, final ByteString review) { <START> final ItemRequest.Builder build = ItemRequest.newBuilder(); <END> build.setQuery(ItemQuery.EXPERIMENT); for (String key : experiments.keySet()) { if (SELF_ID.equals(key)) { continue; } final Object experimentId = experiments.get(key); if (experimentId == null || experimentId instanceof ObjectId) { continue; } final String sketchId = experiments.get(key).toString(); LOG.info("SketchId: {}", sketchId); build.addItemId(sketchId); } build.setAdvanceQuery(review); return build.build(); }</code><technical_language>change this variable name? itemRequest something</technical_language>

Target:
private static ItemRequest createSubmissionRequest(final DBObject experiments, final ByteString review) { final ItemRequest.Builder itemRequest = ItemRequest.newBuilder(); itemRequest.setQuery(ItemQuery.EXPERIMENT); for (String key : experiments.keySet()) { if (SELF_ID.equals(key)) { continue; } final Object experimentId = experiments.get(key); if (experimentId == null || experimentId instanceof ObjectId) { continue; } final String sketchId = experiments.get(key).toString(); LOG.info("SketchId: {}", sketchId); itemRequest.addItemId(sketchId); } itemRequest.setAdvanceQuery(review); return itemRequest.build(); }
Source:
<code>public ElasticAgentExtension(PluginManager pluginManager) { super(pluginManager, new PluginRequestHelper(pluginManager, SUPPORTED_VERSIONS, ElasticAgentPluginConstants.EXTENSION_NAME), ElasticAgentPluginConstants.EXTENSION_NAME); addHandler(ElasticAgentExtensionConverterV1.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV1()); addHandler(ElasticAgentExtensionConverterV2.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV2()); <START> jsonMessageHandlersForRequestProcessor.put(ElasticAgentExtensionConverterV1.VERSION, new JsonMessageHandlerForRequestProcessor1_0()); <END> jsonMessageHandlersForRequestProcessor.put(ElasticAgentExtensionConverterV2.VERSION, new JsonMessageHandlerForRequestProcessor1_0()); }</code><technical_language>This added addHandler method</technical_language>

Target:
public ElasticAgentExtension(PluginManager pluginManager) { super(pluginManager, new PluginRequestHelper(pluginManager, SUPPORTED_VERSIONS, ElasticAgentPluginConstants.EXTENSION_NAME), ElasticAgentPluginConstants.EXTENSION_NAME); addHandler(ElasticAgentExtensionConverterV1.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV1(), new JsonMessageHandlerForRequestProcessor1_0()); addHandler(ElasticAgentExtensionConverterV2.VERSION, new PluginSettingsJsonMessageHandler1_0(), new ElasticAgentExtensionConverterV2(), new JsonMessageHandlerForRequestProcessor1_0()); }
Source:
<code>protected boolean canDoAction() { boolean returnValue = true; <START> StorageServerConnections paramConnection = getConnection(); <END> if (StringUtils.isNotEmpty(paramConnection.getid())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { returnValue = false; addCanDoActionMessage(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (isConnWithSameDetailsExists()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); } if (getParameters().getVdsId().equals(Guid.Empty)) { returnValue = InitializeVds(); } else if (getVds() == null) { addCanDoActionMessage(VdcBllMessages.VDS_INVALID_SERVER_ID); returnValue = false; } else if (getVds().getStatus() != VDSStatus.Up) { addCanDoActionMessage(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); returnValue = false; } return returnValue; }</code><technical_language>This is longer paramConnection, connection</technical_language>

Target:
protected boolean canDoAction() { boolean returnValue = true; StorageServerConnections paramConnection = getConnection(); if (StringUtils.isNotEmpty(paramConnection.getid())) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ID_NOT_EMPTY); } if (paramConnection.getstorage_type() == StorageType.NFS && !new NfsMountPointConstraint().isValid(paramConnection.getconnection(), null)) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_INVALID); } if (paramConnection.getstorage_type() == StorageType.POSIXFS && (StringUtils.isEmpty(paramConnection.getVfsType()))) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_VFSTYPE); } if (paramConnection.getstorage_type() == StorageType.ISCSI && StringUtils.isEmpty(paramConnection.getiqn())) { return failCanDoAction(VdcBllMessages.VALIDATION_STORAGE_CONNECTION_EMPTY_IQN); } if (checkIsConnectionFieldEmpty(paramConnection)) { return false; } if (isConnWithSameDetailsExists()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_CONNECTION_ALREADY_EXISTS); } if (getParameters().getVdsId().equals(Guid.Empty)) { if (!initializeVds()) { return false; } } else if (getVds() == null) { return failCanDoAction(VdcBllMessages.VDS_INVALID_SERVER_ID); } else if (getVds().getStatus() != VDSStatus.Up) { return failCanDoAction(VdcBllMessages.VDS_ADD_STORAGE_SERVER_STATUS_MUST_BE_UP); } return true; }