auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = (RevCommit) getSelection(getPage()).getFirstElement(); RevCommit newHead; Repository repo = getRepository(event); RevertCommand cherryPick; Git git = new Git(repo); try { cherryPick = git.revert().include(commit.getId()); newHead = cherryPick.call(); } catch (Exception e) { throw new ExecutionException(CoreText.RevertOperation_InternalError, e); } if (newHead == null) throw new ExecutionException(CoreText.RevertOperation_Failed); return null; }

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { RevCommit commit = (RevCommit) getSelection(getPage()).getFirstElement(); RevCommit newHead; Repository repo = getRepository(event); RevertCommand revert; Git git = new Git(repo); try { revert = git.revert().include(commit.getId()); newHead = revert.call(); } catch (Exception e) { throw new ExecutionException(CoreText.RevertOperation_InternalError, e); } if (newHead == null) throw new ExecutionException(CoreText.RevertOperation_Failed); return null; }
Source:
protected static ImmutableList<SpecializedCommand> toSpecializedCommands(final ImmutableList<Ds3Request> ds3Requests) { if (isEmpty(ds3Requests)) { return ImmutableList.of(); } final ImmutableList.Builder<SpecializedCommand> builder = ImmutableList.builder(); for (final Ds3Request ds3Request : ds3Requests) { if (isGetObjectAmazonS3Request(ds3Request)) { builder.add(toGetObjectCommand(ds3Request)); } } return builder.build(); }

Target:
protected static ImmutableList<SpecializedCommand> toSpecializedCommands(final ImmutableList<Ds3Request> ds3Requests) { if (isEmpty(ds3Requests)) { return ImmutableList.of(); } return ds3Requests.stream() .filter(Ds3RequestClassificationUtil::isGetObjectAmazonS3Request) .map(BaseClientGenerator::toGetObjectCommand) .collect(GuavaCollectors.immutableList()); }
Source:
protected void closeConnection() { for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if ((socket != null) && (!socket.isClosed())) { try { socket.close(); } catch (IOException e) { logger.warn("Could not close socket in {}: {}", receiverNode, this.thing.getUID(), e); } } receiverNodes.put(receiverNode, null); } isConnected = false; }

Target:
protected void closeConnection() { for (IpNode receiverNode : receiverNodes.keySet()) { Socket socket = receiverNodes.get(receiverNode); if ((socket != null) && (!socket.isClosed())) { try { socket.close(); } catch (IOException e) { logger.warn("Could not close socket in {}: {}", receiverNode, this.thing.getUID(), e); } } receiverNodes.put(receiverNode, null); } }
Source:
public BlobHolder convert(String converterName, BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { ConverterDescriptor desc = converterDescriptors.get(converterName); if (desc == null) { throw new ConversionException("Converter " + converterName + " can not be found", blobHolder); } String mimeType = blobHolder.getBlob().getMimeType(); if (desc.isBypassIfSameMimeTypet() && desc.getDestinationMimeType().equals(mimeType)) { return blobHolder; } if (parameters == null) { parameters = new HashMap<>(); } ConverterCheckResult check = isConverterAvailable(converterName); if (!check.isAvailable()) { throw new ConverterNotAvailable(converterName, blobHolder); } if (!hasSourceMimeType(desc, mimeType)) { throw new ConversionException( String.format("%s mime type not supported by %s converter", mimeType, desc.getConverterName()), blobHolder); } String cacheKey = CacheKeyGenerator.computeKey(converterName, blobHolder, parameters); BlobHolder result = ConversionCacheHolder.getFromCache(cacheKey); if (result == null) { Converter converter = desc.getConverterInstance(); result = converter.convert(blobHolder, parameters); if (config.isCacheEnabled()) { ConversionCacheHolder.addToCache(cacheKey, result); } } else if (result.getBlobs() != null && result.getBlobs().size() == 1) { result.getBlob().setFilename(null); } if (result != null) { updateResultBlobMimeType(result, desc); updateResultBlobFileName(blobHolder, result); } return result; }

Target:
public BlobHolder convert(String converterName, BlobHolder blobHolder, Map<String, Serializable> parameters) throws ConversionException { if (parameters == null) { parameters = new HashMap<>(); } ConverterCheckResult check = isConverterAvailable(converterName); if (!check.isAvailable()) { throw new ConverterNotAvailable(converterName, blobHolder); } ConverterDescriptor desc = converterDescriptors.get(converterName); if (desc == null) { throw new ConversionException("Converter " + converterName + " can not be found", blobHolder); } String mimeType = blobHolder.getBlob().getMimeType(); if (!hasSourceMimeType(desc, mimeType)) { throw new ConversionException( String.format("%s mime type not supported by %s converter", mimeType, desc.getConverterName()), blobHolder); } if (desc.isBypassIfSameMimeType() && desc.getDestinationMimeType().equals(mimeType)) { return blobHolder; } String cacheKey = CacheKeyGenerator.computeKey(converterName, blobHolder, parameters); BlobHolder result = ConversionCacheHolder.getFromCache(cacheKey); if (result == null) { Converter converter = desc.getConverterInstance(); result = converter.convert(blobHolder, parameters); if (config.isCacheEnabled()) { ConversionCacheHolder.addToCache(cacheKey, result); } } else if (result.getBlobs() != null && result.getBlobs().size() == 1) { result.getBlob().setFilename(null); } if (result != null) { updateResultBlobMimeType(result, desc); updateResultBlobFileName(blobHolder, result); } return result; }
Source:
protected void testExecute_asStudentGetHasRespondedForSession_shouldPass() { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); loginAsStudent(student1InCourse1.googleId); FeedbackSessionAttributes feedbackSession = typicalBundle.feedbackSessions.get("session1InCourse1"); String[] params = new String[] { Const.ParamsNames.COURSE_ID, student1InCourse1.course, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSession.getFeedbackSessionName(), Const.ParamsNames.ENTITY_TYPE, "student", }; GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); HasResponsesData hasResponsesData = (HasResponsesData) jsonResult.getOutput(); assertEquals(HttpStatus.SC_OK, jsonResult.getStatusCode()); assertTrue(hasResponsesData.hasResponses()); }

Target:
protected void testExecute_asStudentGetHasRespondedForSession_shouldPass() { StudentAttributes student1InCourse1 = typicalBundle.students.get("student1InCourse1"); loginAsStudent(student1InCourse1.googleId); FeedbackSessionAttributes feedbackSession = typicalBundle.feedbackSessions.get("session1InCourse1"); FeedbackResponseAttributes feedbackResponse = typicalBundle.feedbackResponses.get("response1ForQ1S1C1"); assertEquals(feedbackResponse.getFeedbackSessionName(), feedbackSession.getFeedbackSessionName()); assertEquals(feedbackResponse.getGiver(), student1InCourse1.getEmail()); String[] params = new String[] { Const.ParamsNames.COURSE_ID, student1InCourse1.course, Const.ParamsNames.FEEDBACK_SESSION_NAME, feedbackSession.getFeedbackSessionName(), Const.ParamsNames.ENTITY_TYPE, Const.EntityType.STUDENT, }; GetHasResponsesAction getHasResponsesAction = getAction(params); JsonResult jsonResult = getJsonResult(getHasResponsesAction); HasResponsesData hasResponsesData = (HasResponsesData) jsonResult.getOutput(); assertEquals(HttpStatus.SC_OK, jsonResult.getStatusCode()); assertTrue(hasResponsesData.hasResponses()); }
Source:
public void showInterstitial() { Context context = mInterstitialContext != null ? mInterstitialContext.get() : null; if (mInterstitialSpot.getSelectedUnitController() instanceof InneractiveFullscreenUnitController && context != null) { if (mInterstitialSpot.isReady()) { ((InneractiveFullscreenUnitController) mInterstitialSpot .getSelectedUnitController()).show(context); } else { Log.w(TAG, "showInterstitial called, but Ad has expired."); mMediationInterstitialListener.onAdFailedToLoad(this, AdRequest.ERROR_CODE_INTERNAL_ERROR); mMediationInterstitialListener.onAdOpened(this); mMediationInterstitialListener.onAdClosed(this); } } else { Log.w(TAG, "showInterstitial called, but context reference was lost, or wrong spot has been used (should not happen)"); mMediationInterstitialListener.onAdFailedToLoad(this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } }

Target:
public void showInterstitial() { Context context = mInterstitialContext != null ? mInterstitialContext.get() : null; if (mInterstitialSpot.getSelectedUnitController() instanceof InneractiveFullscreenUnitController && context != null) { if (mInterstitialSpot.isReady()) { ((InneractiveFullscreenUnitController) mInterstitialSpot .getSelectedUnitController()).show(context); } else { Log.w(TAG, "showInterstitial called, but Ad has expired."); mMediationInterstitialListener.onAdOpened(this); mMediationInterstitialListener.onAdClosed(this); } } else { Log.w(TAG, "showInterstitial called, but context reference was lost, or wrong spot has been used (should not happen)"); mMediationInterstitialListener.onAdFailedToLoad(this, AdRequest.ERROR_CODE_INTERNAL_ERROR); } }
Source:
public static Map<String, SQLStmt> getSQLStmtMap(VoltCompiler compiler, Class<?> procClass) throws VoltCompilerException { VoltProcedure procInstance; try { procInstance = (VoltProcedure) procClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Error instantiating procedure \"%s\"" + procClass.getName(), e); } Map<String, SQLStmt> stmtMap = getValidSQLStmts(compiler, procClass.getSimpleName(), procClass, procInstance, true); return stmtMap; }

Target:
public static Map<String, SQLStmt> getSQLStmtMap(VoltCompiler compiler, Class<?> procClass) throws VoltCompilerException { VoltProcedure procInstance; try { procInstance = (VoltProcedure) procClass.newInstance(); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException("Error instantiating procedure " + procClass.getName(), e); } Map<String, SQLStmt> stmtMap = getValidSQLStmts(compiler, procClass.getSimpleName(), procClass, procInstance, true); return stmtMap; }
Source:
public static Field getInheritableThreadLocalsField() { String javaVersion = System.getProperty("java.specification.version"); if (Integer.valueOf(javaVersion.split(".")[0]) >= 9) { return null; } try { Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocals.setAccessible(true); return inheritableThreadLocals; } catch (Throwable t) { return null; } }

Target:
public static Field getInheritableThreadLocalsField() { try { Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocals.setAccessible(true); return inheritableThreadLocals; } catch (Throwable t) { return null; } }
Source:
protected Session doReadSession(final Serializable sessionId) { if (sessionId == null) { return null; } final String recordId = sessionId.toString(); final SessionModelDao sessionModelDao = jdbcSessionSqlDao.read(recordId); if (sessionModelDao == null) { return null; } try { return sessionModelDao.toSimpleSession(); } catch (final IOException e) { log.warn("Corrupted cookie", e); return null; } }

Target:
protected Session doReadSession(final Serializable sessionId) { if (sessionId == null) { return null; } final String sessionIdString = sessionId.toString(); final SessionModelDao sessionModelDao = jdbcSessionSqlDao.read(sessionIdString); if (sessionModelDao == null) { return null; } try { return sessionModelDao.toSimpleSession(); } catch (final IOException e) { log.warn("Corrupted cookie", e); return null; } }
Source:
protected void executeVmCommand() { VM vm = getVm(); vm.setConsoleCurrentUserName(getParameters().getConsoleUserName()); final VmDynamicDAO dao = DbFacade.getInstance().getVmDynamicDao(); dao.update(vm.getDynamicData()); setSucceeded(true); }

Target:
protected void executeVmCommand() { VM vm = getVm(); vm.setConsoleCurrentUserName(getParameters().getConsoleUserName()); VDSParametersBase updateVmDynamicParams = new UpdateVmDynamicDataVDSCommandParameters(getVdsId(), vm.getDynamicData()); runVdsCommand(VDSCommandType.UpdateVmDynamicData, updateVmDynamicParams); setSucceeded(true); }
Source:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); m_toLeader = false; m_ackRequestedFromSender = true; }

Target:
public CompleteTransactionMessage(long initiatorHSId, long coordinatorHSId, long txnId, boolean isReadOnly, int hash, boolean isRollback, boolean requiresAck, boolean isRestart, boolean isForReplay) { super(initiatorHSId, coordinatorHSId, txnId, 0, isReadOnly, isForReplay); m_hash = hash; setBit(ISROLLBACK, isRollback); setBit(REQUIRESACK, requiresAck); setBit(ISRESTART, isRestart); }
Source:
public static <T> AttributeSensor<T> newSensor(ConfigBag params) { String name = Preconditions.checkNotNull(params.get(SENSOR_NAME), "name must be supplied when defining a sensor"); String className = Preconditions.checkNotNull(params.get(SENSOR_TYPE), "target class must be supplied when defining a sensor"); Class<T> type = null; try { type = (Class<T>) Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Invalid target type"); } return Sensors.newSensor(type, name); }

Target:
public static <T> AttributeSensor<T> newSensor(ConfigBag params) { String name = Preconditions.checkNotNull(params.get(SENSOR_NAME), "name must be supplied when defining a sensor"); String className = getFullClassName(params.get(SENSOR_TYPE)); Class<T> type = null; try { type = (Class<T>) Class.forName(className); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Invalid target type for sensor "+name+": " + className); } return Sensors.newSensor(type, name); }
Source:
public void testConcurrentWriteAndRestart() { final int THREADS = 4; final AtomicBoolean run = new AtomicBoolean(true); final CountDownLatch started = new CountDownLatch(THREADS); ExecutorService executor = Executors.newFixedThreadPool(THREADS); for (int i = 0; i < THREADS; ++i) { executor.execute(new Runnable() { @Override public void run() { started.countDown(); int i = 0; while (run.get()) { InternalCacheEntry entry = TestInternalCacheEntryFactory.create("k" + i, "v" + i); MarshalledEntry me = TestingUtil.marshalledEntry(entry, getMarshaller()); cl.write(me); ++i; } } }); } try { started.await(); Thread.sleep(1000); cl.stop(); Thread.sleep(1000); cl.start(); Thread.sleep(1000); } catch (InterruptedException e) { throw new IllegalStateException(e); } finally { run.set(false); executor.shutdown(); } }

Target:
public void testConcurrentWriteAndRestart() { concurrentWriteAndRestart(true); }
Source:
public void purgeDefinition_shouldPurgeDesignsAndRequestsAndDefinition() throws Exception { executeDataSet("org/openmrs/module/reporting/include/ReportDefinitionServiceImplTest.xml"); assertNotNull(reportService.getReportDesign(3)); assertNotNull(reportService.getReportDesign(4)); assertNotNull(reportService.getReportRequest(1)); assertNotNull(reportService.getReportRequest(3)); reportDefinitionService.purgeDefinition("c11f5354-9567-4cc5-b3ef-163e28873926"); assertNull(reportService.getReportDesign(3)); assertNull(reportService.getReportDesign(4)); assertNull(reportService.getReportRequest(1)); assertNull(reportService.getReportRequest(3)); assertNull(reportDefinitionService.getDefinition(80)); }

Target:
public void purgeDefinition_shouldPurgeDesignsAndRequestsAndDefinition() throws Exception { executeDataSet("org/openmrs/module/reporting/include/ReportDefinitionServiceImplTest.xml"); assertNotNull(reportService.getReportDesignByUuid("d7a82b63-1066-4c1d-9b43-b405851fc467")); assertNotNull(reportService.getReportDesignByUuid("e7a82b63-1066-4c1d-9b43-b405851fc467")); assertNotNull(reportService.getReportRequestByUuid("h8a82b63-1066-4c1d-9b43-b405851fc467")); assertNotNull(reportService.getReportRequestByUuid("b0a82b63-1066-4c1d-9b43-b405851fc467")); Context.clearSession(); reportDefinitionService.purgeDefinition("c11f5354-9567-4cc5-b3ef-163e28873926"); assertNull(reportService.getReportDesignByUuid("d7a82b63-1066-4c1d-9b43-b405851fc467")); assertNull(reportService.getReportDesignByUuid("e7a82b63-1066-4c1d-9b43-b405851fc467")); assertNull(reportService.getReportRequestByUuid("h8a82b63-1066-4c1d-9b43-b405851fc467")); assertNull(reportService.getReportRequestByUuid("b0a82b63-1066-4c1d-9b43-b405851fc467")); assertNull(reportDefinitionService.getDefinitionByUuid("c11f5354-9567-4cc5-b3ef-163e28873926")); }
Source:
public static void tearDown() throws Exception { testSupport.stop(); PathUtil.deleteSilentlyRecursively(runtimeConfigurationStateChangeFile); PathUtil.deleteSilentlyRecursively(runningStateChangeFile); }

Target:
public static void tearDown() throws Exception { testSupport.stop(); PathUtil.deleteSilentlyRecursively(data); }
Source:
public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; if (!traceElem.getTraceType().equals(TRACE_TYPE_ID)) { return false; } int arraySize = 0; try (FileReader fileReader = new FileReader(traceElem.getLocation().getPath())) { try (JsonReader reader = new JsonReader(fileReader);) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); } } catch (IOException e) { return false; } return arraySize > 1; }

Target:
public boolean isEnabled() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); IWorkbenchPart part = page.getActivePart(); if (part == null) { return false; } ISelectionProvider selectionProvider = part.getSite().getSelectionProvider(); if (selectionProvider == null) { return false; } ISelection selection = selectionProvider.getSelection(); Object firstElement = ((IStructuredSelection) selection).getFirstElement(); final TmfCommonProjectElement traceElem = (firstElement instanceof TmfTraceElement) ? ((TmfTraceElement) firstElement).getElementUnderTraceFolder() : (TmfCommonProjectElement) firstElement; if (!traceElem.getTraceType().equals(TRACE_TYPE_ID)) { return false; } int arraySize = 0; try (FileReader fileReader = new FileReader(traceElem.getLocation().getPath())) { try (JsonReader reader = new JsonReader(fileReader)) { Gson gson = new Gson(); JsonObject object = gson.fromJson(reader, JsonObject.class); arraySize = object.get(DATA_KEY).getAsJsonArray().size(); } } catch (IOException e) { return false; } return arraySize > 1; }
Source:
protected boolean needsEviction(final String token) { boolean needsEviction; needsEviction = isUnknown(token); if (!needsEviction) { needsEviction = (getTokenExpiration(token) + TimeUnit.SECONDS.toMillis(tokenEvictionGracePeriod)) <= System.currentTimeMillis(); } return needsEviction; }

Target:
protected boolean needsEviction(final String token) { return ((getTokenExpiration(token) + TimeUnit.SECONDS.toMillis(tokenEvictionGracePeriod)) <= System.currentTimeMillis()); }
Source:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { toggle(); if(getSlidingMenu().isMenuShowing() && menu.isAdded()) setTitle(((ITitleable)menu).getTitle()); return true; } return false; }

Target:
public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == android.R.id.home) { toggle(); if(getSlidingMenu().isMenuShowing() && menu.isAdded()){ setTitle(((ITitleable)menu).getTitle()); } return true; } return false; }
Source:
public int getNumOfChoicesForMsq(String courseId, FeedbackParticipantType generateOptionsFor) { if (generateOptionsFor == FeedbackParticipantType.NONE) { return msqChoices.size(); } else if (generateOptionsFor == FeedbackParticipantType.STUDENTS || generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); int sizeOfStudentlist = studentList.size(); return generateOptionsFor == FeedbackParticipantType.STUDENTS ? sizeOfStudentlist : sizeOfStudentlist - 1; } else if (generateOptionsFor == FeedbackParticipantType.TEAMS || generateOptionsFor == FeedbackParticipantType.TEAMS_EXCLUDING_SELF) { try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); int sizeOfTeamlist = teamList.size(); return generateOptionsFor == FeedbackParticipantType.TEAMS ? sizeOfTeamlist : sizeOfTeamlist - 1; } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } } else { List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); return instructorList.size(); } return 0; }

Target:
public int getNumOfChoicesForMsq(String courseId, FeedbackParticipantType generateOptionsFor) { if (generateOptionsFor == FeedbackParticipantType.NONE) { return msqChoices.size(); } if (generateOptionsFor == FeedbackParticipantType.STUDENTS || generateOptionsFor == FeedbackParticipantType.STUDENTS_EXCLUDING_SELF) { List<StudentAttributes> studentList = StudentsLogic.inst().getStudentsForCourse(courseId); int sizeOfStudentlist = studentList.size(); return generateOptionsFor == FeedbackParticipantType.STUDENTS ? sizeOfStudentlist : sizeOfStudentlist - 1; } if (generateOptionsFor == FeedbackParticipantType.TEAMS || generateOptionsFor == FeedbackParticipantType.TEAMS_EXCLUDING_SELF) { try { List<TeamDetailsBundle> teamList = CoursesLogic.inst().getTeamsForCourse(courseId); int sizeOfTeamlist = teamList.size(); return generateOptionsFor == FeedbackParticipantType.TEAMS ? sizeOfTeamlist : sizeOfTeamlist - 1; } catch (EntityDoesNotExistException e) { Assumption.fail("Course disappeared"); } } List<InstructorAttributes> instructorList = InstructorsLogic.inst().getInstructorsForCourse(courseId); return instructorList.size(); }
Source:
public SimpleHttpServer(HttpServerConfig config, Map<String, HttpHandler> handler) throws IOException { this.config = config; this.service = Executors.newFixedThreadPool( config.threads(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(config.name() + "-%d") .build()); InetSocketAddress inetSocketAddress = new InetSocketAddress("localhost", config.port()); server = HttpServer.create(inetSocketAddress, config.backlog()); server.setExecutor(service); for (Entry<String, HttpHandler> entry : handler.entrySet()) { server.createContext(entry.getKey(), entry.getValue()); } if (config.enabled()) { server.start(); } LOG.info("Started admin server on port {}", config.port()); }

Target:
public SimpleHttpServer(HttpServerConfig config, Map<String, HttpHandler> handler) throws IOException { this.config = config; this.service = Executors.newFixedThreadPool( config.threads(), new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat(config.name() + "-%d") .build()); InetSocketAddress inetSocketAddress = new InetSocketAddress(config.port()); server = HttpServer.create(inetSocketAddress, config.backlog()); server.setExecutor(service); for (Entry<String, HttpHandler> entry : handler.entrySet()) { server.createContext(entry.getKey(), entry.getValue()); } if (config.enabled()) { server.start(); } LOG.info("Started admin server on port {}", config.port()); }
Source:
public void removeSomeEntriesRemovesThoseEntriesFromEntriesList() { List<BibEntry> allEntries = new ArrayList<>(); BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); allEntries.add(entry1); allEntries.add(entry2); allEntries.add(entry3); database.insertEntries(allEntries); List<BibEntry> entriesToDelete = new ArrayList<>(); entriesToDelete.add(entry1); entriesToDelete.add(entry3); database.removeEntries(entriesToDelete); assertEquals(Collections.singletonList(entry2), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertTrue(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); }

Target:
public void removeSomeEntriesRemovesThoseEntriesFromEntriesList() { BibEntry entry1 = new BibEntry(); BibEntry entry2 = new BibEntry(); BibEntry entry3 = new BibEntry(); List<BibEntry> allEntries = Arrays.asList(entry1, entry2, entry3); database.insertEntries(allEntries); List<BibEntry> entriesToDelete = Arrays.asList(entry1, entry3); database.removeEntries(entriesToDelete); assertEquals(Collections.singletonList(entry2), database.getEntries()); assertFalse(database.containsEntryWithId(entry1.getId())); assertTrue(database.containsEntryWithId(entry2.getId())); assertFalse(database.containsEntryWithId(entry3.getId())); }
Source:
public void onApplicationEvent(ContextRefreshedEvent event) { if (!this.listenerRegistered && isAutoStartup()) { doStart(); } }

Target:
public void onApplicationEvent(ContextRefreshedEvent event) { if (!this.listenerRegisteredOnStartup.getAndSet(true) && isAutoStartup()) { doStart(); } }
Source:
public void run() { for (ReportableEntityType type : ReportableEntityType.values()) { AtomicLong samples = perEntitySamples.computeIfAbsent(type, k -> new AtomicLong(0)); long rate = handlerFactory.getReceivedRate(type); if (rate > 0 || samples.get() > 0) { samples.incrementAndGet(); Sample sample = perEntityStats.computeIfAbsent(type, x -> new ExponentiallyDecayingSample(DEFAULT_SAMPLE_SIZE, DEFAULT_ALPHA)); sample.update(rate); if (samples.get() >= 300) { RecyclableRateLimiter rateLimiter = entityProps.get(type).getRateLimiter(); double suggestedLimit = (MIN_RATE_LIMIT + sample.getSnapshot().getMedian()) * HEADROOM; if (Math.abs(rateLimiter.getRate() - suggestedLimit) > rateLimiter.getRate() * 0.05) { rateLimiter.setRate(suggestedLimit); } } } } }

Target:
public void run() { for (ReportableEntityType type : ReportableEntityType.values()) { AtomicLong samples = perEntitySamples.computeIfAbsent(type, k -> new AtomicLong(0)); EntityProperties props = entityProps.get(type); long rate = props.getTotalReceivedRate(); boolean hasBacklog = props.getTotalBacklogSize() > 0; if (rate > 0 || samples.get() > 0) { samples.incrementAndGet(); Sample stats = updateStats(type, rate); if (samples.get() >= 300) { RecyclableRateLimiter rateLimiter = props.getRateLimiter(); adjustRateLimiter(type, stats, rateLimiter, hasBacklog); } } } }
Source:
public int indexActivities(final String accessToken) { final Collection<AppActivity> activities = new ArrayList<>(); final String username = getAppState(accessToken).getUsername(); for (final RunkeeperActivityItem item : getActivities(accessToken, calculateFetchDate()).getItemsAsList()) { if(!repository.exists(item.getId())) { final AppActivity activity = new AppActivity(item.getId(), username, item.getType(), item.getDate(), item.getDistance(), item.getFormattedDuration()); LOGGER.debug("prepare {}", activity); activities.add(activity); } } LOGGER.info("new activities: {}", activities.size()); if (!activities.isEmpty()) { repository.save(activities); } return activities.size(); }

Target:
public int indexActivities(final String accessToken) { final Collection<AppActivity> activities = new ArrayList<>(); final String username = getAppState(accessToken).getUsername(); getActivities(accessToken, calculateFetchDate()).getItemsAsList().stream() .filter(item -> !repository.exists(item.getId())) .forEach(item -> addActivity(item, username, activities)); LOGGER.info("new activities: {}", activities.size()); if (!activities.isEmpty()) { repository.save(activities); } return activities.size(); }
Source:
private ServiceReference<Marshalling>[] getXmlMarshallers() { String filterString = String.format("(&(kura.service.pid=%s))", "org.eclipse.kura.marshalling.xml.provider"); return ServiceUtil.getServiceReferences(this.bundleContext, Marshalling.class, filterString); }

Target:
private ServiceReference<Marshaller>[] getXmlMarshallers() { String filterString = String.format("(&(kura.service.pid=%s))", "org.eclipse.kura.xml.marshaller.unmarshaller.provider"); return ServiceUtil.getServiceReferences(this.bundleContext, Marshaller.class, filterString); }
Source:
public static Builder overriding(ExecutableElement method) { checkNotNull(method, "method == null"); Set<Modifier> modifiers = method.getModifiers(); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) { throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers); } String methodName = method.getSimpleName().toString(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName); methodBuilder.addAnnotation(Override.class); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); methodBuilder.addModifiers(modifiers.toArray(new Modifier[modifiers.size()])); for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { methodBuilder.addTypeVariable( TypeVariableName.get((TypeVariable) typeParameterElement.asType())); } methodBuilder.returns(TypeName.get(method.getReturnType())); for (VariableElement parameter : method.getParameters()) { methodBuilder.addParameter(TypeName.get(parameter.asType()), parameter.getSimpleName().toString()); } for (TypeMirror thrownType : method.getThrownTypes()) { methodBuilder.addException(TypeName.get(thrownType)); } return methodBuilder; }

Target:
public static Builder overriding(ExecutableElement method) { checkNotNull(method, "method == null"); Set<Modifier> modifiers = method.getModifiers(); if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.FINAL) || modifiers.contains(Modifier.STATIC)) { throw new IllegalArgumentException("cannot override method with modifiers: " + modifiers); } String methodName = method.getSimpleName().toString(); MethodSpec.Builder methodBuilder = MethodSpec.methodBuilder(methodName); methodBuilder.addAnnotation(Override.class); modifiers = new LinkedHashSet<>(modifiers); modifiers.remove(Modifier.ABSTRACT); methodBuilder.addModifiers(modifiers); for (TypeParameterElement typeParameterElement : method.getTypeParameters()) { methodBuilder.addTypeVariable( TypeVariableName.get((TypeVariable) typeParameterElement.asType())); } methodBuilder.returns(TypeName.get(method.getReturnType())); for (VariableElement parameter : method.getParameters()) { methodBuilder.addParameter(TypeName.get(parameter.asType()), parameter.getSimpleName().toString()); } for (TypeMirror thrownType : method.getThrownTypes()) { methodBuilder.addException(TypeName.get(thrownType)); } return methodBuilder; }
Source:
public void testSupplierSetsAttribute() throws Exception { entity = app.addChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 100l) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(stringSensor, new Supplier<String>() { @Override public String get() { return reference.get(); } }))); Entities.startManagement(entity); app.start(ImmutableList.of(loc)); reference.set("new"); Thread.sleep(200l); String value = entity.getAttribute(stringSensor); assertNotNull(value); assertEquals(value, "new"); }

Target:
public void testSupplierSetsAttribute() throws Exception { entity = app.createAndManageChild(EntitySpec.create(DataEntity.class) .configure(DataEntity.POLL_PERIOD, 50L) .configure(DataEntity.SENSOR_SUPPLIER_MAP, MutableMap.<AttributeSensor<?>, Supplier<?>>of(stringSensor, new Supplier<String>() { @Override public String get() { return reference.get(); } }))); app.start(ImmutableList.of(loc)); reference.set("new"); EntityTestUtils.assertAttributeEqualsEventually(entity, stringSensor, "new"); }
Source:
public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { final long delay = unit.toMillis(delayTime); final Runnable delayLaunch = new Runnable() { @Override public void run() { try { Thread.sleep(delay); } catch (InterruptedException e) { System.err.println("iOS post-delay thread interrupted"); } } }; final Runnable runnable = new Runnable() { @Override public void run() { if (isUnsubscribed()) { return; } action.call(); } }; NSBlockOperation delayOperation = new NSBlockOperation(); NSBlockOperation runOperation = new NSBlockOperation(); delayOperation.addExecutionBlock$(delayLaunch); runOperation.addExecutionBlock$(runnable); runOperation.addDependency$(delayOperation); operationQueue.addOperation$(delayOperation); operationQueue.addOperation$(runOperation); return Subscriptions.empty(); }

Target:
public Subscription schedule(final Action0 action, long delayTime, TimeUnit unit) { ScheduledExecutorService executor = Executors.newScheduledThreadPool(1); final NSBlockOperation runOperation = new NSBlockOperation(); executor.schedule(new Runnable() { @Override public void run() { if (isUnsubscribed()) { return; } final Runnable actionRunner = new Runnable() { @Override public void run() { action.call(); } }; runOperation.addExecutionBlock$(actionRunner); operationQueue.addOperation(runOperation); } }, delayTime, unit); return Subscriptions.create(new Action0() { @Override public void call() { runOperation.cancel(); } }); }
Source:
public void setCredentials(String user, String password) { if (user != null && password != null) { Credentials credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); } }

Target:
public void setCredentials(String user, String password) { Credentials credentials = null; if (user != null && password != null) credentials = new UsernamePasswordCredentials(user, password); this.client.getCredentialsProvider().setCredentials( new AuthScope(httpHost.getHostName(), httpHost.getPort()), credentials); }
Source:
public Sheet sheet() { try { return new RestSheet( URI.create( new JdkRequest(UriBuilder.fromUri(this.home).build()) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .method(Request.GET) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/links/link[@rel='account']/@href") .get(0) ), this.token ); } catch (IOException ex) { throw new IllegalStateException(ex); } }

Target:
public Sheet sheet() { try { return new RestSheet( URI.create( new JdkRequest(this.home) .header(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML) .header(HttpHeaders.AUTHORIZATION, this.token) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK) .as(XmlResponse.class) .xml() .xpath("/page/links/link[@rel='account']/@href") .get(0) ), this.token ); } catch (IOException ex) { throw new IllegalStateException(ex); } }
Source:
public void conceptListHelper_shouldReturnEmptyListWhenGivenDescriptorIsNullOrEmpty() { List<Concept> list = OpenmrsUtil.conceptListHelper(""); assertTrue(list.size() == 0); list = OpenmrsUtil.conceptListHelper(null); assertTrue(list.size() == 0); }

Target:
public void conceptListHelper_shouldReturnEmptyListWhenGivenDescriptorIsNullOrEmpty() { assertTrue(OpenmrsUtil.conceptListHelper("").isEmpty()); assertTrue(OpenmrsUtil.conceptListHelper(null).isEmpty()); }
Source:
public void shoudAvailableLocalesBeNonEmpty() { List<String> locales = LocaleUtils.getAvailableLocales(); int localesSize = locales.size(); assertTrue(localesSize > 0); }

Target:
public void shoudAvailableLocalesBeNonEmpty() { List<String> locales = LocaleUtils.getAvailableLocales(); assertThat(locales, is(not(empty()))); }
Source:
public Phone setAccount(Account account) { if(((AbstractResource)account).isMaterialized()) { setResourceProperty(ACCOUNT,account); } else{ setMaterializableResourceProperty(ACCOUNT,account); } return this; }

Target:
public Phone setAccount(Account account) { setMaterializableResourceProperty(ACCOUNT, account); return this; }
Source:
public SmeltingRecipe build() { checkState(exemplaryResult != null && exemplaryResult != ItemStackSnapshot.NONE, "The result must be specified."); checkState(exemplaryIngredient != null && exemplaryIngredient != ItemStackSnapshot.NONE, "The ingredient must be specified."); checkState(ingredientPredicate != null, "You must specify the ingredient predicate."); checkState(ingredientPredicate.test(exemplaryIngredient), "The ingredient predicate does not allow the specified exemplary ingredient."); checkState(experience >= 0, "The experience must be non-negative."); return new SpongeSmeltingRecipe(exemplaryResult, exemplaryIngredient, ingredientPredicate, experience); }

Target:
public SmeltingRecipe build() { checkState(this.exemplaryResult != null && this.exemplaryResult != ItemStackSnapshot.NONE, "The result must be specified."); checkState(this.exemplaryIngredient != null && this.exemplaryIngredient != ItemStackSnapshot.NONE, "The ingredient must be specified."); checkState(this.ingredientPredicate != null, "You must specify the ingredient predicate."); checkState(this.ingredientPredicate.test(this.exemplaryIngredient), "The ingredient predicate does not allow the specified exemplary ingredient."); checkState(this.experience >= 0, "The experience must be non-negative."); return new SpongeSmeltingRecipe(this.exemplaryResult, this.exemplaryIngredient, this.ingredientPredicate, this.experience); }
Source:
public static void tickEntity(final Consumer<net.minecraft.entity.Entity> consumer, final net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); final EntityBridge mixinEntity = (EntityBridge) entity; if (!mixinEntity.bridge$shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext().source(entity); try (final EntityTickContext context = tickContext; final Timing entityTiming = ((TimingBridge) entity).bridge$getTimingsHandler() ) { if (entity instanceof OwnershipTrackedBridge) { ((OwnershipTrackedBridge) entity).tracked$getNotifierReference() .ifPresent(context::notifier); ((OwnershipTrackedBridge) entity).tracked$getOwnerReference() .ifPresent(context::owner); } context.buildAndSwitch(); entityTiming.startTiming(); consumer.accept(entity); if (ShouldFire.MOVE_ENTITY_EVENT_POSITION || ShouldFire.ROTATE_ENTITY_EVENT) { SpongeCommonEventFactory.callMoveEntityEvent(entity, context); } } catch (Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, tickContext); } }

Target:
public static void tickEntity(final Consumer<net.minecraft.entity.Entity> consumer, final net.minecraft.entity.Entity entity) { checkArgument(entity instanceof Entity, "Entity %s is not an instance of SpongeAPI's Entity!", entity); checkNotNull(entity, "Cannot capture on a null ticking entity!"); final EntityBridge mixinEntity = (EntityBridge) entity; if (!mixinEntity.bridge$shouldTick()) { return; } final EntityTickContext tickContext = TickPhase.Tick.ENTITY.createPhaseContext(PhaseTracker.SERVER).source(entity); try (final EntityTickContext context = tickContext; final Timing entityTiming = ((TimingBridge) entity).bridge$getTimingsHandler() ) { if (entity instanceof OwnershipTrackedBridge) { ((OwnershipTrackedBridge) entity).tracked$getNotifierReference() .ifPresent(context::notifier); ((OwnershipTrackedBridge) entity).tracked$getOwnerReference() .ifPresent(context::owner); } context.buildAndSwitch(); entityTiming.startTiming(); consumer.accept(entity); if (ShouldFire.MOVE_ENTITY_EVENT_POSITION || ShouldFire.ROTATE_ENTITY_EVENT) { SpongeCommonEventFactory.callMoveEntityEvent(entity, context); } } catch (Exception | NoClassDefFoundError e) { PhasePrinter.printExceptionFromPhase(PhaseTracker.getInstance().stack, e, tickContext); } }
Source:
private List<FenceProxySourceType> getFenceProxySources() { List<FenceProxySourceType> fenceProxySources = _vds.getFenceProxySources(); if (fenceProxySources == null || fenceProxySources.isEmpty()) { fenceProxySources = FenceProxySourceTypeHelper.parseFromString( Config.<String> getValue(ConfigValues.FenceProxyDefaultPreferences)); } return fenceProxySources; }

Target:
private List<FenceProxySourceType> getFenceProxySources() { List<FenceProxySourceType> fenceProxySources = _vds.getFenceProxySources(); if (CollectionUtils.isEmpty(fenceProxySources)) { fenceProxySources = FenceProxySourceTypeHelper.parseFromString( Config.<String> getValue(ConfigValues.FenceProxyDefaultPreferences)); } return fenceProxySources; }
Source:
private void createNestedRepo(String path) throws IOException { File gitLinkDir = new File(db.getWorkTree(), path); FileUtils.mkdir(gitLinkDir); FileRepositoryBuilder nestedBuilder = new FileRepositoryBuilder(); nestedBuilder.setWorkTree(gitLinkDir); Repository nestedRepo = nestedBuilder.build(); nestedRepo.create(); File readme1 = new File(gitLinkDir, "README1.md"); FileUtils.createNewFile(readme1); PrintWriter writer1 = new PrintWriter(readme1); writer1.print("content"); writer1.close(); File readme2 = new File(gitLinkDir, "README2.md"); FileUtils.createNewFile(readme2); PrintWriter writer2 = new PrintWriter(readme2); writer2.print("content"); writer2.close(); try (Git git = new Git(nestedRepo)) { git.add().addFilepattern(".").call(); git.commit().setMessage("subrepo commit").call(); } catch (GitAPIException e) { throw new RuntimeException(e); } }

Target:
private void createNestedRepo(String path) throws IOException { File gitLinkDir = new File(db.getWorkTree(), path); FileUtils.mkdir(gitLinkDir); FileRepositoryBuilder nestedBuilder = new FileRepositoryBuilder(); nestedBuilder.setWorkTree(gitLinkDir); Repository nestedRepo = nestedBuilder.build(); nestedRepo.create(); writeTrashFile(path, "README1.md", "content"); writeTrashFile(path, "README2.md", "content"); try (Git git = new Git(nestedRepo)) { git.add().addFilepattern(".").call(); git.commit().setMessage("subrepo commit").call(); } catch (GitAPIException e) { throw new RuntimeException(e); } }
Source:
private String exportBase64Certificate(PemObject pemObject) throws InternalErrorException { String exportedCert; try { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); Certificate certificate = certFact.generateCertificate(new ByteArrayInputStream(pemObject.getContent())); exportedCert = "-----BEGIN CERTIFICATE-----" + "\n"; exportedCert += Base64.getMimeEncoder().encodeToString(certificate.getEncoded()); exportedCert += "\n" + "-----END CERTIFICATE-----"; } catch (CertificateException ex) { throw new InternalErrorException(ex); } return exportedCert; }

Target:
private String exportBase64Certificate(PemObject pemObject) throws InternalErrorException { String exportedCert; try (ByteArrayInputStream bis = new ByteArrayInputStream(pemObject.getContent())) { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); Certificate certificate = certFact.generateCertificate(bis); exportedCert = "-----BEGIN CERTIFICATE-----" + "\n"; exportedCert += Base64.getMimeEncoder().encodeToString(certificate.getEncoded()); exportedCert += "\n" + "-----END CERTIFICATE-----"; } catch (CertificateException | IOException ex) { throw new InternalErrorException(ex); } return exportedCert; }
Source:
RGB acquireCurrentColorSelectionGtk3(long handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); rgb = new RGB (red, green, blue); return rgb; }

Target:
RGB acquireCurrentColorSelectionGtk3(long handle, GdkRGBA rgba) { int red = 0; int green = 0; int blue = 0; OS.gtk_color_chooser_get_rgba (handle, rgba); red = (int) (rgba.red * 255); green = (int) (rgba.green * 255); blue = (int) (rgba.blue * 255); return new RGB (red, green, blue); }
Source:
protected MatchResult matchAndParseHeader(String headerName, String headerValue) { return new MatchResult("<LINK_0>", PrettyPrinterDisplayType.TEXT); }

Target:
protected MatchResult matchAndParseHeader(String headerName, String headerValue) { if (headerName.equals(TEST_HEADER_NAME) && headerValue.equals(TEST_HEADER_VALUE)) { return new MatchResult("<LINK_0>", PrettyPrinterDisplayType.TEXT); } else { return null; } }
Source:
public boolean isClosedWithinPastHour() { Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC")); now.add(Calendar.MILLISECOND, (int) (60 * 60 * 1000 * timeZone)); Calendar start = Calendar.getInstance(TimeZone.getTimeZone("UTC")); start.setTime(startTime); Calendar deadline = Calendar.getInstance(TimeZone.getTimeZone("UTC")); deadline.setTime(endTime); long nowMillis = now.getTimeInMillis(); long deadlineMillis = deadline.getTimeInMillis(); long differenceBetweenNowAndDeadline = (deadlineMillis - nowMillis) / (60 * 60 * 1000); return now.after(start) && differenceBetweenNowAndDeadline >= 0 && differenceBetweenNowAndDeadline < 1; }

Target:
public boolean isClosedWithinPastHour() { return TimeHelper.isWithinPastHourFromNow(new Date(endTime.getTime() + gracePeriod * 60000)); }
Source:
public final void detectAndSendChanges() { super.detectAndSendChanges(); if (FMLCommonHandler.instance().getSide() == Side.SERVER) { sendUpdateToClient(); sendWidgetsServerData(); } }

Target:
public final void detectAndSendChanges() { super.detectAndSendChanges(); if (FMLCommonHandler.instance().getEffectiveSide() == Side.SERVER) { sendUpdateToClient(); sendWidgetsServerData(); } }
Source:
public void verifyAsyncMetadataOptionExplicitDisabled() throws Exception { verifyAsyncIs( defaultMetadata, false ); }

Target:
public void verifyAsyncMetadataOptionExplicitDisabled() throws Exception { verifyAsyncIs( syncMetadata, false ); }
Source:
public User createUser(User user, String password) throws APIException { if (user.getUserId() != null) { throw new APIException("This method can be used for only creating new users"); } Context.requirePrivilege(PrivilegeConstants.ADD_USERS); checkPrivileges(user); if (hasDuplicateUsername(user)) { throw new DAOException(String.format("Username %s or system id %s is already in use.", user.getUsername(), user.getSystemId())); } OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); return dao.saveUser(user, password); }

Target:
public User createUser(User user, String password) throws APIException { if (user.getUserId() != null) { throw new APIException("This method can be used for only creating new users"); } Context.requirePrivilege(PrivilegeConstants.ADD_USERS); checkPrivileges(user); if (password == null || password.length() < 1) { throw new APIException("User.creating.password.required", (Object[]) null); } if (hasDuplicateUsername(user)) { throw new DAOException("Username " + user.getUsername() + " or system id " + user.getSystemId() + " is already in use."); } OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId()); return dao.saveUser(user, password); }