auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void changeSessionIdThenPreserveParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); String id = request.getSession().getId(); request.getSession(); request.setServletPath("/login"); request.setMethod("POST"); request.setParameter("username", "user"); request.setParameter("password", "password"); HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); CsrfToken token = repository.generateToken(request); repository.saveToken(token, request, response); request.setParameter(token.getParameterName(), token.getToken()); loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class); springSecurityFilterChain.doFilter(request, response, chain); Assert.assertNotEquals(id, request.getSession().getId()); Assert.assertEquals(request.getParameter(token.getParameterName()), token.getToken()); Assert.assertEquals(request.getParameter("username"), "user"); Assert.assertEquals(request.getParameter("password"), "password"); }

Target:
public void changeSessionIdThenPreserveParameters() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest("GET", ""); String id = request.getSession().getId(); request.getSession(); request.setServletPath("/login"); request.setMethod("POST"); request.setParameter("username", "user"); request.setParameter("password", "password"); HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository(); CsrfToken token = repository.generateToken(request); repository.saveToken(token, request, response); request.setParameter(token.getParameterName(), token.getToken()); request.getSession().setAttribute("attribute1", "value1"); loadConfig(SessionManagementDefaultSessionFixationServlet31Config.class); springSecurityFilterChain.doFilter(request, response, chain); assertThat(!request.getSession().getId().equals(id)); assertThat(request.getSession().getAttribute("attribute1").equals("value1")); }
Source:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; }

Target:
public void unsetMavenWorkspaceRepository(MavenWorkspaceRepository mavenWorkspaceRepository) { if (this.mavenWorkspaceRepository == mavenWorkspaceRepository) { this.mavenWorkspaceRepository = null; } }
Source:
private void createImageForMemoryDump() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePoolId, storageDomainId, imageGroupId, getVm().getTotalMemorySizeInBytes(), VolumeType.Preallocated, VolumeFormat.RAW, volumeId, "", getStoragePool().getcompatibility_version().toString())); if (!retVal.getSucceeded()) { throw new VdcBLLException(VdcBllErrors.VolumeCreationError, "CreateAllSnapshotsFromVmCommand::executeVmCommand: Failed to create image for memory!"); } Guid guid = createTask(retVal.getCreationInfo(), VdcActionType.CreateAllSnapshotsFromVm, VdcObjectType.Storage, getStorageDomainId().getValue()); getTaskIdList().add(guid); }

Target:
private void createImageForMemoryDump() { VDSReturnValue retVal = Backend .getInstance() .getResourceManager() .RunVdsCommand( VDSCommandType.CreateImage, new CreateImageVDSCommandParameters( storagePoolId, storageDomainId, memoryDumpImageGroupId, getVm().getTotalMemorySizeInBytes(), VolumeType.Preallocated, VolumeFormat.RAW, memoryDumpVolumeId, "", getStoragePool().getcompatibility_version().toString())); if (!retVal.getSucceeded()) { throw new VdcBLLException(VdcBllErrors.VolumeCreationError, "CreateAllSnapshotsFromVmCommand::executeVmCommand: Failed to create image for memory!"); } Guid guid = createTask(retVal.getCreationInfo(), VdcActionType.CreateAllSnapshotsFromVm, VdcObjectType.Storage, getStorageDomainId().getValue()); getTaskIdList().add(guid); }
Source:
public void onNext(final StartTime startTime) { LOG.log(Level.INFO, "StartTime: {0}", startTime); final EventHandler<AllocatedEvaluator> evalAllocHandlerForServer = getEvalAllocHandlerForServer(); final List<EventHandler<ActiveContext>> contextActiveHandlersForServer = new ArrayList<>(2); contextActiveHandlersForServer.add(getFirstContextActiveHandlerForServer()); contextActiveHandlersForServer.add(getSecondContextActiveHandlerForServer()); evaluatorManager.allocateEvaluators(initServerCount, evalAllocHandlerForServer, contextActiveHandlersForServer); final EventHandler<AllocatedEvaluator> evalAllocHandlerForWorker = getEvalAllocHandlerForWorker(); final List<EventHandler<ActiveContext>> contextActiveHandlersForWorker = new ArrayList<>(2); contextActiveHandlersForWorker.add(getFirstContextActiveHandlerForWorker()); contextActiveHandlersForWorker.add(getSecondContextActiveHandlerForWorker()); evaluatorManager.allocateEvaluators(dataLoadingService.getNumberOfPartitions(), evalAllocHandlerForWorker, contextActiveHandlersForWorker); workerEM.getNetworkSetup().registerConnectionFactory(identifierFactory.getNewInstance(driverId)); serverEM.getNetworkSetup().registerConnectionFactory(identifierFactory.getNewInstance(driverId)); psNetworkSetup.registerConnectionFactory(identifierFactory.getNewInstance(driverId)); }

Target:
public void onNext(final StartTime startTime) { LOG.log(Level.INFO, "StartTime: {0}", startTime); final EventHandler<AllocatedEvaluator> evalAllocHandlerForServer = getEvalAllocHandlerForServer(); final List<EventHandler<ActiveContext>> contextActiveHandlersForServer = new ArrayList<>(2); contextActiveHandlersForServer.add(getFirstContextActiveHandlerForServer()); contextActiveHandlersForServer.add(getSecondContextActiveHandlerForServer()); evaluatorManager.allocateEvaluators(initServerCount, evalAllocHandlerForServer, contextActiveHandlersForServer); final EventHandler<AllocatedEvaluator> evalAllocHandlerForWorker = getEvalAllocHandlerForWorker(); final List<EventHandler<ActiveContext>> contextActiveHandlersForWorker = new ArrayList<>(2); contextActiveHandlersForWorker.add(getFirstContextActiveHandlerForWorker()); contextActiveHandlersForWorker.add(getSecondContextActiveHandlerForWorker()); evaluatorManager.allocateEvaluators(dataLoadingService.getNumberOfPartitions(), evalAllocHandlerForWorker, contextActiveHandlersForWorker); final Identifier driverId = identifierFactory.getNewInstance(driverIdStr); workerEMWrapper.getNetworkSetup().registerConnectionFactory(driverId); serverEMWrapper.getNetworkSetup().registerConnectionFactory(driverId); psNetworkSetup.registerConnectionFactory(driverId); }
Source:
public Iterator<Row> getTransitiveClosureOver(Row startingPoint, Relationships.Direction direction, String... relationshipNames) { String startingCP = startingPoint.getString(Statements.CP); if (startingCP == null) { return Collections.<Row>emptyList().iterator(); } Observable<Row> closureContent = getRelationshipTables(direction) .flatMap(table -> { Statement q = select().all().from(table).where(in(Statements.NAME, Arrays.asList(relationshipNames))); return session.execute(q); }) .map(relationships -> computeTransitiveClosure(startingCP, relationships)) .flatMap(this::loadEntities); return closureContent.toBlocking().getIterator(); }

Target:
public Iterator<Row> getTransitiveClosureOver(Row startingPoint, Relationships.Direction direction, String... relationshipNames) { String startingCP = startingPoint.getString(Statements.CP); if (startingCP == null) { return Collections.<Row>emptyList().iterator(); } TransitiveClosureProcessor runner = new TransitiveClosureProcessor( cp -> getRelationshipOtherEnds(cp, direction, Arrays.asList(relationshipNames))); return runner.process(startingCP) .toList() .flatMap(listCP -> loadEntities(listCP).toList() .map(unsorted -> reorderEntities(unsorted, listCP))) .toBlocking() .first() .iterator(); }
Source:
protected SshAction<Session> newSessionAction() { return new SshAction<Session>() { private Session session = null; @Override public void clear() throws TransportException, ConnectionException { closeWhispering(session, this); session = null; } @Override public Session create() throws Exception { checkConnected(); sshClientConnection.ssh.getConnection().setMaxPacketSize(256 * 1024); session = sshClientConnection.ssh.startSession(); if (allocatePTY) { session.allocatePTY(TERM, 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap()); } return session; } @Override public String toString() { return "Session()"; } }; }

Target:
protected SshAction<Session> newSessionAction() { return new SshAction<Session>() { private Session session = null; @Override public void clear() throws TransportException, ConnectionException { closeWhispering(session, this); session = null; } @Override public Session create() throws Exception { checkConnected(); sshClientConnection.ssh.getConnection().setMaxPacketSize(maxPacketSize); session = sshClientConnection.ssh.startSession(); if (allocatePTY) { session.allocatePTY(TERM, 80, 24, 0, 0, Collections.<PTYMode, Integer> emptyMap()); } return session; } @Override public String toString() { return "Session()"; } }; }
Source:
private static URL[] getUrls(ClassLoader classLoader, boolean wasWrappedJar) { URL[] urls = getClassLoaderUrls(classLoader); if (urls != null) { if (wasWrappedJar && urls.length == 1) { try { String jarClassPath = new JarInputStream(urls[0].openStream()).getManifest().getMainAttributes().getValue("Class-Path"); String[] urlStrings = jarClassPath.split(" "); URL[] newUrls = new URL[urlStrings.length]; for (int i = 0; i < urlStrings.length; i++) { newUrls[i] = new URL(urlStrings[i]); } return newUrls; } catch (Exception e) { return null; } } } return urls; }

Target:
private static URL[] getUrls(ClassLoader classLoader, boolean wasWrappedJar) { URL[] urls = getClassLoaderUrls(classLoader); if (wasWrappedJar && urls != null && urls.length == 1) { try { String jarClassPath = new JarInputStream(urls[0].openStream()).getManifest().getMainAttributes().getValue("Class-Path"); String[] urlStrings = jarClassPath.split(" "); URL[] newUrls = new URL[urlStrings.length]; for (int i = 0; i < urlStrings.length; i++) { newUrls[i] = new URL(urlStrings[i]); } return newUrls; } catch (Exception e) { e.printStackTrace(); return null; } } return urls; }
Source:
public void updateCustomizedViews(String customizedStateType, List<CustomizedView> customizedViews) { for (CustomizedView cv : customizedViews) { if (_customizedViewCacheMap.containsKey(customizedStateType)) { _customizedViewCacheMap.get(customizedStateType).getCustomizedViewCache().setProperty(cv); } else { CustomizedViewCache customizedViewCache = new CustomizedViewCache(getClusterName(), customizedStateType); customizedViewCache.getCustomizedViewCache().setProperty(cv); _customizedViewCacheMap.put(customizedStateType, customizedViewCache); } } }

Target:
public void updateCustomizedViews(String customizedStateType, List<CustomizedView> customizedViews) { if (!_customizedViewCacheMap.containsKey(customizedStateType)) { CustomizedViewCache customizedViewCache = new CustomizedViewCache(getClusterName(), customizedStateType); _customizedViewCacheMap.put(customizedStateType, customizedViewCache); } for (CustomizedView cv : customizedViews) { _customizedViewCacheMap.get(customizedStateType).getCustomizedViewCache().setProperty(cv); } }
Source:
public int hashCode() { return 123456789; }

Target:
public int hashCode() { return System.identityHashCode( this ); }
Source:
private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Desktop: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); default: return null; } }

Target:
private static ImageResource getPoolVmImageResource(VmType vmType, boolean nextRunConfigurationExists) { switch (vmType) { case Desktop: return nextRunConfigurationExists ? resources.manyDesktopsChangesImage() : resources.manyDesktopsImage(); case Server: return nextRunConfigurationExists ? resources.manyServersChangesImage() : resources.manyServersImage(); default: log.severe("Invalid VmType."); return null; } }
Source:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); checkArgument(tableName.getSchema().isPresent(), "Cassandra does not like you when you don't have keyspace defined"); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getInternalNameInDatabase())) { queryExecutor.executeQuery(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }

Target:
public TableInstance<RelationalTableDefinition> createImmutable(RelationalTableDefinition tableDefinition, TableHandle tableHandle) { TableName tableName = createImmutableTableName(tableHandle); checkArgument(tableName.getSchema().isPresent(), "Cassandra requires table with schema"); if (!queryExecutor.tableExists(tableName.getSchema().get(), tableName.getSchemalessNameInDatabase())) { executeQueryIgnoreTypeError(tableDefinition.getCreateTableDDL(tableName.getNameInDatabase())); RelationalDataSource dataSource = tableDefinition.getDataSource(); insertData(tableName, dataSource); } return new CassandraTableInstance(tableName, tableDefinition); }
Source:
public static synchronized DoorsColumnType fromString(String value) { if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } if (rawStringToDataType.isEmpty()) { for (DoorsColumnType enumStatus : DoorsColumnType.values()) { DoorsColumnType.rawStringToDataType.put(enumStatus.columnType, enumStatus); } } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }

Target:
public static DoorsColumnType fromString(String value) { if (value.contains("Verification Criteria")) { value = "Verification Criteria"; } DoorsColumnType returnVal = rawStringToDataType.get(value); return returnVal != null ? returnVal : OTHER; }
Source:
public HaplotypeProbabilitiesFromSequence(final HaplotypeProbabilitiesFromSequence other) { this(other.getHaplotype() , other.obsAllele1,other.obsAllele2,other.obsAlleleOther); }

Target:
public HaplotypeProbabilitiesFromSequence(final HaplotypeProbabilitiesFromSequence other) { super(other); obsAllele1 = other.obsAllele1; obsAllele2 = other.obsAllele2; obsAlleleOther = other.obsAlleleOther; }
Source:
public void invalidationDoesNotProceedIfTimelockPingUnsuccessful() { when(timestampManagementService.ping()).thenThrow(EXCEPTION); TimeLockMigrator migrator = TimeLockMigrator.create(timestampManagementService, invalidator); assertThatThrownBy(migrator::migrate).isInstanceOf(AtlasDbDependencyException.class); verify(invalidator, never()).backupAndInvalidate(); }

Target:
public void invalidationDoesNotProceedIfTimelockPingUnsuccessful() { when(timestampManagementService.ping()).thenThrow(EXCEPTION); TimeLockMigrator migrator = TimeLockMigrator.create(timestampManagementService, invalidator); assertThatThrownBy(migrator::migrate).isInstanceOf(AtlasDbDependencyException.class) .hasCause(EXCEPTION); verify(timestampManagementService).ping(); verify(invalidator, never()).backupAndInvalidate(); }
Source:
protected NamedValue<?> parseNamedValueType(NamedValuePropertyType namedValueProperty) throws OwsExceptionReport { if (namedValueProperty.isSetNamedValue()) { NamedValueType namedValue = namedValueProperty.getNamedValue(); NamedValue<?> sosNamedValue = parseNamedValueValue(namedValue.getValue()); ReferenceType referenceType = (ReferenceType) CodingHelper.decodeXmlObject(namedValue.getName()); sosNamedValue.setName(referenceType); return sosNamedValue; } else if (namedValueProperty.isSetHref()) { NamedValue<?> sosNamedValue = new NamedValue<ReferenceType>(); ReferenceType referenceType = new ReferenceType(namedValueProperty.getHref()); if (namedValueProperty.isSetTitle()) { referenceType.setTitle(namedValueProperty.getTitle()); } sosNamedValue.setName(referenceType); return sosNamedValue; } else { throw new UnsupportedDecoderInputException(this, namedValueProperty); } }

Target:
protected NamedValue<?> parseNamedValueType(NamedValuePropertyType namedValueProperty) throws OwsExceptionReport { if (namedValueProperty.isSetNamedValue()) { NamedValueType namedValue = namedValueProperty.getNamedValue(); NamedValue<?> sosNamedValue = parseNamedValueValue(namedValue.getValue()); ReferenceType referenceType = (ReferenceType) CodingHelper.decodeXmlObject(namedValue.getName()); sosNamedValue.setName(referenceType); return sosNamedValue; } else if (namedValueProperty.isSetHref()) { NamedValue<ReferenceType> sosNamedValue = new NamedValue<ReferenceType>(); ReferenceType referenceType = new ReferenceType(namedValueProperty.getHref()); if (namedValueProperty.isSetTitle()) { referenceType.setTitle(namedValueProperty.getTitle()); } sosNamedValue.setName(referenceType); return sosNamedValue; } else { throw new UnsupportedDecoderInputException(this, namedValueProperty); } }
Source:
public void modified(final Map<Object, Object> config) { runtimeConfiguration = new ISYActiveBindingConfig(config); setProperlyConfigured(true); if (this.insteonClient != null) { this.insteonClient.stop(); } this.insteonClient = new InsteonClient(runtimeConfiguration.getUser(), runtimeConfiguration.getPassword(), this); Errors.addErrorListener(new ErrorHandler()); if (runtimeConfiguration.isUseUpnp()) { this.logger.info("ISY: using UPNP to communicate with ISY"); this.insteonClient.start(); } else { this.logger.info("ISY: using URL to communicate with ISY"); try { this.insteonClient.start(runtimeConfiguration.getUuid(), String.format("http://%s:%s", runtimeConfiguration.getIpAddress(), runtimeConfiguration.getPort())); } catch (Exception e) { throw new RuntimeException(e); } } }

Target:
public void modified(final Map<Object, Object> config) { runtimeConfiguration = new ISYActiveBindingConfig(config); if (this.insteonClient != null) { this.insteonClient.stop(); } this.insteonClient = new InsteonClient(runtimeConfiguration.getUser(), runtimeConfiguration.getPassword(), this); Errors.addErrorListener(new ErrorHandler()); if (runtimeConfiguration.isUseUpnp()) { this.logger.info("ISY: using UPNP to communicate with ISY"); this.insteonClient.start(); } else { this.logger.info("ISY: using URL to communicate with ISY"); try { this.insteonClient.start(runtimeConfiguration.getUuid(), String.format("http://%s:%s", runtimeConfiguration.getIpAddress(), runtimeConfiguration.getPort())); } catch (Exception e) { throw new RuntimeException(e); } } setProperlyConfigured(true); }
Source:
protected boolean isShowCrossReferenceInfo() { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean prefShowInfo = store.getBoolean(TraditionalRenderingPreferenceConstants.MEM_CROSS_REFERENCE_INFO); return (!fIsDisplayLittleEndian && prefShowInfo); }

Target:
protected boolean isShowCrossReferenceInfo() { IPreferenceStore store = TraditionalRenderingPlugin.getDefault().getPreferenceStore(); boolean prefShowInfo = store.getBoolean(TraditionalRenderingPreferenceConstants.MEM_CROSS_REFERENCE_INFO); return (!isDisplayLittleEndian() && prefShowInfo); }
Source:
private synchronized void loadAccounts() { if (accountFile == null || !accountFile.exists()) return; if (accountFile.length() == 0) return; LOG.debug("loading accounts from file: " + accountFile.getAbsolutePath()); FileInputStream dataIn = null; try { dataIn = new FileInputStream(accountFile); byte[] encryptedAccountData = IOUtils.toByteArray(dataIn); XStream xStream = createXStream(); Pair<XMPPAccount, Set<XMPPAccount>> accountData = (ImmutablePair<XMPPAccount, Set<XMPPAccount>>) xStream.fromXML( new ByteArrayInputStream(Crypto.decrypt(encryptedAccountData, secretKey))); activeAccount = accountData.getLeft(); accounts = accountData.getRight(); } catch (RuntimeException e) { LOG.error("internal error while loading account data", e); return; } catch (Exception e) { LOG.error("could not load account data", e); return; } finally { IOUtils.closeQuietly(dataIn); } accounts.remove(activeAccount); accounts.add(activeAccount); LOG.debug("loaded " + accounts.size() + " account(s)"); }

Target:
private synchronized void loadAccounts() { if (accountFile == null || !accountFile.exists()) return; LOG.debug("loading accounts from file: " + accountFile.getAbsolutePath()); FileInputStream dataIn = null; try { long accountFileSize = accountFile.length(); if (accountFileSize <= 0 || accountFileSize > MAX_ACCOUNT_DATA_SIZE) throw new IOException( "account data seems malformed, refused to load " + accountFileSize + " bytes into memory"); dataIn = new FileInputStream(accountFile); byte[] encryptedAccountData = IOUtils.toByteArray(dataIn); XStream xStream = createXStream(); AccountStoreInformation accountData = (AccountStoreInformation) xStream.fromXML( new ByteArrayInputStream(Crypto.decrypt(encryptedAccountData, secretKey))); accounts = new HashSet<>(accountData.configuredAccounts); activeAccount = accountData.configuredAccounts.get(accountData.activeAccountIndex); } catch (RuntimeException e) { LOG.error("internal error while loading account data", e); return; } catch (Exception e) { LOG.error("could not load account data", e); return; } finally { IOUtils.closeQuietly(dataIn); } accounts.remove(activeAccount); accounts.add(activeAccount); LOG.debug("loaded " + accounts.size() + " account(s)"); }
Source:
protected String getLaunchCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String command = "java " + vmArguments + " -jar " + jar + " " + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }

Target:
protected String getLaunchCommand(JBossServer jbossServer) throws CoreException { String programArguments = getLaunchProgramArgs(); String vmArguments = getLaunchVMArgs(); String jar = getJar(jbossServer.getServer()); String command = "java " + vmArguments + " -jar " + jar + IJBossRuntimeConstants.SPACE + programArguments + "&"; return command; }
Source:
private boolean executePresendScript(ExtendedEmailPublisherContext context, MimeMessage msg) throws RuntimeException { boolean cancel = false; String script = ContentBuilder.transformText(presendScript, context, getRuntimeMacros(context)); if (StringUtils.isNotBlank(script)) { debug(context.getListener().getLogger(), "Executing pre-send script"); ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader; ScriptSandbox sandbox = null; CompilerConfiguration cc = new CompilerConfiguration(); cc.setScriptBaseClass(EmailExtScript.class.getCanonicalName()); cc.addCompilationCustomizers(new ImportCustomizer().addStarImports( "jenkins", "jenkins.model", "hudson", "hudson.model")); expandClasspath(context, cc); if (getDescriptor().isSecurityEnabled()) { debug(context.getListener().getLogger(), "Setting up sandbox for pre-send script"); cc.addCompilationCustomizers(new SandboxTransformer()); sandbox = new ScriptSandbox(); } Binding binding = new Binding(); binding.setVariable("build", context.getBuild()); binding.setVariable("run", context.getRun()); binding.setVariable("msg", msg); binding.setVariable("listener", context.getListener()); binding.setVariable("logger", context.getListener().getLogger()); binding.setVariable("cancel", cancel); binding.setVariable("trigger", context.getTrigger()); binding.setVariable("triggered", ImmutableMultimap.copyOf(context.getTriggered())); GroovyShell shell = new GroovyShell(cl, binding, cc); StringWriter out = new StringWriter(); PrintWriter pw = new PrintWriter(out); if (sandbox != null) { sandbox.register(); } try { shell.evaluate(script); cancel = ((Boolean) shell.getVariable("cancel")); debug(context.getListener().getLogger(), "Pre-send script set cancel to %b", cancel); } catch (SecurityException e) { context.getListener().getLogger().println("Pre-send script tried to access secured objects: " + e.getMessage()); } catch (Throwable t) { t.printStackTrace(pw); context.getListener().getLogger().println(out.toString()); } debug(context.getListener().getLogger(), out.toString()); } return !cancel; }

Target:
private boolean executePresendScript(ExtendedEmailPublisherContext context, MimeMessage msg) throws RuntimeException { return executeScript(presendScript, "pre-send", context, msg, null, null); }
Source:
protected List<File> getFilesFromProperty(String property) { List<File> result = Lists.newArrayList(); String fileList = settings.getString(property); if (StringUtils.isNotEmpty(fileList)) { Iterable<String> fileNames = Splitter.on(SEPARATOR).omitEmptyStrings().split(fileList); for (String pathPattern : fileNames) { boolean isLibraryProperty = property.endsWith("libraries"); List<File> libraryFilesForPattern = getFilesForPattern(fs.baseDir(), pathPattern, isLibraryProperty); if (validateLibraries && libraryFilesForPattern.isEmpty() && hasJavaSources) { LOG.error("Invalid value for " + property); String message = "No files nor directories matching '" + pathPattern + "'"; throw new IllegalStateException(message); } result.addAll(libraryFilesForPattern); } } return result; }

Target:
protected List<File> getFilesFromProperty(String property) { List<File> result = Lists.newArrayList(); String fileList = settings.getString(property); if (StringUtils.isNotEmpty(fileList)) { Iterable<String> fileNames = Splitter.on(SEPARATOR).omitEmptyStrings().split(fileList); File baseDir = fs.baseDir(); boolean isLibraryProperty = property.endsWith("libraries"); for (String pathPattern : fileNames) { List<File> libraryFilesForPattern = getFilesForPattern(baseDir, pathPattern, isLibraryProperty); if (validateLibraries && libraryFilesForPattern.isEmpty() && hasJavaSources()) { LOG.error("Invalid value for " + property); String message = "No files nor directories matching '" + pathPattern + "'"; throw new IllegalStateException(message); } result.addAll(libraryFilesForPattern); } } return result; }
Source:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); if (!shouldAutoRefresh) { for (Control control : editorComposite.getChildren()) { control.dispose(); } } else { } if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; if (!shouldAutoRefresh) { for (IFormPart part : getManagedForm().getParts()) { part.dispose(); getManagedForm().removePart(part); } } editorComposite.setMenu(menu); if (!shouldAutoRefresh) { createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }

Target:
public void refresh() { if (getManagedForm() == null || getManagedForm().getForm().isDisposed()) { return; } try { showEditorBusy(true); boolean hasIncoming = false; if (getTask() != null) { hasIncoming = getTask().getSynchronizationState().isIncoming(); } if (model != null) { doSave(new NullProgressMonitor()); refreshInput(); } else { initModel(getTaskEditor().getTaskEditorInput()); } if (taskData != null) { try { setReflow(false); Menu menu = editorComposite.getMenu(); CommonUiUtil.setMenu(editorComposite, null); if (focusTracker != null) { focusTracker.reset(); } lastSelection = null; editorComposite.setMenu(menu); if (!shouldAutoRefresh) { createFormContentInternal(); } getTaskEditor().setMessage(null, 0); if (hasIncoming) { getTaskEditor().setActivePage(getId()); } setSubmitEnabled(true); } finally { setReflow(true); } } updateOutlinePage(); updateHeaderMessage(); getManagedForm().dirtyStateChanged(); getTaskEditor().updateHeaderToolBar(); } finally { showEditorBusy(false); } reflow(); }
Source:
public ListenableFuture<?> submit(final Runnable runnable) { final Runnable wrappedPrioritizedRunnable = new PrioritizedRunnable() { @Override public int getPriority() { if (runnable instanceof PrioritizedRunnable) { return ((PrioritizedRunnable) runnable).getPriority(); } else { return 0; } } @Override public void run() { final Long threadUserTime; if (threadMXBean.isThreadCpuTimeEnabled()) { threadUserTime = threadMXBean.getCurrentThreadUserTime(); } else { threadUserTime = null; } runnable.run(); if (threadUserTime != null) { emitter.emit( metricBuilder .setDimension("priority", String.format("%d", getPriority())) .build("exec/cpu", threadMXBean.getCurrentThreadUserTime() - threadUserTime) ); } } }; emitMetrics(); return delegate.submit(wrappedPrioritizedRunnable); }

Target:
public ListenableFuture<?> submit(final Runnable runnable) { return submit(runnable, (Object) null); }
Source:
boolean deletcContentFromCollection(Collection collection, Session session, Path contentTargetPath, String uri) throws IOException { boolean deleted; Path uriPath = Paths.get(uri); CMSLogEvent event = info().collectionID(collection).uri(contentTargetPath); if (isDataVisualisationFile(contentTargetPath)) { event.log("deleting data viz zip form collection content"); deleted = collection.deleteDataVisContent(session, Paths.get(uri)); } else if (Files.isDirectory(contentTargetPath)) { event.log("deleting directory form collection content"); deleted = collection.deleteContentDirectory(session.getEmail(), uri); } else if (Content.isDataJsonFile(uri)) { event.log("deleting data.json and related files from collection content"); deleted = collection.deleteFileAndRelated(uri); } else { event.log("deleting single file from colleciton content"); deleted = collection.deleteFile(uri); } return deleted; }

Target:
boolean deletcContentFromCollection(Collection collection, Session session, Path contentTargetPath, String uri) throws IOException { boolean deleted; Path uriPath = Paths.get(uri); CMSLogEvent event = info().collectionID(collection).uri(contentTargetPath); if (isDataVisualisationFile(contentTargetPath)) { event.log("deleting data viz zip from collection content"); deleted = collection.deleteDataVisContent(session, Paths.get(uri)); } else if (Files.isDirectory(contentTargetPath)) { event.log("deleting directory from collection content"); deleted = collection.deleteContentDirectory(session.getEmail(), uri); } else if (Content.isDataJsonFile(uri)) { event.log("deleting data.json and related files from collection content"); deleted = collection.deleteFileAndRelated(uri); } else { event.log("deleting single file from colleciton content"); deleted = collection.deleteFile(uri); } return deleted; }
Source:
public void testMultiThreadRemoveDisjointRanges() throws InterruptedException { final int numThreads = 8; final int removesPerThread = 100000; final int totalNumberOfRemoves = numThreads * removesPerThread; final CountDownLatch countDownLatch = new CountDownLatch(numThreads); for (int i = 0; i < totalNumberOfRemoves; i++) { assertTrue(MSG_FALSE_RESULT, partitionManager.registerPartition(EVAL_ID, DATA_TYPE, 3 * i, 3 * i + 1)); } final Runnable[] threads = new Runnable[numThreads]; for (int index = 0; index < numThreads; index++) { threads[index] = new RemoveThread(countDownLatch, partitionManager, index, numThreads, removesPerThread, IndexParity.ALL_INDEX); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION, 0, partitionManager.getRangeSet(EVAL_ID, DATA_TYPE).size()); }

Target:
public void testMultiThreadRemoveDisjointRanges() throws InterruptedException { final int numThreads = 8; final int removesPerThread = 100000; final long rangeTerm = 3; final long rangeLength = 2; final int initialOffset = 0; final int totalNumberOfRemoves = numThreads * removesPerThread; final CountDownLatch countDownLatch = new CountDownLatch(numThreads); for (int i = 0; i < totalNumberOfRemoves; i++) { final int rangeStart = (int) (initialOffset + rangeTerm * i); final int rangeEnd = (int) (rangeStart + rangeLength - 1); assertTrue(MSG_REGISTER_UNEXPECTED_RESULT, partitionManager.register(EVAL_ID_PREFIX, DATA_TYPE_PREFIX, rangeStart, rangeEnd)); } final Runnable[] threads = new Runnable[numThreads]; for (int index = 0; index < numThreads; index++) { threads[index] = new RemoveThread(countDownLatch, partitionManager, index, numThreads, removesPerThread, IndexParity.ALL_INDEX, EVAL_ID_PREFIX, DATA_TYPE_PREFIX, rangeTerm, rangeLength, initialOffset); } TestUtils.runConcurrently(threads); final boolean allThreadsFinished = countDownLatch.await(60, TimeUnit.SECONDS); assertTrue(MSG_THREADS_NOT_FINISHED, allThreadsFinished); assertEquals(MSG_SIZE_ASSERTION, 0, partitionManager.getRangeSet(EVAL_ID_PREFIX, DATA_TYPE_PREFIX).size()); }
Source:
PieChart getGlobalPC() { return fGlobalPC; }

Target:
synchronized PieChart getGlobalPC() { return fGlobalPC; }
Source:
protected OAuth10Credentials getOAuthCredentials(final WebContext context) { final Optional<String> tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN); final Optional<String> verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER); if (tokenParameter.isPresent() && verifierParameter.isPresent()) { final OAuth1RequestToken tokenSession = (OAuth1RequestToken) context .getSessionStore().get(context, configuration.getRequestTokenSessionAttributeName(client.getName())).orElse(null); logger.debug("tokenRequest: {}", tokenSession); final String token = OAuthEncoder.decode(tokenParameter.get()); final String verifier = OAuthEncoder.decode(verifierParameter.get()); logger.debug("token: / verifier: {}", token, verifier); return new OAuth10Credentials(tokenSession, token, verifier); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }

Target:
protected OAuth10Credentials getOAuthCredentials(final WebContext context) { final Optional<String> tokenParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_TOKEN); final Optional<String> verifierParameter = context.getRequestParameter(OAuth10Configuration.OAUTH_VERIFIER); if (tokenParameter.isPresent() && verifierParameter.isPresent()) { final Optional<OAuth1RequestToken> tokenSession = context .getSessionStore() .get(context, configuration.getRequestTokenSessionAttributeName(client.getName())); logger.debug("tokenRequest: {}", tokenSession); final String token = OAuthEncoder.decode(tokenParameter.get()); final String verifier = OAuthEncoder.decode(verifierParameter.get()); logger.debug("token: / verifier: {}", token, verifier); return new OAuth10Credentials(tokenSession.get(), token, verifier); } else { final String message = "No credential found"; throw new OAuthCredentialsException(message); } }
Source:
public void testReplicateLFShouldCopyFailedBookieFragmentsToTargetBookie() throws Exception { byte[] data = "TestLedgerFragmentReplication".getBytes(); LedgerHandle lh = bkc.createLedger(3, 3, TEST_DIGEST_TYPE, TEST_PSSWD); for (int i = 0; i < 10; i++) { lh.addEntry(data); } BookieSocketAddress replicaToKill = lh.getLedgerMetadata().getAllEnsembles() .get(0L).get(0); LOG.info("Killing Bookie : {}", replicaToKill); killBookie(replicaToKill); BookieSocketAddress newBkAddr = startNewBookieAndReturnAddress(); LOG.info("New Bookie addr : {}", newBkAddr); for (int i = 0; i < 10; i++) { lh.addEntry(data); } Set<LedgerFragment> result = getFragmentsToReplicate(lh); BookKeeperAdmin admin = new BookKeeperAdmin(baseClientConf); lh.close(); for (LedgerFragment lf : result) { admin.replicateLedgerFragment(lh, lf, null); } SortedMap<Long, ? extends List<BookieSocketAddress>> allBookiesBeforeReplication = lh .getLedgerMetadata().getAllEnsembles(); for (Entry<Long, ? extends List<BookieSocketAddress>> entry : allBookiesBeforeReplication.entrySet()) { List<BookieSocketAddress> bookies = entry.getValue(); for (BookieSocketAddress bookie : bookies) { if (newBkAddr.equals(bookie)) { continue; } killBookie(bookie); } } verifyRecoveredLedgers(lh, 0, 9); }

Target:
public void testReplicateLFShouldCopyFailedBookieFragmentsToTargetBookie() throws Exception { byte[] data = "TestLedgerFragmentReplication".getBytes(); LedgerHandle lh = bkc.createLedger(3, 3, TEST_DIGEST_TYPE, TEST_PSSWD); for (int i = 0; i < 10; i++) { lh.addEntry(data); } BookieSocketAddress replicaToKill = lh.getLedgerMetadata().getAllEnsembles() .get(0L).get(0); LOG.info("Killing Bookie : {}", replicaToKill); killBookie(replicaToKill); BookieSocketAddress newBkAddr = startNewBookieAndReturnAddress(); LOG.info("New Bookie addr : {}", newBkAddr); for (int i = 0; i < 10; i++) { lh.addEntry(data); } Set<LedgerFragment> result = getFragmentsToReplicate(lh); BookKeeperAdmin admin = new BookKeeperAdmin(baseClientConf); lh.close(); for (LedgerFragment lf : result) { admin.replicateLedgerFragment(lh, lf, NOOP_BICONSUMER); } SortedMap<Long, ? extends List<BookieSocketAddress>> allBookiesBeforeReplication = lh .getLedgerMetadata().getAllEnsembles(); for (Entry<Long, ? extends List<BookieSocketAddress>> entry : allBookiesBeforeReplication.entrySet()) { List<BookieSocketAddress> bookies = entry.getValue(); for (BookieSocketAddress bookie : bookies) { if (newBkAddr.equals(bookie)) { continue; } killBookie(bookie); } } verifyRecoveredLedgers(lh, 0, 9); }
Source:
public void testInitBareRepository() { String directory = new File(trash, "test2").getPath(); try { InitCommand command = new InitCommand(); command.setDirectory(directory); command.setBare(true); Repository repository = command.call().getRepository(); assertNotNull(repository); assertTrue(repository.isBare()); } catch (Exception e) { fail(e.getMessage()); } }

Target:
public void testInitBareRepository() { try { File directory = createTempDirectory("testInitBareRepository"); InitCommand command = new InitCommand(); command.setDirectory(directory); command.setBare(true); Repository repository = command.call().getRepository(); assertNotNull(repository); assertTrue(repository.isBare()); } catch (Exception e) { fail(e.getMessage()); } }
Source:
public CatalogServiceImpl( CatalogFramework framework, AttachmentParser attachmentParser, AttributeRegistry attributeRegistry) { LOGGER.trace("Constructing REST Endpoint"); this.catalogFramework = framework; this.attachmentParser = attachmentParser; this.attributeRegistry = attributeRegistry; LOGGER.trace(("Rest Endpoint constructed successfully")); }

Target:
public CatalogServiceImpl( CatalogFramework framework, AttachmentParser attachmentParser, AttributeRegistry attributeRegistry) { LOGGER.trace("Constructing CatalogServiceImpl"); this.catalogFramework = framework; this.attachmentParser = attachmentParser; this.attributeRegistry = attributeRegistry; LOGGER.trace(("CatalogServiceImpl constructed successfully")); }
Source:
protected void setPRPAINBuilder(Patient query) { PRPAIN201305UV02Builder builder = new PRPAIN201305UV02BuilderImpl(); ((PRPAIN201305UV02BuilderImpl) builder).setPatient(query); pdMessageDirector.setPRPAIN201305UV02Builder(builder); }

Target:
protected void setPRPAINBuilder(Patient query) { PRPAIN201305UV02BuilderImpl builder = new PRPAIN201305UV02BuilderImpl(); builder.setPatient(query); pdMessageDirector.setPRPAIN201305UV02Builder(builder); }
Source:
public @ResponseBody Map<String, Object> findGroupsOfUser(@PathVariable Integer userId) { try { Set<UserGroup> userGroupsSet = this.service.getGroupsOfUser(userId); return ResultSet.success(userGroupsSet); } catch (Exception e) { LOG.error("Error finding user with id " + userId + ": " + e.getMessage()); return ResultSet.error("Error finding user with id " + userId); } }

Target:
public ResponseEntity<Set<UserGroup>> findGroupsOfUser(@PathVariable Integer userId) { try { Set<UserGroup> userGroupsSet = this.service.getGroupsOfUser(userId); return new ResponseEntity<Set<UserGroup>>(userGroupsSet, HttpStatus.OK); } catch (Exception e) { LOG.error("Error finding user with id " + userId + ": " + e.getMessage()); return new ResponseEntity<Set<UserGroup>>(HttpStatus.NOT_FOUND); } }
Source:
public void onCollide(ICollidable other) { if (other instanceof IEatable) { IEatable eatable = (IEatable) other; if (eatable.canBeEatenBy(this)) { eatable.eat(); this.addPoints((int) (eatable.getSize() / 200)); double dSize = settings.getInteger("GROWTH_SPEED") * eatable.getSize() / getSize(); getBoundingArea().increaseSize(dSize); State old = getState(); notifyObservers(old, getState(), "EnemyKill"); } if (this.canBeEatenBy(eatable)) { eatable.eat(this); } } }

Target:
public void onCollide(ICollidable other) { if (other instanceof IEatable) { IEatable eatable = (IEatable) other; if (eatable.canBeEatenBy(this)) { eatable.eat(); this.addPoints((int) (eatable.getSize() / 200)); double dSize = getGrowthSpeed() * eatable.getSize() / getSize(); getBoundingArea().increaseSize(dSize); State old = getState(); notifyObservers(old, getState(), "EnemyKill"); } if (this.canBeEatenBy(eatable)) { eatable.eat(this); } } }
Source:
private synchronized void notifyListeners(CruiseConfig newCruiseConfig) { LOGGER.info("About to notify config listeners"); for (ConfigChangedListener listener : listeners) { try { long startTime = System.currentTimeMillis(); listener.onConfigChange(newCruiseConfig); LOGGER.debug("Notifying " + listener.getClass() + " took (in ms): " + (System.currentTimeMillis() - startTime)); } catch (Exception e) { LOGGER.error("Failed to fire config changed event for listener: " + listener, e); } } LOGGER.info("Finished notifying all listeners"); }

Target:
private synchronized void notifyListeners(CruiseConfig newCruiseConfig) { LOGGER.info("About to notify config listeners"); for (ConfigChangedListener listener : listeners) { try { long startTime = System.currentTimeMillis(); listener.onConfigChange(newCruiseConfig); LOGGER.debug("Notifying took (in ms): {}", listener.getClass(), (System.currentTimeMillis() - startTime)); } catch (Exception e) { LOGGER.error("Failed to fire config changed event for listener: " + listener, e); } } LOGGER.info("Finished notifying all listeners"); }
Source:
public boolean deleteTemplate(DeleteTemplateCmd cmd) { Long templateId = cmd.getId(); Account caller = CallContext.current().getCallingAccount(); VMTemplateVO template = _tmpltDao.findById(templateId); if (template == null) { throw new InvalidParameterValueException("unable to find template with id " + templateId); } List<VMInstanceVO> vmInstanceVOList; if(cmd.getZoneId() != null) { vmInstanceVOList = _vmInstanceDao.listNonExpungedByZoneAndTemplate(cmd.getZoneId(), templateId); } else { vmInstanceVOList = _vmInstanceDao.listNonExpungedByTemplate(templateId); } if(!cmd.isForced() && CollectionUtils.isNotEmpty(vmInstanceVOList)) { StringBuilder s = new StringBuilder("Unable to delete template with id: " + templateId + " because some VM instances are using it. "); for (VMInstanceVO elm : vmInstanceVOList) { s.append(elm.getInstanceName() + ", "); } s_logger.warn(s.substring(0,s.length()-2)); throw new InvalidParameterValueException(s.substring(0,s.length()-2)); } _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template); if (template.getFormat() == ImageFormat.ISO) { throw new InvalidParameterValueException("Please specify a valid template."); } TemplateAdapter adapter = getAdapter(template.getHypervisorType()); TemplateProfile profile = adapter.prepareDelete(cmd); return adapter.delete(profile); }

Target:
public boolean deleteTemplate(DeleteTemplateCmd cmd) { Long templateId = cmd.getId(); Account caller = CallContext.current().getCallingAccount(); VMTemplateVO template = _tmpltDao.findById(templateId); if (template == null) { throw new InvalidParameterValueException("unable to find template with id " + templateId); } List<VMInstanceVO> vmInstanceVOList; if(cmd.getZoneId() != null) { vmInstanceVOList = _vmInstanceDao.listNonExpungedByZoneAndTemplate(cmd.getZoneId(), templateId); } else { vmInstanceVOList = _vmInstanceDao.listNonExpungedByTemplate(templateId); } if(!cmd.isForced() && CollectionUtils.isNotEmpty(vmInstanceVOList)) { final String message = String.format("Unable to delete template with id: %1$s because VM instances: [%2$s] are using it.", templateId, Joiner.on(",").join(vmInstanceVOList)); s_logger.warn(message); throw new InvalidParameterValueException(message); } _accountMgr.checkAccess(caller, AccessType.OperateEntry, true, template); if (template.getFormat() == ImageFormat.ISO) { throw new InvalidParameterValueException("Please specify a valid template."); } TemplateAdapter adapter = getAdapter(template.getHypervisorType()); TemplateProfile profile = adapter.prepareDelete(cmd); return adapter.delete(profile); }
Source:
public int hashCode() { return Objects.hash( routers, ttl ); }

Target:
public int hashCode() { return Objects.hash( routers, timeToLiveMillis ); }
Source:
private int getPinFromHeader(int header) { return header & 0x0F; }

Target:
private int getPinFromHeader(int header) { return header & BITMASK_PIN; }
Source:
public void testPartialQueryLoadsInBulkMode() throws XPathSyntaxException, UnfullfilledRequirementsException, XmlPullParserException, IOException, InvalidStructureException { ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/indexed_fixture/partial_lookup_load_body_large_scope.xml"), sandbox); EvaluationContext ec = MockDataUtils.buildContextWithInstance(sandbox, "testfixture", "jr://fixture/testfixture"); EvaluationContext ecForTest = ec.spawnWithCleanLifecycle(); QueryContext context = ecForTest.getCurrentQueryContext(); ScopeLimitedReferenceRequestCache cache = context.getQueryCache(ScopeLimitedReferenceRequestCache.class); String exprString = "instance('testfixture')/test/entry[@filter_attribute = 'pass'][true() and filter_one = 'pass']/name"; XPathExpression expr = XPathParseTool.parseXPath(exprString); cache.addTreeReferencesToLimitedScope(new TreeReferenceAccumulatingAnalyzer(ecForTest).accumulate(expr)); CaseTestUtils.xpathEvalAndAssert(ecForTest, exprString, "succeed"); }

Target:
public void testPartialQueryLoadsInBulkMode() throws XPathSyntaxException, UnfullfilledRequirementsException, XmlPullParserException, IOException, InvalidStructureException { ParseUtils.parseIntoSandbox(getClass().getResourceAsStream("/indexed_fixture/partial_lookup_load_body_large_scope.xml"), sandbox); doPartialLookupTest(); }