auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Repo<Master> call(long tid, Master environment) throws Exception { KeyExtent extent = new KeyExtent(tableInfo.tableId, null, null); MetadataTableUtil.addTablet(extent, tableInfo.dir, environment, tableInfo.timeType, environment.getMasterLock()); if (tableInfo.props.containsKey(Property.TABLE_OFFLINE_OPTS + "create.initial.splits")) { return new CreateInitialSplits(tableInfo); } else { return new FinishCreateTable(tableInfo); } }

Target:
public Repo<Master> call(long tid, Master environment) throws Exception { KeyExtent extent = new KeyExtent(tableInfo.tableId, null, null); MetadataTableUtil.addTablet(extent, tableInfo.defaultTabletDir, environment, tableInfo.timeType, environment.getMasterLock()); if (tableInfo.initialSplitSize > 0) { SortedSet<Text> splits = Utils .getSortedSetFromFile(environment.getInputStream(tableInfo.splitFile), true); SortedSet<Text> dirs = Utils .getSortedSetFromFile(environment.getInputStream(tableInfo.splitDirsFile), false); Map<Text,Text> splitDirMap = createSplitDirectoryMap(splits, dirs); try (BatchWriter bw = environment.getConnector().createBatchWriter("accumulo.metadata")) { writeSplitsToMetadataTable(tableInfo.tableId, splits, splitDirMap, tableInfo.timeType, environment.getMasterLock(), bw); } } return new FinishCreateTable(tableInfo); }
Source:
@Override public String getAllowedSignatures(String name) { return "<ARRAY>[<INTEGER>]\n" + "<MAP>[<VALUE>]\n" + "<ROW>[<CHARACTER>|<INTEGER>]"; }

Target:
@Override public String getAllowedSignatures(String name) { return "<ARRAY>[<INTEGER>]\n" + "<MAP>[<ANY>]\n" + "<ROW>[<CHARACTER>|<INTEGER>]"; }
Source:
Grid createBlankRow(final HostInterfaceLineModel lineModel) { Grid row = new Grid(1, 4); row.getColumnFormatter().setWidth(0, VLanPanel.CHECK_BOX_COLUMN_WIDTH); row.getColumnFormatter().setWidth(1, VLanPanel.NETWORK_NAME_COLUMN_WIDTH); row.getColumnFormatter().setWidth(2, VLanPanel.OUT_OF_SYNC_WIDTH); row.getColumnFormatter().setWidth(3, VLanPanel.ADDRESS_COLUMN_WIDTH); row.setWidth("100%"); row.setHeight("100%"); row.setWidget(0, 0, new Label()); Label networkName = new Label(lineModel.getNetworkName()); if (lineModel.getIsManagement()) { networkName.getElement().getStyle().setFontWeight(FontWeight.BOLD); networkName.setText("* " + lineModel.getNetworkName()); } row.setWidget(0, 1, networkName); VdsNetworkInterface iface = lineModel.getIsBonded()? lineModel.getInterface() : lineModel.getInterfaces().get(0).getInterface(); VdsNetworkInterface.NetworkImplementationDetails ifaceNetworkImpDetails = (iface != null) ? iface.getNetworkImplementationDetails() : null; boolean isSYnc = (ifaceNetworkImpDetails != null) ? ifaceNetworkImpDetails.isInSync() : true; row.setWidget(0, 2, getSyncPanel(isSYnc)); row.setWidget(0, 3, new Label(lineModel.getAddress())); return row; }

Target:
Grid createBlankRow(final HostInterfaceLineModel lineModel) { VdsNetworkInterface iface = lineModel.getIsBonded() ? lineModel.getInterface() : lineModel.getInterfaces().get(0).getInterface(); return createVlanRowColumn(new Label(), lineModel.getIsManagement(), lineModel.getNetworkName(), createSyncPanel(iface.getNetworkImplementationDetails().isInSync()), new Label(lineModel.getAddress())); }
Source:
public QuotaViolationException(MetricName metricName, double value, double bound) { super(metricName + " violated quota."); this.metricName = metricName; this.value = value; this.bound = bound; }

Target:
public QuotaViolationException(MetricName metricName, double value, double bound) { this.metricName = metricName; this.value = value; this.bound = bound; }
Source:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { File file = new File(fileName); FileInputStream fileInput = new FileInputStream(file); topologyProperties.load(fileInput); fileInput.close(); }

Target:
public void loadProvidedPropertyFile(String fileName, Properties topologyProperties) throws IOException { FileInputStream fileInput = new FileInputStream(fileName); topologyProperties.load(fileInput); fileInput.close(); }
Source:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkArgument( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } return new ApacheHttpResponse(request, httpClient.execute(request)); }

Target:
public LowLevelHttpResponse execute() throws IOException { if (getStreamingContent() != null) { Preconditions.checkState( request instanceof HttpEntityEnclosingRequest, "Apache HTTP client does not support %s requests with content.", request.getRequestLine().getMethod()); ContentEntity entity = new ContentEntity(getContentLength(), getStreamingContent()); entity.setContentEncoding(getContentEncoding()); entity.setContentType(getContentType()); if (getContentLength() == -1) { entity.setChunked(true); } ((HttpEntityEnclosingRequest) request).setEntity(entity); } return new ApacheHttpResponse(request, httpClient.execute(request)); }
Source:
public void testInheritSubmit_OverridesAndDeniesOfRef() { inherited.add(grant(SUBMIT, registered, "refs/*", 1, 1)); local.add(grant(SUBMIT, registered, "refs/*", -1, -1)); local.add(grant(SUBMIT, registered, "refs/heads/*", -1, 1)); ProjectControl u = user(); assertFalse("can't submit", u.controlForRef("refs/foobar").canSubmit()); assertTrue("can submit", u.controlForRef("refs/heads/foobar").canSubmit()); }

Target:
public void testInheritSubmit_OverridesAndDeniesOfRef() { grant(false, SUBMIT, registered, "refs/*", 1); grant(true, SUBMIT, registered, "refs/*", 0); grant(true, SUBMIT, registered, "refs/heads/*", -1, 1); ProjectControl u = user(); assertFalse("can't submit", u.controlForRef("refs/foobar").canSubmit()); assertFalse("can't submit", u.controlForRef("refs/tags/foobar").canSubmit()); assertTrue("can submit", u.controlForRef("refs/heads/foobar").canSubmit()); }
Source:
public static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { MessageDigest digest; try { digest = MessageDigest.getInstance("SHA-1"); digest.update(Application.get().getCustomApiUrl().getBytes()); regionName = Application.get().getString(R.string.analytics_label_custom_url) + ": " + Application.getHex(digest.digest()); } catch (Exception e) { regionName = Application.get().getString(R.string.analytics_label_custom_url); } } return regionName; }

Target:
public static String getObaRegionName() { String regionName = null; ObaRegion region = Application.get().getCurrentRegion(); if (region != null && region.getName() != null) { regionName = region.getName(); } else if (Application.get().getCustomApiUrl() != null) { regionName = createHashCode(Application.get().getCustomApiUrl().getBytes()); } return regionName; }
Source:
protected void addListener() { HashSet<Class> filterAnnotations = new HashSet<>(Arrays.asList(CacheEntryCreated.class, CacheEntryModified.class, CacheEntryRemoved.class, CacheEntryExpired.class)); n.addFilteredListener(cl, null, new ToStringConverter(), filterAnnotations); }

Target:
protected void addListener() { Set<Class> filterAnnotations = Util.<Class> asSet(CacheEntryCreated.class, CacheEntryModified.class, CacheEntryRemoved.class, CacheEntryExpired.class); n.addFilteredListener(cl, null, (key, oldValue, oldMetadata, newValue, newMetadata, eventType) -> "custom event for test (" + eventType.getType().name() + "," + key + "," + newValue + ")", filterAnnotations); }
Source:
public void testCreateMeasurementRowsFromEnvironments() { final MeasurementVariable variable = MeasurementVariableTestDataInitializer.createMeasurementVariable(TermId.PLOT_CODE.getId(), TermId.PLOT_CODE.name(), null); variable.setDataTypeId(TermId.NUMERIC_VARIABLE.getId()); final Instance instance = new Instance(); instance.setStockId(1); instance.setExperimentId(12); instance.setInstanceId(1); final List<MeasurementRow> row = WorkbookUtil.createMeasurementRowsFromEnvironments(Arrays.asList(instance), Arrays.asList(variable), new ExpDesignParameterUi()); Assert.assertNotNull(row); Assert.assertEquals(instance.getExperimentId(), row.get(0).getExperimentId()); Assert.assertEquals(instance.getStockId(), row.get(0).getStockId()); }

Target:
public void testCreateMeasurementRowsFromEnvironments() { final MeasurementVariable variable = MeasurementVariableTestDataInitializer.createMeasurementVariable(TermId.PLOT_CODE.getId(), TermId.PLOT_CODE.name(), null); variable.setDataTypeId(TermId.NUMERIC_VARIABLE.getId()); final Instance instance = new Instance(); instance.setStockId(Long.parseLong(RandomStringUtils.randomNumeric(5))); instance.setExperimentId(Integer.parseInt(RandomStringUtils.randomNumeric(5))); instance.setInstanceId(Long.parseLong(RandomStringUtils.randomNumeric(5))); final List<MeasurementRow> row = WorkbookUtil.createMeasurementRowsFromEnvironments(Arrays.asList(instance), Arrays.asList(variable), new ExpDesignParameterUi()); Assert.assertNotNull(row); Assert.assertEquals(instance.getExperimentId(), row.get(0).getExperimentId()); Assert.assertEquals(instance.getStockId(), row.get(0).getStockId()); }
Source:
private void initFloatPredicate() { if (floatPredicate != null) { return; } synchronized (initLock) { if (floatPredicate != null) { return; } final Float valueAsFloat = Floats.tryParse(value); if (valueAsFloat == null) { floatPredicate = DruidFloatPredicate.ALWAYS_FALSE; } else { final int floatInts = Float.floatToIntBits(valueAsFloat); floatPredicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Float.floatToIntBits(input) == floatInts; } }; } } }

Target:
private void initFloatPredicate() { if (floatPredicate != null) { return; } synchronized (initLock) { if (floatPredicate != null) { return; } final Float valueAsFloat = Floats.tryParse(value); if (valueAsFloat == null) { floatPredicate = DruidFloatPredicate.ALWAYS_FALSE; } else { final int floatBits = Float.floatToIntBits(valueAsFloat); floatPredicate = new DruidFloatPredicate() { @Override public boolean applyFloat(float input) { return Float.floatToIntBits(input) == floatBits; } }; } } }
Source:
public String getXML() { StringBuffer retval = new StringBuffer(); if (!Const.isEmpty(m_yamlPath)) { retval.append("\n ").append( XMLHandler.addTagValue("yaml_path", m_yamlPath)); } if (!Const.isEmpty(directory)) { retval.append("\n ").append( XMLHandler.addTagValue("output_directory", directory)); } if (!Const.isEmpty(cassandraKeyspace)) { retval.append("\n ").append( XMLHandler.addTagValue("cassandra_keyspace", cassandraKeyspace)); } if (!Const.isEmpty(cassandraKeyspace)) { retval.append("\n ").append( XMLHandler.addTagValue("cassandra_keyspace", cassandraKeyspace)); } if (!Const.isEmpty(columnFamily)) { retval.append("\n ").append( XMLHandler.addTagValue("column_family", columnFamily)); } if (!Const.isEmpty(keyField)) { retval.append("\n ").append( XMLHandler.addTagValue("key_field", keyField)); } if (!Const.isEmpty(bufferSize)) { retval.append("\n ").append( XMLHandler.addTagValue("buffer_size_mb", bufferSize)); } retval.append("\n ").append( XMLHandler.addTagValue("use_cql3", m_useCQL3)); return retval.toString(); }

Target:
public String getXML() { StringBuffer retval = new StringBuffer(); if ( !Const.isEmpty( m_yamlPath ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "yaml_path", m_yamlPath ) ); } if ( !Const.isEmpty( directory ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "output_directory", directory ) ); } if ( !Const.isEmpty( cassandraKeyspace ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "cassandra_keyspace", cassandraKeyspace ) ); } if ( !Const.isEmpty( columnFamily ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "column_family", columnFamily ) ); } if ( !Const.isEmpty( keyField ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "key_field", keyField ) ); } if ( !Const.isEmpty( bufferSize ) ) { retval.append( "\n " ).append( XMLHandler.addTagValue( "buffer_size_mb", bufferSize ) ); } retval.append( "\n " ).append( XMLHandler.addTagValue( "use_cql3", m_useCQL3 ) ); return retval.toString(); }
Source:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; oldMessageCount = messageCount; messageCount = 0; } toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); }

Target:
void moveAllEventsTo (Synchronizer toReceiveTheEvents) { RunnableLock[] oldMessages; int oldMessageCount; synchronized (messageLock) { oldMessages = messages; messages = null; oldMessageCount = messageCount; messageCount = 0; } toReceiveTheEvents.addFirst(oldMessages, oldMessageCount); }
Source:
public void setShowIgnoreFilesButtons(boolean showButtons) { showButtonsState = showButtons; this.breakToolbarFactory.setShowIgnoreFilesButtons(showButtons); mainBreakButtons.setShowIgnoreFilesButtons(showButtons); requestBreakButtons.setShowIgnoreFilesButtons(showButtons); responseBreakButtons.setShowIgnoreFilesButtons(showButtons); }

Target:
protected void setShowIgnoreFilesButtons(boolean showButtons) { this.breakToolbarFactory.setShowIgnoreFilesButtons(showButtons); mainBreakButtons.setShowIgnoreFilesButtons(showButtons); requestBreakButtons.setShowIgnoreFilesButtons(showButtons); responseBreakButtons.setShowIgnoreFilesButtons(showButtons); }
Source:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); if (!context.reauthorizationRequired() || context.getAuthorizedClient().getRefreshToken() == null) { return null; } HttpServletRequest request = context.getAttribute(HTTP_SERVLET_REQUEST_ATTRIBUTE_NAME); HttpServletResponse response = context.getAttribute(HTTP_SERVLET_RESPONSE_ATTRIBUTE_NAME); Assert.notNull(request, "The context attribute cannot be null '" + HTTP_SERVLET_REQUEST_ATTRIBUTE_NAME + "'"); Assert.notNull(response, "The context attribute cannot be null '" + HTTP_SERVLET_RESPONSE_ATTRIBUTE_NAME + "'"); String requestScope = context.getAttribute(REQUEST_SCOPE_ATTRIBUTE_NAME); Set<String> scopes = null; if (!StringUtils.isEmpty(requestScope)) { String delimiter = requestScope.indexOf(',') != -1 ? "," : " "; scopes = Arrays.stream(StringUtils.delimitedListToStringArray(requestScope, delimiter, " ")).collect(Collectors.toSet()); } OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest(context.getAuthorizedClient(), scopes); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(refreshTokenGrantRequest); OAuth2AuthorizedClient authorizedClient = new OAuth2AuthorizedClient( context.getClientRegistration(), context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()); this.authorizedClientRepository.saveAuthorizedClient( authorizedClient, context.getPrincipal(), request, response); return authorizedClient; }

Target:
public OAuth2AuthorizedClient authorize(OAuth2AuthorizationContext context) { Assert.notNull(context, "context cannot be null"); OAuth2AuthorizedClient authorizedClient = context.getAuthorizedClient(); if (authorizedClient == null || authorizedClient.getRefreshToken() == null || !hasTokenExpired(authorizedClient.getAccessToken())) { return null; } Object requestScope = context.getAttribute(OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME); Set<String> scopes = Collections.emptySet(); if (requestScope != null) { Assert.isInstanceOf(String[].class, requestScope, "The context attribute must be of type String[] '" + OAuth2AuthorizationContext.REQUEST_SCOPE_ATTRIBUTE_NAME + "'"); scopes = new HashSet<>(Arrays.asList((String[]) requestScope)); } OAuth2RefreshTokenGrantRequest refreshTokenGrantRequest = new OAuth2RefreshTokenGrantRequest( authorizedClient.getClientRegistration(), authorizedClient.getAccessToken(), authorizedClient.getRefreshToken(), scopes); OAuth2AccessTokenResponse tokenResponse = this.accessTokenResponseClient.getTokenResponse(refreshTokenGrantRequest); return new OAuth2AuthorizedClient(context.getAuthorizedClient().getClientRegistration(), context.getPrincipal().getName(), tokenResponse.getAccessToken(), tokenResponse.getRefreshToken()); }
Source:
public static List<String> xPathFuncList() { return new ArrayList<>(funcList.values()); }

Target:
public static List<String> xPathFuncList() { return new ArrayList<>(funcList.keySet()); }
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositoryGroups groups = new RepositoryGroups(); String groupName = getNewGroupName( getActiveShell(event), UIText.RepositoriesView_RepoGroup_Add_Title, groups, ""); if (groupName != null) { UUID groupId = groups.addGroup(groupName); List<String> repoDirs = getSelectedRepositories(event); if (!repoDirs.isEmpty()) { groups.addRepositoriesToGroup(groupId, repoDirs); } getView(event).refresh(); } return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RepositoryGroups groupsUtil = RepositoryGroups.getInstance(); String groupName = getNewGroupName(getActiveShell(event), UIText.RepositoriesView_RepoGroup_Add_Title, groupsUtil, ""); if (groupName != null) { UUID groupId = groupsUtil.addGroup(groupName); List<File> repoDirs = getSelectedRepositories(event); if (!repoDirs.isEmpty()) { groupsUtil.addRepositoriesToGroup(groupId, repoDirs); } getView(event).refresh(); } return null; }
Source:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String username = Strings.nullToEmpty(req.getParameter("username")).trim(); String password = Strings.nullToEmpty(req.getParameter("password")); String remember = Strings.nullToEmpty(req.getParameter("rememberme")); if (username.isEmpty() || password.isEmpty()) { sendForm(req, res, "Invalid username or password."); return; } AuthRequest areq = AuthRequest.forUser(username); areq.setPassword(password); AuthResult ares; try { ares = accountManager.authenticate(areq); } catch (AccountUserNameException e) { sendForm(req, res, e.getMessage()); return; } catch (AuthenticationUnavailableException e) { sendForm(req, res, "Authentication unavailable at this time."); return; } catch (AccountException e) { log.info(String.format("'%s' failed to sign in: %s", username, e.getMessage())); sendForm(req, res, "Invalid username or password."); return; } catch (RuntimeException e) { log.error("LDAP authentication failed", e); sendForm(req, res, "Authentication unavailable at this time."); return; } String token = LoginUrlToken.getToken(req); StringBuilder dest = new StringBuilder(); dest.append(urlProvider.get(req)); dest.append(token); CacheHeaders.setNotCacheable(res); webSession.get().login(ares, "1".equals(remember)); res.sendRedirect(dest.toString()); }

Target:
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String username = Strings.nullToEmpty(req.getParameter("username")).trim(); String password = Strings.nullToEmpty(req.getParameter("password")); String remember = Strings.nullToEmpty(req.getParameter("rememberme")); if (username.isEmpty() || password.isEmpty()) { sendForm(req, res, "Invalid username or password."); return; } AuthRequest areq = AuthRequest.forUser(username); areq.setPassword(password); AuthResult ares; try { ares = accountManager.authenticate(areq); } catch (AccountUserNameException e) { sendForm(req, res, e.getMessage()); return; } catch (AuthenticationUnavailableException e) { sendForm(req, res, "Authentication unavailable at this time."); return; } catch (AccountException e) { log.info(String.format("'%s' failed to sign in: %s", username, e.getMessage())); sendForm(req, res, "Invalid username or password."); return; } catch (RuntimeException e) { log.error("LDAP authentication failed", e); sendForm(req, res, "Authentication unavailable at this time."); return; } StringBuilder dest = new StringBuilder(); dest.append(urlProvider.get(req)); dest.append(LoginUrlToken.getToken(req)); CacheHeaders.setNotCacheable(res); webSession.get().login(ares, "1".equals(remember)); res.sendRedirect(dest.toString()); }
Source:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } lockDecorationUpdater.unregister(); }

Target:
public void dispose() { super.dispose(); if (this.tabFolder != null) { this.tabFolder.dispose(); this.tabFolder = null; } tabItems.clear(); for (ModelExplorerTabDescriptor tabDescriptor : ModelExplorerTabRegistry.getRegisteredExtensions()) { IModelExplorerTabExtension tab = tabDescriptor.getTabExtension(); if (tab != null) { tab.dispose(); } } lockDecorationUpdater.unregister(); lockDecorationUpdater = null; }
Source:
public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { cachedMethods.putIfAbsent(methodKey, getMethodToRun(instance, methodName)); } methodToRun = cachedMethods.get(methodKey); String correlationId = LoggedUtils.getObjectId(this); CorrelationIdTracker.setCorrelationId(correlationId); invokeMethod(instance, methodToRun, methodParams); CorrelationIdTracker.setCorrelationId(null); } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } }

Target:
public void execute(JobExecutionContext context) throws JobExecutionException { String methodName = null; try { JobDataMap data = context.getJobDetail().getJobDataMap(); Map paramsMap = data.getWrappedMap(); methodName = (String) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_NAME); final Object instance = getInstanceToRun(paramsMap); final Object[] methodParams = (Object[]) paramsMap.get(SchedulerUtilBaseImpl.RUN_METHOD_PARAM); String methodKey = getMethodKey(instance.getClass().getName(), methodName); final Method methodToRun; if (!cachedMethods.containsKey(methodKey)) { cachedMethods.putIfAbsent(methodKey, getMethodToRun(instance, methodName)); } methodToRun = cachedMethods.get(methodKey); String correlationId = LoggedUtils.getObjectId(this); CorrelationIdTracker.setCorrelationId(correlationId); invokeMethod(instance, methodToRun, methodParams); } catch (Exception e) { log.error("Failed to invoke scheduled method {}: {}", methodName, e.getMessage()); log.debug("Exception", e); JobExecutionException jee = new JobExecutionException("failed to execute job"); jee.setStackTrace(e.getStackTrace()); throw jee; } finally { CorrelationIdTracker.setCorrelationId(null); } }
Source:
public void hoverClickAndViewStudentPhotoOnHeading(String panelHeadingIndex, String urlRegex) { String idOfPanelHeading = "panelHeading-" + panelHeadingIndex; waitForElementPresence(By.id(idOfPanelHeading)); WebElement photoDiv = browser.driver.findElement(By.id(idOfPanelHeading)) .findElement(By.className("profile-pic-icon-hover")); executeScript("arguments[0].scrollIntoView(true);", photoDiv); Actions actions = new Actions(browser.driver); actions.moveToElement(photoDiv).perform(); waitForElementPresence(By.cssSelector(".popover-content")); executeScript("document.getElementsByClassName('popover-content')[0]" + ".getElementsByTagName('a')[0].click();"); waitForElementPresence(By.cssSelector(".popover-content > img")); AssertHelper.assertContainsRegex(urlRegex, browser.driver.findElements(By.cssSelector(".popover-content > img")) .get(0) .getAttribute("src")); executeScript("document.getElementsByClassName('popover')[0].parentNode.removeChild(" + "document.getElementsByClassName('popover')[0])"); }

Target:
public void hoverClickAndViewStudentPhotoOnHeading(String panelHeadingIndex, String urlRegex) { String headingSelector = "#panelHeading-" + panelHeadingIndex; String popoverSelector = headingSelector + " .popover-content"; moveToElement(By.cssSelector(headingSelector + " .profile-pic-icon-hover")); waitForElementPresence(By.cssSelector(popoverSelector + " > a")).click(); String imgSrc = getElementSrcWithRetryAfterWaitForPresence(By.cssSelector(popoverSelector + " > img")); AssertHelper.assertContainsRegex(urlRegex, imgSrc); }
Source:
public EventReceiverFirehoseMonitor( EventReceiverFirehoseRegister eventReceiverFirehoseRegister, Properties props ) { this.register = eventReceiverFirehoseRegister; this.dimensions = MonitorsConfig.getDimensions(props); }

Target:
public EventReceiverFirehoseMonitor( EventReceiverFirehoseRegister eventReceiverFirehoseRegister, Properties props ) { this.register = eventReceiverFirehoseRegister; this.dimensions = MonitorsConfig.extractDimensions( props, Lists.newArrayList(DruidMetrics.DATASOURCE, DruidMetrics.TASK_ID) ); }
Source:
public static String[] getMatches(String regExpression, String source) throws TransformationException { if (regExpression == null || source == null) { throw new TransformationException("the given parameters 'regex' and 'source' must not be null"); } logger.debug("about to transform '{}' by the function '{}'", source, regExpression); if (isSubtitution(regExpression)) { Matcher substMatcher = SUBST_PATTERN.matcher(regExpression); if (substMatcher.matches()) { logger.debug("Using substitution form of regex transformation"); String regex = substMatcher.group(1); String substitution = substMatcher.group(2); String options = substMatcher.group(3); String result; if (options.equals("g")) { result = source.trim().replaceAll(regex, substitution); } else { result = source.trim().replaceFirst(regex, substitution); } return new String[] { result }; } } Matcher matcher = getPattern(regExpression).matcher(source.trim()); List<String> results = new ArrayList<String>(); while (matcher.find()) { results.add(matcher.group(1)); } return results.toArray(new String[results.size()]); }

Target:
public static String[] getMatches(String regExpression, String source) throws TransformationException { if (regExpression == null || source == null) { throw new TransformationException("The given parameters 'regExpression' and 'source' must not be null"); } logger.debug("about to transform '{}' by the function '{}'", source, regExpression); if (isSubtitution(regExpression)) { Matcher substMatcher = SUBST_PATTERN.matcher(regExpression); String result = source; if (substMatcher.matches()) { logger.debug("Using substitution form of regex transformation"); String regex = substMatcher.group(1); String substitution = substMatcher.group(2); String options = substMatcher.group(3); if (options.equals("g")) { result = source.trim().replaceAll(regex, substitution); } else { result = source.trim().replaceFirst(regex, substitution); } } return new String[] { result }; } else { Matcher matcher = getPattern(regExpression).matcher(source.trim()); List<String> results = new ArrayList<>(); while (matcher.find()) { results.add(matcher.group(1)); } return results.toArray(new String[results.size()]); } }
Source:
private ConversionUtils() { throw new AssertionError("Must not instantiate an element of this class"); }

Target:
private ConversionUtils() { throw new AssertionError("Must not instantiate this class"); }
Source:
public Response uploadIcon(@ApiParam("The image for stack") Iterator<FileItem> formData, @ApiParam("The stack id") @PathParam("id") String stackId) throws NotFoundException, ServerException, BadRequestException, ForbiddenException { requireNonNullAndNonEmpty(stackId, "Stack id required"); if (formData.hasNext()) { FileItem fileItem = formData.next(); String iconName = fileItem.getName(); try { StackIcon stackIcon = new StackIcon(fileItem.getContentType(), fileItem.get()); StackImpl stack = stackDao.getById(stackId); User user = EnvironmentContext.getCurrent().getUser(); if (!user.isMemberOf("system/admin") && !permissionChecker.hasAccess(stack, user.getId(), "write")) { throw new ForbiddenException(format("User %s doesn't have access to stack %s", stack.getId(), stack.getId())); } stack.setIcon(stackIcon); stackDao.update(stack); } catch (IOException | ConflictException e) { throw new ServerException(format("Failed upload icon %s for stack %s", iconName, stackId), e); } } return Response.ok().build(); }

Target:
public Response uploadIcon(@ApiParam("The image for stack") Iterator<FileItem> formData, @ApiParam("The stack id") @PathParam("id") String stackId) throws NotFoundException, ServerException, BadRequestException, ForbiddenException { requireNonNullAndNonEmpty(stackId, "Stack id required"); if (formData.hasNext()) { FileItem fileItem = formData.next(); String iconName = fileItem.getName(); try { StackIcon stackIcon = new StackIcon(fileItem.getContentType(), fileItem.get()); DecoratedStackImpl stack = stackDao.getById(stackId); User user = EnvironmentContext.getCurrent().getUser(); if (!user.isMemberOf("system/admin") && !permissionChecker.hasAccess(stack, user.getId(), stack.getCreator(), "write")) { throw new ForbiddenException(format("User %s doesn't have access to stack %s", stack.getId(), stack.getId())); } stack.setIcon(stackIcon); stackDao.update(stack); } catch (IOException | ConflictException e) { throw new ServerException(format("Failed upload icon %s for stack %s", iconName, stackId), e); } } return Response.ok().build(); }
Source:
public void setup() throws Exception { Configuration conf = new Configuration(); conf.setClass(S3_CLIENT_FACTORY_IMPL, MockS3ClientFactory.class, S3ClientFactory.class); conf.setClass(S3_METADATA_STORE_IMPL, LocalMetadataStore.class, MetadataStore.class); conf.setBoolean(CommitConstants.MAGIC_COMMITTER_ENABLED, true); conf.setLong(Constants.MULTIPART_SIZE, MULTIPART_MIN_SIZE); fs = new S3AFileSystem(); URI uri = URI.create(FS_S3A + "://" + BUCKET); fs.initialize(uri, conf); s3 = fs.getAmazonS3ClientForTesting("mocking"); }

Target:
public void setup() throws Exception { Configuration conf = createConfiguration(); fs = new S3AFileSystem(); URI uri = URI.create(FS_S3A + "://" + BUCKET); fs.initialize(uri, conf); s3 = fs.getAmazonS3ClientForTesting("mocking"); }
Source:
private DelegatingResourceDescription getBuildCreatableProperties(SimpleObject propertiesToCreate) { DelegatingResourceDescription description = getCreatableProperties(); if (propertiesToCreate.containsKey("uuid")) { description.addProperty("uuid"); } return description; }

Target:
private DelegatingResourceDescription getBuildCreatableProperties(SimpleObject propertiesToCreate) { DelegatingResourceDescription description = getCreatableProperties(); if (propertiesToCreate.containsKey(RestConstants.PROPERTY_UUID)) { description.addProperty(RestConstants.PROPERTY_UUID); } return description; }
Source:
public FileSystem getTestFileSystem() throws IOException { return FileSystem.get(URI.create("sftp://user:password@localhost"), conf); }

Target:
public FileSystem getTestFileSystem() throws IOException { return FileSystem.get(TEST_URI, conf); }
Source:
public Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { if (this.errorMapper == null) { this.errorMapper = errorMapper; } return this; }

Target:
Builder errorMapperIfAbsent(ServiceProviderErrorMapper errorMapper) { if (this.errorMapper == null) { this.errorMapper = errorMapper; } return this; }
Source:
protected @Nullable String getProcessName(@NonNull ITmfEvent event) { String pName = super.getProcessName(event); if (pName == null) { pName = event.getContent().getFieldValue(String.class, "pid"); } if (pName == null) { int processId = getProcessId(event); ITmfTrace trace = event.getTrace(); Iterable<@NonNull ProcessNameAspect> aspects = TmfTraceUtils.getAnalysisModulesOfClass(trace, ProcessNameAspect.class); for (ProcessNameAspect aspect : aspects) { pName = aspect.resolve(event); if (pName != null) { return pName; } } pName = (processId == UNKNOWN_PID) ? UNKNOWN : Integer.toString(processId); } return pName; }

Target:
protected @Nullable String getProcessName(@NonNull ITmfEvent event) { String pName = super.getProcessName(event); if (pName == null) { pName = event.getContent().getFieldValue(String.class, "pid"); } if (pName == null) { int processId = getProcessId(event); pName = (processId == UNKNOWN_PID) ? UNKNOWN : Integer.toString(processId); } return pName; }
Source:
public static UserGroupInformation createSecurityEnabledProxyUser(String userToProxy, Logger log) throws IOException { String filelocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (filelocation == null) { throw new RuntimeException("hadoop token information not set."); } if (!new File(filelocation).exists()) { throw new RuntimeException("hadoop token file doesn't exist."); } log.info("Found token file " + filelocation); log.info("Setting " + HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY + " to " + filelocation); System.setProperty(HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY, filelocation); UserGroupInformation loginUser = null; loginUser = UserGroupInformation.getLoginUser(); log.info("Current logged in user is " + loginUser.getUserName()); log.info("Creating proxy user."); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(userToProxy, loginUser); for (Token<?> token : loginUser.getTokens()) { proxyUser.addToken(token); } return proxyUser; }

Target:
public static UserGroupInformation createSecurityEnabledProxyUser(String userToProxy, Logger log) throws IOException { String filelocation = System.getenv(HADOOP_TOKEN_FILE_LOCATION); if (filelocation == null) { throw new RuntimeException("hadoop token information not set."); } if (!new File(filelocation).exists()) { throw new RuntimeException("hadoop token file doesn't exist."); } log.info("Found token file. Setting " + HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY + " to " + filelocation); System.setProperty(HadoopSecurityManager.MAPREDUCE_JOB_CREDENTIALS_BINARY, filelocation); UserGroupInformation loginUser = null; loginUser = UserGroupInformation.getLoginUser(); log.info("Current logged in user is " + loginUser.getUserName()); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(userToProxy, loginUser); for (Token<?> token : loginUser.getTokens()) { proxyUser.addToken(token); } return proxyUser; }
Source:
private void update() { final Metric metric = serverTiming.start("processUpdate", "Update of OS process list"); try { List<OSProcess> procs = Arrays.asList(os.getProcesses(10, OperatingSystem.ProcessSort.CPU)); for (OSProcess process : procs) { ProcessBean bean = null; if (processList.getItems().size() <= procs.indexOf(process)) { bean = beanManager.create(ProcessBean.class); processList.getItems().add(bean); } else { bean = processList.getItems().get(procs.indexOf(process)); } bean.setProcessID(new Integer(process.getProcessID()).toString()); bean.setCpuPercentage(format.format(100d * (process.getKernelTime() + process.getUserTime()) / process.getUpTime())); bean.setMemoryPercentage(format.format(100d * process.getResidentSetSize() / memory.getTotal())); bean.setName(process.getName()); } asyncServerRunner.execute(new Runnable() { @Override public void run() { sessionExecutor.runLaterInClientSession(() -> update()); } }); } finally { metric.stop(); } }

Target:
private void update() { final Metric metric = serverTiming.start("processUpdate", "Update of OS process list"); try { final List<OSProcess> procs = Arrays.asList(os.getProcesses(10, OperatingSystem.ProcessSort.CPU)); for (final OSProcess process : procs) { ProcessBean bean = null; if (processList.getItems().size() <= procs.indexOf(process)) { bean = beanManager.create(ProcessBean.class); processList.getItems().add(bean); } else { bean = processList.getItems().get(procs.indexOf(process)); } bean.setProcessID(Integer.toString(process.getProcessID())); bean.setCpuPercentage(format.format(100d * (process.getKernelTime() + process.getUserTime()) / process.getUpTime())); bean.setMemoryPercentage(format.format(100d * process.getResidentSetSize() / memory.getTotal())); bean.setName(process.getName()); } asyncServerRunner.execute(() -> sessionExecutor.runLaterInClientSession(this::update)); } finally { metric.stop(); } }
Source:
public String getDescriptiveText(String xmllang) { try { return descriptiveTexts.get(xmllang); } catch (NullPointerException | IllegalArgumentException | ClassCastException e) { return null; } }

Target:
public String getDescriptiveText(String xmllang) { Objects.requireNonNull(xmllang, "xmllang must not be null"); return descriptiveTexts.get(xmllang); }
Source:
private void printSystemViewContent(VisorSystemViewTaskResult taskRes, Logger log) { List<String> colTitles = taskRes.systemViewAttributes(); List<? extends List<?>> sysViewRows = taskRes.systemViewContent(); List<Integer> colLenghts = colTitles.stream().map(String::length).collect(Collectors.toList()); List<List<String>> rows = new ArrayList<>(sysViewRows.size()); sysViewRows.forEach(sysViewRow -> { ListIterator<Integer> colLenIter = colLenghts.listIterator(); rows.add(sysViewRow.stream().map(attr -> { String colVal = String.valueOf(attr); colLenIter.set(Math.max(colLenIter.next(), colVal.length())); return colVal; }).collect(Collectors.toList())); }); printRow(colTitles, nCopies(colTitles.size(), STRING), colLenghts, log); rows.forEach(row -> printRow(row, taskRes.systemViewAttributeTypes(), colLenghts, log)); }

Target:
private void printSystemViewContent(VisorSystemViewTaskResult taskRes, Logger log) { List<String> titles = taskRes.attributes(); List<List<?>> viewRows = taskRes.rows(); List<Integer> colSzs = titles.stream().map(String::length).collect(Collectors.toList()); List<List<String>> rows = new ArrayList<>(viewRows.size()); viewRows.forEach(sysViewRow -> { ListIterator<Integer> colSzIter = colSzs.listIterator(); rows.add(sysViewRow.stream().map(attr -> { String val = String.valueOf(attr); colSzIter.set(Math.max(colSzIter.next(), val.length())); return val; }).collect(Collectors.toList())); }); printRow(titles, nCopies(titles.size(), STRING), colSzs, log); rows.forEach(row -> printRow(row, taskRes.types(), colSzs, log)); }
Source:
private boolean copyData(VmBase source, VmBase dest) { for (Field srcFld : VmBase.class.getDeclaredFields()) { try { if (srcFld.getAnnotation(CopyOnNewVersion.class) != null) { srcFld.setAccessible(true); Field dstFld = VmBase.class.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(dest, srcFld.get(source)); } } catch (Exception exp) { log.error("Failed to copy field '{}' of new version to VM '{}' ({}), error: {}", srcFld.getName(), source.getName(), source.getId(), exp.getMessage()); return false; } } return true; }

Target:
private boolean copyData(VmBase source, VmBase dest) { for (Field srcFld : VmBase.class.getDeclaredFields()) { try { if (srcFld.getAnnotation(CopyOnNewVersion.class) != null) { srcFld.setAccessible(true); Field dstFld = VmBase.class.getDeclaredField(srcFld.getName()); dstFld.setAccessible(true); dstFld.set(dest, srcFld.get(source)); } } catch (Exception exp) { log.error("Failed to copy field '{}' of new version to VM '{}' ({}): {}", srcFld.getName(), source.getName(), source.getId(), exp.getMessage()); log.debug("Exception", exp); return false; } } return true; }
Source:
public List<WorkflowStateDto> list() throws IOException { return workflowManager.listUserWorkflows().stream().map(WorkflowStateDto::new).collect(Collectors.toList()); }

Target:
public List<WorkflowStateDto> list() throws IOException { return workflowManager.listUserWorkflows().stream().map(Dtos::asDto).collect(Collectors.toList()); }
Source:
AccountSummary unmarshallAccountSummary(HibernateAccount hibernateAccount) { StudyIdentifier studyId = null; if (StringUtils.isNotBlank(hibernateAccount.getStudyId())) { studyId = new StudyIdentifierImpl(hibernateAccount.getStudyId()); } Set<String> callerSubstudyIds = BridgeUtils.getRequestContext().getCallerSubstudies(); Set<String> substudyIds = new HashSet<>(); Set<String> externalIds = new HashSet<>(); if (hibernateAccount.getId() != null) { List<HibernateAccountSubstudy> accountSubstudies = hibernateHelper.queryGet( "FROM HibernateAccountSubstudy WHERE accountId=:accountId", ImmutableMap.of("accountId", hibernateAccount.getId()), null, null, HibernateAccountSubstudy.class); for (AccountSubstudy acctSubstudy : accountSubstudies) { if (callerSubstudyIds.isEmpty() || callerSubstudyIds.contains(acctSubstudy.getSubstudyId())) { substudyIds.add(acctSubstudy.getSubstudyId()); if (acctSubstudy.getExternalId() != null) { externalIds.add(acctSubstudy.getExternalId()); } } } } if (hibernateAccount.getExternalId() != null) { externalIds.add(hibernateAccount.getExternalId()); } return new AccountSummary(hibernateAccount.getFirstName(), hibernateAccount.getLastName(), hibernateAccount.getEmail(), hibernateAccount.getPhone(), externalIds, hibernateAccount.getId(), hibernateAccount.getCreatedOn(), hibernateAccount.getStatus(), studyId, substudyIds); }

Target:
AccountSummary unmarshallAccountSummary(HibernateAccount hibernateAccount) { StudyIdentifier studyId = null; if (StringUtils.isNotBlank(hibernateAccount.getStudyId())) { studyId = new StudyIdentifierImpl(hibernateAccount.getStudyId()); } SubstudyAssociations assoc = null; if (hibernateAccount.getId() != null) { List<HibernateAccountSubstudy> accountSubstudies = hibernateHelper.queryGet( "FROM HibernateAccountSubstudy WHERE accountId=:accountId", ImmutableMap.of("accountId", hibernateAccount.getId()), null, null, HibernateAccountSubstudy.class); assoc = BridgeUtils.substudyAssociationsVisibleToCaller(accountSubstudies); } else { assoc = BridgeUtils.substudyAssociationsVisibleToCaller(null); } return new AccountSummary(hibernateAccount.getFirstName(), hibernateAccount.getLastName(), hibernateAccount.getEmail(), hibernateAccount.getPhone(), hibernateAccount.getExternalId(), assoc.getExternalIdsVisibleToCaller(), hibernateAccount.getId(), hibernateAccount.getCreatedOn(), hibernateAccount.getStatus(), studyId, assoc.getSubstudyIdsVisibleToCaller()); }
Source:
private long getPullIndex( File storeDir ) throws IOException { ReadOnlyTransactionIdStore txIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDir ); long lastCleanTxId = txIdStore.getLastCommittedTransactionId(); ReadOnlyTransactionStore txStore = new ReadOnlyTransactionStore( pageCache, fs, storeDir, new Monitors() ); long lastTxId = BASE_TX_ID; try ( Lifespan ignored = new Lifespan( txStore ) ) { try ( TransactionCursor cursor = txStore.getTransactions( lastCleanTxId ) ) { while ( cursor.next() ) { CommittedTransactionRepresentation tx = cursor.get(); lastTxId = tx.getCommitEntry().getTxId(); } if ( lastTxId < lastCleanTxId ) { throw new IllegalStateException( "Metadata index was higher than transaction log index." ); } return lastTxId + 1; } catch ( NoSuchTransactionException e ) { log.info( "No transaction logs found. Will use metadata store as base for pull request." ); return lastCleanTxId; } } }

Target:
private long getPullIndex( File storeDir ) throws IOException { ReadOnlyTransactionIdStore txIdStore = new ReadOnlyTransactionIdStore( pageCache, storeDir ); long lastCleanTxId = txIdStore.getLastCommittedTransactionId(); ReadOnlyTransactionStore txStore = new ReadOnlyTransactionStore( pageCache, fs, storeDir, new Monitors() ); long lastTxId = BASE_TX_ID; try ( Lifespan ignored = new Lifespan( txStore ); TransactionCursor cursor = txStore.getTransactions( lastCleanTxId ) ) { while ( cursor.next() ) { CommittedTransactionRepresentation tx = cursor.get(); lastTxId = tx.getCommitEntry().getTxId(); } if ( lastTxId < lastCleanTxId ) { throw new IllegalStateException( "Metadata index was higher than transaction log index." ); } return lastTxId + 1; } catch ( NoSuchTransactionException e ) { log.info( "No transaction logs found. Will use metadata store as base for pull request." ); return lastCleanTxId; } }
Source:
public String get(Properties properties) { return new org.postgresql.util.ExpressionProperties(properties).getProperty(_name, _defaultValue); }

Target:
public String get(Properties properties) { return properties.getProperty(_name, _defaultValue); }
Source:
protected void map( Writable key, Writable value, Context context ) throws IOException, InterruptedException { try { final InputRow inputRow; try { inputRow = parseInputRow(value, parser); } catch (Exception e) { if (config.isIgnoreInvalidRows()) { log.warn(e, "Ignoring invalid row [%s] due to parsing error", value.toString()); context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER).increment(1); return; } else { throw e; } } if (!granularitySpec.bucketIntervals().isPresent() || granularitySpec.bucketInterval(new DateTime(inputRow.getTimestampFromEpoch())) .isPresent()) { innerMap(inputRow, value, context); } } catch (RuntimeException e) { throw new RE(e, "Failure on row[%s]", value); } }

Target:
protected void map( Writable key, Writable value, Context context ) throws IOException, InterruptedException { try { final InputRow inputRow; try { inputRow = parseInputRow(value, parser); } catch (Exception e) { if (config.isIgnoreInvalidRows()) { log.debug(e, "Ignoring invalid row [%s] due to parsing error", value.toString()); context.getCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER).increment(1); return; } else { throw e; } } if (!granularitySpec.bucketIntervals().isPresent() || granularitySpec.bucketInterval(new DateTime(inputRow.getTimestampFromEpoch())) .isPresent()) { innerMap(inputRow, value, context); } } catch (RuntimeException e) { throw new RE(e, "Failure on row[%s]", value); } }