auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void putObject(String bucketName, String objectName, String fileName, String contentType) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); try { putObject(bucketName, objectName, contentType, size, file); } finally { file.close(); } }

Target:
public void putObject(String bucketName, String objectName, String fileName, String contentType) throws InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, IOException, InvalidKeyException, NoResponseException, XmlPullParserException, ErrorResponseException, InternalException, InvalidArgumentException, InsufficientDataException { if (fileName == null || "".equals(fileName)) { throw new InvalidArgumentException("empty file name is not allowed"); } Path filePath = Paths.get(fileName); if (!Files.isRegularFile(filePath)) { throw new InvalidArgumentException("'" + fileName + "': not a regular file"); } if (contentType == null) { contentType = Files.probeContentType(filePath); } long size = Files.size(filePath); RandomAccessFile file = new RandomAccessFile(filePath.toFile(), "r"); try { putObject(bucketName, objectName, contentType, size, file); } finally { file.close(); } }
Source:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); System.out.println(advancedCache(0).getCacheConfiguration().clustering().partitionHandling().getMergePolicy()); cache(0).put(conflictKey, "BEFORE SPLIT"); }

Target:
void beforeSplit() { conflictKey = new MagicKey(cache(2), cache(0)); cache(0).put(conflictKey, "BEFORE SPLIT"); }
Source:
public void shouldNotDisableAgentsWhenInvalidAgentUUIDIsprovided() throws Exception { AgentConfig agentConfig1 = new AgentConfig(UUID.randomUUID().toString(), "remote-host1", "50.40.30.21"); AgentConfig agentConfig2 = new AgentConfig(UUID.randomUUID().toString(), "remote-host2", "50.40.30.22"); agentConfigService.addAgent(agentConfig1, Username.ANONYMOUS); agentConfigService.addAgent(agentConfig2, Username.ANONYMOUS); CruiseConfig cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); ArrayList<String> uuids = new ArrayList<>(); uuids.add(agentConfig1.getUuid()); uuids.add(agentConfig2.getUuid()); uuids.add("invalid-uuid"); agentConfigService.bulkUpdateAgentAttributes(Username.ANONYMOUS, result, uuids, new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), TriState.FALSE); cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(result.isSuccessful()); assertThat(result.toString(), result.httpCode(), is(400)); assertTrue(result.toString(), result.toString().contains("AGENTS_WITH_UUIDS_NOT_FOUND")); assertTrue(result.toString(), result.toString().contains("invalid-uuid")); }

Target:
public void shouldNotDisableAgentsWhenInvalidAgentUUIDIsprovided() throws Exception { AgentConfig agentConfig1 = new AgentConfig(UUID.randomUUID().toString(), "remote-host1", "50.40.30.21"); AgentConfig agentConfig2 = new AgentConfig(UUID.randomUUID().toString(), "remote-host2", "50.40.30.22"); agentConfigService.addAgent(agentConfig1, Username.ANONYMOUS); agentConfigService.addAgent(agentConfig2, Username.ANONYMOUS); CruiseConfig cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); HttpLocalizedOperationResult result = new HttpLocalizedOperationResult(); ArrayList<String> uuids = new ArrayList<>(); uuids.add(agentConfig1.getUuid()); uuids.add(agentConfig2.getUuid()); uuids.add("invalid-uuid"); agentConfigService.bulkUpdateAgentAttributes(Username.ANONYMOUS, result, uuids, new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), new ArrayList<String>(), TriState.FALSE); cruiseConfig = goConfigDao.load(); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig1.getUuid()).isDisabled()); assertFalse(cruiseConfig.agents().getAgentByUuid(agentConfig2.getUuid()).isDisabled()); assertFalse(result.isSuccessful()); assertThat(result.toString(), result.httpCode(), is(400)); assertTrue(result.toString(), result.toString().contains("AGENTS_WITH_UUIDS_NOT_FOUND")); assertTrue(result.toString(), result.toString().contains("invalid-uuid")); }
Source:
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .onErrorResume(throwable -> { logger.warn("Unexpected exception from thread {}", Thread.currentThread().getId(), throwable); return Mono.error(throwable); }) .then(this.afterProcessChanges(context)); }

Target:
public Mono<Void> processChanges(ChangeFeedObserverContext context, List<CosmosItemProperties> docs) { return this.observer.processChanges(context, docs) .doOnError(throwable -> { logger.warn("Unexpected exception from thread {}", Thread.currentThread().getId(), throwable); }) .then(this.afterProcessChanges(context)); }
Source:
public void testOpenTransientSession() { SWTBotTreeItem projectTreeItemBot = modelExplorerViewBot.tree().expandNode(getProjectName(), true); SWTBotTreeItem modelResourceTreeItemBot = projectTreeItemBot.getNode(SEMANTIC_RESOURCE_NAME); modelResourceTreeItemBot.select(); SWTBotUtils.clickContextMenu(modelResourceTreeItemBot, "Sirius Ecore Editor"); SWTBotUtils.waitAllUiEvents(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.editors().size() == 1; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Sirius Ecore Editor should be opened"; } }); modelResourceTreeItemBot.select().doubleClick(); assertTrue("Double click on the opened model should not open a second editor", bot.editors().size() == 1); assertTrue("The double click action should not open a second session", localSession.getOpenedSession().getAllSessionResources().size() == 1); }

Target:
public void testOpenTransientSession() { SWTBotTreeItem projectTreeItemBot = modelExplorerViewBot.tree().expandNode(getProjectName(), true); SWTBotTreeItem modelResourceTreeItemBot = projectTreeItemBot.getNode(SEMANTIC_RESOURCE_NAME); modelResourceTreeItemBot.select(); SWTBotUtils.clickContextMenu(modelResourceTreeItemBot, "Sirius Ecore Editor"); SWTBotUtils.waitAllUiEvents(); bot.waitUntil(new ICondition() { @Override public boolean test() throws Exception { return bot.editors().size() == 1; } @Override public void init(SWTBot bot) { } @Override public String getFailureMessage() { return "Sirius Ecore Editor should be opened"; } }); modelResourceTreeItemBot.select().doubleClick(); assertEquals("Double click on the opened model should not open a second editor", true, bot.editors().size() == 1); assertEquals("The double click action should not open a second session", true, localSession.getOpenedSession().getAllSessionResources().size() == 1); }
Source:
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException { final String res = DateTimeFormatter.ISO_INSTANT.format(value.withZoneSameInstant(ZoneId.of("Z"))); gen.writeString(res); }

Target:
public void serialize(ZonedDateTime value, JsonGenerator gen, SerializerProvider arg2) throws IOException { final String res = DateTimeFormatter.ISO_INSTANT.format(value.withZoneSameInstant(ZoneOffset.UTC)); gen.writeString(res); }
Source:
private void copyPrivateKeysWithPermissions(PodSpec podSpec, VolumeMount sshKeysVolumeMount) { String copiedSshKeysVolumeName = "copied-private-keys"; podSpec .getVolumes() .add( new VolumeBuilder() .withName(copiedSshKeysVolumeName) .withNewEmptyDir() .endEmptyDir() .build()); VolumeMount copiedSshKeysVolumeMount = new VolumeMountBuilder() .withName(copiedSshKeysVolumeName) .withMountPath(SSH_PRIVATE_KEYS_PATH + "-copy") .build(); Container initContainer = new ContainerBuilder() .withName("ssh-private-keys-modifier") .withImage("centos:centos7") .withVolumeMounts(sshKeysVolumeMount, copiedSshKeysVolumeMount) .withCommand( asList( "/bin/sh", "-c", format( "(cp -r %1$s/. %1$s-copy && chmod -R 600 %1$s-copy) || exit 0", SSH_PRIVATE_KEYS_PATH))) .build(); podSpec .getContainers() .forEach(container -> container.getVolumeMounts().add(copiedSshKeysVolumeMount)); podSpec.getInitContainers().add(initContainer); }

Target:
private void copyPrivateKeysWithPermissions(PodSpec podSpec, VolumeMount sshKeysVolumeMount) { String copiedSshKeysVolumeName = "copied-private-keys"; podSpec .getVolumes() .add( new VolumeBuilder() .withName(copiedSshKeysVolumeName) .withNewEmptyDir() .endEmptyDir() .build()); VolumeMount copiedSshKeysVolumeMount = new VolumeMountBuilder() .withName(copiedSshKeysVolumeName) .withMountPath(SSH_PRIVATE_KEYS_PATH + "-copy") .build(); Container initContainer = new ContainerBuilder() .withName("ssh-private-keys-modifier") .withImage(jobImage) .withVolumeMounts(sshKeysVolumeMount, copiedSshKeysVolumeMount) .withCommand( asList( "/bin/sh", "-c", format( "(cp -r %1$s/. %1$s-copy && chmod -R 600 %1$s-copy) || exit 0", SSH_PRIVATE_KEYS_PATH))) .build(); podSpec .getContainers() .forEach(container -> container.getVolumeMounts().add(copiedSshKeysVolumeMount)); podSpec.getInitContainers().add(initContainer); }
Source:
private URI determineRepositoryPath(URI baseUri) throws IOException, FcrepoOperationFailedException { PID parentPid = null; try (FcrepoResponse response = client.post(baseUri).perform()) { parentPid = PIDs.get(response.getLocation()); } catch(FcrepoOperationFailedException e) { if (e.getStatusCode() != HttpStatus.SC_CONFLICT) { throw e; } } return parentPid.getRepositoryUri(); }

Target:
private URI determineRepositoryPath(URI baseUri) throws IOException, FcrepoOperationFailedException { URI repoPath = null; try (FcrepoResponse response = client.post(baseUri).perform()) { repoPath = response.getLocation(); } catch(FcrepoOperationFailedException e) { if (e.getStatusCode() != HttpStatus.SC_CONFLICT) { throw e; } } return repoPath; }
Source:
public void onMessage(String message) { InputStream in = null; try { in = StreamUtils.getInputStream(message); JsonReader reader = Json.createReader(in); JsonObject json = reader.readObject(); reader.close(); JsonObject dataJson = json.getJsonObject(ATTRIBUTE_DATA); URLNotification notification = URLNotificationJSONConverter.parseJSON(dataJson); receiveNotification(notification); HeartbeatListener.sendHeartbeatMessage(getName(), "nats notification timestamp", json.getJsonNumber(TIMESTAMP_PROPERTY).toString()); sequence = json.getJsonNumber(SEQUENCE_PROPERTY).toString(); writeTrackingFile(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while processing URLNotification ", e); } finally { StreamUtils.closeStream(in); } }

Target:
public void onMessage(String message) { JsonObject json; try (InputStream in = StreamUtils.getInputStream(message); JsonReader reader = Json.createReader(in)) { json = reader.readObject(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while receiving notification; is it encoded as JSON? ", e); return; } try { JsonObject dataJson = json.getJsonObject(ATTRIBUTE_DATA); URLNotification notification = URLNotificationJSONConverter.parseJSON(dataJson); receiveNotification(notification); HeartbeatListener.sendHeartbeatMessage(getName(), "nats notification timestamp", json.getJsonNumber(TIMESTAMP_PROPERTY).toString()); sequence = json.getJsonNumber(SEQUENCE_PROPERTY).toString(); writeTrackingFile(); } catch (Exception e) { LOGGER.log(Level.WARNING, "[" + getName() + "] exception while processing URLNotification ", e); } }
Source:
public List<CategoryDTO> fetchInstallableApplications() { final String[] urls = sourceUrl.split(";"); final ApplicationsSource applicationsSource = new MultipleApplicationSource(Arrays.stream(urls).map(this::toApplicationSource).collect(Collectors.toList())); return applicationsSource.fetchInstallableApplications(); }

Target:
public List<CategoryDTO> fetchInstallableApplications() { return applicationsSource.fetchInstallableApplications(); }
Source:
protected void convertAllTitlesToUnderscores(SQLiteDatabase db) { Cursor cursor = db.query(getTableName(), null, null, null, null, null, null); int idIndex = cursor.getColumnIndexOrThrow("_id"); int titleIndex = cursor.getColumnIndexOrThrow(Col.TITLE.getName()); ContentValues values = new ContentValues(); while (cursor.moveToNext()) { String title = cursor.getString(titleIndex); if (title.contains(" ")) { values.put(Col.TITLE.getName(), title.replace(" ", "_")); String id = Long.toString(cursor.getLong(idIndex)); db.updateWithOnConflict(getTableName(), values, "_id = ?", new String[]{id}, SQLiteDatabase.CONFLICT_REPLACE); } } cursor.close(); }

Target:
protected void convertAllTitlesToUnderscores(SQLiteDatabase db) { Cursor cursor = db.query(getTableName(), null, null, null, null, null, null); ContentValues values = new ContentValues(); while (cursor.moveToNext()) { String title = Col.TITLE.val(cursor); if (title.contains(" ")) { values.put(Col.TITLE.getName(), title.replace(" ", "_")); String id = Long.toString(Col.ID.val(cursor)); db.updateWithOnConflict(getTableName(), values, Col.ID.getName() + " = ?", new String[]{id}, SQLiteDatabase.CONFLICT_REPLACE); } } cursor.close(); }
Source:
public void testIsValid_collection_all_is_invalid() throws Exception { Name_Collection name = new Name_Collection(Arrays.asList("ＡＢＣ", "GHI"), Arrays.asList("ABC", "ＧＨＩ")); Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); Set<ConstraintViolation<Name_Collection>> violations = validator .validate(name); assertThat(violations, is(notNullValue())); assertThat(violations.size(), is(2)); Iterator<ConstraintViolation<Name_Collection>> iterator = violations .iterator(); List<ConstraintViolation<Name_Collection>> lst = new ArrayList<ConstraintViolation<Name_Collection>>(2); lst.add(iterator.next()); lst.add(iterator.next()); Collections.sort(lst, new Comparator<ConstraintViolation<Name_Collection>>() { @Override public int compare(ConstraintViolation<Name_Collection> o1, ConstraintViolation<Name_Collection> o2) { return o1.getPropertyPath().toString().compareTo(o2 .getPropertyPath().toString()); } }); assertThat(lst.get(0).getPropertyPath().toString(), is( "firstNameList[0].<list element>")); assertThat(lst.get(0).getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); assertThat(lst.get(1).getPropertyPath().toString(), is( "lastNameList[1].<list element>")); assertThat(lst.get(1).getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); }

Target:
public void testIsValid_collection_all_is_invalid() throws Exception { Name_Collection name = new Name_Collection(Arrays.asList("GHI", "ABC"), Arrays.asList("GHI", "ABC")); Validator validator = Validation.buildDefaultValidatorFactory() .getValidator(); Set<ConstraintViolation<Name_Collection>> violations = validator .validate(name); assertThat(violations, is(notNullValue())); assertThat(violations.size(), is(2)); Iterator<ConstraintViolation<Name_Collection>> iterator = violations .stream().sorted(comparing(v -> v.getPropertyPath().toString())) .iterator(); ConstraintViolation<Name_Collection> violation = iterator.next(); assertThat(violation.getPropertyPath().toString(), is( "firstNames[0].<list element>")); assertThat(violation.getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); violation = iterator.next(); assertThat(violation.getPropertyPath().toString(), is( "lastNames[1].<list element>")); assertThat(violation.getMessage(), is( "{org.terasoluna.gfw.common.codepoints.ConsistOf.message}")); }
Source:
public void shouldPurgeAnIdentifierSource() throws Exception { assertNotNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); handle(newDeleteRequest(getURI() + "/" + IDENTIFIER_SOURCE_TO_PURGE_UUID, new Parameter("purge", ""))); assertNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); }

Target:
public void shouldPurgeAnIdentifierSource() throws Exception { assertNotNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); handle(newDeleteRequest(getURI() + "/" + IDENTIFIER_SOURCE_TO_PURGE_UUID, new Parameter("purge", "true"))); assertNull(service.getIdentifierSourceByUuid(IDENTIFIER_SOURCE_TO_PURGE_UUID)); }
Source:
public void run() { int numRetries = 0; InetSocketAddress addr; Socket client = null; while((!shutdown) && (numRetries < 3)){ try { ss = new ServerSocket(); ss.setReuseAddress(true); if (self.getQuorumListenOnAllIPs()) { int port = self.getElectionAddress().getPort(); addr = new InetSocketAddress(port); } else { self.recreateSocketAddresses(self.getId()); addr = self.getElectionAddress(); } LOG.info("My election bind port: " + addr.toString()); setName(addr.toString()); ss.bind(addr); while (!shutdown) { client = ss.accept(); setSockOpts(client); LOG.info("Received connection request " + client.getRemoteSocketAddress()); receiveConnection(client); numRetries = 0; } } catch (IOException e) { if (shutdown) { break; } LOG.error("Exception while listening", e); numRetries++; try { ss.close(); Thread.sleep(1000); } catch (IOException ie) { LOG.error("Error closing server socket", ie); } catch (InterruptedException ie) { LOG.error("Interrupted while sleeping. " + "Ignoring exception", ie); } closeSocket(client); } catch (ConfigException ce) { LOG.error(ce.getMessage()); throw new RuntimeException(ce); } } LOG.info("Leaving listener"); if (!shutdown) { LOG.error("As I'm leaving the listener thread, " + "I won't be able to participate in leader " + "election any longer: " + self.getElectionAddress()); } else if (ss != null) { try { ss.close(); } catch (IOException ie) { LOG.debug("Error closing server socket", ie); } } }

Target:
public void run() { int numRetries = 0; InetSocketAddress addr; Socket client = null; ConfigException configException = null; while((!shutdown) && (numRetries < 3)){ try { ss = new ServerSocket(); ss.setReuseAddress(true); if (self.getQuorumListenOnAllIPs()) { int port = self.getElectionAddress().getPort(); addr = new InetSocketAddress(port); } else { self.recreateSocketAddresses(self.getId()); addr = self.getElectionAddress(); } LOG.info("My election bind port: " + addr.toString()); setName(addr.toString()); ss.bind(addr); while (!shutdown) { client = ss.accept(); setSockOpts(client); LOG.info("Received connection request " + client.getRemoteSocketAddress()); receiveConnection(client); numRetries = 0; } } catch (IOException e) { if (shutdown) { break; } LOG.error("Exception while listening", e); numRetries++; try { ss.close(); Thread.sleep(1000); } catch (IOException ie) { LOG.error("Error closing server socket", ie); } catch (InterruptedException ie) { LOG.error("Interrupted while sleeping. " + "Ignoring exception", ie); } } catch (ConfigException e) { LOG.error(e.getMessage()); configException = e; break; } finally { closeSocket(client); } } LOG.info("Leaving listener"); if (!shutdown) { LOG.error("As I'm leaving the listener thread, " + "I won't be able to participate in leader " + "election any longer: " + self.getElectionAddress()); } else if (ss != null) { try { ss.close(); } catch (IOException ie) { LOG.debug("Error closing server socket", ie); } } if (configException !=null) throw new RuntimeException(configException); }
Source:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } List<QuotaConsumptionParameter> consumptionParameters = new ArrayList<QuotaConsumptionParameter>(); switch (this.getActionType().getQuotaDependency()) { case NONE: return true; case STORAGE: consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); break; case VDS: consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; case BOTH: consumptionParameters.addAll(((QuotaStorageDependent) this).getQuotaStorageConsumptionParameters()); consumptionParameters.addAll(((QuotaVdsDependent) this).getQuotaVdsConsumptionParameters()); break; } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper; if (getStoragePool() != null) { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( this.getStoragePool(), this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); } else { quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper( null,this.getReturnValue().getCanDoActionMessages(), this); quotaConsumptionParametersWrapper.setParameters(consumptionParameters); log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } return consumptionParameters.isEmpty() ? true: true; }

Target:
private boolean internalValidateAndSetQuota() { if (isInternalExecution()) { return true; } if (getStoragePool() == null) { log.error("Command: " + this.getClass().getName() + ". Storage pool is not available for quota calculation. "); } QuotaConsumptionParametersWrapper quotaConsumptionParametersWrapper = new QuotaConsumptionParametersWrapper(this, getReturnValue().getCanDoActionMessages()); quotaConsumptionParametersWrapper.setParameters(getQuotaConsumptionParameters()); return true; }
Source:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy = resourcePolicyService.create(c); policy = srp.copyToDSpaceObject(policy,dest); resourcePolicyService.update(c,policy); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }

Target:
public void addPolicies(Context c, List<ResourcePolicy> policies, DSpaceObject dest) throws SQLException, AuthorizeException { List<ResourcePolicy> newPolicies = new LinkedList<>(); for (ResourcePolicy srp : policies) { ResourcePolicy policy =resourcePolicyService.copyToDSpaceObject(c,srp,dest); newPolicies.add(policy); } resourcePolicyService.update(c, newPolicies); }
Source:
public static Expression newDefaultExpression(AST ast, ITypeBinding type) { if (type.isPrimitive()) { String name= type.getName(); if (null == name) { return ast.newNumberLiteral("0"); } else switch (name) { case "boolean": return ast.newBooleanLiteral(false); case "void": return null; default: return ast.newNumberLiteral("0"); } } return ast.newNullLiteral(); }

Target:
public static Expression newDefaultExpression(AST ast, ITypeBinding type) { if (type.isPrimitive()) { String name= type.getName(); boolean nomatch= false; if (name != null) switch (name) { case "boolean": return ast.newBooleanLiteral(false); case "void": return null; default: nomatch= true; break; } if (nomatch) { return ast.newNumberLiteral("0"); } } return ast.newNullLiteral(); }
Source:
private boolean isAllowed(MutableHttpServletRequest request, String method) { String typeNameParam = "typeNames"; if (StringUtils.isEmpty(request.getParameterIgnoreCase(typeNameParam))) { typeNameParam = "typeName"; } return isAllowed(request, typeNameParam, method); }

Target:
private boolean isAllowed(MutableHttpServletRequest request, String method) { String typeNameParam = OgcEnum.EndPoint.TYPENAMES.toString(); if (StringUtils.isEmpty(request.getParameterIgnoreCase(typeNameParam))) { typeNameParam = OgcEnum.EndPoint.TYPENAME.toString(); } return isAllowed(request, typeNameParam, method); }
Source:
protected NatEventData getNatEventData(final Object evaluationContext) { if (evaluationContext instanceof NatEventData) { return (NatEventData) evaluationContext; } NatEventData eventData = null; if (evaluationContext instanceof IEvaluationContext) { Object value = ((IEvaluationContext) evaluationContext).getVariable(MenuItemProviders.NAT_EVENT_DATA_KEY); if (value instanceof NatEventData) { eventData = (NatEventData) value; } } if (eventData == null) { Point cursorLocation = Display.getDefault().getCursorLocation(); Control control = null; final PapyrusMultiDiagramEditor activeEditor = ((PapyrusMultiDiagramEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor()); if(null != activeEditor){ final INattableModelManager nattableModelManager = activeEditor.getActiveEditor().getAdapter(INattableModelManager.class); if(null != nattableModelManager){ control = nattableModelManager.getAdapter(NatTable.class); } } if (control instanceof NatTable) { cursorLocation = control.toControl(cursorLocation); Event e = new Event(); e.x = cursorLocation.x; e.y = cursorLocation.y; e.display = Display.getDefault(); e.widget = control; MouseEvent event = new MouseEvent(e); eventData = NatEventData.createInstanceFromEvent(event); } } return eventData; }

Target:
protected NatEventData getNatEventData(final Object evaluationContext) { if (evaluationContext instanceof NatEventData) { return (NatEventData) evaluationContext; } NatEventData eventData = null; if (evaluationContext instanceof IEvaluationContext) { Object value = ((IEvaluationContext) evaluationContext).getVariable(MenuItemProviders.NAT_EVENT_DATA_KEY); if (value instanceof NatEventData) { eventData = (NatEventData) value; } } if (eventData == null) { Point cursorLocation = Display.getDefault().getCursorLocation(); Control control = null; final IEditorPart activeEditor = EditorHelper.getCurrentEditor(); if (null != activeEditor) { INattableModelManager nattableModelManager = null; if(activeEditor instanceof IMultiPageEditorPart && null != ((IMultiPageEditorPart)activeEditor).getActiveEditor()){ nattableModelManager = ((IMultiPageEditorPart)activeEditor).getActiveEditor().getAdapter(INattableModelManager.class); }else if(activeEditor instanceof IAdaptable){ nattableModelManager = ((IAdaptable)activeEditor).getAdapter(INattableModelManager.class); } if(null != nattableModelManager){ control = nattableModelManager.getAdapter(NatTable.class); } } if (control instanceof NatTable) { cursorLocation = control.toControl(cursorLocation); Event e = new Event(); e.x = cursorLocation.x; e.y = cursorLocation.y; e.display = Display.getDefault(); e.widget = control; MouseEvent event = new MouseEvent(e); eventData = NatEventData.createInstanceFromEvent(event); } } return eventData; }
Source:
public boolean isNullable(VariableElement variableElement) { if (hasPrimaryKey()) { if (variableElement.equals(getPrimaryKey())) { String elementTypeCanonicalName = variableElement.asType().toString(); String columnType = Constants.JAVA_TO_COLUMN_TYPES.get(elementTypeCanonicalName); if (columnType != null && columnType.equals("RealmFieldType.STRING")) { return true; } else { return false; } } } return nullableFields.contains(variableElement); }

Target:
public boolean isNullable(VariableElement variableElement) { return nullableFields.contains(variableElement); }
Source:
public synchronized void heartbeat() { List<alluxio.grpc.ClientMetrics> fsClientMetrics = new ArrayList<>(); String source = mConf.isSet(PropertyKey.USER_APP_ID) ? mConf.get(PropertyKey.USER_APP_ID) : NetworkAddressUtils.getClientHostName(mConf); List<alluxio.grpc.Metric> metrics = MetricsSystem.reportClientMetrics(); if (metrics.size() == 0) { return; } fsClientMetrics.add(ClientMetrics.newBuilder() .setSource(source) .addAllMetrics(metrics) .build()); try { mMasterClient.heartbeat(fsClientMetrics); } catch (IOException e) { SAMPLING_LOG.warn("Failed to send metrics to master: {}", e.toString()); } }

Target:
public synchronized void heartbeat() { List<alluxio.grpc.ClientMetrics> fsClientMetrics = new ArrayList<>(); List<alluxio.grpc.Metric> metrics = MetricsSystem.reportClientMetrics(); if (metrics.size() == 0) { return; } fsClientMetrics.add(ClientMetrics.newBuilder() .setSource(mApplicationId) .addAllMetrics(metrics) .build()); try { mMasterClient.heartbeat(fsClientMetrics); } catch (IOException e) { SAMPLING_LOG.warn("Failed to send metrics to master: {}", e.toString()); } }
Source:
public int getTankCapacity(int tank) { return 0; }

Target:
public int getTankCapacity(int tank) { return BloodBottleIItem.AMOUNT * MULTIPLIER; }
Source:
private Properties readConfig(String filename) { BufferedInputStream stream = null; File configFile = new File(filename); try { stream = new BufferedInputStream(new FileInputStream(configFile)); final Properties formatterOptions = new Properties(); formatterOptions.load(stream); return formatterOptions; } catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } System.err.println(errorMessage); } finally { if (stream != null) { try { stream.close(); } catch (IOException e) { } } } return null; }

Target:
private Properties readConfig(String filename) { File configFile = new File(filename); try (BufferedInputStream stream = new BufferedInputStream(new FileInputStream(configFile))) { final Properties formatterOptions = new Properties(); formatterOptions.load(stream); return formatterOptions; } catch (IOException e) { String canonicalPath = null; try { canonicalPath = configFile.getCanonicalPath(); } catch(IOException e2) { canonicalPath = configFile.getAbsolutePath(); } String errorMessage; if (!configFile.exists() && !configFile.isAbsolute()) { errorMessage = Messages.bind(Messages.ConfigFileNotFoundErrorTryFullPath, new Object[] { canonicalPath, System.getProperty("user.dir") }); } else { errorMessage = Messages.bind(Messages.ConfigFileReadingError, canonicalPath); } System.err.println(errorMessage); } return null; }
Source:
boolean validate(String optionValue) throws ValidationException { if (optionValue != null) { String[] requestTracingValues = optionValue.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)"); if (requestTracingValues.length <= 2) { if (requestTracingValues[0].matches("\\d+") && (requestTracingValues.length == 2 && !requestTracingValues[1].matches("\\D+"))) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } if (requestTracingValues[0].matches("\\D+") && (requestTracingValues.length == 2)) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } else { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } return true; } return true; }

Target:
boolean validate(String optionValue) throws ValidationException { if (optionValue != null) { String[] requestTracingValues = optionValue.split("(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)"); if (requestTracingValues.length <= 2) { if (requestTracingValues[0].matches("\\d+") && (requestTracingValues.length == 2 && !requestTracingValues[1].matches("\\D+"))) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } if (requestTracingValues[0].matches("\\D+") && (requestTracingValues.length == 2)) { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } else { throw new ValidationException(MessageFormat.format( RuntimeOptions.commandlogstrings.getString("requestTracingIncorrect"), optionValue)); } } return true; }
Source:
protected Rectangle getBox() { PrecisionRectangle rBox = null; Object figure = getFigure(); if (figure instanceof IRoundedRectangleFigure) { rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) figure)).getRoundedRectangleBounds()); } else if (figure instanceof IFigure) { rBox = new PrecisionRectangle(getOwner().getBounds()); } if (rBox != null) { ((IFigure) figure).translateToAbsolute(rBox); return rBox.expand(offset.width, offset.height); } return null; }

Target:
protected Rectangle getBox() { PrecisionRectangle rBox = null; Object figure = getFigure(); if (figure instanceof IRoundedRectangleFigure) { rBox = new PrecisionRectangle(((IRoundedRectangleFigure) ((IFigure) figure)).getRoundedRectangleBounds()); } else if (figure instanceof IFigure) { rBox = new PrecisionRectangle(getOwner().getBounds()); } if (null != rBox) { ((IFigure) figure).translateToAbsolute(rBox); rBox.expand(offset.width, offset.height); } return rBox; }
Source:
public static void initializeOprofileModule() { if (!isKernelModuleLoaded()) initializeOprofile(); if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); } else { initializeOprofileCore(); } }

Target:
private static void initializeOprofileModule() { if (!isKernelModuleLoaded()) initializeOprofile(); if (!isKernelModuleLoaded()) { OprofileCorePlugin.showErrorDialog("oprofileInit", null); } else { initializeOprofileCore(); } }
Source:
private Mono<Integer> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { GenericExecuteSpec executeSpec = databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL); for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper.apply(authorizedClient, principal) .entrySet()) { executeSpec = executeSpec.bind(entry.getKey(), entry.getValue()); } return executeSpec.fetch().rowsUpdated(); }

Target:
private Mono<Integer> updateAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal) { GenericExecuteSpec executeSpec = this.databaseClient.sql(UPDATE_AUTHORIZED_CLIENT_SQL); for (Entry<String, Parameter> entry : this.authorizedClientParametersMapper .apply(new OAuth2AuthorizedClientHolder(authorizedClient, principal)).entrySet()) { executeSpec = executeSpec.bind(entry.getKey(), entry.getValue()); } return executeSpec.fetch().rowsUpdated(); }
Source:
public Integer getNextEntryNumber(final Integer studyId) { try { final String queryString = "SELECT MAX(Convert(s.uniquename, SIGNED)) FROM stock s where s.project_id = :studyId"; final SQLQuery query = this.getSession().createSQLQuery(queryString); query.setParameter("studyId", studyId); final BigInteger highestEntryNumber = (BigInteger) query.uniqueResult(); if(highestEntryNumber == null) { return 1; } else { return highestEntryNumber.intValue() + 1; } } catch (final HibernateException e) { final String errorMessage = "Error in getNextEntryNumber for studyId=" + studyId + StockDao.IN_STOCK_DAO + e.getMessage(); LOG.error(errorMessage, e); throw new MiddlewareQueryException(errorMessage, e); } }

Target:
public Integer getNextEntryNumber(final Integer studyId) { try { final String queryString = "SELECT IFNULL(MAX(Convert(s.uniquename, SIGNED)), 0) + 1 FROM stock s where s.project_id = :studyId"; final SQLQuery query = this.getSession().createSQLQuery(queryString); query.setParameter("studyId", studyId); return ((BigInteger) query.uniqueResult()).intValue(); } catch (final HibernateException e) { final String errorMessage = "Error in getNextEntryNumber for studyId=" + studyId + StockDao.IN_STOCK_DAO + e.getMessage(); LOG.error(errorMessage, e); throw new MiddlewareQueryException(errorMessage, e); } }
Source:
public Response addOrUpdateModelInfo( @PathParam("id") final Long modelId, @FormDataParam("modelInfo") final MLModelInfo modelInfo, @FormDataParam("pmmlFile") final InputStream pmmlInputStream, @FormDataParam("pmmlFile") final FormDataContentDisposition fileDisposition) throws IOException { if (pmmlInputStream == null) { throw BadRequestException.missingParameter("pmmlFile"); } try { MLModelInfo createdModelInfo = modelRegistryService.addOrUpdateModelInfo( modelId, modelInfo, pmmlInputStream, fileDisposition); return WSUtils.respondEntity(createdModelInfo, CREATED); } catch (Exception exception) { LOG.debug("Error occured while adding the pmml model", exception); throw exception; } finally { try { if (pmmlInputStream != null) { pmmlInputStream.close(); } } catch (IOException exception) { LOG.debug("Error while closing the pmml file stream", exception); throw exception; } } }

Target:
public Response addOrUpdateModelInfo( @PathParam("id") final Long modelId, @FormDataParam("modelInfo") final MLModelInfo modelInfo, @FormDataParam("pmmlFile") final InputStream pmmlInputStream, @FormDataParam("pmmlFile") final FormDataContentDisposition fileDisposition) throws IOException { if (pmmlInputStream == null) { throw BadRequestException.missingParameter("pmmlFile"); } try { MLModelInfo createdModelInfo = modelRegistryService.addOrUpdateModelInfo( modelId, modelInfo, pmmlInputStream, fileDisposition.getFileName()); return WSUtils.respondEntity(createdModelInfo, CREATED); } catch (Exception exception) { LOG.debug("Error occured while adding the pmml model", exception); throw exception; } finally { try { if (pmmlInputStream != null) { pmmlInputStream.close(); } } catch (IOException exception) { LOG.debug("Error while closing the pmml file stream", exception); throw exception; } } }
Source:
protected void executeQueryCommand() { Integer numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); getQueryReturnValue().setReturnValue(numOfVms); }

Target:
protected void executeQueryCommand() { int numOfVms = getDbFacade().getVdsGroupDao().getVmsCountByClusterId(getParameters().getId()); getQueryReturnValue().setReturnValue(numOfVms); }
Source:
protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setRecursive(true); startWalk.setFilter(PathFilterGroup.createFromStrings(paths)); boolean checkoutIndex = (startCommit == null && startPoint == null); if (!checkoutIndex) { startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); } else { startWalk.addTree(new DirCacheIterator(dc)); } final File workTree = repo.getWorkTree(); final ObjectReader r = repo.getObjectDatabase().newReader(); try { while (startWalk.next()) { final ObjectId blobId = startWalk.getObjectId(0); final FileMode mode = startWalk.getFileMode(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); ent.setFileMode(mode); try { DirCacheCheckout.checkoutEntry(repo, new File( workTree, ent.getPathString()), ent, r); } catch (IOException e) { throw new RuntimeException(e); } } }); } editor.commit(); } finally { startWalk.release(); r.release(); } } finally { dc.unlock(); revWalk.release(); } return this; }

Target:
protected CheckoutCommand checkoutPaths() throws IOException, RefNotFoundException { RevWalk revWalk = new RevWalk(repo); DirCache dc = repo.lockDirCache(); try { DirCacheEditor editor = dc.editor(); TreeWalk startWalk = new TreeWalk(revWalk.getObjectReader()); startWalk.setRecursive(true); startWalk.setFilter(PathFilterGroup.createFromStrings(paths)); boolean checkoutIndex = startCommit == null && startPoint == null; if (!checkoutIndex) startWalk.addTree(revWalk.parseCommit(getStartPoint()) .getTree()); else startWalk.addTree(new DirCacheIterator(dc)); final File workTree = repo.getWorkTree(); final ObjectReader r = repo.getObjectDatabase().newReader(); try { while (startWalk.next()) { final ObjectId blobId = startWalk.getObjectId(0); final FileMode mode = startWalk.getFileMode(0); editor.add(new PathEdit(startWalk.getPathString()) { public void apply(DirCacheEntry ent) { ent.setObjectId(blobId); ent.setFileMode(mode); try { DirCacheCheckout.checkoutEntry(repo, new File( workTree, ent.getPathString()), ent, r); } catch (IOException e) { throw new JGitInternalException( MessageFormat.format( JGitText.get().checkoutConflictWithFile, ent.getPathString()), e); } } }); } editor.commit(); } finally { startWalk.release(); r.release(); } } finally { dc.unlock(); revWalk.release(); } return this; }
Source:
public void setEncoding(Encoding encoding) throws IOException { if (encodingWriter != null) { encodingWriter.close(); } this.encoding = encoding; OutputStream interceptor = new FilterOutputStream(pg_output) { @Override public void flush() throws IOException { } @Override public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }

Target:
public void setEncoding(Encoding encoding) throws IOException { if (encodingWriter != null) encodingWriter.close(); this.encoding = encoding; OutputStream interceptor = new FilterOutputStream(pg_output) { public void flush() throws IOException { } public void close() throws IOException { super.flush(); } }; encodingWriter = encoding.getEncodingWriter(interceptor); }
Source:
protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { log.error("Work category '{}' cannot be assigned to work queue '%s'" + " because it is already assigned to work queue '%s'", c, d.getId(), v); } return v; }); categoryToQueueId.putIfAbsent(c, d.getId()); })); }

Target:
protected void index() { List<WorkQueueDescriptor> descriptors = getDescriptors(QUEUES_EP); descriptors.forEach(d -> d.categories.forEach(c -> { categoryToQueueId.computeIfPresent(c, (k, v) -> { if (!v.equals(d.getId())) { log.error("Work category '{}' cannot be assigned to work queue '{}'" + " because it is already assigned to work queue '{}'", c, d.getId(), v); } return v; }); categoryToQueueId.putIfAbsent(c, d.getId()); })); }
Source:
public static Iterator iteratorFrom( Object iterable ) { if ( iterable instanceof Iterable ) { return ((Iterable) iterable).iterator(); } else if ( iterable instanceof PrimitiveEntityStream ) { return ((PrimitiveEntityStream) iterable).iterator(); } else if ( iterable instanceof Long) { return (LongStream.of((Long) iterable)).iterator(); } else if ( iterable instanceof LongStream ) { return ((LongStream) iterable).iterator(); } else if ( iterable instanceof Double) { return (DoubleStream.of((Double) iterable)).iterator(); } else if ( iterable instanceof DoubleStream ) { return ((DoubleStream) iterable).iterator(); } else if ( iterable instanceof Integer) { return (IntStream.of((Integer) iterable)).iterator(); } else if ( iterable instanceof IntStream ) { return ((IntStream) iterable).iterator(); } else if ( iterable == null ) { return Collections.emptyIterator(); } else if ( iterable instanceof String ) { String[] singleStringArray = {(String) iterable}; return getIterator( singleStringArray, 1 ); } else if ( iterable.getClass().isArray() ) { int len = Array.getLength( iterable ); return getIterator( iterable, len ); } else { throw new CypherTypeException( "Don't know how to create an iterator out of " + iterable.getClass().getSimpleName(), null ); } }

Target:
public static Iterator iteratorFrom( Object iterable ) { if ( iterable instanceof Iterable ) { return ((Iterable) iterable).iterator(); } else if ( iterable instanceof PrimitiveEntityStream ) { return ((PrimitiveEntityStream) iterable).iterator(); } else if ( iterable instanceof LongStream ) { return ((LongStream) iterable).iterator(); } else if ( iterable instanceof DoubleStream ) { return ((DoubleStream) iterable).iterator(); } else if ( iterable instanceof IntStream ) { return ((IntStream) iterable).iterator(); } else if ( iterable == null ) { return Collections.emptyIterator(); } else if ( iterable.getClass().isArray() ) { int len = Array.getLength( iterable ); return new Iterator() { private int position = 0; @Override public boolean hasNext() { return position < len; } @Override public Object next() { if ( position >= len ) { throw new NoSuchElementException(); } return Array.get( iterable, position++ ); } }; } else { return Stream.of(iterable).iterator(); } }
Source:
public void testCorrect() { Set<String> previousNames = new HashSet<String>(); int i = 0; for (String each : wrongNames) { String name = NameUtil.correct(each, i++, previousNames); Assert.assertTrue("too many underline", countUnderLine(name) <= (name.length() / 2)); previousNames.add(name); } Assert.assertEquals("after the correct, we miss some one or create a duplicated one, please check the NameUtil class", wrongNames.length, previousNames.size()); }

Target:
public void testCorrect() { Set<String> resultNames = new HashSet<String>(); int i = 0; Set<String> expectedSet = new HashSet<>(); expectedSet.addAll(Arrays.asList(expectedNames)); for (String each : wrongNames) { String name = NameUtil.correct(each, i++, resultNames); resultNames.add(name); } Assert.assertEquals(expectedSet, resultNames); }
Source:
public void executeRule() { try { testRulesPath.resetIterator(); File[] ruleFiles = rulesPath.getNextRule(); File[] ruleTestFiles = findMatchingTestFile(ruleFiles[0], ruleFiles[1]); Assert.assertNotNull("No test file found", ruleTestFiles); LOG.info(String.format("Testing execution of rule %s%n", ruleFiles[0].getName())); visit(ruleTestFiles[0], ruleTestFiles[1]); } catch(AssertionError ae) { LOG.error(ae.getMessage()); throw ae; } }

Target:
public void executeRule() { try { testRulesPath.resetIterator(); File[] ruleFiles = rulesPath.getNextRule(); File[] ruleTestFiles = findMatchingTestFile(ruleFiles[0], ruleFiles[1]); Assert.assertNotNull("No test file matching rule", ruleTestFiles); LOG.info(String.format("Testing execution of rule %s%n", ruleFiles[0].getName())); visit(ruleTestFiles[0], ruleTestFiles[1]); } catch(AssertionError ae) { LOG.error(ae.getMessage()); throw ae; } }
Source:
public boolean validate(URL definitionUrl) { boolean isValid = false; try { String definitionContent = IOUtils.toString(definitionUrl.openStream()); isValid = validate(definitionContent); } catch (IOException e) { log.error("Error in reading content in the definition URL: " + definitionUrl, e); } return isValid; }

Target:
public boolean validate(URL definitionUrl) throws DefinitionValidationException { boolean isValid; try { String definitionContent = IOUtils.toString(definitionUrl.openStream()); isValid = validate(definitionContent); } catch (IOException e) { throw new DefinitionValidationException("Error in reading content in the definition URL: " + definitionUrl, e); } return isValid; }
Source:
public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(DisplayRealm.getRealm(display), () -> { Shell shell = new Shell(display); shell.setText("ISideEffect & AggregateValidationStatus"); shell.setLayout(new GridLayout(2, false)); new Label(shell, SWT.NONE).setText("Enter '5' to be valid:"); Text text = new Text(shell, SWT.BORDER); WritableValue<String> value = new WritableValue<>(); Button okButton = new Button(shell, SWT.BORDER); okButton.setText("Ok"); GridDataFactory.swtDefaults().hint(200, SWT.DEFAULT).applyTo(okButton); DataBindingContext dbc = new DataBindingContext(); dbc.bindValue(WidgetProperties.text(SWT.Modify).observe(text), value, new UpdateValueStrategy().setAfterConvertValidator(textValue -> ("5".equals(textValue)) ? Status.OK_STATUS : ValidationStatus.error("The value was '" + value + "', not '5'")), null); AggregateValidationStatus validationStatus = new AggregateValidationStatus(dbc.getBindings(), AggregateValidationStatus.MAX_SEVERITY); ISideEffect okButtonEnablement = ISideEffect.create(() -> validationStatus.getValue().isOK(), okButton::setEnabled); shell.addDisposeListener(e -> { dbc.dispose(); okButtonEnablement.dispose(); }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } }); display.dispose(); }

Target:
public static void main(String[] args) { final Display display = new Display(); Realm.runWithDefault(DisplayRealm.getRealm(display), () -> run(display)); display.dispose(); }