auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); if(!sslEnabledColos.contains(replicaId.getDataNodeId().getDatacenterName())) { return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, false); } else { return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest, true); } }

Target:
protected OperationRequest makeOperationRequest(ReplicaId replicaId) { DeleteRequest deleteRequest = new DeleteRequest(context.getCorrelationId(), context.getClientId(), blobId); return new DeleteOperationRequest(connectionPool, responseQueue, context, blobId, replicaId, deleteRequest); }
Source:
public void test_getDisplayThread() { final Display display = new Display (); try { final AtomicBoolean isDisplayThread = new AtomicBoolean (false); display.syncExec (new Runnable () { public void run () { isDisplayThread.set (display.isCurrentThread ()); } }); assertTrue (isDisplayThread.get ()); } finally { display.dispose (); } }

Target:
public void test_getDisplayThread() { final Display display = new Display (); try { final AtomicBoolean isDisplayThread = new AtomicBoolean (false); display.syncExec (new Runnable () { public void run () { isDisplayThread.set (display.isDisplayThread ()); } }); assertTrue (isDisplayThread.get ()); } finally { display.dispose (); } }
Source:
private WorkbenchThemeManager() { defaultThemeColorRegistry = new ColorRegistry(PlatformUI.getWorkbench() .getDisplay()); defaultThemeFontRegistry = new FontRegistry(PlatformUI.getWorkbench() .getDisplay()); FontRegistry jfaceFonts = JFaceResources.getFontRegistry(); for (Iterator i = jfaceFonts.getKeySet().iterator(); i.hasNext();) { String key = (String) i.next(); defaultThemeFontRegistry.put(key, jfaceFonts.getFontData(key)); } String themeId = PrefUtil.getAPIPreferenceStore().getDefaultString(IWorkbenchPreferenceConstants.CURRENT_THEME_ID); if (themeId.length() == 0) themeId = IThemeManager.DEFAULT_THEME; final boolean highContrast = Display.getCurrent().getHighContrast(); Display.getCurrent().addListener(SWT.Settings, new Listener() { public void handleEvent(Event event) { updateThemes(); } }); if (highContrast) themeId = SYSTEM_DEFAULT_THEME; PrefUtil.getAPIPreferenceStore().setDefault( IWorkbenchPreferenceConstants.CURRENT_THEME_ID, themeId); context = (IEclipseContext) Workbench.getInstance().getService(IEclipseContext.class); eventBroker = (IEventBroker) Workbench.getInstance().getService(IEventBroker.class); eventBroker.subscribe(UIEvents.UILifeCycle.CSS_THEME_CHANGED, cssThemeChangedHandler); }

Target:
private WorkbenchThemeManager() { defaultThemeColorRegistry = new ColorRegistry(PlatformUI.getWorkbench() .getDisplay()); defaultThemeFontRegistry = new FontRegistry(PlatformUI.getWorkbench() .getDisplay()); FontRegistry jfaceFonts = JFaceResources.getFontRegistry(); for (Iterator i = jfaceFonts.getKeySet().iterator(); i.hasNext();) { String key = (String) i.next(); defaultThemeFontRegistry.put(key, jfaceFonts.getFontData(key)); } String themeId = PrefUtil.getAPIPreferenceStore().getDefaultString(IWorkbenchPreferenceConstants.CURRENT_THEME_ID); if (themeId.length() == 0) themeId = IThemeManager.DEFAULT_THEME; final boolean highContrast = Display.getCurrent().getHighContrast(); Display.getCurrent().addListener(SWT.Settings, new Listener() { public void handleEvent(Event event) { updateThemes(); } }); if (highContrast) themeId = SYSTEM_DEFAULT_THEME; PrefUtil.getAPIPreferenceStore().setDefault( IWorkbenchPreferenceConstants.CURRENT_THEME_ID, themeId); context = (IEclipseContext) Workbench.getInstance().getService(IEclipseContext.class); eventBroker = (IEventBroker) Workbench.getInstance().getService(IEventBroker.class); if (eventBroker != null) { eventBroker.subscribe(UIEvents.UILifeCycle.THEME_CHANGED, themeChangedHandler); } }
Source:
void testDescribeInstances() { for (String region : ec2Api.getConfiguredRegions()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); assertTrue(allResults.size() >= 0); } }

Target:
void testDescribeInstances() { for (String region : ec2Api.getConfiguredRegions()) { Set<? extends Reservation<? extends RunningInstance>> allResults = client.describeInstancesInRegion(region); assertNotNull(allResults); } }
Source:
protected void initialize() { getInFilter().add("breadcrumbId"); getInFilter().add("org.apache.kafka.clients.producer.RecordMetadata"); setOutFilterPattern("(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*"); setInFilterPattern("(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*"); }

Target:
protected void initialize() { getInFilter().add("org.apache.kafka.clients.producer.RecordMetadata"); setOutFilterPattern("(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*"); setInFilterPattern("(?i)(Camel|org\\.apache\\.camel)[\\.|a-z|A-z|0-9]*"); }
Source:
public void testAccessControl() throws Exception { String iDOfCourseOfStudent = dataBundle.students .get("student1InCourse1").course; String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of same course can access"); verifyAccessibleForStudentsOfTheSameCourse(submissionParams); ______TS("Admin can access to Masquerade as student"); verifyAccessibleForAdminToMasqueradeAsStudent(submissionParams); ______TS("Unaccessible without login"); verifyUnaccessibleWithoutLogin(submissionParams); iDOfCourseOfStudent = dataBundle.students.get("student2InCourse1").course; submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; ______TS("Student of different course can not access"); verifyUnaccessibleForStudentsOfOtherCourses(submissionParams); ______TS("UnregisteredUsers cannot access"); verifyUnaccessibleForUnregisteredUsers(submissionParams); }

Target:
public void testAccessControl() throws Exception { String iDOfCourseOfStudent = dataBundle.students .get("student1InCourse1").course; String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; verifyAccessibleForStudentsOfTheSameCourse(submissionParams); verifyAccessibleForAdminToMasqueradeAsStudent(submissionParams); verifyUnaccessibleWithoutLogin(submissionParams); iDOfCourseOfStudent = dataBundle.students.get("student2InCourse1").course; submissionParams = new String[] { Const.ParamsNames.COURSE_ID, iDOfCourseOfStudent }; verifyUnaccessibleForStudentsOfOtherCourses(submissionParams); verifyUnaccessibleForUnregisteredUsers(submissionParams); }
Source:
private boolean containsRedundantUnwrapAttr(Attribute attribute) { return attribute.getName().equalsIgnoreCase(UNWRAP_ATTRIBUTE_NAME) && StringUtils.isBlank(attribute.getValue()) && getExpressions(attribute.getValue()).isEmpty(); }

Target:
private boolean containsRedundantUnwrapAttr(Attribute attribute) { return UNWRAP_ATTRIBUTE_NAME.equalsIgnoreCase(attribute.getName()) && StringUtils.isBlank(attribute.getValue()) && getExpressions(attribute.getValue()).isEmpty(); }
Source:
public RecoveryMethod(String recoveryMethodName, Method originalMethod, Object[] args, Object target) throws NoSuchMethodException, ClassCastException { Class[] params = originalMethod.getParameterTypes(); Class[] recoveryParams = Arrays.copyOf(params, params.length + 1); recoveryParams[params.length] = Throwable.class; Method recovery = ReflectionUtils.findMethod(target.getClass(), recoveryMethodName, recoveryParams); if (recovery == null) { throw new NoSuchMethodException(String.format("%s.%s(%s)", target.getClass(), recoveryMethodName, StringUtils.arrayToDelimitedString(recoveryParams, ","))); } Class<?> originalReturnType = originalMethod.getReturnType(); if (!originalReturnType.isAssignableFrom(recovery.getReturnType())) { throw new ClassCastException(String.format("recovery return type not matched (expected: %s, actual :%s)", originalReturnType.getName(), recovery.getReturnType().getName())); } this.recovery = recovery; this.args = args; this.target = target; }

Target:
public RecoveryMethod(String recoveryMethodName, Method originalMethod, Object[] args, Object target) throws NoSuchMethodException { Class<?>[] params = originalMethod.getParameterTypes(); Class<?> originalReturnType = originalMethod.getReturnType(); Map<Class<?>, Method> methods = extractMethods(recoveryMethodName, params, originalReturnType, target.getClass()); if (methods.isEmpty()) { throw new NoSuchMethodException(String.format("%s %s.%s(%s,%s)", originalReturnType, target.getClass(), recoveryMethodName, StringUtils.arrayToDelimitedString(params, ","), Throwable.class)); } this.recoveryMethods = methods; this.args = args; this.target = target; this.returnType = originalReturnType; }
Source:
public byte[] getSerialized() { if (serialized == null) { ByteArrayBuilder bab = new ByteArrayBuilder() .append(VERSION_BYTES, VERSION_BYTES_LEN); for (String key : headerMap.keySet()) { for (String value : values(key)) { bab.append(key); bab.append(COLON_BYTES, COLON_BYTES_LEN); bab.append(value); bab.append(CRLF_BYTES, CRLF_BYTES_LEN); } } bab.append(CRLF_BYTES, CRLF_BYTES_LEN); serialized = bab.toByteArray(); } return serialized; }

Target:
public byte[] getSerialized() { if (serialized == null) { ByteArrayBuilder bab = new ByteArrayBuilder(projectedLength + VERSION_BYTES_PLUS_CRLF_LEN) .append(VERSION_BYTES_PLUS_CRLF); for (String key : headerMap.keySet()) { for (String value : values(key)) { bab.append(key); bab.append(COLON_BYTES); bab.append(value); bab.append(CRLF_BYTES); } } bab.append(CRLF_BYTES); serialized = bab.toByteArray(); } return serialized; }
Source:
public static Xpp3Dom getPluginGoalConfig(Plugin plugin, String goal, Log log) { Xpp3Dom config = null; String execId = "default"; int numExec = 0; List<PluginExecution> executions = plugin.getExecutions(); if (executions != null) { for (PluginExecution e : executions) { if (e.getGoals() != null && e.getGoals().contains(goal)) { if (numExec == 0) { config = (Xpp3Dom) e.getConfiguration(); execId = e.getId(); } numExec++; } } if (config == null) { config = (Xpp3Dom) plugin.getConfiguration(); } } else { config = (Xpp3Dom) plugin.getConfiguration(); } if (numExec > 1) { log.warn(plugin.getArtifactId() + ":" + goal + " goal has multiple execution configrations (default to \"" + execId + "\" execution)"); } if (config == null) { config = configuration(); } else { config = Xpp3Dom.mergeXpp3Dom(configuration(), config); config = validateConfiguration(plugin, goal, config, log); } log.debug(plugin.getArtifactId() + ":" + goal + " configuration\n" + config); return config; }

Target:
public static Xpp3Dom getPluginGoalConfig(Plugin plugin, String goal, Log log) { Xpp3Dom config = null; String execId = "default"; int numExec = 0; List<PluginExecution> executions = plugin.getExecutions(); if (executions != null) { for (PluginExecution e : executions) { if (e.getGoals() != null && e.getGoals().contains(goal)) { if (numExec == 0) { config = (Xpp3Dom) e.getConfiguration(); execId = e.getId(); } numExec++; } } if (config == null) { config = (Xpp3Dom) plugin.getConfiguration(); } } else { config = (Xpp3Dom) plugin.getConfiguration(); } if (numExec > 1) { log.warn(plugin.getArtifactId() + ":" + goal + " goal has multiple execution configurations (default to \"" + execId + "\" execution)"); } if (config == null) { config = configuration(); } else { config = Xpp3Dom.mergeXpp3Dom(configuration(), config); config = validateConfiguration(plugin, goal, config, log); } log.debug(plugin.getArtifactId() + ":" + goal + " configuration\n" + config); return config; }
Source:
public UserIdentity identifyUser(String sessionID) throws UserIdentityException { if (StringUtils.isEmpty(sessionID)) { logWarn("identify user error, no auth token was provided").log(); throw new UserIdentityException("user not authenticated", SC_UNAUTHORIZED); } Session session; try { session = sessionServiceSupplier.getService().get(sessionID); } catch (IOException e) { logError(e, "identify user error, unexpected error while attempting to get user session") .sessionID(sessionID) .log(); throw new UserIdentityException("internal server error", SC_INTERNAL_SERVER_ERROR); } if (session == null) { logWarn("identify user error, session with specified ID could not be found") .sessionID(sessionID) .log(); throw new UserIdentityException("user not authenticated", SC_UNAUTHORIZED); } try { if (!userServiceSupplier.getService().exists(session.getEmail())) { logWarn("identify user error, valid user session found but user no longer exists") .session(session) .log(); throw new UserIdentityException("user does not exist", SC_NOT_FOUND); } } catch (IOException e) { logError(e, "identify user error, unexpected error while checking if user exists") .session(session) .log(); throw new UserIdentityException("internal server error", SC_INTERNAL_SERVER_ERROR); } return new UserIdentity(session); }

Target:
public UserIdentity identifyUser(String sessionID) throws UserIdentityException { if (StringUtils.isEmpty(sessionID)) { logWarn("identify user error, no auth token was provided").log(); throw new UserIdentityException(AUTHENTICATED_ERROR, SC_UNAUTHORIZED); } Session session; try { session = sessionServiceSupplier.getService().get(sessionID); } catch (IOException e) { logError(e, "identify user error, unexpected error while attempting to get user session") .sessionID(sessionID) .log(); throw new UserIdentityException(INTERNAL_ERROR, SC_INTERNAL_SERVER_ERROR); } if (session == null) { logWarn("identify user error, session with specified ID could not be found") .sessionID(sessionID) .log(); throw new UserIdentityException(AUTHENTICATED_ERROR, SC_UNAUTHORIZED); } try { if (!userServiceSupplier.getService().exists(session.getEmail())) { logWarn("identify user error, valid user session found but user no longer exists") .session(session) .log(); throw new UserIdentityException(USER_NOT_FOUND, SC_NOT_FOUND); } } catch (IOException e) { logError(e, "identify user error, unexpected error while checking if user exists") .session(session) .log(); throw new UserIdentityException(INTERNAL_ERROR, SC_INTERNAL_SERVER_ERROR); } return new UserIdentity(session); }
Source:
protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); TaskAttribute assignee = getTaskData().getRoot().getAttribute(BugzillaAttribute.SET_DEFAULT_ASSIGNEE.getKey()); if (assignee != null) { attributes.add(assignee); } attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); String useParam = getTaskData().getAttributeMapper() .getTaskRepository() .getProperty(IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT); if (useParam == null || (useParam != null && useParam.equals("true"))) { attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.QA_CONTACT.getKey())); } attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.NEWCC.getKey())); addSelfToCC(attributes); attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.CC.getKey())); for (TaskAttribute attribute : allAttributes.values()) { if (TaskAttribute.TYPE_PERSON.equals(attribute.getMetaData().getType())) { if (!attribute.getId().endsWith("_name") && !attribute.getId().equals(BugzillaAttribute.EXPORTER_NAME.getKey())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } } return attributes; }

Target:
protected Collection<TaskAttribute> getAttributes() { Map<String, TaskAttribute> allAttributes = getTaskData().getRoot().getAttributes(); List<TaskAttribute> attributes = new ArrayList<TaskAttribute>(allAttributes.size()); attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_ASSIGNED)); TaskAttribute assignee = getTaskData().getRoot().getAttribute(BugzillaAttribute.SET_DEFAULT_ASSIGNEE.getKey()); if (assignee != null) { attributes.add(assignee); } attributes.add(getTaskData().getRoot().getMappedAttribute(TaskAttribute.USER_REPORTER)); String useQaContact = getTaskData().getAttributeMapper() .getTaskRepository() .getProperty(IBugzillaConstants.BUGZILLA_PARAM_USEQACONTACT); if (useQaContact == null || Boolean.parseBoolean(useQaContact)) { attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.QA_CONTACT.getKey())); } attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.NEWCC.getKey())); addSelfToCC(attributes); attributes.add(getTaskData().getRoot().getMappedAttribute(BugzillaAttribute.CC.getKey())); for (TaskAttribute attribute : allAttributes.values()) { if (TaskAttribute.TYPE_PERSON.equals(attribute.getMetaData().getType())) { if (!attribute.getId().endsWith("_name") && !attribute.getId().equals(BugzillaAttribute.EXPORTER_NAME.getKey())) { if (!attributes.contains(attribute)) { attributes.add(attribute); } } } } return attributes; }
Source:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; try { if (NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } } catch (NullPointerException ex) { LOG.warn("Could not obtain HCID from HomeCommunity in assertion.", ex); } return homeCommunity; }

Target:
public static String getHomeCommunityIdFromAssertion(AssertionType assertion) { String homeCommunity = null; if (assertion != null && assertion.getHomeCommunity() != null && NullChecker.isNotNullish(assertion.getHomeCommunity().getHomeCommunityId())) { homeCommunity = assertion.getHomeCommunity().getHomeCommunityId(); } return homeCommunity; }
Source:
public void execute(String[] args, ConsoleReader reader) throws Exception { ApplicationReport[] apps; if (args.length == 1) { if (currentApp == null) { throw new CliException("No application selected"); } else { apps = new ApplicationReport[]{currentApp}; } } else { apps = new ApplicationReport[args.length - 1]; for (int i = 1; i < args.length; i++) { ApplicationReport ap = findApplicationReportFromAppNameOrId(args[i]); if (ap == null) { throw new CliException("Streaming application with id or name " + args[i] + " is not found."); } else { apps[i - 1] = ap; } } } for (ApplicationReport app : apps) { try { JSONObject response = getResource(new StramAgent.StramUriSpec().path(StramWebServices.PATH_SHUTDOWN), app, new WebServicesClient.WebServicesHandler<JSONObject>() { @Override public JSONObject process(WebResource.Builder webResource, Class<JSONObject> clazz) { return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject()); } }); if (consolePresent) { System.out.println("Shutdown requested: " + response); } currentApp = null; } catch (Exception e) { throw new CliException("Failed to request shutdown for appid " + app.getApplicationId().toString(), e); } } }

Target:
public void execute(String[] args, ConsoleReader reader) throws Exception { Map<String, ApplicationReport> appIdReports = new LinkedHashMap<>(); if (args.length == 1) { if (currentApp == null) { throw new CliException("No application selected"); } else { appIdReports.put(currentApp.getApplicationId().toString(), currentApp); } } else { String[] appNamesOrIds = Arrays.copyOfRange(args, 1, args.length); for (String appNameOrId : appNamesOrIds) { ApplicationReport ap = findApplicationReportFromAppNameOrId(appNameOrId); appIdReports.put(appNameOrId, ap); } } for (Map.Entry<String, ApplicationReport> entry : appIdReports.entrySet()) { String appNameOrId = entry.getKey(); ApplicationReport app = entry.getValue(); shutdownApp(appNameOrId, app); } }
Source:
public void getVariables() { TestSuiteModel testSuite = new TestSuiteModel(); String variable_indentifier = "variable_indentifier"; String variable_content = "variable_content"; String variable_description = "variable_description"; assertEquals(0, testSuite.getVariables().size()); testSuite.addVariable(variable_indentifier, variable_content, variable_description); assertEquals(1, testSuite.getVariables().size()); }

Target:
public void getVariables() { TestSuiteModel testSuite = new TestSuiteModel(); for (int index = 0; index < elements; index++) { testSuite.setVariable(variableIndentifier[index], variableContent[index], variableDescription[index]); assertEquals(index + 1, testSuite.getVariables().size()); } }
Source:
private static boolean isExternalStorageWritable() { return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); }

Target:
private static boolean isExternalStorageWritable() { return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); }
Source:
private void requestPurchasesForDeletionCheck() { final Blog currentBlog = WordPress.getCurrentBlog(); WordPress.getRestClientUtils().getSitePurchases(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { showPurchasesOrDeleteSiteDialog(response, currentBlog); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { ToastUtils.showToast(getActivity(), getString(R.string.purchases_request_error)); AppLog.e(AppLog.T.API, error.toString()); } }); }

Target:
private void requestPurchasesForDeletionCheck() { final Blog currentBlog = WordPress.getCurrentBlog(); final ProgressDialog progressDialog = ProgressDialog.show(getActivity(), "", getString(R.string.checking_purchases), true, false); WordPress.getRestClientUtils().getSitePurchases(currentBlog.getDotComBlogId(), new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { progressDialog.dismiss(); if (isAdded()) { showPurchasesOrDeleteSiteDialog(response, currentBlog); } } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { progressDialog.dismiss(); if (isAdded()) { ToastUtils.showToast(getActivity(), getString(R.string.purchases_request_error)); AppLog.e(AppLog.T.API, "Error occurred while requesting purchases for deletion check: " + error.toString()); } } }); }
Source:
private boolean areBundlesReady(Set<String> toCheck) { BundleStates states = getUnavailableBundles(toCheck); if (!states.getFailedBundles().isEmpty()) { throw new SynchronizedInstallerException( "Bundles failed to start [" + bundleSymbolicNamesToString(states.getFailedBundles()) + "]"); } if (!states.getUnavailableBundles().isEmpty()) { String unavailableBundles = bundleSymbolicNamesToString(states.getUnavailableBundles()); LOGGER.debug( "Waiting on the following bundles to reach a ready state [{}]", unavailableBundles); return false; } return true; }

Target:
private boolean areBundlesReady(Set<String> toCheck) { BundleStates states = getUnavailableBundles(toCheck); if (!states.getFailedBundles().isEmpty()) { throw new SynchronizedInstallerException( "Bundles failed to start [" + bundleSymbolicNamesToString(states.getFailedBundles()) + "]"); } if (!states.getUnavailableBundles().isEmpty()) { if (LOGGER.isDebugEnabled()) { String unavailableBundles = bundleSymbolicNamesToString(states.getUnavailableBundles()); LOGGER.debug( "Waiting on the following bundles to reach a ready state [{}]", unavailableBundles); } return false; } return true; }
Source:
public static boolean showYesNoDialog(Project project, final String message, final String title) throws IllegalAWTContextException { if (application.isWriteAccessAllowed()) { throw new IllegalAWTContextException("AWT events are not allowed inside write actions."); } LOG.info("Showing yes/no dialog: " + title + " - " + message); final AtomicReference<Integer> response = new AtomicReference<>(); application.invokeAndWait( () -> { Integer option = Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()); response.set(option); }, ModalityState.defaultModalityState()); Integer result = response.get(); if (result == null) { throw new IllegalStateException("Synchronous yes-no dialog did not provide any results"); } switch (result) { case Messages.YES: return true; case Messages.NO: return false; default: throw new IllegalStateException("Encountered unknown dialog answer " + result); } }

Target:
public static boolean showYesNoDialog(Project project, final String message, final String title) throws IllegalAWTContextException { if (application.isWriteAccessAllowed()) { throw new IllegalAWTContextException("AWT events are not allowed inside write actions."); } LOG.info("Showing yes/no dialog: " + title + " - " + message); final AtomicReference<Integer> response = new AtomicReference<>(); application.invokeAndWait( () -> { Integer option = Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon()); response.set(option); }, ModalityState.defaultModalityState()); Integer result = response.get(); switch (result) { case Messages.YES: return true; case Messages.NO: return false; default: throw new IllegalStateException("Encountered unknown dialog answer " + result); } }
Source:
public void anEvent(final int amount, final Map<String, String> data) throws Exception { final Device device = this.deviceRepository .findByDeviceIdentification(getString(data, Keys.KEY_DEVICE_IDENTIFICATION)); for (int i = 0; i < amount; i++) { final Event event = new Event(device, getDateTime(getString(data, Keys.TIMESTAMP, "now")).toDate(), getEnum(data, Keys.EVENT_TYPE, EventType.class, EventType.ALARM_NOTIFICATION), getString(data, Keys.KEY_DESCRIPTION, ""), getInteger(data, Keys.KEY_INDEX, Defaults.DEFAULT_INDEX)); this.eventRepository.save(event); } }

Target:
public void anEvent(final int amount, final Map<String, String> data) throws Exception { final Device device = this.deviceRepository .findByDeviceIdentification(getString(data, Keys.KEY_DEVICE_IDENTIFICATION)); for (int i = 0; i < amount; i++) { final Event event = new Event(device, getDateTime(getString(data, Keys.TIMESTAMP, Defaults.TIMESTAMP)).toDate(), getEnum(data, Keys.EVENT_TYPE, EventType.class, EventType.ALARM_NOTIFICATION), getString(data, Keys.KEY_DESCRIPTION), getInteger(data, Keys.KEY_INDEX, Defaults.DEFAULT_INDEX)); this.eventRepository.save(event); } }
Source:
private void fetchCredentials(Intent intent) { final ListenableFuture<OAuthTokenCredential> future = oauthLoginManager.fetchOAuthTokenCredentialAsync(intent); future.addDoneListener(new Runnable() { @Override public void run() { try { oauthCred = future.get(); } catch (Exception e) { e.printStackTrace(); return; } } }); }

Target:
private void fetchCredentials(Intent intent) { final ListenableFuture<OAuthTokenCredential> future = oauthLoginManager.fetchOAuthTokenCredentialAsync(intent); future.addDoneListener(new Runnable() { @Override public void run() { try { oauthCred = future.get(); } catch (Exception e) { e.printStackTrace(); } } }); }
Source:
public static List<IteratorTestCase> findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); Reflections reflections = new Reflections(IteratorTestCase.class.getPackage().getName()); final List<IteratorTestCase> testCases = new ArrayList<>(); final Set<Class<? extends IteratorTestCase>> classes = reflections.getSubTypesOf(IteratorTestCase.class); for (Class<? extends IteratorTestCase> clz : classes) { if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers())) { log.debug("Skipping " + clz); continue; } try { testCases.add(clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; }

Target:
public static List<IteratorTestCase> findAllTestCases() { log.info("Searching {}", IteratorTestCase.class.getPackage().getName()); ClassPath cp; try { cp = ClassPath.from(IteratorTestCaseFinder.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException(e); } ImmutableSet<ClassInfo> classes = cp.getTopLevelClasses(IteratorTestCase.class.getPackage().getName()); final List<IteratorTestCase> testCases = new ArrayList<>(); for (ClassInfo classInfo : classes) { Class<?> clz; try { clz = Class.forName(classInfo.getName()); } catch (Exception e) { log.warn("Could not get class for " + classInfo.getName(), e); continue; } if (clz.isInterface() || Modifier.isAbstract(clz.getModifiers()) || !IteratorTestCase.class.isAssignableFrom(clz)) { log.debug("Skipping " + clz); continue; } try { testCases.add((IteratorTestCase) clz.newInstance()); } catch (IllegalAccessException | InstantiationException e) { log.warn("Could not instantiate {}", clz, e); } } return testCases; }
Source:
public File getDatabasePath(String name) { return new File(path); }

Target:
public File getDatabasePath(String name) { return new File(path + File.separator + name); }
Source:
protected VcloudClient newVcloudClient(String endpoint, String identity, String credential, String trustStore, String trustStorePassword, Level logLevel) { try { if (logLevel != null) { VcloudClient.setLogLevel(logLevel); } VcloudClient vcloudClient = null; boolean versionFound = false; for (Version version : VCLOUD_VERSIONS) { try { vcloudClient = new VcloudClient(endpoint, version); LOG.debug("VCloudClient - trying login to using {}", endpoint, version); vcloudClient.login(identity, credential); if (trustStore != null && trustStorePassword != null) { vcloudClient.registerScheme("https", 443, CustomSSLSocketFactory.getInstance(trustStore, trustStorePassword)); } else { LOG.warn("Ignoring the Certificate Validation using FakeSSLSocketFactory"); vcloudClient.registerScheme("https", 443, FakeSSLSocketFactory.getInstance()); } versionFound = true; LOG.info("VCloudClient - Logged into using version {}", endpoint, version); break; } catch (VCloudException e) { LOG.debug("VCloudClient - Cannot login to " + endpoint + " using " + version, e); } } if (!versionFound) { throw new IllegalStateException("Cannot login to " + endpoint + " using any of " + VCLOUD_VERSIONS); } return vcloudClient; } catch (Exception e) { throw Exceptions.propagate(e); } }

Target:
protected VcloudClient newVcloudClient(String endpoint, String identity, String credential, String trustStore, String trustStorePassword, Level logLevel) { if (trustStore == null) { trustStore = getDefaultTrustStore(); } try { if (logLevel != null) { VcloudClient.setLogLevel(logLevel); } VcloudClient vcloudClient = null; boolean versionFound = false; for (Version version : VCLOUD_VERSIONS) { try { vcloudClient = new VcloudClient(endpoint, version); LOG.debug("VCloudClient - trying login to using {}", endpoint, version); if (Strings.isNonBlank(trustStorePassword)) { LOG.debug("Registering HTTPS scheme using trustStore ='{}'", trustStore); vcloudClient.registerScheme("https", 443, CustomSSLSocketFactory.getInstance(trustStore, trustStorePassword)); } else { LOG.warn("Registering HTTPS scheme using FakeSSLSocketFactory, as trustStore ='{}' and/or trustStorePassword are not valid.", trustStore); vcloudClient.registerScheme("https", 443, FakeSSLSocketFactory.getInstance()); } vcloudClient.login(identity, credential); versionFound = true; LOG.info("VCloudClient - Logged into using version {}", endpoint, version); break; } catch (VCloudException e) { LOG.debug("VCloudClient - Cannot login to " + endpoint + " using " + version, e); } } if (!versionFound) { throw new IllegalStateException("Cannot login to " + endpoint + " using any of " + VCLOUD_VERSIONS); } return vcloudClient; } catch (Exception e) { throw Exceptions.propagate(e); } }
Source:
protected static void validateDisplaySizeIfNotNull(String displaySize, List<String> validationErrors) { if (isNotBlank(displaySize) && (!StringUtils.isNumeric(displaySize) || Integer.valueOf(displaySize) < 1 || Integer.valueOf(displaySize) > 500)) { validationErrors.add("display_size"); } }

Target:
protected static void validateDisplaySizeIfNotNull(String displaySize, List<String> validationErrors) { if (isNotBlank(displaySize) && (!NumericValidator.isValid(displaySize) || Integer.valueOf(displaySize) < 1 || Integer.valueOf(displaySize) > 500)) { validationErrors.add("display_size"); } }
Source:
public static List<String> getInputAlgo(HashMap<String, String> inputContent) throws IOException, DatasetsException, PathologyException { List<String> nodesToBeChecked = new ArrayList<>(); String datasets; String[] userDatasets = null; String pathology = null; HashMap<String, String[]> nodeDatasets = new HashMap<>(); if (inputContent == null ) { for (ContainerProxy containerProxy : ArtRegistryLocator.getArtRegistryProxy().getContainers()) { System.out.println("ContainerProxy : " + containerProxy.getEntityName().getIP()); nodesToBeChecked.add(containerProxy.getEntityName().getIP()); } return nodesToBeChecked; } else if(inputContent.size()==1 && inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); for (ContainerProxy containerProxy : ArtRegistryLocator.getArtRegistryProxy().getContainers()) { System.out.println("ContainerProxy : " + containerProxy.getEntityName().getIP()); nodesToBeChecked.add(containerProxy.getEntityName().getIP()); } return nodesToBeChecked; } else { if (inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); } if (inputContent.containsKey("dataset")) { datasets = inputContent.get("dataset"); userDatasets = datasets.split(","); } nodesToBeChecked = checkDatasets(nodeDatasets, userDatasets, pathology); } return nodesToBeChecked; }

Target:
public static List<ContainerProxy> getInputAlgo(HashMap<String, String> inputContent) throws IOException, DatasetsException, PathologyException { List<ContainerProxy> nodesToBeChecked = new ArrayList<>(); String datasets; String[] userDatasets = null; String pathology = null; HashMap<String, String[]> nodeDatasets = new HashMap<>(); if (inputContent == null ) { nodesToBeChecked.addAll(Arrays.asList(ArtRegistryLocator.getArtRegistryProxy().getContainers())); return nodesToBeChecked; } else if(inputContent.size()==1 && inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); nodesToBeChecked.addAll(Arrays.asList(ArtRegistryLocator.getArtRegistryProxy().getContainers())); return nodesToBeChecked; } else { if (inputContent.containsKey("pathology")) { pathology = inputContent.get("pathology"); nodeDatasets = getNodesForPathology(pathology); } else throw new PathologyException("The parameter pathology should not be blank"); if (inputContent.containsKey("dataset")) { datasets = inputContent.get("dataset"); userDatasets = datasets.split(","); } else throw new DatasetsException("The parameter dataset should not be blank"); if(nodeDatasets.isEmpty()){ throw new PathologyException("Existing nodes do not have data for pathology: "+pathology); } nodesToBeChecked = checkDatasets(nodeDatasets, userDatasets, pathology); } return nodesToBeChecked; }
Source:
private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(walk.getObjectReader(), depth); for (RevObject o : wantAll) { if (o instanceof RevCommit) depthWalk.markStart(depthWalk.parseCommit(o)); } RevObject o; while ((o = depthWalk.next()) != null) { DepthWalk.Commit c = (DepthWalk.Commit)o; if (c.depth == depth && !clientShallowCommits.contains(c)) { pckOut.writeString("shallow " + o.name()); } if (c.depth < depth && clientShallowCommits.contains(c)) { unshallowCommits.add(c); pckOut.writeString("unshallow " + c.name()); } } pckOut.end(); }

Target:
private void processShallow() throws IOException { DepthWalk.RevWalk depthWalk = new DepthWalk.RevWalk(walk.getObjectReader(), depth); for (RevObject o : wantAll) { if (o instanceof RevCommit) depthWalk.markStart(depthWalk.parseCommit(o)); } RevObject o; while ((o = depthWalk.next()) != null) { DepthWalk.Commit c = (DepthWalk.Commit)o; if (c.getDepth() == depth && !clientShallowCommits.contains(c)) pckOut.writeString("shallow " + o.name()); if (c.getDepth() < depth && clientShallowCommits.contains(c)) { unshallowCommits.add(c.copy()); pckOut.writeString("unshallow " + c.name()); } } pckOut.end(); }
Source:
public static Class<?>[] getClasses(Class<?> annotation, String... paths) { List<String> names = new FastClasspathScanner(paths).scan().getNamesOfClassesWithAnnotation(annotation); List<Class<?>> classes = new ArrayList<Class<?>>(); for (String c : names) { Class<?> classType; try { classType = Class.forName(c); } catch (ClassNotFoundException e) { throw new JaversException(JaversExceptionCode.CANT_FIND_CLASS_WITH_TYPENAME, c); } classes.add(classType); } return null; }

Target:
public static List<Class<?>> getClasses(Class<?> annotation, String... paths) { List<String> names = new FastClasspathScanner(paths).scan().getNamesOfClassesWithAnnotation(annotation); List<Class<?>> classes = new ArrayList<Class<?>>(); for (String c : names) { Class<?> classType; try { classType = Class.forName(c); } catch (ClassNotFoundException e) { throw new JaversException(JaversExceptionCode.CANT_FIND_CLASS_WITH_TYPENAME, c); } classes.add(classType); } return classes; }
Source:
public JobCoordinatorMetadata(String epochId, String configId, String jobModelId) { this.configId = configId; this.epochId = epochId; this.jobModelId = jobModelId; }

Target:
public JobCoordinatorMetadata(String epochId, String configId, String jobModelId) { Preconditions.checkState(StringUtils.isNotBlank(epochId), "Epoch ID cannot be empty"); Preconditions.checkState(StringUtils.isNotBlank(configId), "Config ID cannot be empty"); Preconditions.checkState(StringUtils.isNotBlank(jobModelId), "Job Model ID cannot be empty"); this.configId = configId; this.epochId = epochId; this.jobModelId = jobModelId; }
Source:
public VmTemplate readVmTemplateFromOvf(String ovf) throws OvfReaderException { VmTemplate vmTemplate = new VmTemplate(); ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>(); ArrayList<VmNetworkInterface> interfaces = new ArrayList<VmNetworkInterface>(); ovfManager.ImportTemplate(ovf, vmTemplate, diskImages, interfaces); vmTemplate.setImages(diskImages); vmTemplate.setInterfaces(interfaces); Map<Guid, List<DiskImage>> images = ImagesHandler .getImagesLeaf(diskImages); for (Map.Entry<Guid, List<DiskImage>> entry : images.entrySet()) { List<DiskImage> list = entry.getValue(); vmTemplate.getDiskTemplateMap().put(entry.getKey(), list.get(list.size() - 1)); } return vmTemplate; }

Target:
public VmTemplate readVmTemplateFromOvf(String ovf) throws OvfReaderException { ArrayList<DiskImage> diskImages = new ArrayList<DiskImage>(); ArrayList<VmNetworkInterface> interfaces = new ArrayList<VmNetworkInterface>(); VmTemplate template = new VmTemplate(); ovfManager.ImportTemplate(ovf, template, diskImages, interfaces); template.setInterfaces(interfaces); for (DiskImage disk : diskImages) { template.getDiskTemplateMap().put(disk.getId(), disk); } return template; }
Source:
private String doLoad(String name, ClassLoader loader) { String ldLibraryPath = null; String dexPath = null; if (loader != null && loader instanceof BaseDexClassLoader) { ldLibraryPath = ((BaseDexClassLoader) loader).getLdLibraryPath(); dexPath = ((BaseDexClassLoader) loader).getDexPath(); } synchronized (this) { return nativeLoad(name, loader, ldLibraryPath, dexPath); } }

Target:
private String doLoad(String name, ClassLoader loader) { String ldLibraryPath = null; String dexPath = null; if (loader != null && loader instanceof BaseDexClassLoader) { BaseDexClassLoader dexClassLoader = (BaseDexClassLoader) loader; ldLibraryPath = dexClassLoader.getLdLibraryPath(); dexPath = dexClassLoader.getDexPath(); } synchronized (this) { return nativeLoad(name, loader, ldLibraryPath, dexPath); } }
Source:
private static boolean isValidAttributeName(String name) { if (name.length() == 0) return false; if (name.charAt(0) == '-') return false; for (int index = 0; index < name.length(); index++) { final char ch = name.charAt(index); if (!(ch == '-' || ch == '.' || ch == '_' || ('0' <= ch && ch <= '9') || ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z'))) return false; } return true; }

Target:
private static boolean isValidAttributeName(String name) { if (name.length() == 0) return false; if (name.charAt(0) == '-') return false; for (int index = 0; index < name.length(); index++) { final char ch = name.charAt(index); if ('0' <= ch && ch <= '9') continue; if ('a' <= ch && ch <= 'z') continue; if ('A' <= ch && ch <= 'Z') continue; if (ch == '-' || ch == '.' || ch == '_') continue; return false; } return true; }
Source:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { position -= mDrawerList.getHeaderViewsCount(); mSelectedTag = mTagsAdapter.getItem(position); checkEmptyListText(false); setSelectedTagActive(); mDrawerLayout.closeDrawer(mNavigationView); updateNavigationDrawerItems(); if (mNoteListFragment.isHidden()) { FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN); ft.show(mNoteListFragment); ft.commitAllowingStateLoss(); fm.executePendingTransactions(); } if (mDrawerList.getCheckedItemPosition() == TRASH_SELECTED_ID) { getNoteListFragment().getListView().setLongClickable(false); } else { getNoteListFragment().getListView().setLongClickable(true); } getNoteListFragment().refreshListFromNavSelect(); if (position > 1) { AnalyticsTracker.track( AnalyticsTracker.Stat.LIST_TAG_VIEWED, AnalyticsTracker.CATEGORY_TAG, "selected_tag_in_navigation_drawer" ); } }

Target:
public void onItemClick(AdapterView<?> parent, View view, int position, long id) { position -= mDrawerList.getHeaderViewsCount(); mSelectedTag = mTagsAdapter.getItem(position); checkEmptyListText(false); setSelectedTagActive(); mDrawerLayout.closeDrawer(mNavigationView); updateNavigationDrawerItems(); if (mNoteListFragment.isHidden()) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); ft.show(mNoteListFragment); ft.commitNowAllowingStateLoss(); } if (mDrawerList.getCheckedItemPosition() == TRASH_SELECTED_ID) { getNoteListFragment().getListView().setLongClickable(false); } else { getNoteListFragment().getListView().setLongClickable(true); } getNoteListFragment().refreshListFromNavSelect(); if (position > 1) { AnalyticsTracker.track( AnalyticsTracker.Stat.LIST_TAG_VIEWED, AnalyticsTracker.CATEGORY_TAG, "selected_tag_in_navigation_drawer" ); } }
Source:
protected Promise<List<T>> run(final Context context) throws Exception { final SettablePromise<List<T>> result = Promises.settable(); if (_tasks.isEmpty()) { result.done(Collections.<T>emptyList()); return result; } final PromiseListener<?> listener = new PromiseListener<Object>() { @Override public void onResolved(Promise<Object> resolvedPromise) { boolean allEarlyFinish = true; final List<T> taskResult = new ArrayList<T>(); final List<Throwable> errors = new ArrayList<Throwable>(); for (Task<? extends T> task : _tasks) { if (task.isFailed()) { if (allEarlyFinish && ResultType.fromTask(task) != ResultType.EARLY_FINISH) { allEarlyFinish = false; } errors.add(task.getError()); } else { taskResult.add(task.get()); } } if (!errors.isEmpty()) { result .fail(allEarlyFinish ? errors.get(0) : new MultiException("Multiple errors in 'ParTask' task.", errors)); } else { result.done(taskResult); } } }; InternalUtil.after(listener, _tasks.toArray(new Task<?>[_tasks.size()])); for (Task<?> task : _tasks) { context.run(task); } return result; }

Target:
protected Promise<List<T>> run(final Context context) throws Exception { if (_tasks.isEmpty()) { return Promises.value(Collections.<T>emptyList()); } final SettablePromise<List<T>> result = Promises.settable(); final PromiseListener<?> listener = new PromiseListener<Object>() { @Override public void onResolved(Promise<Object> resolvedPromise) { boolean allEarlyFinish = true; final List<T> taskResult = new ArrayList<T>(); final List<Throwable> errors = new ArrayList<Throwable>(); for (Task<? extends T> task : _tasks) { if (task.isFailed()) { if (allEarlyFinish && ResultType.fromTask(task) != ResultType.EARLY_FINISH) { allEarlyFinish = false; } errors.add(task.getError()); } else { taskResult.add(task.get()); } } if (!errors.isEmpty()) { result .fail(allEarlyFinish ? errors.get(0) : new MultiException("Multiple errors in 'ParTask' task.", errors)); } else { result.done(taskResult); } } }; InternalUtil.after(listener, _tasks.toArray(new Task<?>[_tasks.size()])); for (Task<?> task : _tasks) { context.run(task); } return result; }
Source:
public PageableResult search(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); UserService service = Context.getUserService(); String source = context.getRequest().getParameter("source"); String fromDate = context.getRequest().getParameter("fromDate"); String toDate = context.getRequest().getParameter("toDate"); String identifier = context.getRequest().getParameter("identifier"); String comment = context.getRequest().getParameter("comment"); String generatedBy = context.getRequest().getParameter("generatedBy"); List<LogEntry> logEntries = new ArrayList<LogEntry>(); IdentifierSource logSource = source != null ? identifierSourceService.getIdentifierSourceByUuid(source) : null; Date dateFrom = fromDate != null ? (Date) ConversionUtil.convert(fromDate, Date.class) : null; Date dateTo = toDate != null ? (Date) ConversionUtil.convert(toDate, Date.class) : null; User user = generatedBy != null ? service.getUserByUuid(generatedBy): null; if (logSource == null && identifier == null && comment == null && dateFrom == null && dateTo == null && user == null) { return new EmptySearchResult(); } logEntries = identifierSourceService.getLogEntries(logSource, dateFrom, dateTo, identifier, user, comment); return new NeedsPaging<LogEntry>(logEntries, context); }

Target:
public PageableResult search(RequestContext context) throws ResponseException { IdentifierSourceService identifierSourceService = Context.getService(IdentifierSourceService.class); UserService service = Context.getUserService(); String source = context.getRequest().getParameter("source"); String fromDate = context.getRequest().getParameter("fromDate"); String toDate = context.getRequest().getParameter("toDate"); String identifier = context.getRequest().getParameter("identifier"); String comment = context.getRequest().getParameter("comment"); String generatedBy = context.getRequest().getParameter("generatedBy"); IdentifierSource logSource = source != null ? identifierSourceService.getIdentifierSourceByUuid(source) : null; Date dateFrom = fromDate != null ? (Date) ConversionUtil.convert(fromDate, Date.class) : null; Date dateTo = toDate != null ? (Date) ConversionUtil.convert(toDate, Date.class) : null; User user = generatedBy != null ? service.getUserByUuid(generatedBy): null; if (logSource == null && identifier == null && comment == null && dateFrom == null && dateTo == null && user == null) { return new EmptySearchResult(); } List<LogEntry> logEntries = identifierSourceService.getLogEntries(logSource, dateFrom, dateTo, identifier, user, comment); return new NeedsPaging<LogEntry>(logEntries, context); }