auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArrayWritableObjectInspector that = (ArrayWritableObjectInspector) o; if (isRoot != that.isRoot) { return false; } if (typeInfo != null ? !typeInfo.equals(that.typeInfo) : that.typeInfo != null) { return false; } if (fieldInfos != null ? !fieldInfos.equals(that.fieldInfos) : that.fieldInfos != null) { return false; } if (fieldNames != null ? !fieldNames.equals(that.fieldNames) : that.fieldNames != null) { return false; } if (fields != null ? !fields.equals(that.fields) : that.fields != null) { return false; } return fieldsByName != null ? fieldsByName.equals(that.fieldsByName) : that.fieldsByName == null; }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } ArrayWritableObjectInspector that = (ArrayWritableObjectInspector) o; if (isRoot != that.isRoot || (typeInfo != null ? !typeInfo.equals(that.typeInfo) : that.typeInfo != null) || (fieldInfos != null ? !fieldInfos.equals(that.fieldInfos) : that.fieldInfos != null) || (fieldNames != null ? !fieldNames.equals(that.fieldNames) : that.fieldNames != null) || (fields != null ? !fields.equals(that.fields) : that.fields != null)) { return false; } return fieldsByName != null ? fieldsByName.equals(that.fieldsByName) : that.fieldsByName == null; }
Source:
public String getTasksWithNoParent() throws SQLException { ArrayList<TaskObject> existedTask = mProductBacklogHelper.getTasksWithNoParent(); Gson gson = new Gson(); return gson.toJson(existedTask); }

Target:
public String getTasksWithNoParent() throws SQLException { ArrayList<TaskObject> existingTasks = mProductBacklogHelper.getTasksWithNoParent(); Gson gson = new Gson(); return gson.toJson(existingTasks); }
Source:
public void process() { if (material == null) { shaderManager.disableShader(); } else { material.enable(); } }

Target:
public void process() { material.enable(); }
Source:
private boolean defaultAutodiscoverRedirectionUrlValidationCallback( String redirectionUrl) throws AutodiscoverLocalException { throw new AutodiscoverLocalException(String.format( "Autodiscover blocked a potentially insecure redirection to %s. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload.", redirectionUrl)); }

Target:
private boolean defaultAutodiscoverRedirectionUrlValidationCallback( String redirectionUrl) throws AutodiscoverLocalException { throw new AutodiscoverLocalException(String.format( "Autodiscover blocked a potentially insecure redirection to %s. To allow Autodiscover to follow the " + "redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) " + "overload.", redirectionUrl)); }
Source:
public void resolveMessageShouldResolveMessageWhenMessageKeyExists() { messageSource.addMessage(BIRTHDAY_MESSAGE_KEY, dummyLocale, BIRTHDAY_MESSAGE); String message = messageKeyResolver.resolveMessage(BIRTHDAY_MESSAGE_KEY); assertThat(message, equalTo(BIRTHDAY_MESSAGE)); }

Target:
public void resolveMessageShouldResolveMessageWhenMessageKeyExists() throws MessageResolutionFailedException { String message = messageKeyResolver.resolveMessage(EXAMPLE_MESSAGE_KEY); assertThat(message, equalTo(EXAMPLE_MESSAGE)); }
Source:
private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request, HttpContext context, String message, Class<T> clz, boolean isReturnServerError) throws XtentisException { if (null == request) { throw new IllegalArgumentException("null request"); } HttpResponse response = null; try { response = client.execute(request, context); StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 501) { throw new OperationIgnoredException(Messages.HttpClientUtil_Error_501); } return wrapResponse(response, message, clz, isReturnServerError); } catch (OperationIgnoredException ex) { throw ex; } catch (InternalServerErrorException ex) { throw ex; } catch (XtentisException ex) { throw ex; } catch (Exception e) { LOG.error(e.getMessage(), e); request.abort(); throw new XtentisException(e.getMessage(), e); } finally { closeResponse(response); } }

Target:
private static <T> T getResponseContent(DefaultHttpClient client, HttpUriRequest request, HttpContext context, String message, Class<T> clz, boolean isReturnServerError) throws XtentisException { if (null == request) { throw new IllegalArgumentException("null request"); } HttpResponse response = null; try { response = client.execute(request, context); StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 501) { throw new OperationIgnoredException(Messages.HttpClientUtil_Error_501); } return wrapResponse(response, message, clz, isReturnServerError); } catch (OperationIgnoredException ex) { throw ex; } catch (InternalServerErrorException ex) { throw ex; } catch (XtentisException ex) { throw ex; } catch (Exception e) { LOG.error(e.getMessage(), e); try { request.abort(); } catch (Exception e1) { } throw new XtentisException(e.getMessage(), e); } finally { closeResponse(response); } }
Source:
public static void cacheRealmWithEverything(KeycloakSession session, String realmName) { RealmModel realm = session.realms().getRealmByName(realmName); for (ClientModel client : realm.getClients()) { realm.getClientById(client.getId()); realm.getClientByClientId(client.getClientId()); cacheRoles(session, realm, client); } cacheRoles(session, realm, realm); for (GroupModel group : realm.getTopLevelGroups()) { cacheGroupRecursive(realm, group); } for (ClientScopeModel clientTemplate : realm.getClientScopes()) { realm.getClientScopeById(clientTemplate.getId()); } for (UserModel user : session.users().getUsers(realm)) { session.users().getUserById(user.getId(), realm); if (user.getEmail() != null) { session.users().getUserByEmail(user.getEmail(), realm); } session.users().getUserByUsername(user.getUsername(), realm); session.users().getConsents(realm, user.getId()); for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) { session.users().getUserByFederatedIdentity(fedIdentity, realm); } } }

Target:
public static void cacheRealmWithEverything(KeycloakSession session, String realmName) { RealmModel realm = session.realms().getRealmByName(realmName); for (ClientModel client : realm.getClients()) { realm.getClientById(client.getId()); realm.getClientByClientId(client.getClientId()); cacheRoles(session, realm, client); } cacheRoles(session, realm, realm); for (GroupModel group : realm.getTopLevelGroups()) { cacheGroupRecursive(realm, group); } for (ClientScopeModel clientScope : realm.getClientScopes()) { realm.getClientScopeById(clientScope.getId()); } for (UserModel user : session.users().getUsers(realm)) { session.users().getUserById(user.getId(), realm); if (user.getEmail() != null) { session.users().getUserByEmail(user.getEmail(), realm); } session.users().getUserByUsername(user.getUsername(), realm); session.users().getConsents(realm, user.getId()); for (FederatedIdentityModel fedIdentity : session.users().getFederatedIdentities(user, realm)) { session.users().getUserByFederatedIdentity(fedIdentity, realm); } } }
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode operationModel = new ModelNode(); populateModel(operation, operationModel); String attributeName = NAME.resolveModelAttribute(context, operationModel).asString(); AttributeAccess attributeAccess = context.getResourceRegistration().getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName); if (attributeAccess == null) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName))); } else if (requiredReadWriteAccess && attributeAccess.getAccessType() != AttributeAccess.AccessType.READ_WRITE) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.attributeNotWritable(attributeName))); } Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel().get(attributeName); updateModel(context, operationModel, attributeAccess.getAttributeDefinition(), model); if (requiredReadWriteAccess) { final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); ModelNode writeOperation = Util.createOperation(WriteAttributeHandler.DEFINITION, address); writeOperation.get(NAME.getName()).set(attributeName); writeOperation.get(ModelDescriptionConstants.VALUE).set(model); context.addStep(writeOperation, WriteAttributeHandler.INSTANCE, OperationContext.Stage.MODEL); } context.stepCompleted(); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { ModelNode operationModel = new ModelNode(); populateModel(operation, operationModel); final String attributeName = NAME.resolveModelAttribute(context, operationModel).asString(); final AttributeAccess attributeAccess = context.getResourceRegistration().getAttributeAccess(PathAddress.EMPTY_ADDRESS, attributeName); if (attributeAccess == null) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.unknownAttribute(attributeName))); } else if (requiredReadWriteAccess && attributeAccess.getAccessType() != AttributeAccess.AccessType.READ_WRITE) { throw new OperationFailedException(new ModelNode().set(ControllerLogger.ROOT_LOGGER.attributeNotWritable(attributeName))); } final PathAddress address = PathAddress.pathAddress(operation.get(OP_ADDR)); Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS); ModelNode model = resource.getModel().get(attributeName); updateModel(context, operationModel, attributeAccess.getAttributeDefinition(), model); if (requiredReadWriteAccess) { ModelNode writeOperation = Util.createOperation(WriteAttributeHandler.DEFINITION, address); writeOperation.get(NAME.getName()).set(attributeName); writeOperation.get(ModelDescriptionConstants.VALUE).set(model); context.addStep(writeOperation, WriteAttributeHandler.INSTANCE, OperationContext.Stage.MODEL); } context.stepCompleted(); }
Source:
public void testRepeat() { { Assert.assertEquals("", StringUtils.repeat("foo", 0)); Assert.assertEquals("foo", StringUtils.repeat("foo", 1)); Assert.assertEquals("foofoofoo", StringUtils.repeat("foo", 3)); } { Assert.assertEquals("", StringUtils.repeat("", 0)); Assert.assertEquals("", StringUtils.repeat("", 1)); Assert.assertEquals("", StringUtils.repeat("", 3)); } { expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("count is negative, -1"); Assert.assertEquals("", StringUtils.repeat("foo", -1)); } }

Target:
public void testRepeat() { Assert.assertEquals("", StringUtils.repeat("foo", 0)); Assert.assertEquals("foo", StringUtils.repeat("foo", 1)); Assert.assertEquals("foofoofoo", StringUtils.repeat("foo", 3)); Assert.assertEquals("", StringUtils.repeat("", 0)); Assert.assertEquals("", StringUtils.repeat("", 1)); Assert.assertEquals("", StringUtils.repeat("", 3)); expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("count is negative, -1"); Assert.assertEquals("", StringUtils.repeat("foo", -1)); }
Source:
protected Content(Content source) { this.setUuid(source.getUuid()); this.setId(source.getId()); this.setCreated(source.getCreated()); this.setUpdated(source.getUpdated()); this.setType(source.getType()); this.setLabel(source.getLabel()); this.setOwners(source.getOwners()); this.setName(source.getName()); this.setVendor(source.getVendor()); this.setContentUrl(source.getContentUrl()); this.setRequiredTags(source.getRequiredTags()); this.setReleaseVer(source.getReleaseVer()); this.setGpgUrl(source.getGpgUrl()); this.setMetadataExpire(source.getMetadataExpire()); this.setModifiedProductIds(source.getModifiedProductIds()); this.setArches(source.getArches()); }

Target:
protected Content(Content source) { this.setUuid(source.getUuid()); this.setId(source.getId()); this.setCreated(source.getCreated() != null ? (Date) source.getCreated().clone() : null); this.setUpdated(source.getUpdated() != null ? (Date) source.getUpdated().clone() : null); this.setType(source.getType()); this.setLabel(source.getLabel()); this.setOwners(source.getOwners()); this.setName(source.getName()); this.setVendor(source.getVendor()); this.setContentUrl(source.getContentUrl()); this.setRequiredTags(source.getRequiredTags()); this.setReleaseVer(source.getReleaseVer()); this.setGpgUrl(source.getGpgUrl()); this.setMetadataExpire(source.getMetadataExpire()); this.setArches(source.getArches()); this.setModifiedProductIds(source.getModifiedProductIds() != null ? new HashSet<String>(source.getModifiedProductIds()) : null); }
Source:
public static void main(String[] args) { System.setProperty("spring.jpa.hibernate.naming_strategy", "org.hibernate.cfg.ImprovedNamingStrategy"); SpringApplication.run(ResourceServer.class, args); }

Target:
public static void main(String[] args) { SpringApplication application = new SpringApplication(ResourceServer.class, args); application.setDefaultProperties(NAMING_STRATEGY); application.run(); }
Source:
public TaskRepository repository() { if (repository != null) { return repository; } repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); if (Boolean.parseBoolean(getProperty("api_key_enabled"))) { repository.setProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY, Boolean.toString(true)); repository.setProperty(IBugzillaRestConstants.REPOSITORY_API_KEY, userAPIKeyMap.getOrDefault(credentials.getUserName(), "")); repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), ""), false); } else { repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), true); } return repository; }

Target:
public TaskRepository repository() { if (repository != null) { return repository; } repository = new TaskRepository(getConnectorKind(), getRepositoryUrl()); UserCredentials credentials = CommonTestUtil.getCredentials(PrivilegeLevel.USER); if (Boolean.parseBoolean(getProperty(IBugzillaRestConstants.API_KEY_ENABLED_PROPERTY))) { repository.setProperty(IBugzillaRestConstants.REPOSITORY_USE_API_KEY, Boolean.toString(true)); repository.setProperty(IBugzillaRestConstants.REPOSITORY_API_KEY, userAPIKeyMap.getOrDefault(credentials.getUserName(), "")); repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), ""), false); } else { repository.setCredentials(org.eclipse.mylyn.commons.net.AuthenticationType.REPOSITORY, new AuthenticationCredentials(credentials.getUserName(), credentials.getPassword()), true); } return repository; }
Source:
public GraphDatabaseService create() { LOG.infof( "1. Try create new service instance for dbPath %s", dbLocation ); final String dbLocationAbsolutePath = dbLocation.getAbsolutePath(); LOG.infof( "2. Try create new service instance for dbPath %s", dbLocationAbsolutePath ); return GRAPH_DATABASE_SERVICE_MAP.computeIfAbsent( dbLocationAbsolutePath, ( String path ) -> { LOG.infof( " Create new service instance for dbPath %s", dbLocationAbsolutePath ); return buildGraphDatabaseService(); } ); }

Target:
public GraphDatabaseService create() { LOG.infof( "1. Try create new service instance for dbPath %s", dbLocation ); final String dbLocationAbsolutePath = dbLocation.getAbsolutePath(); LOG.infof( "2. Try create new service instance for dbPath %s", dbLocationAbsolutePath ); if ( !GRAPH_DATABASE_SERVICE_MAP.containsKey( dbLocationAbsolutePath ) ) { synchronized (GRAPH_DATABASE_SERVICE_MAP) { if ( !GRAPH_DATABASE_SERVICE_MAP.containsKey( dbLocationAbsolutePath ) ) { LOG.infof( " Create new service instance for dbPath %s", dbLocationAbsolutePath ); GraphDatabaseService service = buildGraphDatabaseService(); LOG.infof( " Create dnew service %s instance for dbPath %s",service, dbLocationAbsolutePath ); GRAPH_DATABASE_SERVICE_MAP.put( dbLocationAbsolutePath, service ); } } } return GRAPH_DATABASE_SERVICE_MAP.get( dbLocationAbsolutePath ); }
Source:
private void initTitleActions() { List<Action> tools = new ArrayList<Action>(); saveAction = new DefaultAction("SAVE_MAP", I18N.tr("Save"), I18N.tr("Save the Map"), OrbisGISIcon.getIcon("save"), EventHandler.create(ActionListener.class, this, "onSaveMapContext"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveAction.setEnabled(false); tools.add(saveAction); DefaultAction addWMSAction = new DefaultAction("ADD_WMS_LAYER", I18N.tr("Add"), I18N.tr("Add WMS layer"), OrbisGISIcon.getIcon("add"), EventHandler.create(ActionListener.class, this, "onAddWMSLayer"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); tools.add(addWMSAction); dockingPanelParameters.setDockActions(tools); }

Target:
private void initTitleActions() { List<Action> tools = new ArrayList<Action>(); saveAction = new DefaultAction("SAVE_MAP", I18N.tr("Save"), I18N.tr("Save the Map"), OrbisGISIcon.getIcon("save"), EventHandler.create(ActionListener.class, this, "onSaveMapContext"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); saveAction.setEnabled(false); tools.add(saveAction); DefaultAction addWMSAction = new DefaultAction("ADD_WMS_LAYER", I18N.tr("WMS layer"), I18N.tr("Add WMS layer"), OrbisGISIcon.getIcon("add"), EventHandler.create(ActionListener.class, this, "onAddWMSLayer"), KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK)); tools.add(addWMSAction); dockingPanelParameters.setDockActions(tools); }
Source:
private static void doLoadScenarioExecution(final JaasEnvApiClient.JaasResponse jaasResponse, final URL directory) { JaasExecApiClient execApiClient = null; try { execApiClient = new JaasExecApiClient(jaasResponse.getExecutionId(), environmentProperties.getProperty("realtime.jaas.endpoint") ); Optional<TestExecutionEntity> optionalExecution = execApiClient.getExecution(); if (!optionalExecution.isPresent()) { return; } TestExecutionEntity execution = optionalExecution.get(); if (execution.getStatus() != TestExecutionEntity.TestExecutionStatus.PENDING) { log.warn("Received execution is not in PENDING state. Going to proceed with next..."); return; } execApiClient.startExecution(); String sessionId = null; if (execution.getTestProjectURL() == null) { environmentProperties.setProperty(LOAD_SCENARIO_ID_PROP, execution.getLoadScenarioId()); System.setProperty(USER_CONFIGS_PACKAGE, environmentProperties.getProperty(USER_CONFIGS_PACKAGE)); sessionId = doLaunchMaster(directory); } else { sessionId = executeDynamicLoadScenario(execution.getLoadScenarioId(), execution.getTestProjectURL(), directory); } execApiClient.completeExecution(sessionId); } catch (Exception e) { log.error("Error during a load scenario execution", e); if (execApiClient != null) { execApiClient.failExecution(ExceptionUtils.getMessage(e) + " With root cause message: " + ExceptionUtils .getRootCauseMessage(e)); } } }

Target:
private static void doLoadScenarioExecution(final JaasEnvApiClient.JaasResponse jaasResponse, final URL directory) { JaasExecApiClient execApiClient = null; try { execApiClient = new JaasExecApiClient(jaasResponse.getExecutionId(), environmentProperties.getProperty("realtime.jaas.endpoint") ); Optional<TestExecutionEntity> optionalExecution = execApiClient.getExecution(); if (!optionalExecution.isPresent()) { return; } TestExecutionEntity execution = optionalExecution.get(); if (execution.getStatus() != TestExecutionEntity.TestExecutionStatus.PENDING) { log.warn("Received execution with id '{}' is not in PENDING state. Going to proceed with next...", execution.getId()); return; } execApiClient.startExecution(); String sessionId = null; if (execution.getTestProjectURL() == null) { environmentProperties.setProperty(LOAD_SCENARIO_ID_PROP, execution.getLoadScenarioId()); System.setProperty(USER_CONFIGS_PACKAGE, environmentProperties.getProperty(USER_CONFIGS_PACKAGE)); sessionId = doLaunchMaster(directory); } else { sessionId = executeDynamicLoadScenario(execution.getLoadScenarioId(), execution.getTestProjectURL(), directory); } execApiClient.completeExecution(sessionId); } catch (Exception e) { log.error("Error during a load scenario execution", e); if (execApiClient != null) { execApiClient.failExecution(ExceptionUtils.getMessage(e) + " With root cause message: " + ExceptionUtils .getRootCauseMessage(e)); } } }
Source:
public final void startDatabase() { if (!databaseStarted) { synchronized (this) { if (!databaseStarted) { LOG.debug("Starting a connection to the database"); onStartDatabase(); } } } }

Target:
public final void startDatabase() { if (!databaseStarted) { synchronized (this) { if (!databaseStarted) { LOG.debug("Starting a connection to the database."); onStartDatabase(); } } } }
Source:
static Optional<ImmutablePair<String, String>> findSupportedTargetPath(List<ProvisionInterface> pluginList, List<String> targetPaths) { for (String target : targetPaths) { URI objectIdentifier = URI.create(target); String scheme = objectIdentifier.getScheme().toLowerCase(); if (scheme != null) { for (ProvisionInterface provisionInterface : pluginList) { if (StringUtils.containsIgnoreCase(provisionInterface.schemesHandled().iterator().next(), scheme)) { return Optional.of(new ImmutablePair<>(target, scheme)); } } } } return Optional.empty(); }

Target:
static Optional<ImmutablePair<String, String>> findSupportedTargetPath(List<ProvisionInterface> pluginList, List<String> targetPaths) { for (String target : targetPaths) { try { URI objectIdentifier = URI.create(target); String scheme = (objectIdentifier.getScheme() != null) ? objectIdentifier.getScheme().toLowerCase() : null; if (scheme != null) { for (ProvisionInterface provisionInterface : pluginList) { for (String currentScheme : provisionInterface.schemesHandled()) { if (StringUtils.containsIgnoreCase(currentScheme, scheme)) { return Optional.of(new ImmutablePair<>(target, scheme)); } } } } } catch (IllegalArgumentException e) { LOG.info("Bad target"); } } return Optional.empty(); }
Source:
public static BlobProperties deserializeBlobProperties(CrcInputStream crcStream) throws IOException, DataCorruptException { try { DataInputStream dataStream = new DataInputStream(crcStream); SystemMetadataType type = SystemMetadataType.values()[dataStream.readShort()]; if (type != SystemMetadataType.BlobPropertyRecord) throw new IllegalArgumentException("Invalid system metadata type"); BlobProperties properties = BlobPropertySerDe.getBlobPropertyFromStream(dataStream); long crc = crcStream.getValue(); if (crc != dataStream.readLong()) { logger.error("corrupt data while parsing blob properties"); throw new DataCorruptException("Blob property data is corrupt"); } return properties; } catch (Exception e) { logger.error("Blob property failed to be parsed. Data may be corrupt with exception {}", e); throw new DataCorruptException("Blob property failed to be parsed. Data may be corrupt"); } }

Target:
public static BlobProperties deserializeBlobProperties(CrcInputStream crcStream) throws IOException, DataCorruptException { try { DataInputStream dataStream = new DataInputStream(crcStream); SystemMetadataRecordType type = SystemMetadataRecordType.values()[dataStream.readShort()]; if (type != SystemMetadataRecordType.BlobPropertyRecord) throw new IllegalArgumentException("Invalid system metadata type"); BlobProperties properties = BlobPropertySerDe.getBlobPropertyFromStream(dataStream); long crc = crcStream.getValue(); if (crc != dataStream.readLong()) { logger.error("corrupt data while parsing blob properties"); throw new DataCorruptException("Blob property data is corrupt"); } return properties; } catch (Exception e) { logger.error("Blob property failed to be parsed. Data may be corrupt with exception {}", e); throw new DataCorruptException("Blob property failed to be parsed. Data may be corrupt"); } }
Source:
private void handleMenuElementRemove(MenuManager manager, Iterable<MMenuElement> menuElements) { Iterator<MMenuElement> iterMenuElements = menuElements.iterator(); if (!iterMenuElements.hasNext()) return; while (iterMenuElements.hasNext()) { MMenuElement menuElement = iterMenuElements.next(); if (menuElement instanceof MMenu) { MMenu menuModel = (MMenu) menuElement; MenuManager mi = getManager(menuModel); manager.remove(mi); clearModelToManager(menuModel, mi); handleMenuElementRemove(mi, menuModel.getChildren()); mi.dispose(); } else { IContributionItem ci = getContribution(menuElement); manager.remove(ci); clearModelToContribution(menuElement, ci); ci.dispose(); } } if (!disposingMenuUIElement) { manager.updateAll(false); } }

Target:
private void handleMenuElementRemove(MenuManager manager, Iterable<MMenuElement> menuElements) { Iterator<MMenuElement> iterMenuElements = menuElements.iterator(); if (!iterMenuElements.hasNext()) return; while (iterMenuElements.hasNext()) { MMenuElement menuElement = iterMenuElements.next(); if (menuElement instanceof MMenu) { MMenu menuModel = (MMenu) menuElement; MenuManager mi = getManager(menuModel); if (mi == null) { continue; } manager.remove(mi); clearModelToManager(menuModel, mi); handleMenuElementRemove(mi, menuModel.getChildren()); mi.dispose(); } else { IContributionItem ci = getContribution(menuElement); if (ci == null) { continue; } manager.remove(ci); clearModelToContribution(menuElement, ci); ci.dispose(); } } if (!disposingMenuUIElement) { manager.updateAll(false); } }
Source:
public void testRestartWithKarafRestart() throws Exception { final ApplicationServiceBean serviceBean = new ApplicationServiceBean( testAppService, testConfigAdminExt, mBeanServer, mockFeaturesService, mockSystemService); serviceBean.restart(); assertThat( "Restart system property was cleared", System.getProperty(RESTART_JVM), equalTo("false")); assertThat(ddfBin.resolve("restart.jvm").toFile().exists(), equalTo(true)); verify(mockSystemService).halt(); verify(mockWrapperManager, Mockito.never()).restart(); }

Target:
public void testRestartWithKarafRestart() throws Exception { final ApplicationServiceBean serviceBean = newApplicationServiceBean(); serviceBean.restart(); assertThat( "Restart system property was cleared", System.getProperty(RESTART_JVM), equalTo("false")); assertThat(ddfBin.resolve("restart.jvm").toFile(), FileMatchers.anExistingFile()); verify(mockSystemService).halt(); verify(mockWrapperManager, Mockito.never()).restart(); }
Source:
public AddPartitionsToTxnResponse getErrorResponse(int throttleTimeMs, Throwable e) { final HashMap<TopicPartition, Errors> errors = new HashMap<>(); for (TopicPartition partition : Builder.getPartitions(data)) { errors.put(partition, Errors.forException(e)); } return new AddPartitionsToTxnResponse(throttleTimeMs, errors); }

Target:
public AddPartitionsToTxnResponse getErrorResponse(int throttleTimeMs, Throwable e) { final HashMap<TopicPartition, Errors> errors = new HashMap<>(); for (TopicPartition partition : partitions()) { errors.put(partition, Errors.forException(e)); } return new AddPartitionsToTxnResponse(throttleTimeMs, errors); }
Source:
protected void sendDmxData() { long now = System.currentTimeMillis(); universe.calculateBuffer(now); for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if (socket.isConnected()) { try { socket.getOutputStream().write(universe.getBuffer()); } catch (IOException e) { logger.warn("Could not send to in {}: {}", receiverNode, this.thing.getUID(), e); isConnected = false; return; } } else { isConnected = false; return; } } }

Target:
protected void sendDmxData() { if (this.thing.getStatus().equals(ThingStatus.ONLINE)) { long now = System.currentTimeMillis(); universe.calculateBuffer(now); for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if (socket.isConnected()) { try { socket.getOutputStream().write(universe.getBuffer()); } catch (IOException e) { logger.debug("Could not send to in {}: {}", receiverNode, this.thing.getUID(), e); closeConnection(ThingStatusDetail.COMMUNICATION_ERROR, "could not send DMX data"); return; } } else { closeConnection(ThingStatusDetail.NONE, "reconnect"); return; } } } else { openConnection(); } }
Source:
DiskSpaceRequirements getDiskSpaceRequirements() throws StoreException { synchronized (lock) { checkStarted(); DiskSpaceRequirements requirements = log.getDiskSpaceRequirements(); if (requirements != null) { requirements = new DiskSpaceRequirements(requirements.getSegmentSizeInBytes(), requirements.getSegmentsNeeded(), requirements.getSwapSegmentsInUse() + compactor.getSwapSegmentsInUse()); } return requirements; } }

Target:
DiskSpaceRequirements getDiskSpaceRequirements() throws StoreException { checkStarted(); DiskSpaceRequirements requirements = log.isLogSegmented() ? new DiskSpaceRequirements(log.getSegmentCapacity(), log.getRemainingUnallocatedSegments(), compactor.getSwapSegmentsInUse()) : null; logger.debug("Store has disk space requirements: {}", storeId, requirements); return requirements; }
Source:
public String executeCommand() { String cliOutput = ""; ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); try { client.executeCommand(command, null, out, null); cliOutput = new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { String m = String.format("SSH error running command %1$s '%2$s': %3$s", this.host, command, e.getMessage()); log.error(m, e); } return cliOutput; }

Target:
protected String executeCommand() { String cliOutput = ""; ByteArrayOutputStream out = new ConstraintByteArrayOutputStream(500); String command = Config.<String> GetValue(ConfigValues.GlusterPeerStatusCommand); client.setUser("root"); client.setPassword(getParameters().getRootPassword()); try { client.authenticate(); client.executeCommand(command, null, out, null); cliOutput = new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { String m = String.format("SSH error running command %1$s '%2$s': %3$s", this.host, command, e.getMessage()); log.error(m, e); throw new RuntimeException(e); } return cliOutput; }
Source:
public String getAuthorizationUrl(OAuthConfig config) { System.out.print("Authorisation URL: "); String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }

Target:
public String getAuthorizationUrl(OAuthConfig config) { String url = String.format(AUTHORIZE_URL, OAuthEncoder.encode(config.getApiKey()), OAuthEncoder.encode(config.getCallback()), OAuthEncoder.encode(config.getScope()), OAuthEncoder.encode(config.getState())); return url; }
Source:
public void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { serve(req, rsp, true); }

Target:
public void doGet(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException { nocache(rsp); sendPlainText(packList(req), req, rsp); }
Source:
private static boolean validateWildcard(MetaClass bindable) { if(bindable.isFinal()) { log.info("@Bindable types cannot be final, ignoring: " + bindable.getFullyQualifiedName()); return false; } return true; }

Target:
private static boolean validateWildcard(MetaClass bindable) { if (bindable.isFinal()) { log.debug("@Bindable types cannot be final, ignoring: {}", bindable.getFullyQualifiedName()); return false; } return true; }
Source:
public String getNewBtcAddress() { try { BitcoinCli newAddress = new BitcoinCli(config, "getnewaddress").run(); if (newAddress.isError()) fail(format("Could generate new bitcoin address:%n%s", newAddress.getErrorMessage())); return newAddress.getOutput(); } catch (IOException | InterruptedException ex) { fail(ex); return null; } }

Target:
public String getNewBtcAddress() { try { BitcoinCli newAddress = new BitcoinCli(config, "getnewaddress").run(); if (newAddress.isError()) fail(format("Could not generate new bitcoin address:%n%s", newAddress.getErrorMessage())); return newAddress.getOutput(); } catch (IOException | InterruptedException ex) { fail(ex); return null; } }
Source:
boolean areAllContainersRunning(Pod pod) { return pod.getSpec().getContainers().size() == pod.getStatus().getContainerStatuses().size() && !PodUtils.getContainerStatus(pod).stream().anyMatch(cs -> !cs.getReady()); }

Target:
boolean areAllContainersRunning(Pod pod) { return pod.getSpec().getContainers().size() == pod.getStatus().getContainerStatuses().size() && PodUtils.getContainerStatus(pod).stream().allMatch(ContainerStatus::getReady); }
Source:
private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); final Bitmap savedImageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); new SaneAsyncTask<String>(SaneAsyncTask.SINGLE_THREAD) { @Override public String performTask() throws Throwable { String localUrl = MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), savedImageBitmap, pageTitle.getDisplayText(), galleryItem.getName()); if (localUrl == null) { throw new RuntimeException(getString(R.string.gallery_save_error_mediastore)); } return localUrl; } @Override public void onFinish(String localUrl) { if (!isAdded()) { return; } FeedbackUtil.showMessage(parentActivity, R.string.gallery_save_success); displayImageSavedNotification(galleryItem, savedImageBitmap, localUrl); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } FeedbackUtil.showError(parentActivity, caught); } }.execute(); }

Target:
private void saveImageToMediaStore() { if (galleryItem == null) { return; } parentActivity.getFunnel().logGallerySave(pageTitle, galleryItem.getName()); final Bitmap savedImageBitmap = ((BitmapDrawable) imageView.getDrawable()).getBitmap(); new SaneAsyncTask<String>(SaneAsyncTask.SINGLE_THREAD) { @Override public String performTask() throws Throwable { String localUrl = MediaStore.Images.Media.insertImage(parentActivity.getContentResolver(), savedImageBitmap, pageTitle.getDisplayText(), galleryItem.getName()); if (localUrl == null) { throw new RuntimeException(getString(R.string.gallery_save_error_mediastore)); } return localUrl; } @Override public void onFinish(String localUrl) { if (!isAdded()) { return; } FeedbackUtil.showMessage(parentActivity, R.string.gallery_save_success); SavedImageNotificationHelper.displayImageSavedNotification(imageTitle.getText(), imageTitle.getCanonicalUri(), savedImageBitmap, localUrl); } @Override public void onCatch(Throwable caught) { if (!isAdded()) { return; } FeedbackUtil.showError(parentActivity, caught); } }.execute(); }
Source:
private void progressTo(ShardAndStrategy shardStrategy, long newProgress) { if (newProgress < 0) { log.warn("Wasn't able to progress targeted sweep for since last swept timestamp is negative.", shardStrategy.toText(), newProgress); return; } progress.updateLastSweptTimestamp(shardStrategy, newProgress); log.info("Progressed last swept timestamp for to {}.", shardStrategy.toText(), newProgress); }

Target:
private void progressTo(ShardAndStrategy shardStrategy, long newProgress) { if (newProgress < 0) { log.warn("Wasn't able to progress targeted sweep for since last swept timestamp is negative.", SafeArg.of("shardStrategy", shardStrategy.toText()), SafeArg.of("timestamp", newProgress)); return; } progress.updateLastSweptTimestamp(shardStrategy, newProgress); log.info("Progressed last swept timestamp for to {}.", SafeArg.of("shardStrategy", shardStrategy.toText()), SafeArg.of("timestamp", newProgress)); }
Source:
public List<Integer> getPartitionIdList() { return partitions.stream() .map(p -> p.id) .sorted() .collect(Collectors.toList()); }

Target:
public Set<Integer> getPartitionIdList() { return partitions.stream() .map(p -> p.id) .collect(Collectors.toSet()); }
Source:
private String buildMMPkPath() { File extStorDir = Environment.getExternalStorageDirectory(); String extSDCardDirName = this.getResources().getString(R.string.config_data_sdcard_offline_dir); String filename = this.getString(R.string.config_mmpk_name); String path= extStorDir.getAbsolutePath() + File.separator + extSDCardDirName + File.separator + filename + ".mmpk"; return path; }

Target:
private String buildMMPkPath() { File extStorDir = Environment.getExternalStorageDirectory(); String extSDCardDirName = this.getResources().getString(R.string.config_data_sdcard_offline_dir); String filename = this.getString(R.string.config_mmpk_name); return extStorDir.getAbsolutePath() + File.separator + extSDCardDirName + File.separator + filename + ".mmpk"; }
Source:
public int getADCValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand("IS")); if (response == null || response.getResponseStatus() != ATCommandStatus.OK) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getAnalogValues().get(ioLine); }

Target:
public int getADCValue(IOLine ioLine) throws InvalidOperatingModeException, XBeeException { if (!connectionInterface.isOpen()) throw new XBeeException(XBeeException.CONNECTION_NOT_OPEN); if (ioLine == null) throw new NullPointerException("IO line cannot be null."); ATCommandResponse response = sendATCommand(new ATCommand(ioLine.getReadIOATCommand())); if (response == null || response.getResponseStatus() != ATCommandStatus.OK || response == null || response.getResponse().length == 0) throw new XBeeException(XBeeException.INVALID_OPERATION); IOSample ioSample = new IOSample(response.getResponse()); if (!ioSample.hasAnalogValues() || !ioSample.getAnalogValues().containsKey(ioLine)) throw new XBeeException(XBeeException.INVALID_OPERATION); return ioSample.getAnalogValues().get(ioLine); }
Source:
public boolean equals(Object o) { if (!(o instanceof ObjectProperty)) { return false; } ObjectProperty that = (ObjectProperty) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } return super.equals(o); }

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ObjectProperty)) { return false; } ObjectProperty that = (ObjectProperty) o; if (properties != null ? !properties.equals(that.properties) : that.properties != null) { return false; } return super.equals(o); }
Source:
public void invokeCallbackMethods() { initCommandExecutor(); CommandEntity cmdEntity; for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext();) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); switch (status) { case FAILED: try { callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { handleError(ex, status, cmdId); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: try { callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); } catch (Exception ex) { handleError(ex, status, cmdId); } coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE: cmdEntity = coco.getCommandEntity(cmdId); if (cmdEntity.isExecuted()) { try { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } catch (Exception ex) { handleError(ex, status, cmdId); } } break; default: break; } } }

Target:
public void invokeCallbackMethods() { initCommandExecutor(); CommandEntity cmdEntity; for (Iterator<Entry<Guid, CommandCallBack>> iterator = cmdCallBackMap.entrySet().iterator(); iterator.hasNext(); ) { Entry<Guid, CommandCallBack> entry = iterator.next(); Guid cmdId = entry.getKey(); CommandCallBack callBack = entry.getValue(); CommandStatus status = coco.getCommandStatus(cmdId); try { switch (status) { case FAILED: callBack.onFailed(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case SUCCEEDED: callBack.onSucceeded(cmdId, coco.getChildCommandIds(cmdId)); coco.updateCallBackNotified(cmdId); iterator.remove(); break; case ACTIVE: cmdEntity = coco.getCommandEntity(cmdId); if (cmdEntity.isExecuted()) { callBack.doPolling(cmdId, coco.getChildCommandIds(cmdId)); } break; default: break; } } catch (Exception ex) { handleError(ex, status, cmdId); if (CommandStatus.FAILED.equals(status)) { coco.updateCallBackNotified(cmdId); iterator.remove(); } } } }
Source:
public void testByteBuf2BytesEmptyByteBuf() { ByteBuf buf = Unpooled.buffer(); ArrayAsserts.assertArrayEquals(new byte[]{}, ByteBufUtils.byteBuf2Bytes(buf)); buf.release(); }

Target:
public void testByteBuf2BytesEmptyByteBuf() { ByteBuf buf = Unpooled.buffer(); try { ArrayAsserts.assertArrayEquals(new byte[]{}, ByteBufUtils.byteBuf2Bytes(buf)); } finally { buf.release(); } }
Source:
void copyFiles(File srcDir, File dstDir, String filter) throws IOException { File[] list; if ((list = srcDir.listFiles()) != null) { for (File file: list) { String name = file.getName(); if (name.startsWith(filter)) { File dest = new File(dstDir, name); LOG.info("Renaming " + file + " to " + dest); if (!file.renameTo(dest)) { throw new IOException("Unable to rename " + file + " to " + dest); } } } } }

Target:
void copyFiles(File srcDir, File dstDir, String filter) throws IOException { File[] list = srcDir.listFiles(); if (list != null) { for (File file: list) { String name = file.getName(); if (name.startsWith(filter)) { File dest = new File(dstDir, name); LOG.info("Renaming " + file + " to " + dest); if (!file.renameTo(dest)) { throw new IOException("Unable to rename " + file + " to " + dest); } } } } }
Source:
public void applyStreamLinks() { for (String id : streamLinks.keySet()) { StreamMeta s = getStream(id); for (Map.Entry<Operator.OutputPort<?>, Operator.InputPort<?>> pair : streamLinks.get(id).entries()) { if (s.getSource() == null) { Operator.OutputPort<?> outputPort = pair.getKey(); while (outputPort instanceof ProxyOutputPort) { outputPort = ((ProxyOutputPort)outputPort).get(); } s.setSource(outputPort); } Operator.InputPort<?> inputPort = pair.getValue(); while (inputPort instanceof ProxyInputPort) { inputPort = ((ProxyInputPort)inputPort).get(); } s.addSink(inputPort); } } }

Target:
public void applyStreamLinks() { for (String id : streamLinks.keySet()) { StreamMeta s = getStream(id); for (Map.Entry<Operator.OutputPort<?>, Operator.InputPort<?>> pair : streamLinks.get(id).entries()) { if (s.getSource() == null) { Operator.OutputPort<?> outputPort = pair.getKey(); while (outputPort instanceof ProxyOutputPort) { outputPort = ((ProxyOutputPort<?>)outputPort).get(); } s.setSource(outputPort); } Operator.InputPort<?> inputPort = pair.getValue(); while (inputPort instanceof ProxyInputPort) { inputPort = ((ProxyInputPort<?>)inputPort).get(); } s.addSink(inputPort); } } }
Source:
public Long getContentLength() { try { if (Files.isSymbolicLink(file) && Files.notExists(file)) { return 0L; } return Files.size(file); } catch (IOException e) { throw new RuntimeException(e); } }

Target:
public Long getContentLength() { try { if (Files.isSymbolicLink(file) && Files.notExists(file)) { return null; } return Files.size(file); } catch (IOException e) { throw new RuntimeException(e); } }
Source:
protected StringWriter doInBackground(java.lang.Object... params) { if (params.length != 2) throw new IllegalArgumentException("The parameters to " + TextLoadAsyncTask.class.getName() + " must be (1) the file location and (2) the text view to update"); final String location = (String) params[0]; mTextView = (TextView) params[1]; FileInputStream inputStream = null; Scanner sc = null; StringWriter source = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(source); try { inputStream = new FileInputStream(location); sc = new Scanner(inputStream); while (sc.hasNextLine()) { bufferedWriter.append(sc.nextLine()); if (sc.hasNextLine()) bufferedWriter.append("\n"); } bufferedWriter.close(); IOException exc = sc.ioException(); if (exc != null) throw exc; } catch (IOException e) { finish(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { finish(); } } if (sc != null) { sc.close(); } } return source; }

Target:
protected StringWriter doInBackground(java.lang.Object... params) { if (params.length != 1) { throw new IllegalArgumentException("The parameter to " + TextLoadAsyncTask.class.getName() + " must be (1) the file location"); } final String location = (String) params[0]; FileInputStream inputStream = null; Scanner sc = null; StringWriter source = new StringWriter(); BufferedWriter bufferedWriter = new BufferedWriter(source); try { inputStream = new FileInputStream(location); sc = new Scanner(inputStream); while (sc.hasNextLine()) { bufferedWriter.append(sc.nextLine()); if (sc.hasNextLine()) bufferedWriter.append("\n"); } bufferedWriter.close(); IOException exc = sc.ioException(); if (exc != null) throw exc; } catch (IOException e) { Log_OC.e(TAG, e.getMessage(), e); finish(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { Log_OC.e(TAG, e.getMessage(), e); finish(); } } if (sc != null) { sc.close(); } } return source; }
Source:
public double variance() { return ( (entries > 1) ? newS /(entries - 1) : 0.0 ); }

Target:
public double variance() { return mean2 / (entries - 1.0d); }
Source:
private void updatePatternPathRouter() throws WebSocketEndpointAnnotationException { endpointPatternPathRouter = PatternPathRouter.create(); for (Map.Entry entry : webSocketEndpointMap.entrySet()) { Object endpoint = entry.getValue(); endpointPatternPathRouter.add(new EndpointDispatcher().getUri(endpoint), endpoint); } }

Target:
private void updatePatternPathRouter() { endpointPatternPathRouter = PatternPathRouter.create(); webSocketEndpointMap.entrySet().forEach( entry -> endpointPatternPathRouter.add(entry.getKey(), entry.getValue()) ); }
Source:
protected void postStart() { List<PrioritizedMethod> methods = new ArrayList<>(componentLookup.size()); for (Component c : componentLookup.values()) { if (c != null) Collections.addAll(methods, c.postStartMethods); } invokePrioritizedMethods(methods); }

Target:
protected void postStart() { List<PrioritizedMethod> methods = new ArrayList<>(componentLookup.size()); for (Component c : componentLookup.values()) { Collections.addAll(methods, c.postStartMethods); } invokePrioritizedMethods(methods); }