auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { if (debugEnabled) { log.debug("Event received from the topic of " + jmsDestination.getTopicName()); } handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } } catch (JMSException | ArtifactSynchronizerException e) { log.error("JMSException occurred when processing the received message ", e); } }

Target:
public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { if (debugEnabled) { log.debug("Event received from the topic of " + jmsDestination.getTopicName()); } handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } } catch (JMSException e) { log.error("JMSException occurred when processing the received message ", e); } }
Source:
private static String key() { return "key-" + ThreadLocalRandom.current().nextLong(recordCount); }

Target:
private static String key() { return "key-" + String.format("%19d", ThreadLocalRandom.current().nextLong(recordCount)); }
Source:
private CategoryProviderFactory() { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(POINT_ID); for (IConfigurationElement element : point.getConfigurationElements()) { String name = element.getAttribute("name"); String uri = element.getAttribute("uri"); Class<? extends ICategoryFilter> categoryFilterClass = getCategoryFilterClass(element); Class<? extends IPropertySetViewer> propertySetViewerClass = getPropertySetViewerClass(element); knownDescriptors.add(new CategoryDescriptor(name, uri, categoryFilterClass, propertySetViewerClass)); } }

Target:
private CategoryProviderFactory() { IExtensionPoint point = Platform.getExtensionRegistry().getExtensionPoint(POINT_ID); for (IConfigurationElement element : point.getConfigurationElements()) { String name = element.getAttribute("name"); if(name == null){ WebUiPlugin.getDefault().logError("Attribute \"name\" should be defined in extension point " + element.getNamespaceIdentifier()); } String uri = element.getAttribute("uri"); if(uri == null){ WebUiPlugin.getDefault().logError("Attribute \"uri\" should be defined in extension point " + element.getNamespaceIdentifier()); } Class<? extends IPropertySetViewer> propertySetViewerClass = getPropertySetViewerClass(element); if(propertySetViewerClass == null){ WebUiPlugin.getDefault().logError("Attribute \"property-set-viewer-class\" should be defined in extension point " + element.getNamespaceIdentifier()); } Class<? extends ICategoryFilter> categoryFilterClass = getCategoryFilterClass(element); if(name != null && uri != null && propertySetViewerClass != null){ knownDescriptors.add(new CategoryDescriptor(name, uri, categoryFilterClass, propertySetViewerClass)); } } }
Source:
private Path getWorkingDir(String workingDir){ if(workingDir!= null){ return Paths.get("file://"+workingDir); } else{ return null; } }

Target:
private Path getWorkingDir(String workingDir){ if(workingDir!= null){ return Paths.get("file://"+workingDir); } return null; }
Source:
public void schedule(ServiceExecution serviceExecution) throws ServiceExecutionSchedulerException { if (serviceExecution == null) throw new ServiceExecutionSchedulerException("Could not schedule service execution: ServiceExecution is null"); if (serviceExecution.getService() == null) throw new ServiceExecutionSchedulerException("Could not schedule service execution: No IService defined in ServiceExecution"); if (serviceExecution.getTrigger() == null) throw new ServiceExecutionSchedulerException("Could not schedule service execution: No Trigger defined in ServiceExecution"); log.debug("Scheduling new Service Execution for service [" + serviceExecution.getService().getClass().getName() + "]"); try { JobDetail jobDetail = new JobDetailBuilder().withExecutionService(executionService).withServiceExecution(serviceExecution) .withServiceExecutionCallback(serviceExecutionCallback).build(); Trigger trigger = new TriggerBuilder().usingTrigger(serviceExecution.getTrigger()).build(); quartzScheduler.scheduleJob(jobDetail, trigger); scheduledJobs.put(serviceExecution, jobDetail.getKey()); } catch (SchedulerException e) { log.error("Could not schedule service execution: ", e); throw new ServiceExecutionSchedulerException(e); } log.info("Service Execution scheduled for service [" + serviceExecution.getService().getClass().getName() + "]"); }

Target:
public void schedule(ServiceExecution serviceExecution) throws ServiceExecutionSchedulerException { if (serviceExecution == null) throw new IllegalArgumentException("Could not schedule service execution: ServiceExecution is null"); log.debug("Scheduling new Service Execution for service [" + serviceExecution.getService().getClass().getName() + "]"); try { JobDetail jobDetail = new JobDetailBuilder().withExecutionService(executionService).withServiceExecution(serviceExecution) .withServiceExecutionCallback(serviceExecutionCallback).build(); Trigger trigger = new TriggerBuilder().usingTrigger(serviceExecution.getTrigger()).build(); quartzScheduler.scheduleJob(jobDetail, trigger); scheduledJobs.put(serviceExecution, jobDetail.getKey()); } catch (SchedulerException e) { log.error("Could not schedule service execution: ", e); throw new ServiceExecutionSchedulerException(e); } log.info("Service Execution scheduled for service [" + serviceExecution.getService().getClass().getName() + "]"); }
Source:
public IVdsAsyncCommand RemoveAsyncRunningCommand(Guid vmId) { IVdsAsyncCommand command = null; if (_asyncRunningCommands.containsKey(vmId)) { command = _asyncRunningCommands.remove(vmId); } return command; }

Target:
public IVdsAsyncCommand RemoveAsyncRunningCommand(Guid vmId) { return _asyncRunningCommands.remove(vmId); }
Source:
private static void assertAllParentShardsAreClosed(Set<String> inconsistentShardIds) throws KinesisClientLibIOException { if (!inconsistentShardIds.isEmpty()) { String ids = ""; for (String id : inconsistentShardIds) { ids += " " + id; } throw new KinesisClientLibIOException(String.valueOf(inconsistentShardIds.size()) + " open child shards (" + ids + ") are inconsistent." + "This can happen due to a race condition between describeStream and a reshard operation."); } }

Target:
private static void assertAllParentShardsAreClosed(Set<String> inconsistentShardIds) throws KinesisClientLibIOException { if (!inconsistentShardIds.isEmpty()) { String ids = StringUtils.join(inconsistentShardIds, ' '); throw new KinesisClientLibIOException(String.format("%d open child shards (%s) are inconsistent. " + "This can happen due to a race condition between describeStream and a reshard operation.", inconsistentShardIds.size(), ids)); } }
Source:
public void tryEnableCancelPolicyShouldInvokeMethodOnExecutor() { ScheduledThreadPoolExecutor executor = spy(new ScheduledThreadPoolExecutor(1)); boolean result = NewThreadWorker.tryEnableCancelPolicy(executor); assertTrue(result); verify(executor).setRemoveOnCancelPolicy(true); verifyNoMoreInteractions(executor); }

Target:
public void tryEnableCancelPolicyShouldInvokeMethodOnExecutor() { ScheduledExecutorServiceWithSetRemoveOnCancelPolicy executor = mock(ScheduledExecutorServiceWithSetRemoveOnCancelPolicy.class); boolean result = NewThreadWorker.tryEnableCancelPolicy(executor); assertTrue(result); verify(executor).setRemoveOnCancelPolicy(true); verifyNoMoreInteractions(executor); }
Source:
public FontManager getFontManager() { return this.getFontManager(); }

Target:
public FontManager getFontManager() { return this.mEngine.getFontManager(); }
Source:
protected Object process(Object inputData) { long detectedObjectCount; if (inputData instanceof Object[]) { Object[] arguments = (Object[]) inputData; if (arguments.length == 2) { if (arguments[0] instanceof String && arguments[1] instanceof String) { String imageHex = (String) arguments[0]; String cascadeFilePath = (String) arguments[1]; detectedObjectCount = this.detectObjects(imageHex, cascadeFilePath); } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade " + "path is expected."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path " + "is expected."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path is " + "expected."); } return detectedObjectCount; }

Target:
protected Object process(Object inputData) { long detectedObjectCount; if (inputData instanceof Object[]) { Object[] arguments = (Object[]) inputData; if (arguments.length == 2) { if (arguments[0] instanceof String && arguments[1] instanceof String) { String imageHex = (String) arguments[0]; String cascadeFilePath = (String) arguments[1]; detectedObjectCount = this.detectObjects(imageHex, cascadeFilePath); } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade " + "path is expected. The received arguments are not String objects."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path " + "is expected. Did not receive 2 arguments."); } } else { throw new IllegalArgumentException( "2 String arguments of the hex string of the image and the cascade path is " + "expected. But received a non-object array."); } return detectedObjectCount; }
Source:
public OMElement serialize(OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); if (name != null && !"".equals(name)) { endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, getName())); } OMElement loadbalance = fac.createOMElement("loadbalance", synNS); loadbalance.addAttribute(fac.createOMAttribute("algorithm", nullNS, algorithmClassName)); if (isBuildMessage()) { loadbalance.addAttribute(fac.createOMAttribute("buildMessage", nullNS, Boolean.toString(true))); } if (sessionType != null) { OMElement session = fac.createOMElement("session", synNS); session.addAttribute(fac.createOMAttribute( "type", nullNS, sessionType)); OMElement sessionTimeout = fac.createOMElement("sessionTimeout", synNS); sessionTimeout.setText(String.valueOf(getSessionTimeout())); session.addChild(sessionTimeout); endpoint.addChild(session); } if (properties != null && properties.length() != 0) { String[] props = properties.split("::"); for (String s : props) { String[] elements = s.split(","); OMElement property = fac.createOMElement("property", synNS); property.addAttribute(fac.createOMAttribute("name", nullNS, elements[0])); property.addAttribute(fac.createOMAttribute("value", nullNS, elements[1])); property.addAttribute(fac.createOMAttribute("scope", nullNS, elements[2])); endpoint.addChild(property); } } endpoint.addChild(loadbalance); serializeChildren(loadbalance, getList()); if (parent != null) { parent.addChild(endpoint); } return endpoint; }

Target:
public OMElement serialize(OMElement parent) { OMElement endpoint = fac.createOMElement("endpoint", synNS); if (name != null && !"".equals(name)) { endpoint.addAttribute(fac.createOMAttribute( "name", nullNS, getName())); } OMElement loadbalance = fac.createOMElement("loadbalance", synNS); loadbalance.addAttribute(fac.createOMAttribute("algorithm", nullNS, algorithmClassName)); if (buildMessage) { loadbalance.addAttribute(fac.createOMAttribute("buildMessage", nullNS, Boolean.toString(true))); } if (sessionType != null) { OMElement session = fac.createOMElement("session", synNS); session.addAttribute(fac.createOMAttribute( "type", nullNS, sessionType)); OMElement sessionTimeout = fac.createOMElement("sessionTimeout", synNS); sessionTimeout.setText(String.valueOf(getSessionTimeout())); session.addChild(sessionTimeout); endpoint.addChild(session); } if (properties != null && properties.length() != 0) { String[] props = properties.split("::"); for (String s : props) { String[] elements = s.split(","); OMElement property = fac.createOMElement("property", synNS); property.addAttribute(fac.createOMAttribute("name", nullNS, elements[0])); property.addAttribute(fac.createOMAttribute("value", nullNS, elements[1])); property.addAttribute(fac.createOMAttribute("scope", nullNS, elements[2])); endpoint.addChild(property); } } endpoint.addChild(loadbalance); serializeChildren(loadbalance, getList()); if (parent != null) { parent.addChild(endpoint); } return endpoint; }
Source:
public boolean include(T object) { boolean include = false; for (Filter<T> f : filters) { if (!f.include(object)) { if (f.toString().contains("IncludeRegExpPaths") && include) { continue; } return false; } include = true; } return true; }

Target:
public boolean include(T object) { if (filters.isEmpty()) { return true; } for (Filter<T> filter : filters) { if (!filter.include(object)) { return false; } } return true; }
Source:
public void testPrefixWithoutTrailingSlash() throws Exception { writeTrashFile("baz", "a file"); writeTrashFile("foo/bar", "another file"); git.add().addFilepattern("baz").call(); git.add().addFilepattern("foo").call(); git.commit().setMessage("sample commit").call(); final byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=my- --format=zip master", db); String[] expect = { "my-baz", "my-foo/bar" }; String[] actual = listZipEntries(result); Arrays.sort(expect); Arrays.sort(actual); assertArrayEquals(expect, actual); }

Target:
public void testPrefixWithoutTrailingSlash() throws Exception { commitBazAndFooSlashBar(); byte[] result = CLIGitCommand.rawExecute( "git archive --prefix=my- --format=zip master", db); String[] expect = { "my-baz", "my-foo/bar" }; String[] actual = listZipEntries(result); Arrays.sort(expect); Arrays.sort(actual); assertArrayEquals(expect, actual); }
Source:
public JournalContext createJournalContext() throws UnavailableException { LockResource sharedLockResource; try { sharedLockResource = mMasterContext.getStateLockManager().lockShared(); } catch (InterruptedException e) { throw new UnavailableException("Failed to acquire state-lock in shared mode."); } return new StateChangeJournalContext(mJournal.createJournalContext(), sharedLockResource); }

Target:
public JournalContext createJournalContext() throws UnavailableException { LockResource sharedLockResource; try { sharedLockResource = mMasterContext.getStateLockManager().lockShared(); } catch (InterruptedException e) { throw new UnavailableException( "Failed to acquire state-lock due to ongoing backup activity."); } return new StateChangeJournalContext(mJournal.createJournalContext(), sharedLockResource); }
Source:
private static Map<ProgramInterface, List<String>> processAdditionalArguments(final List<String> arguments) { final Map<ProgramInterface, List<String>> map = new HashMap<>(); final Pattern pattern = Pattern.compile("(?<program>.*)::(?<argumentAndValue>.+?)( +(?<optionalValue>.+))?"); for (String str : arguments) { final Matcher matcher = pattern.matcher(str); if (!matcher.matches()) { throw new IllegalArgumentException("couldn't understand EXTRA_ARGUMENT " + str + " it doesn't conform to the regular expression given by " + pattern.pattern()); } final String programName = matcher.group("program"); final ProgramInterface program; try { program = Program.valueOf(programName); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Couldn't find program with value " + programName, e); } final String argumentAndValue = matcher.group("argumentAndValue"); map.computeIfAbsent(program, (k)->new ArrayList<>()).add(argumentAndValue); final String optionalValue = matcher.group("optionalValue"); if (optionalValue!=null && !optionalValue.equals("")) { map.get(program).add(optionalValue); } } return map; }

Target:
private static Map<ProgramInterface, List<String>> processAdditionalArguments(final List<String> arguments) { final Map<ProgramInterface, List<String>> map = new HashMap<>(); final Pattern pattern = Pattern.compile("(?<program>.*)::(?<argumentAndValue>.+?)( +(?<optionalValue>.+))?"); for (String str : arguments) { final Matcher matcher = pattern.matcher(str); if (!matcher.matches()) { throw new CommandLineException("couldn't understand EXTRA_ARGUMENT " + str + " it doesn't conform to the form '<PROGRAM>::<ARGUMENT_AND_VALUE>'."); } final String programName = matcher.group("program"); final ProgramInterface program; try { program = Program.valueOf(programName); } catch (IllegalArgumentException e) { throw new CommandLineException("Couldn't find program with value " + programName, e); } final String argumentAndValue = matcher.group("argumentAndValue"); map.computeIfAbsent(program, (k) -> new ArrayList<>()).add(argumentAndValue); final String optionalValue = matcher.group("optionalValue"); if (!StringUtils.isEmpty(optionalValue)) { map.get(program).add(optionalValue); } } return map; }
Source:
public LocalityManager(Config config, MetricsRegistry metricsRegistry, Serde<String> keySerde, Serde<String> valueSerde) { this.config = config; MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); this.metadataStore = metadataStoreFactory.getMetadataStore(SetContainerHostMapping.TYPE, config, metricsRegistry); this.keySerde = keySerde; this.valueSerde = valueSerde; this.taskAssignmentManager = new TaskAssignmentManager(config, metricsRegistry, keySerde, valueSerde); }

Target:
LocalityManager(Config config, MetricsRegistry metricsRegistry, Serde<String> keySerde, Serde<String> valueSerde) { this.config = config; MetadataStoreFactory metadataStoreFactory = Util.getObj(new JobConfig(config).getMetadataStoreFactory(), MetadataStoreFactory.class); this.metadataStore = metadataStoreFactory.getMetadataStore(SetContainerHostMapping.TYPE, config, metricsRegistry); this.metadataStore.init(config, metricsRegistry); this.keySerde = keySerde; this.valueSerde = valueSerde; this.taskAssignmentManager = new TaskAssignmentManager(config, metricsRegistry, keySerde, valueSerde); }
Source:
public static Optional<List<Symbol>> pruneInputs(Collection<Symbol> availableInputs, Collection<Expression> expressions) { List<Symbol> prunedInputs = availableInputs.stream() .filter(DependencyExtractor.extractUnique(expressions)::contains) .collect(toImmutableList()); if (prunedInputs.size() == availableInputs.size()) { return Optional.empty(); } return Optional.of(prunedInputs); }

Target:
public static Optional<List<Symbol>> pruneInputs(Collection<Symbol> availableInputs, Collection<Expression> expressions) { Set<Symbol> available = new HashSet<>(availableInputs); Set<Symbol> required = SymbolsExtractor.extractUnique(expressions); Set<Symbol> used = Sets.intersection(required, available); if (used.size() == available.size()) { return Optional.empty(); } return Optional.of(ImmutableList.copyOf(used)); }
Source:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new JcloudsMachineNamer(getAllConfigBag()); } }

Target:
private CloudMachineNamer getCloudMachineNamer(ConfigBag config) { String namerClass = config.get(LocationConfigKeys.CLOUD_MACHINE_NAMER_CLASS); if (namerClass != null) { try { return (CloudMachineNamer) getManagementContext().getCatalog().getRootClassLoader().loadClass(namerClass) .getDeclaredConstructor(ConfigBag.class).newInstance(config); } catch (Exception e) { throw Exceptions.propagate(e); } } else { return new JcloudsMachineNamer(config); } }
Source:
private void UpdateOptionsNonLocalFS() { if (hosts == null || allHosts == null || (getEntity().supportsGlusterService() && isAnyHostUpInCluster == null)) { return; } UICommand addHostAction = new UICommand("AddHost", this); if (hosts.size() > 1) { hosts.remove(0); } if (hosts.isEmpty()) { addHostAction.setTitle(ClusterConfigureHostsAction); getCompulsoryActions().add(addHostAction); } else if (!getEntity().supportsGlusterService() || isAnyHostUpInCluster) { addHostAction.setTitle(ClusterAddAnotherHostAction); getOptionalActions().add(addHostAction); } if (getEntity().getStoragePoolId() == null) { addHostAction.getExecuteProhibitionReasons().add(ConstantsManager.getInstance() .getConstants() .theClusterIsntAttachedToADcClusterGuide()); addHostAction.setIsExecutionAllowed(false); return; } ArrayList<VDS> availableHosts = new ArrayList<VDS>(); for (VDS vds : allHosts) { if (!getEntity().getId().equals(vds.getVdsGroupId()) && (vds.getStatus() == VDSStatus.Maintenance || vds.getStatus() == VDSStatus.PendingApproval) && vds.getSupportedClusterVersionsSet().contains(getEntity().getcompatibility_version())) { availableHosts.add(vds); } } UICommand selectHostAction = new UICommand("SelectHost", this); if (availableHosts.size() > 0) { if (hosts.isEmpty()) { selectHostAction.setTitle(SelectHostsAction); getCompulsoryActions().add(selectHostAction); } else if (!getEntity().supportsGlusterService() || isAnyHostUpInCluster) { selectHostAction.setTitle(SelectHostsAction); getOptionalActions().add(selectHostAction); } } StopProgress(); }

Target:
private void UpdateOptionsNonLocalFS() { if (hosts == null || allHosts == null || !isUpHostCheckCompleted()) { return; } if (getEntity() == null) { StopProgress(); setWindow(null); return; } UICommand addHostAction = new UICommand("AddHost", this); if (hosts.size() > 1) { hosts.remove(0); } if (hosts.isEmpty()) { addHostAction.setTitle(ClusterConfigureHostsAction); getCompulsoryActions().add(addHostAction); } else if (isAnyUpHostInCluster()) { addHostAction.setTitle(ClusterAddAnotherHostAction); getOptionalActions().add(addHostAction); } if (getEntity().getStoragePoolId() == null) { addHostAction.getExecuteProhibitionReasons().add(ConstantsManager.getInstance() .getConstants() .theClusterIsntAttachedToADcClusterGuide()); addHostAction.setIsExecutionAllowed(false); return; } ArrayList<VDS> availableHosts = new ArrayList<VDS>(); for (VDS vds : allHosts) { if (!getEntity().getId().equals(vds.getVdsGroupId()) && (vds.getStatus() == VDSStatus.Maintenance || vds.getStatus() == VDSStatus.PendingApproval) && vds.getSupportedClusterVersionsSet().contains(getEntity().getcompatibility_version())) { availableHosts.add(vds); } } UICommand selectHostAction = new UICommand("SelectHost", this); if (availableHosts.size() > 0) { if (hosts.isEmpty()) { selectHostAction.setTitle(SelectHostsAction); getCompulsoryActions().add(selectHostAction); } else if (isAnyUpHostInCluster()) { selectHostAction.setTitle(SelectHostsAction); getOptionalActions().add(selectHostAction); } } StopProgress(); }
Source:
public FileObject resolveFile(Session session, String dataspace, String pathname) throws FileSystemException, NotConnectedRestException, PermissionRestException { try { return USER.equalsIgnoreCase(dataspace) | SchedulerConstants.USERSPACE_NAME.toString().equalsIgnoreCase(dataspace) ? fileSystem(session).resolveFileInUserspace(pathname) : fileSystem( session).resolveFileInGlobalspace(pathname); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } }

Target:
public FileObject resolveFile(Session session, String dataspace, String pathname) throws FileSystemException, NotConnectedRestException, PermissionRestException { try { return USER.equalsIgnoreCase(dataspace) || SchedulerConstants.USERSPACE_NAME.toString().equalsIgnoreCase(dataspace) ? fileSystem(session).resolveFileInUserspace(pathname) : fileSystem( session).resolveFileInGlobalspace(pathname); } catch (NotConnectedException e) { throw new NotConnectedRestException(e); } catch (PermissionException e) { throw new PermissionRestException(e); } }
Source:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); for (Guid storageId : imageToDestinationDomainMap.values()) { permissionList.add(new PermissionSubject(storageId, VdcObjectType.Storage, getActionType().getActionGroup())); } permissionList.add(new PermissionSubject(getParameters().getSourceDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; }

Target:
public List<PermissionSubject> getPermissionCheckSubjects() { List<PermissionSubject> permissionList = super.getPermissionCheckSubjects(); permissionList.addAll(getStoragePermissionCheckSubjects()); permissionList.add(new PermissionSubject(getParameters().getSourceDomainId(), VdcObjectType.Storage, getActionType().getActionGroup())); if (getVm() != null && !StringUtils.isEmpty(getVm().getCustomProperties())) { permissionList.add(new PermissionSubject(getClusterId(), VdcObjectType.Cluster, ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES)); } return permissionList; }
Source:
public ItemWriter<Integer> itemWriter() { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultChannel(requests()); ChunkMessageChannelItemWriter<Integer> chunkMessageChannelItemWriter = new ChunkMessageChannelItemWriter<>(); chunkMessageChannelItemWriter.setMessagingOperations(messagingTemplate); chunkMessageChannelItemWriter.setReplyChannel(replies()); return chunkMessageChannelItemWriter; }

Target:
public ChunkMessageChannelItemWriter<Integer> itemWriter() { MessagingTemplate messagingTemplate = new MessagingTemplate(); messagingTemplate.setDefaultChannel(requests()); ChunkMessageChannelItemWriter<Integer> chunkMessageChannelItemWriter = new ChunkMessageChannelItemWriter<>(); chunkMessageChannelItemWriter.setMessagingOperations(messagingTemplate); chunkMessageChannelItemWriter.setReplyChannel(replies()); return chunkMessageChannelItemWriter; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mImage = new ImageView(this); setContentView(mImage); Bundle extras = getIntent().getExtras(); int orientation = ActivityInfo.SCREEN_ORIENTATION_USER; if (extras.getBoolean(POSTER)) { orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT; } else { orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE; } setRequestedOrientation(orientation); String imagePath = getIntent().getExtras().getString(PATH); ImageProvider.getInstance(this).loadImage(mImage, imagePath, false); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fullscreen_image_activity); mImage = (ImageView) findViewById(android.R.id.icon); String imagePath = getIntent().getExtras().getString(PATH); mImage.setImageBitmap(ImageProvider.getInstance(this).getImage(imagePath, false)); }
Source:
private void discoverArtifacts(Map<File, ArtifactResult> files, List<DependencyNode> nodes, String parent, List<RemoteRepository> remoteRepositories) throws MojoExecutionException { for (DependencyNode node : nodes) { if (!scopes.contains(node.getDependency() .getScope())) { continue; } List<RemoteRepository> copyOfRepositories = new ArrayList<>(remoteRepositories); copyOfRepositories.addAll(node.getRepositories()); try { ArtifactResult resolvedArtifact = postProcessor.postProcessResult(system.resolveArtifact(session, new ArtifactRequest(node.getArtifact(), copyOfRepositories, parent))); logger.debug("Located file: for artifact {}", resolvedArtifact.getArtifact() .getFile(), resolvedArtifact); files.put(resolvedArtifact.getArtifact() .getFile(), resolvedArtifact); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve the dependency " + node.getArtifact() .toString(), e); } if (includeTransitive) { discoverArtifacts(files, node.getChildren(), node.getRequestContext(), copyOfRepositories); } else { logger.debug("Ignoring transitive dependencies of {}", node.getDependency()); } } }

Target:
private void discoverArtifacts(Map<File, ArtifactResult> files, List<DependencyNode> nodes, String parent, List<RemoteRepository> remoteRepositories) throws MojoExecutionException { for (DependencyNode node : nodes) { if (!scopes.contains(node.getDependency() .getScope())) { continue; } List<RemoteRepository> combinedRepositories = new ArrayList<>(remoteRepositories); combinedRepositories.addAll(node.getRepositories()); try { ArtifactResult resolvedArtifact = postProcessor.postProcessResult(system.resolveArtifact(session, new ArtifactRequest(node.getArtifact(), combinedRepositories, parent))); logger.debug("Located file: for artifact {}", resolvedArtifact.getArtifact() .getFile(), resolvedArtifact); files.put(resolvedArtifact.getArtifact() .getFile(), resolvedArtifact); } catch (ArtifactResolutionException e) { throw new MojoExecutionException("Failed to resolve the dependency " + node.getArtifact() .toString(), e); } if (includeTransitive) { discoverArtifacts(files, node.getChildren(), node.getRequestContext(), combinedRepositories); } else { logger.debug("Ignoring transitive dependencies of {}", node.getDependency()); } } }
Source:
public void setUp() throws Exception { super.setUp(); FakeCheck.reset(); FakeCheck.setReady(true); FileUtils.copyDirectory(getResourceFile("templates/jboss"), new File(nuxeoHome, "templates")); bundles = new File(nuxeoHome, "nxserver/bundles"); bundles.mkdirs(); FileUtils.copyFileToDirectory(getResourceFile("versioned-1.0.jar"), bundles); configGenerator = new ConfigurationGenerator(); bsc = new BackingServiceConfigurator(configGenerator); assertThat(configGenerator.init()).isTrue(); configGenerator.setProperty("nuxeo.home", nuxeoHome.getAbsolutePath()); configGenerator.setProperty("nuxeo.backing.check.retry.maxRetries","5"); configGenerator.setProperty("nuxeo.backing.check.retry.delayInMs","20"); }

Target:
public void setUp() throws Exception { super.setUp(); FakeCheck.reset(); FakeCheck.setReady(true); FileUtils.copyDirectory(getResourceFile("templates/jboss"), new File(nuxeoHome, "templates")); bundles = new File(nuxeoHome, "nxserver/bundles"); bundles.mkdirs(); FileUtils.copyFileToDirectory(getResourceFile("versioned-1.0.jar"), bundles); configGenerator = new ConfigurationGenerator(); bsc = new BackingServiceConfigurator(configGenerator); assertThat(configGenerator.init()).isTrue(); configGenerator.setProperty("nuxeo.home", nuxeoHome.getAbsolutePath()); configGenerator.setProperty(BackingServiceConfigurator.PARAM_RETRY_POLICY_MAX_RETRIES,"5"); configGenerator.setProperty(BackingServiceConfigurator.PARAM_RETRY_POLICY_DELAY_IN_MS,"20"); }
Source:
public void fail_assertThrowsWithCause_if_callable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; Verify.assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); }

Target:
public void fail_assertThrowsWithCause_if_callable_throws_exception_with_different_causes() { final Throwable expectedCause = new EmptyStackException(); final Throwable actualCause = new AclNotFoundException(); final RuntimeException runtimeException = new RuntimeException(actualCause); final Callable throwsRuntimeException = new Callable() { @Override public Object call() { throw runtimeException; } }; assertThrowsWithCause(runtimeException.getClass(), expectedCause.getClass(), throwsRuntimeException); }
Source:
protected void onDestroy() { if (!mIsConfigChange && (mRestartEditorOption == RestartEditorOptions.NO_RESTART)) { if (mPostEditorAnalyticsSession != null) { mPostEditorAnalyticsSession.end(); } } mDispatcher.unregister(this); if (mHandler != null) { mHandler.removeCallbacks(mSave); mHandler = null; } cancelAddMediaListThread(); removePostOpenInEditorStickyEvent(); if (mEditorFragment instanceof AztecEditorFragment) { ((AztecEditorFragment) mEditorFragment).disableContentLogOnCrashes(); } if (mReactNativeRequestHandler != null) mReactNativeRequestHandler.destroy(); super.onDestroy(); }

Target:
protected void onDestroy() { if (!mIsConfigChange && (mRestartEditorOption == RestartEditorOptions.NO_RESTART)) { if (mPostEditorAnalyticsSession != null) { mPostEditorAnalyticsSession.end(); } } mDispatcher.unregister(this); if (mHandler != null) { mHandler.removeCallbacks(mSave); mHandler = null; } mEditorMedia.cancelAddMediaToEditorActions(); removePostOpenInEditorStickyEvent(); if (mEditorFragment instanceof AztecEditorFragment) { ((AztecEditorFragment) mEditorFragment).disableContentLogOnCrashes(); } if (mReactNativeRequestHandler != null) { mReactNativeRequestHandler.destroy(); } super.onDestroy(); }
Source:
public RequestBuilder centerInside() { PicassoBitmapOptions options = getOptions(); if (options.targetWidth == 0 || options.targetHeight == 0) { throw new IllegalStateException("Center crop can only be used after calling resize."); } options.centerInside = true; return this; }

Target:
public RequestBuilder centerInside() { PicassoBitmapOptions options = getOptions(); if (options.targetWidth == 0 || options.targetHeight == 0) { throw new IllegalStateException("Center inside can only be used after calling resize."); } if (options.centerCrop) { throw new IllegalStateException("Center inside can not be used after calling centerCrop"); } options.centerInside = true; return this; }
Source:
public void updateWorkflowWithTooLongStateVariableValueReturnsBadRequest() { UpdateWorkflowInstanceRequest req = new UpdateWorkflowInstanceRequest(); req.stateVariables.put("testUpdate", repeat('a', 8001)); try (Response response = getInstanceIdResource(createResponse.id).put(req)) { assertThat(response.getStatus(), is(BAD_REQUEST.getStatusCode())); assertThat(response.readEntity(String.class), startsWith("Too long value")); } }

Target:
public void updateWorkflowWithTooLongStateVariableValueReturnsBadRequest() { UpdateWorkflowInstanceRequest req = new UpdateWorkflowInstanceRequest(); req.stateVariables.put("testUpdate", repeat('a', 8001)); try (Response response = getInstanceIdResource(createResponse.id).put(req)) { assertThat(response.getStatus(), is(BAD_REQUEST.getStatusCode())); assertThat(response.getMediaType(), is(APPLICATION_JSON_TYPE)); assertThat(response.readEntity(ErrorResponse.class).error, startsWith("Too long value")); } }
Source:
public Set<State> getAllStates() { List<State> result = Lists.newArrayList(); for (Node node : Iterables.filter(Iterables.filter(AllContents.of(getNotationDiagram()), Node.class), State.notationPredicate())) { Option<State> exec = ISequenceElementAccessor.getState(node); assert exec.some() : INTERNAL_ERROR; result.add(exec.get()); } Collections.sort(result, RangeHelper.lowerBoundOrdering().onResultOf(ISequenceEvent.VERTICAL_RANGE)); return Sets.newLinkedHashSet(result); }

Target:
public Set<State> getAllStates() { List<State> allStates = null; LinkedHashSet<State> allOrderedStates = null; if (useCache) { if (allOperandsCache != null) { allStates = Lists.newArrayList(allStatesCache); } allOrderedStates = allOrderedStatesCache; } if (allOrderedStates == null) { if (allStates == null) { allStates = Lists.newArrayList(); for (Node node : Iterables.filter(Iterables.filter(AllContents.of(getNotationDiagram()), Node.class), State.notationPredicate())) { Option<State> exec = ISequenceElementAccessor.getState(node); assert exec.some() : INTERNAL_ERROR; allStates.add(exec.get()); } if (useCache) { allStatesCache = allStates; } } Collections.sort(allStates, RangeHelper.lowerBoundOrdering().onResultOf(ISequenceEvent.VERTICAL_RANGE)); allOrderedStates = Sets.newLinkedHashSet(allStates); if (useCache) { allOrderedStatesCache = allOrderedStates; } } return allOrderedStates; }
Source:
void setEnableLogging(boolean enableLogging) { this.enableLogging = enableLogging; }

Target:
AmplitudeLog setEnableLogging(boolean enableLogging) { this.enableLogging = enableLogging; return instance; }
Source:
private void initSelectedSpiceImpl() { SpiceConsoleModel spiceModel = model.getVmConsoles().getConsoleModel(SpiceConsoleModel.class); if (spiceModel == null) { return; } spiceModel.initConsole(); spiceModel.initConsole(); }

Target:
private void initSelectedSpiceImpl() { SpiceConsoleModel spiceModel = model.getVmConsoles().getConsoleModel(SpiceConsoleModel.class); if (spiceModel == null) { return; } spiceModel.initConsole(); }
Source:
public ScriptEngineManagerImpl() { logger.info("ScriptManager loading..."); }

Target:
public ScriptEngineManagerImpl() { logger.debug("ScriptManager loading..."); }
Source:
protected Iterable<Module> setupModules() { ImmutableSet.Builder<Module> modules = ImmutableSet.builder(); modules.addAll(super.setupModules()); return modules.build(); }

Target:
protected Iterable<Module> setupModules() { ImmutableSet.Builder<Module> modules = ImmutableSet.builder(); modules.addAll(super.setupModules()); modules.add(new OneAndOneRateLimitModule()); return modules.build(); }
Source:
private static String getMessageToLog(String loggerString, AuditLog auditLog) { String message; if (loggerString.isEmpty()) { message = auditLog.toStringForLogging(); } else { message = MessageFormat.format(loggerString, auditLog.getMessage()); } return MessageFormat.format("Audit Log ID: {0}, {1}", auditLog.getAuditLogId(), message); }

Target:
private static String getMessageToLog(String loggerString, AuditLog auditLog) { String message; if (loggerString.isEmpty()) { message = auditLog.toStringForLogging(); } else { message = MessageFormat.format(loggerString, auditLog.getMessage()); } return MessageFormat.format("EVENT_ID: {0}, {1}", auditLog.getLogType().getValue(), message); }
Source:
private String extractJoin(Path.PathElement pathElement) { String relationshipName = pathElement.getFieldName(); Class<?> relationshipClass = pathElement.getFieldType(); String relationshipAlias = FilterPredicate.getTypeAlias(relationshipClass); Class<?> entityClass = pathElement.getType(); String entityAlias = FilterPredicate.getTypeAlias(entityClass); String relationshipIdField = getColumnName(relationshipClass, dictionary.getIdFieldName(relationshipClass)); String relationshipColumnName = getColumnName(entityClass, relationshipName); Subselect subselectAnnotation = dictionary.getAnnotation(relationshipClass, Subselect.class); if (subselectAnnotation == null) { Table tableAnnotation = dictionary.getAnnotation(relationshipClass, Table.class); String relationshipTableName = (tableAnnotation == null) ? dictionary.getJsonAliasFor(relationshipClass) : tableAnnotation.name(); return String.format("LEFT JOIN %s AS %s ON %s.%s = %s.%s", relationshipTableName, relationshipAlias, entityAlias, relationshipColumnName, relationshipAlias, relationshipIdField); } else { return String.format("LEFT JOIN (%s) AS %s ON %s.%s = %s.%s", subselectAnnotation.value(), relationshipAlias, entityAlias, relationshipColumnName, relationshipAlias, relationshipIdField); } }

Target:
private String extractJoin(Path.PathElement pathElement) { Class<?> entityClass = pathElement.getType(); String entityAlias = FilterPredicate.getTypeAlias(entityClass); Class<?> relationshipClass = pathElement.getFieldType(); String relationshipAlias = FilterPredicate.getTypeAlias(relationshipClass); String relationshipName = pathElement.getFieldName(); String relationshipIdField = getColumnName(relationshipClass, dictionary.getIdFieldName(relationshipClass)); String relationshipColumnName = getColumnName(entityClass, relationshipName); return String.format("LEFT JOIN %s AS %s ON %s.%s = %s.%s", SQLSchema.getTableOrSubselect(dictionary, relationshipClass), relationshipAlias, entityAlias, relationshipColumnName, relationshipAlias, relationshipIdField); }
Source:
public PreparedQuery prepareQuery(Session session, String query, WarningCollector warningCollector) throws ParsingException, PrestoException, SemanticException { Statement wrappedStatement = sqlParser.createStatement(query, createParsingOptions(session, warningCollector)); if (SystemSessionProperties.getWarningHandlingLevel(session) == WarningHandlingLevel.AS_ERROR) { throw new PrestoException(WARNING_AS_ERROR, format("Warning handling level set to AS_ERROR. Warnings: %n %s", warningCollector.getWarnings().stream() .map(PrestoWarning::getMessage) .collect(joining(System.lineSeparator())))); } return prepareQuery(session, wrappedStatement, warningCollector); }

Target:
public PreparedQuery prepareQuery(Session session, String query, WarningCollector warningCollector) throws ParsingException, PrestoException, SemanticException { Statement wrappedStatement = sqlParser.createStatement(query, createParsingOptions(session, warningCollector)); if (warningCollector.hasWarnings() && getWarningHandlingLevel(session) == AS_ERROR) { throw new PrestoException(WARNING_AS_ERROR, format("Warning handling level set to AS_ERROR. Warnings: %n %s", warningCollector.getWarnings().stream() .map(PrestoWarning::getMessage) .collect(joining(System.lineSeparator())))); } return prepareQuery(session, wrappedStatement, warningCollector); }
Source:
public void notAddsInvalidHeadersToResponse() throws IOException { final Iterable<String> head = new RsWithHeader( new RsWithHeader(new RsEmpty(), "host:", "c.example.com"), "Host MY", "d.example.com" ).head(); for (final String header: head) { Assert.assertNotNull(header, "header contains null elements"); } }

Target:
public void notAddsInvalidHeadersToResponse() throws IOException { new RsWithHeader( new RsWithHeader(new RsEmpty(), "host:", "c.example.com"), "Host MY", "d.example.com" ).head(); }
Source:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("equals".equals(method.getName())) { try { Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null; return equals(otherHandler); } catch (IllegalArgumentException e) { return false; } } else if ("hashCode".equals(method.getName())) { return hashCode(); } else if ("toString".equals(method.getName())) { return toString(); } try { return dispatch.get(method).invoke(args); } catch (Throwable th) { Throwable cause = th.getCause(); if (th instanceof RetryableException && cause != null) { throw cause; } throw th; } }

Target:
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if ("equals".equals(method.getName())) { try { Object otherHandler = args.length > 0 && args[0] != null ? Proxy.getInvocationHandler(args[0]) : null; return equals(otherHandler); } catch (IllegalArgumentException e) { return false; } } else if ("hashCode".equals(method.getName())) { return hashCode(); } else if ("toString".equals(method.getName())) { return toString(); } return dispatch.get(method).invoke(args); }
Source:
public void testLevelForBin() { SRAIndex index = getIndex(DEFAULT_ACCESSION); Bin bin = new Bin(0, SRA_BIN_OFFSET); Assert.assertEquals(index.getLevelForBin(bin), LAST_BIN_LEVEL); }

Target:
public void testLevelForBin() { final SRAIndex index = getIndex(DEFAULT_ACCESSION); final Bin bin = new Bin(0, SRA_BIN_OFFSET); Assert.assertEquals(index.getLevelForBin(bin), LAST_BIN_LEVEL); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.notifications: NotificationActivity.startYourself(this, "read/unread"); return true; case R.id.list_sheet: if (contributionsActivityPagerAdapter.getItem(1) != null) { ((NearbyFragment)contributionsActivityPagerAdapter.getItem(1)).listOptionMenuIteClicked(); } return true; default: return super.onOptionsItemSelected(item); } }

Target:
public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.notifications: NotificationActivity.startYourself(this, "unread"); return true; case R.id.list_sheet: if (contributionsActivityPagerAdapter.getItem(1) != null) { ((NearbyFragment)contributionsActivityPagerAdapter.getItem(1)).listOptionMenuIteClicked(); } return true; default: return super.onOptionsItemSelected(item); } }
Source:
private void setDcCompatibilityLevelUpgradeNeeded(List<StoragePool> dataCenters) { Config.<Set<Version>> getValue(ConfigValues.SupportedClusterLevels) .stream() .max(Comparator.naturalOrder()) .ifPresent( maxSupportedClusterLevel -> dataCenters.forEach( dataCenter -> dataCenter.setStoragePoolCompatibilityLevelUpgradeNeeded( maxSupportedClusterLevel.compareTo(dataCenter.getCompatibilityVersion()) > 0))); }

Target:
private void setDcCompatibilityLevelUpgradeNeeded(List<StoragePool> dataCenters) { Config.<Set<Version>> getValue(ConfigValues.SupportedClusterLevels) .stream() .max(Comparator.naturalOrder()) .ifPresent(maxSupportedClusterLevel -> setDcCompatibilityLevelUpgradeNeeded(dataCenters, maxSupportedClusterLevel)); }
Source:
public void updateCredentials(String externalId, String username, String password) { InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO(); try { InternalAuth internalAuth = internalAuthDAO.findById(NumberUtils.createLong(externalId)); String passwordEncoded = EncodingUtils.md5EncodeString(password); internalAuthDAO.updateUsernameAndPassword(internalAuth, username, passwordEncoded); } catch (UnsupportedEncodingException e) { throw new SmvcRuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new SmvcRuntimeException(e); } }

Target:
public void updateCredentials(String externalId, String username, String password) { InternalAuthDAO internalAuthDAO = DAOFactory.getInstance().getInternalAuthDAO(); try { InternalAuth internalAuth = internalAuthDAO.findById(NumberUtils.createLong(externalId)); if (internalAuth == null) { throw new IllegalStateException(String.format("InternalAuth for id %s not found", externalId)); } String passwordEncoded = EncodingUtils.md5EncodeString(password); internalAuthDAO.updateUsernameAndPassword(internalAuth, username, passwordEncoded); } catch (UnsupportedEncodingException e) { throw new SmvcRuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new SmvcRuntimeException(e); } }
Source:
private void resetDefaultGame() { setGameData(null); ClientSetting.defaultGameName.resetValue(); ClientSetting.defaultGameUri.resetValue(); ClientSetting.flush(); }

Target:
private void resetDefaultGame() { setGameData(null); setDefaultGame(null, null); }