auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); ResponsePayload responsePayload = new ResponsePayload(); try { byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( decodedNewPassword, "UTF-8")); responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + " was successfully changed."); return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { String errorMsg = "Exception in trying to change the password by username: " + credentials.getUsername(); log.error(errorMsg, e); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Could not change the password."); return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); } catch (UnsupportedEncodingException e) { String errorMsg = "Exception in trying to change the password by username: " + credentials.getUsername(); log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } }

Target:
public static Response buildResetPasswordResponse(UserCredentialWrapper credentials) throws MDMAPIException { UserStoreManager userStoreManager = MDMAPIUtils.getUserStoreManager(); ResponsePayload responsePayload = new ResponsePayload(); try { byte[] decodedNewPassword = Base64.decodeBase64(credentials.getNewPassword()); userStoreManager.updateCredentialByAdmin(credentials.getUsername(), new String( decodedNewPassword, "UTF-8")); responsePayload.setStatusCode(HttpStatus.SC_CREATED); responsePayload.setMessageFromServer("User password by username: " + credentials.getUsername() + " was successfully changed."); return Response.status(HttpStatus.SC_CREATED).entity(responsePayload).build(); } catch (UserStoreException e) { log.error(e.getMessage(), e); responsePayload.setStatusCode(HttpStatus.SC_BAD_REQUEST); responsePayload.setMessageFromServer("Could not change the password."); return Response.status(HttpStatus.SC_BAD_REQUEST).entity(responsePayload).build(); } catch (UnsupportedEncodingException e) { String errorMsg = "Could not change the password of the user: " + credentials.getUsername() + ". The Character Encoding is not supported."; log.error(errorMsg, e); throw new MDMAPIException(errorMsg, e); } }
Source:
public void onAvailabilityChecked(OnAvailabilityChecked event) { if (mRequestedEmail != null && mRequestedEmail.equalsIgnoreCase(event.value)) { if (isInProgress()) { endProgress(); } if (event.isError()) { AppLog.e(T.API, "OnAvailabilityChecked error: " + event.error.type + " - " + event.error.message); showErrorDialog(getString(R.string.signup_email_error_generic)); } else { switch (event.type) { case EMAIL: ActivityUtils.hideKeyboard(getActivity()); if (mLoginListener != null) { if (event.isAvailable) { mLoginListener.showSignupMagicLink(event.value); } else { mAnalyticsListener.trackAnalyticsSignIn(mAccountStore, mSiteStore, true); mLoginListener.showSignupToLoginMessage(); mLoginListener.gotWpcomEmail(event.value); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); } } break; default: AppLog.e(T.API, "OnAvailabilityChecked unhandled event: " + event.error.type); break; } } } }

Target:
public void onAvailabilityChecked(OnAvailabilityChecked event) { if (mRequestedEmail != null && mRequestedEmail.equalsIgnoreCase(event.value)) { if (isInProgress()) { endProgress(); } if (event.isError()) { AppLog.e(T.API, "OnAvailabilityChecked error: " + event.error.type + " - " + event.error.message); showErrorDialog(getString(R.string.signup_email_error_generic)); } else { switch (event.type) { case EMAIL: ActivityUtils.hideKeyboard(getActivity()); if (mLoginListener != null) { if (event.isAvailable) { mLoginListener.showSignupMagicLink(event.value); } else { mAnalyticsListener.trackSignupEmailToLogin(); mLoginListener.showSignupToLoginMessage(); mLoginListener.gotWpcomEmail(event.value); mDispatcher.unregister(this); getActivity().getSupportFragmentManager().beginTransaction().remove(this).commit(); } } break; default: AppLog.e(T.API, "OnAvailabilityChecked unhandled event: " + event.error.type); break; } } } }
Source:
public void testH2Text() throws Exception { int duration = 20 * 1000; final int keyCnt = 5000; final int logFreq = 50; final String txt = "Value"; final int limit = 1000; final GridCacheAdapter<Integer, H2TextValue> c = ((IgniteKernal)grid(0)).internalCache(DEFAULT_CACHE_NAME); IgniteInternalFuture<?> fut1 = multithreadedAsync(new Callable() { @Override public Object call() throws Exception { for (int i = 0; i < keyCnt; i++) { c.getAndPut(i, new H2TextValue(txt)); if (i % logFreq == 0) X.println("Stored values: " + i); } return null; } }, 1); final CacheQuery<Map.Entry<Integer, H2TextValue>> qry = c.context().queries().createFullTextQuery( H2TextValue.class.getName(), txt, limit, false); qry.enableDedup(false); qry.includeBackups(false); qry.timeout(TEST_TIMEOUT); final AtomicBoolean stop = new AtomicBoolean(); IgniteInternalFuture<?> fut2 = multithreadedAsync(new Callable() { @Override public Object call() throws Exception { int cnt = 0; while (!stop.get()) { CacheQueryFuture<Map.Entry<Integer, H2TextValue>> qryFut = qry.execute(); int size = 0; while(qryFut.next() != null) size++; cnt++; if (cnt % logFreq == 0) { X.println("Result set: " + size); X.println("Executed queries: " + cnt); } } return null; } }, 1); Thread.sleep(duration); fut1.get(); stop.set(true); fut2.get(); }

Target:
public void testH2Text() throws Exception { int duration = 20 * 1000; final int keyCnt = 5000; final int logFreq = 50; final String txt = "Value"; final int limit = 0; final GridCacheAdapter<Integer, H2TextValue> c = ((IgniteKernal)grid(0)).internalCache(DEFAULT_CACHE_NAME); IgniteInternalFuture<?> fut1 = multithreadedAsync(new Callable() { @Override public Object call() throws Exception { for (int i = 0; i < keyCnt; i++) { c.getAndPut(i, new H2TextValue(txt)); if (i % logFreq == 0) X.println("Stored values: " + i); } return null; } }, 1); final CacheQuery<Map.Entry<Integer, H2TextValue>> qry = c.context().queries().createFullTextQuery( H2TextValue.class.getName(), txt, limit, false); qry.enableDedup(false); qry.includeBackups(false); qry.timeout(TEST_TIMEOUT); final AtomicBoolean stop = new AtomicBoolean(); IgniteInternalFuture<?> fut2 = multithreadedAsync(new Callable() { @Override public Object call() throws Exception { int cnt = 0; while (!stop.get()) { CacheQueryFuture<Map.Entry<Integer, H2TextValue>> qryFut = qry.execute(); int size = 0; while(qryFut.next() != null) size++; cnt++; if (cnt % logFreq == 0) { X.println("Result set: " + size); X.println("Executed queries: " + cnt); } } return null; } }, 1); Thread.sleep(duration); fut1.get(); stop.set(true); fut2.get(); }
Source:
final public List<IDecoration> setDecorationsNode(List<IPapyrusDecoration> pDecorations, int margin, boolean isVolatile) { decorations = new BasicEList<IDecoration>(); for (IPapyrusDecoration pDecoration : pDecorations) { Image image = addDecorationNode(pDecoration, margin, isVolatile); if (image != null) { margin += image.getBounds().width; } } return decorations; }

Target:
final public List<IDecoration> setDecorationsNode(List<IPapyrusDecoration> pDecorations, int margin, boolean isVolatile) { decorations.clear(); for (IPapyrusDecoration pDecoration : pDecorations) { Image image = addDecorationNode(pDecoration, margin, isVolatile); if (image != null) { margin += image.getBounds().width; } } return decorations; }
Source:
protected String adjustPayloadBeforeSavingResource(ResourceManager mgr, CommandContext context, File f, String payload) { payload = adjustPayloadBeforeSavingResource(mgr, context, f, payload); if (removeRolesAndPermissionsDuringDeployment) { if (resourceMapper == null) { API api = new API(context.getManageClient(), context.getAdminManager()); resourceMapper = new DefaultResourceMapper(api); } Role role = resourceMapper.readResource(payload, Role.class); role.clearPermissionsAndRoles(); return role.getJson(); } return payload; }

Target:
protected String adjustPayloadBeforeSavingResource(ResourceManager mgr, CommandContext context, File f, String payload) { payload = super.adjustPayloadBeforeSavingResource(mgr, context, f, payload); if (removeRolesAndPermissionsDuringDeployment) { if (resourceMapper == null) { API api = new API(context.getManageClient(), context.getAdminManager()); resourceMapper = new DefaultResourceMapper(api); } Role role = resourceMapper.readResource(payload, Role.class); role.clearPermissionsAndRoles(); return role.getJson(); } return payload; }
Source:
private List<Workflow> createServicesAndVersionsFromDockstoreYml(Service12 service, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { final List<Workflow> updatedServices = new ArrayList<>(); if (service != null) { final Path gitRefPath = Path.of(gitReference); final List<String> filters = service.getFilter(); Boolean isFiltered = !filters.isEmpty(); for (String filter : filters) { final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:**/" + filter); if (pathMatcher.matches(gitRefPath)) { isFiltered = false; break; } } if (isFiltered) { return updatedServices; } final DescriptorLanguageSubclass subclass = service.getSubclass(); Workflow workflow = createOrGetWorkflow(Service.class, repository, user, "", subclass.getShortName(), gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedServices.add(workflow); } return updatedServices; }

Target:
private List<Workflow> createServicesAndVersionsFromDockstoreYml(Service12 service, String repository, String gitReference, GitHubSourceCodeRepo gitHubSourceCodeRepo, User user, final SourceFile dockstoreYml) { final List<Workflow> updatedServices = new ArrayList<>(); if (service != null) { if (!DockstoreYamlHelper.filterGitReference(Path.of(gitReference), service.getFilters())) { return updatedServices; } final DescriptorLanguageSubclass subclass = service.getSubclass(); Workflow workflow = createOrGetWorkflow(Service.class, repository, user, "", subclass.getShortName(), gitHubSourceCodeRepo); workflow = addDockstoreYmlVersionToWorkflow(repository, gitReference, dockstoreYml, gitHubSourceCodeRepo, workflow); updatedServices.add(workflow); } return updatedServices; }
Source:
public Long getMegaByteMillis(Configuration jobConf) { if (jobConf == null) { throw new ProcessingException("JobConf is null, cannot calculate megabytemillis"); } Long Xmx75 = getXmxValue(jobConf.get(Constants.JAVA_CHILD_OPTS_CONF_KEY)); if (Xmx75 == 0L) { LOG.error("Xmx value is 0? check why"); throw new ProcessingException("Xmx value is 0! " + jobConf.get(Constants.JAVA_CHILD_OPTS_CONF_KEY)); } Long XmxTotal = getXmxTotal(Xmx75); Long mapSlotMillis = jobHistoryListener.getMapSlotMillis(); Long reduceSlotMillis = jobHistoryListener.getReduceSlotMillis(); LOG.trace("For " + jobKey.toString() + " \n Xmx " + XmxTotal + " " + ": " + mapSlotMillis + " \n " + ": " + reduceSlotMillis + " \n "); Long mbMillis = XmxTotal * mapSlotMillis + XmxTotal * reduceSlotMillis; return mbMillis; }

Target:
public Long getMegaByteMillis(Configuration jobConf) { if (jobHistoryListener == null ) { LOG.error("Cannot call getMegaByteMillis before parsing the history file!"); return Constants.NOTFOUND_VALUE; } Long mapSlotMillis = jobHistoryListener.getMapSlotMillis(); Long reduceSlotMillis = jobHistoryListener.getReduceSlotMillis(); if (mapSlotMillis == Constants.NOTFOUND_VALUE || reduceSlotMillis == Constants.NOTFOUND_VALUE) { throw new ProcessingException("Cannot calculate megabytemillis " + " since mapSlotMillis " + mapSlotMillis + " or reduceSlotMillis " + reduceSlotMillis + " not found!"); } if (jobConf == null) { throw new ProcessingException("JobConf is null, cannot calculate megabytemillis"); } Long xmx75 = getXmxValue(jobConf.get(Constants.JAVA_CHILD_OPTS_CONF_KEY)); if (xmx75 == 0L) { xmx75 = Constants.DEFAULT_XMX_SETTING; LOG.info("Xmx value is 0, now presuming default Xmx size " + Constants.DEFAULT_XMX_SETTING); } Long xmxTotal = getXmxTotal(xmx75); LOG.trace("\n Xmx " + xmxTotal + ": " + mapSlotMillis + " \n " + ": " + reduceSlotMillis + " \n "); Long mbMillis = xmxTotal * mapSlotMillis + xmxTotal * reduceSlotMillis; return mbMillis; }
Source:
Pair<Long, SortedMap<String, Long>> getValidDataSizeBySegment(TimeRange timeRange) { TreeMap<String, Long> map = new TreeMap<>(); long lastBucketEndTime = processTimeRange(timeRange); if (lastBucketEndTime != -1) { synchronized (swapLock) { for (String segmentName : segmentMap.keySet()) { map.put(segmentName, extractValidDataSize(segmentMap, segmentBuckets, segmentName, lastBucketEndTime)); } } return new Pair<>(lastBucketEndTime / time.MsPerSec, map); } else { return new Pair<>(-1L, map); } }

Target:
public Pair<Long, SortedMap<String, Long>> getValidDataSizeBySegment(TimeRange timeRange) { checkForInitialScan(); SortedMap<String, Long> map; Long lastBucketEndTime = processTimeRange(timeRange); if (lastBucketEndTime != -1) { synchronized (swapLock) { map = scanResults.getValidDataSizePerSegment(lastBucketEndTime); } return new Pair<>(lastBucketEndTime / Time.MsPerSec, map); } else { return outOfBoundValidDataSizeBySegmentRequest(timeRange); } }
Source:
private void updateConfig(AliasedDiscoveryConfig config, Node node) { NamedNodeMap attributes = node.getAttributes(); for (int a = 0; a < attributes.getLength(); a++) { Node att = attributes.item(a); String value = getTextContent(att).trim(); if ("enabled".equals(lowerCaseInternal(att.getNodeName()))) { config.setEnabled(getBooleanValue(value)); } else if (att.getNodeName().equals("connection-timeout-seconds")) { config.setProperty("connection-timeout-seconds", value); } } LowercaseHandler lowerCaseHandler = new LowercaseHandler(); for (Node n : childElements(node)) { lowerCaseHandler.put(n.getLocalName(), "eureka".equals(n.getParentNode().getLocalName())); String key = cleanNodeName(n); String value = getTextContent(n).trim(); String normalKey = lowerCaseHandler.get(key); if(normalKey != null) { config.setProperty(normalKey, value); } else { config.setProperty(key, value); } } }

Target:
private void updateConfig(AliasedDiscoveryConfig config, Node node) { NamedNodeMap attributes = node.getAttributes(); for (int a = 0; a < attributes.getLength(); a++) { Node att = attributes.item(a); String value = getTextContent(att).trim(); if ("enabled".equals(lowerCaseInternal(att.getNodeName()))) { config.setEnabled(getBooleanValue(value)); } else if (att.getNodeName().equals("connection-timeout-seconds")) { config.setProperty("connection-timeout-seconds", value); } } for (Node n : childElements(node)) { String key = cleanNodeName(n, !"eureka".equals(n.getParentNode().getLocalName())); String value = getTextContent(n).trim(); config.setProperty(key, value); } }
Source:
public void withSaveFilesBeforeCommand(final Command command, final Command cancelCommand, String commandSource) { if (userPrefs_.saveFilesBeforeBuild().getValue()) { saveUnsavedDocuments(command); } else { String alwaysSaveOption = !userPrefs_.saveFilesBeforeBuild().getValue() ? "Always save files before build" : null; ArrayList<UnsavedChangesTarget> unsavedSourceDocs = getUnsavedChanges(TYPE_FILE_BACKED); if (unsavedSourceDocs.size() > 0) { new UnsavedChangesDialog( commandSource, alwaysSaveOption, unsavedSourceDocs, new OperationWithInput<UnsavedChangesDialog.Result>() { public void execute(UnsavedChangesDialog.Result result) { if (result.getAlwaysSave()) { userPrefs_.saveFilesBeforeBuild().setGlobalValue(true); userPrefs_.writeUserPrefs(); } handleUnsavedChangesBeforeExit( result.getSaveTargets(), command); } }, cancelCommand ).showModal(); } else { command.execute(); } } }

Target:
public void withSaveFilesBeforeCommand(final Command command, final Command cancelCommand, String commandSource) { if (userPrefs_.saveFilesBeforeBuild().getValue()) { saveUnsavedDocuments(command); } else { String alwaysSaveOption = !userPrefs_.saveFilesBeforeBuild().getValue() ? "Always save files before build" : null; ArrayList<UnsavedChangesTarget> unsavedSourceDocs = getUnsavedChanges(TYPE_FILE_BACKED); if (unsavedSourceDocs.size() > 0) { new UnsavedChangesDialog( commandSource, alwaysSaveOption, unsavedSourceDocs, dialogResult -> { if (dialogResult.getAlwaysSave()) { userPrefs_.saveFilesBeforeBuild().setGlobalValue(true); userPrefs_.writeUserPrefs(); } handleUnsavedChangesBeforeExit( dialogResult.getSaveTargets(), command); }, cancelCommand ).showModal(); } else { command.execute(); } } }
Source:
ResponseOutput(String responseId, String giver, String giverTeam, String relatedGiverEmail, String giverSection, String recipient, String recipientTeam, String recipientSection, FeedbackResponseDetails responseDetails, CommentOutput participantComment, List<CommentOutput> instructorComments) { this.responseId = responseId; this.giver = giver; this.relatedGiverEmail = relatedGiverEmail; this.giverTeam = giverTeam; this.giverSection = giverSection; this.recipient = recipient; this.recipientTeam = recipientTeam; this.recipientSection = recipientSection; this.responseDetails = responseDetails; this.participantComment = null; this.participantComment = participantComment; this.instructorComments = instructorComments; }

Target:
ResponseOutput(String responseId, String giver, String giverTeam, String relatedGiverEmail, String giverSection, String recipient, String recipientTeam, String recipientSection, FeedbackResponseDetails responseDetails, CommentOutput participantComment, List<CommentOutput> instructorComments) { this.responseId = responseId; this.giver = giver; this.relatedGiverEmail = relatedGiverEmail; this.giverTeam = giverTeam; this.giverSection = giverSection; this.recipient = recipient; this.recipientTeam = recipientTeam; this.recipientSection = recipientSection; this.responseDetails = responseDetails; this.participantComment = participantComment; this.instructorComments = instructorComments; }
Source:
public String publishRequest(String text) { return text.trim(); }

Target:
public String publishRequest(String text) { return text; }
Source:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { } catch (Exception e) { LOGGER.error(e.getMessage(), e); } }

Target:
public final void run() { try (CloseableRestResponse response = artifactResolver.get(url)) { } catch (Exception e) { logger.error(e.getMessage(), e); } }
Source:
private Map<String, SourceFile> processOtherImports(String repositoryId, String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface, String workingDirectoryForFile) { Map<String, SourceFile> imports = new HashMap<>(); Pattern p = Pattern.compile("include.+?from.+?'.+?'", Pattern.DOTALL); Matcher m = p.matcher(content); while (m.find()) { String path = getRelativeImportPathFromLine(m.group(), workingDirectoryForFile); String absoluteImportPath = convertRelativePathToAbsolutePath(workingDirectoryForFile, path); handleImport(repositoryId, version, imports, path, sourceCodeRepoInterface, absoluteImportPath); } Map<String, SourceFile> recursiveImports = new HashMap<>(); for (Map.Entry<String, SourceFile> importFile : imports.entrySet()) { final Map<String, SourceFile> sourceFiles = processOtherImports(repositoryId, importFile.getValue().getContent(), version, sourceCodeRepoInterface, importFile.getKey()); recursiveImports.putAll(sourceFiles); } recursiveImports.putAll(imports); return recursiveImports; }

Target:
private Map<String, SourceFile> processOtherImports(String repositoryId, String content, Version version, SourceCodeRepoInterface sourceCodeRepoInterface, String workingDirectoryForFile) { Map<String, SourceFile> imports = new HashMap<>(); Matcher m = IMPORT_PATTERN.matcher(content); while (m.find()) { String path = getRelativeImportPathFromLine(m.group(), workingDirectoryForFile); String absoluteImportPath = convertRelativePathToAbsolutePath(workingDirectoryForFile, path); handleImport(repositoryId, version, imports, path, sourceCodeRepoInterface, absoluteImportPath); } Map<String, SourceFile> recursiveImports = new HashMap<>(); for (Map.Entry<String, SourceFile> importFile : imports.entrySet()) { final Map<String, SourceFile> sourceFiles = processOtherImports(repositoryId, importFile.getValue().getContent(), version, sourceCodeRepoInterface, importFile.getKey()); recursiveImports.putAll(sourceFiles); } recursiveImports.putAll(imports); return recursiveImports; }
Source:
protected final void unloadModuleLocal(Module module) throws SecurityException { unloadModuleLocal(null, module); }

Target:
protected final void unloadModuleLocal(Module module) throws SecurityException { if (module == null) { throw new NullPointerException("Module parameter cannot be null"); } unloadModuleLocal(module.getName(), module); }
Source:
public void testGetSetFileSecurityNoSACL() throws Exception { int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; int memSize = 64 * 1024; Memory memorySecurity = new Memory(memSize); IntByReference sizeNeeded = new IntByReference(0); File file = createTempFile(); String filePath = file.getAbsolutePath(); try { assertEquals("GetFileSecurity(" + filePath + ")", true, Advapi32.INSTANCE.GetFileSecurity( filePath, infoType, memorySecurity, memSize, sizeNeeded)); assertEquals("SetFileSecurity(" + filePath + ")", true, Advapi32.INSTANCE.SetFileSecurity( filePath, infoType, memorySecurity.getPointer(0))); } finally { file.delete(); } }

Target:
public void testGetSetFileSecurityNoSACL() throws Exception { int infoType = OWNER_SECURITY_INFORMATION | GROUP_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION; int memSize = 64 * 1024; Memory memorySecurity = new Memory(memSize); IntByReference sizeNeeded = new IntByReference(0); File file = createTempFile(); String filePath = file.getAbsolutePath(); try { assertEquals("GetFileSecurity(" + filePath + ")", true, Advapi32.INSTANCE.GetFileSecurity( filePath, infoType, memorySecurity, memSize, sizeNeeded)); assertEquals("SetFileSecurity(" + filePath + ")", true, Advapi32.INSTANCE.SetFileSecurity( filePath, infoType, memorySecurity)); } finally { file.delete(); } }
Source:
InjectorConfig(InjectorRunner runner) { modules = Collections.unmodifiableList(new ArrayList<Module>(runner.getModules())); name = runner.getInjectorName(); path = runner.getInjectorPath(); parentName = runner.getParentName(); basePackage = runner.getBasePackage(); bundleFilter = runner.getBundleNameFilter(); }

Target:
InjectorConfig(InjectorRunner runner) { modules = Collections.unmodifiableList(new ArrayList<Module>(runner.getModules())); name = runner.getInjectorName(); applicationPath = StringUtils.defaultIfEmpty(runner.getApplicationPath(), DEFAULT_INJECTOR_PATH + name); parentName = runner.getParentName(); basePackage = runner.getBasePackage(); bundleFilter = runner.getBundleNameFilter(); }
Source:
protected Predicate<? super Entity> getEntityFilter() { return getConfig(ENTITY_FILTER); }

Target:
public Predicate<? super Entity> getEntityFilter() { return getConfig(ENTITY_FILTER); }
Source:
private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { List<Device> listCopy = new ArrayList<Device>(mDevices.size()); listCopy.addAll(mDevices); for (Device device : listCopy) { removeDevice(device); mServer.deviceDisconnected(device); } } } } } }

Target:
private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { while (!mDevices.isEmpty()) { Device device = mDevices.remove(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } }
Source:
public boolean isFinished() { boolean finished = (this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null) || isLookupSourceEmpty(); if (finished) { close(); } return finished; }

Target:
public boolean isFinished() { boolean finished = this.finished && probe == null && pageBuilder.isEmpty() && outputPage == null; if (finished) { close(); } return finished; }
Source:
public static String getUsernameAsString(CloudTrailEvent cloudTrailEvent) { if (cloudTrailEvent == null || cloudTrailEvent.getEventData() == null) { return null; } return cloudTrailEvent.getEventData().getUserIdentity().getARN(); }

Target:
public static String getUsernameAsString(CloudTrailEvent cloudTrailEvent) { return ofNullable(cloudTrailEvent) .map(CloudTrailEvent::getEventData) .map(CloudTrailEventData::getUserIdentity) .map(UserIdentity::getARN) .orElse(null); }
Source:
protected void onStart() { super.onStart(); getFirebaseRef().addAuthStateListener(new Firebase.AuthStateListener() { @Override public void onAuthStateChanged(AuthData authData) { if (authData != null) { mChosenProvider = SocialProvider.valueOf(authData.getProvider()); if (mDialog != null) mDialog.dismiss(); onFirebaseLogin(authData); } else { onFirebaseLogout(); } } }); }

Target:
protected void onStart() { super.onStart(); mHandler = new TokenAuthHandler() { @Override public void onSuccess(AuthData data) { } @Override public void onUserError(FirebaseError err) { onFirebaseLoginUserError(err); } @Override public void onProviderError(FirebaseError err) { onFirebaseLoginProviderError(err); } }; mFacebookAuthHelper = new FacebookAuthHelper(this, getFirebaseRef(), mHandler); mGoogleAuthHelper = new GoogleAuthHelper(this, getFirebaseRef(), mHandler); mTwitterAuthHelper = new TwitterAuthHelper(this, getFirebaseRef(), mHandler); mPasswordAuthHelper = new PasswordAuthHelper(this, getFirebaseRef(), mHandler); mDialog = new FirebaseLoginDialog(); mDialog .setContext(this) .setRef(getFirebaseRef()) .setHandler(mHandler); mDialog .setProviderEnabled(SocialProvider.facebook) .setProviderEnabled(SocialProvider.google) .setProviderEnabled(SocialProvider.twitter) .setProviderEnabled(SocialProvider.password); getFirebaseRef().addAuthStateListener(new Firebase.AuthStateListener() { @Override public void onAuthStateChanged(AuthData authData) { if (authData != null) { mChosenProvider = SocialProvider.valueOf(authData.getProvider()); onFirebaseLoginSuccess(authData); Log.d(TAG, "Auth data changed"); } else { onFirebaseLogout(); } } }); }
Source:
public String toString() { return "NamedKey{" + "namespace='" + namespace + '\'' + ", key=" + new String(key) + '}'; }

Target:
public String toString() { return "NamedKey{" + "namespace='" + namespace + '\'' + ", key size=" + key.length + '}'; }
Source:
public void setUpBeforeEveryMethod() throws Exception { this.perun = (PerunBlImpl)super.perun; extSourceManagerBlBackup = perun.getExtSourcesManagerBl(); groupsManagerBl = perun.getGroupsManagerBl(); extSourceManagerBl = perun.getExtSourcesManagerBl(); attributesManagerBl = perun.getAttributesManagerBl(); vo = setUpVo(); setUpBaseGroup(vo); MockitoAnnotations.initMocks(this); doReturn(essa).when(extSourceManagerBl).getExtSourceByName(any(PerunSession.class), any(String.class)); doNothing().when(extSourceManagerBl).addExtSource(any(PerunSession.class), any(Group.class), any(ExtSource.class)); }

Target:
public void setUpBeforeEveryMethod() throws Exception { this.perun = (PerunBlImpl)super.perun; extSourceManagerBlBackup = perun.getExtSourcesManagerBl(); groupsManagerBl = perun.getGroupsManagerBl(); extSourceManagerBl = perun.getExtSourcesManagerBl(); attributesManagerBl = perun.getAttributesManagerBl(); vo = setUpVo(); setUpBaseGroup(vo); MockitoAnnotations.initMocks(this); doReturn(essa).when(extSourceManagerBl).getExtSourceByName(any(PerunSession.class), any(String.class)); doReturn(EXT_SOURCE_NAME).when((ExtSourceLdap)essa).getName(); doNothing().when(extSourceManagerBl).addExtSource(any(PerunSession.class), any(Group.class), any(ExtSource.class)); }
Source:
protected Object findRootObject(ActionInvocation invocation) { ValueStack stack = invocation.getStack(); Object rootObject; if (this.root != null) { LOG.debug("Root was defined as [{}], searching stack for it", this.root); rootObject = stack.findValue(root); } else { LOG.debug("Root was not defined, searching for #action"); rootObject = stack.findValue("#action"); if (rootObject instanceof ModelDriven) { LOG.debug("Action is an instance of ModelDriven, assuming model is on the top of the stack and using it"); rootObject = stack.peek(); } if (rootObject == null) { LOG.debug("Neither #action nor ModelDriven, peeking up object from top of the stack"); rootObject = stack.peek(); } } return rootObject; }

Target:
protected Object findRootObject(ActionInvocation invocation) { ValueStack stack = invocation.getStack(); Object rootObject; if (this.root != null) { LOG.debug("Root was defined as [{}], searching stack for it", this.root); rootObject = stack.findValue(root); } else { LOG.debug("Root was not defined, searching for #action"); rootObject = stack.findValue("#action"); if (rootObject instanceof ModelDriven) { LOG.debug("Action is an instance of ModelDriven, assuming model is on the top of the stack and using it"); rootObject = stack.peek(); } else if (rootObject == null) { LOG.debug("Neither #action nor ModelDriven, peeking up object from the top of the stack"); rootObject = stack.peek(); } } return rootObject; }
Source:
public String getPasswordValue(Object o) { if (o==null) return null; if (o instanceof Secret) { StaplerRequest req = Stapler.getCurrentRequest(); if (req != null) { Item item = req.findAncestorObject(Item.class); if (item != null && !item.hasPermission(Item.CONFIGURE)) { return "********"; } Computer computer = req.findAncestorObject(Computer.class); if (computer != null && !computer.hasPermission(Computer.CONFIGURE)) { return "********"; } } return ((Secret) o).getEncryptedValue(); } if (getIsUnitTest() && !o.equals(PasswordParameterDefinition.DEFAULT_VALUE)) { throw new SecurityException("attempted to render plaintext ‘" + o + "’ in password field; use a getter of type Secret instead"); } return o.toString(); }

Target:
public String getPasswordValue(Object o) { if (o == null) { return null; } if (o.equals(PasswordParameterDefinition.DEFAULT_VALUE)) { return o.toString(); } StaplerRequest req = Stapler.getCurrentRequest(); if (o instanceof Secret || Secret.BLANK_NONSECRET_PASSWORD_FIELDS_WITHOUT_ITEM_CONFIGURE) { if (req != null) { Item item = req.findAncestorObject(Item.class); if (item != null && !item.hasPermission(Item.CONFIGURE)) { return "********"; } Computer computer = req.findAncestorObject(Computer.class); if (computer != null && !computer.hasPermission(Computer.CONFIGURE)) { return "********"; } } } if (o instanceof Secret) { return ((Secret) o).getEncryptedValue(); } if (req != null && (Boolean.getBoolean("hudson.hpi.run") || Boolean.getBoolean("hudson.Main.development"))) { LOGGER.log(Level.WARNING, () -> "<f:password/> form control in " + getJellyViewsInformationForCurrentRequest() + " is not backed by hudson.util.Secret. Learn more: <LINK_0>"); } if (!Secret.AUTO_ENCRYPT_PASSWORD_CONTROL) { return o.toString(); } return Secret.fromString(o.toString()).getEncryptedValue(); }
Source:
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { TypedQuery<String> query = em.createNamedQuery("searchClientsByClientId", String.class); if (firstResult != null && firstResult > 0) { query.setFirstResult(firstResult); } if (maxResults != null && maxResults > 0) { query.setMaxResults(maxResults); } query.setParameter("clientId", clientId); query.setParameter("realm", realm.getId()); List<String> results = query.getResultList(); if (results.isEmpty()) return null; return results.stream().map(id -> session.realms().getClientById(id, realm)).collect(Collectors.toList()); }

Target:
public List<ClientModel> searchClientsByClientId(String clientId, Integer firstResult, Integer maxResults, RealmModel realm) { TypedQuery<String> query = em.createNamedQuery("searchClientsByClientId", String.class); if (firstResult != null && firstResult > 0) { query.setFirstResult(firstResult); } if (maxResults != null && maxResults > 0) { query.setMaxResults(maxResults); } query.setParameter("clientId", clientId); query.setParameter("realm", realm.getId()); List<String> results = query.getResultList(); if (results.isEmpty()) return Collections.EMPTY_LIST; return results.stream().map(id -> session.realms().getClientById(id, realm)).collect(Collectors.toList()); }
Source:
private OffsetDateTime getExpirationTime(String sharedAccessSignature) { String[] parts = sharedAccessSignature.split("&"); return Arrays.stream(parts) .map(part -> part.split("=")) .filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se")) .findFirst() .map(pair -> pair[1]) .map(expirationTimeStr -> { try { long epochSeconds = Long.parseLong(expirationTimeStr); return new Date(epochSeconds * 1000).toInstant().atOffset(ZoneOffset.UTC); } catch (NumberFormatException exception) { return OffsetDateTime.MAX; } }) .orElse(OffsetDateTime.MAX); }

Target:
private OffsetDateTime getExpirationTime(String sharedAccessSignature) { String[] parts = sharedAccessSignature.split("&"); return Arrays.stream(parts) .map(part -> part.split("=")) .filter(pair -> pair.length == 2 && pair[0].equalsIgnoreCase("se")) .findFirst() .map(pair -> pair[1]) .map(expirationTimeStr -> { try { long epochSeconds = Long.parseLong(expirationTimeStr); return Instant.ofEpochSecond(epochSeconds).atOffset(ZoneOffset.UTC); } catch (NumberFormatException exception) { logger.verbose("Invalid expiration time format in the SAS token: {}. Falling back to max " + "expiration time.", expirationTimeStr); return OffsetDateTime.MAX; } }) .orElse(OffsetDateTime.MAX); }
Source:
public void testFloatingUpwardsEnemyCollision() { Bubble bubble = new Bubble(new Point(0, 0), new Point(0, 0), null); ArrayList<Player> playerList = new ArrayList<Player>(); ArrayList<Unit> unitList = new ArrayList<Unit>(); List<Cell> items = new ArrayList<Cell>(); items.add(Cell.EMPTY); Grid<Cell> cells = new Grid<Cell>(items, 1, 1); Level level = new Level(playerList, unitList, cells); final int TIME_FLOAT_UPWARDS = 50; final Point FLOAT_UP_MOTION = new Point(0, -2); for(int i = 0; i < TIME_FLOAT_UPWARDS; i++) { bubble.tick(level); } assertTrue(bubble.isHit()); assertEquals(bubble.getMotion(), FLOAT_UP_MOTION); Enemy enemy = mock(Enemy.class); enemy.setLocation(bubble.getLocation()); assertEquals(bubble.getContains(), null); }

Target:
public void testFloatingUpwardsEnemyCollision() { Bubble bubble = new Bubble(new Point(0, 0), new Point(0, 0), null); ArrayList<Player> playerList = new ArrayList<Player>(); ArrayList<Unit> unitList = new ArrayList<Unit>(); List<Cell> items = new ArrayList<Cell>(); items.add(Cell.EMPTY); Grid<Cell> cells = new Grid<Cell>(items, 1, 1); Level level = new Level(playerList, unitList, cells); for(int i = 0; i < TIME_FLOAT_UPWARDS; i++) { bubble.tick(level); } assertTrue(bubble.isHit()); assertEquals(bubble.getMotion(), FLOAT_UP_MOTION); Enemy enemy = mock(Enemy.class); enemy.setLocation(bubble.getLocation()); assertEquals(bubble.getContains(), null); }
Source:
public void triggerBlockReport(BlockReportOptions options) throws IOException { checkSuperuserPrivilege(); InetSocketAddress namenodeAddr = options.getNamenodeAddr(); for (BPOfferService bpos : blockPoolManager.getAllNamenodeThreads()) { if (bpos != null) { for (BPServiceActor actor : bpos.getBPServiceActors()) { if (namenodeAddr == null || namenodeAddr.equals(actor.nnAddr)) { actor.triggerBlockReport(options); } } } } }

Target:
public void triggerBlockReport(BlockReportOptions options) throws IOException { checkSuperuserPrivilege(); InetSocketAddress namenodeAddr = options.getNamenodeAddr(); boolean shouldTriggerToAllNn = (namenodeAddr == null); for (BPOfferService bpos : blockPoolManager.getAllNamenodeThreads()) { if (bpos != null) { for (BPServiceActor actor : bpos.getBPServiceActors()) { if (shouldTriggerToAllNn || namenodeAddr.equals(actor.nnAddr)) { actor.triggerBlockReport(options); } } } } }
Source:
public CompletableFuture<Iterable<LedgerEntry>> read(long firstEntry, long lastEntry) { CompletableFuture<Enumeration<LedgerEntry>> counter = new CompletableFuture<>(); asyncReadEntries(firstEntry, lastEntry, new SyncReadCallback(), counter); return counter.thenApply(en-> { return () -> Iterators.forEnumeration(en); }); }

Target:
public CompletableFuture<Iterable<org.apache.bookkeeper.client.api.LedgerEntry>> read(long firstEntry, long lastEntry) { FutureReadResult result = new FutureReadResult(); asyncReadEntries(firstEntry, lastEntry, result, null); return result; }
Source:
public List<KeySlice> get_range_slices(TableReference tableRef, SlicePredicate predicate, KeyRange range, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { ColumnParent colFam = new ColumnParent(AbstractKeyValueService.internalTableName(tableRef)); return client.get_range_slices(colFam, predicate, range, consistency_level); }

Target:
public List<KeySlice> get_range_slices(TableReference tableRef, SlicePredicate predicate, KeyRange range, ConsistencyLevel consistency_level) throws InvalidRequestException, UnavailableException, TimedOutException, TException { ColumnParent colFam = getColumnParent(tableRef); return client.get_range_slices(colFam, predicate, range, consistency_level); }
Source:
public void onInit(FMLInitializationEvent event) { BiomeType biomeType = null; try { biomeType = BiomeType.getType("FAKE"); } catch (NullPointerException npe) { LOGGER.warn("EnumHelper in BiomeType is working incorrectly!", npe); } finally { if (biomeType == null || !biomeType.name().equals("FAKE")) { LOGGER.warn("EnumHelper in BiomeType is working incorrectly!"); } } EnumPlantType plantType = null; if (plantType == null || !plantType.name().equals("FAKE")) { ; } try { plantType = EnumPlantType.getPlantType("FAKE"); } catch (NullPointerException npe) { LOGGER.warn("EnumHelper in EnumPlantType is working incorrectly!", npe); } finally { if (plantType == null || !plantType.name().equals("FAKE")) { LOGGER.warn("EnumHelper in EnumPlantType is working incorrectly!"); } } }

Target:
public void onInit(FMLInitializationEvent event) { BiomeType biomeType = null; try { biomeType = BiomeType.getType("FAKE"); } catch (NullPointerException npe) { logger.warn("EnumHelper in BiomeType is working incorrectly!", npe); } finally { if (biomeType == null || !biomeType.name().equals("FAKE")) { logger.warn("EnumHelper in BiomeType is working incorrectly!"); } } EnumPlantType plantType = null; try { plantType = EnumPlantType.getPlantType("FAKE"); } catch (NullPointerException npe) { logger.warn("EnumHelper in EnumPlantType is working incorrectly!", npe); } finally { if (plantType == null || !plantType.name().equals("FAKE")) { logger.warn("EnumHelper in EnumPlantType is working incorrectly!"); } } }
Source:
public void testJNDIBindingsNoAppName() throws Exception { boolean passed = false; Context ctx = getInitialContext(HOST, PORT); Hello ejb = (Hello) ctx.lookup("ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello"); Assert.assertNotNull("Null object returned for local business interface lookup in the ejb namespace", ejb); Assert.assertTrue("Expected JNDI binding message not found", LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, "ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello")); }

Target:
public void testJNDIBindingsNoAppName() throws Exception { Context ctx = getInitialContext(HOST, PORT); Hello ejb = (Hello) ctx.lookup("ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello"); Assert.assertNotNull("Null object returned for local business interface lookup in the ejb namespace", ejb); Assert.assertTrue("Expected JNDI binding message not found", LoggingUtil.hasLogMessage(managementClient, TEST_HANDLER_NAME, "ejb:/ejb-jndi/Hello!org.jboss.as.test.integration.ejb.jndi.logging.Hello")); }
Source:
public boolean attack(EntityDamageEvent source) { if (invulnerable) { return false; } else { performHurtAnimation((int) source.getFinalDamage()); if(source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); boolean instantKill = damager instanceof Player && ((Player) damager).isCreative(); if (instantKill || getDamage() > 40) { if (linkedEntity != null) { mountEntity(linkedEntity); } if (instantKill && (!hasCustomName())) { kill(); } else { if (level.getGameRules().getBoolean("doEntityDrops")) { this.level.dropItem(this, new ItemBoat()); } close(); } } }else{ if (level.getGameRules().getBoolean("doEntityDrops")) { this.level.dropItem(this, new ItemBoat()); } close(); } } return true; }

Target:
public boolean attack(EntityDamageEvent source) { if (invulnerable) { return false; } else { performHurtAnimation((int) source.getFinalDamage()); if(source instanceof EntityDamageByEntityEvent) { Entity damager = ((EntityDamageByEntityEvent) source).getDamager(); boolean instantKill = damager instanceof Player && ((Player) damager).isCreative(); if (instantKill || getDamage() > 40) { if (linkedEntity != null) { this.mountEntity(linkedEntity); } if (instantKill && (!hasCustomName())) { kill(); } else { if (level.getGameRules().getBoolean("doEntityDrops")) { this.level.dropItem(this, new ItemBoat()); } close(); } } }else{ if (level.getGameRules().getBoolean("doEntityDrops")) { this.level.dropItem(this, new ItemBoat()); } close(); } } return true; }
Source:
public Builder addModifiers(Modifier... modifiers) { this.modifiers.addAll(Arrays.asList(modifiers)); return this; }

Target:
public Builder addModifiers(Modifier... modifiers) { Collections.addAll(this.modifiers, modifiers); return this; }
Source:
public ExchangeClientByteArrayAllocator(ArrayPool<byte[]> pool) { this.pool = pool; }

Target:
public ExchangeClientByteArrayAllocator(ArrayPool<byte[]> pool) { this.pool = requireNonNull(pool, "pool is null"); }
Source:
private File getConnectionSettingsDetectionScript( final String scriptName) { final File script = Activator.getDefault().getBundle() .getDataFile(scriptName); if (script != null && !script.exists()) { try (final FileOutputStream output = new FileOutputStream( scriptName); final InputStream is = DockerConnection.class .getResourceAsStream( "/resources/" + scriptName)) { byte[] buff = new byte[1024]; int n; while ((n = is.read(buff)) > 0) { output.write(buff, 0, n); } script.setExecutable(true); } catch (IOException e) { Activator.logErrorMessage(e.getMessage()); } } return script; }

Target:
private File getConnectionSettingsDetectionScript( final String scriptName) { final File script = Activator.getDefault().getBundle() .getDataFile(scriptName); if (script != null && !script.exists()) { try (final FileOutputStream output = new FileOutputStream( script); final InputStream is = DockerConnection.class .getResourceAsStream( "/resources/" + scriptName)) { byte[] buff = new byte[1024]; int n; while ((n = is.read(buff)) > 0) { output.write(buff, 0, n); } script.setExecutable(true); } catch (IOException e) { Activator.logErrorMessage(e.getMessage()); } } return script; }
Source:
public void compile() throws Exception { for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } try { compiledObjects = compiler.compileAll(); } catch (Exception e) { log.error("Unable to compile dynamic classes in memory "); } }

Target:
private void compile() throws Exception { for (Map.Entry<String, String> tablePojo : tableClasses.entrySet()) { log.debug("key: " + tablePojo.getKey() + ", value: " + tablePojo.getValue()); compiler.addSource(PACKAGE_NAME + tablePojo.getKey(), tablePojo.getValue()); } for (Map.Entry<String, String> secPojo : securityClasses.entrySet()) { log.debug("key: " + secPojo.getKey() + ", value: " + secPojo.getValue()); compiler.addSource(PACKAGE_NAME + secPojo.getKey(), secPojo.getValue()); } compiledObjects = compiler.compileAll(); }
Source:
public FutureAssertion<T> hasValue(T value) throws ExecutionException, InterruptedException { assertEquals(actual.get(), value); return this; }

Target:
public FutureAssertion<T> hasValue(T value) throws ExecutionException, InterruptedException, TimeoutException { assertEquals(actual.get(futureGetTimeoutMs, TimeUnit.MILLISECONDS), value); return this; }
Source:
public void testGroupByStringOutputAsLong() { ExtractionFn strlenFn = StrlenExtractionFn.instance(); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec( QueryRunnerTestHelper.qualityDimension, "alias", ValueType.LONG, strlenFn ))) .setDimFilter(new SelectorDimFilter(QueryRunnerTestHelper.qualityDimension, "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults; if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "alias", "13", "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "alias", "13", "rows", 1L, "idx", 166L ) ); } else { expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "alias", 13L, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "alias", 13L, "rows", 1L, "idx", 166L ) ); } Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }

Target:
public void testGroupByStringOutputAsLong() { if (config.getDefaultStrategy().equals(GroupByStrategySelector.STRATEGY_V1)) { expectedException.expect(UnsupportedOperationException.class); expectedException.expectMessage("GroupBy v1 only supports dimensions with an outputType of STRING."); } ExtractionFn strlenFn = StrlenExtractionFn.instance(); GroupByQuery query = GroupByQuery .builder() .setDataSource(QueryRunnerTestHelper.dataSource) .setQuerySegmentSpec(QueryRunnerTestHelper.firstToThird) .setDimensions(Lists.<DimensionSpec>newArrayList(new ExtractionDimensionSpec( QueryRunnerTestHelper.qualityDimension, "alias", ValueType.LONG, strlenFn ))) .setDimFilter(new SelectorDimFilter(QueryRunnerTestHelper.qualityDimension, "entertainment", null)) .setAggregatorSpecs( Arrays.asList( QueryRunnerTestHelper.rowsCount, new LongSumAggregatorFactory("idx", "index") ) ) .setGranularity(QueryRunnerTestHelper.dayGran) .build(); List<Row> expectedResults = Arrays.asList( GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-01", "alias", 13L, "rows", 1L, "idx", 158L ), GroupByQueryRunnerTestHelper.createExpectedRow( "2011-04-02", "alias", 13L, "rows", 1L, "idx", 166L ) ); Iterable<Row> results = GroupByQueryRunnerTestHelper.runQuery(factory, runner, query); TestHelper.assertExpectedObjects(expectedResults, results, ""); }