auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void value(@NonNull File file) throws IOException { super.flush(); beforeValue(false); // add comma if in array // Copy the file contents onto the stream Reader input = null; try { FileInputStream fis = new FileInputStream(file); input = new BufferedReader(new InputStreamReader(fis, "UTF-8")); IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } out.flush(); }

Target:
public void value(@NonNull File file) throws IOException { if (file == null || file.length() <= 0) { return; } super.flush(); beforeValue(false); // add comma if in array // Copy the file contents onto the stream Reader input = null; try { FileInputStream fis = new FileInputStream(file); input = new BufferedReader(new InputStreamReader(fis, "UTF-8")); IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } out.flush(); }
Source:
private void trackSessionIfNeeded(boolean autoCaptured, Session session) { String releaseStage = getReleaseStage(); boolean notifyForRelease = client != null && configuration.shouldNotifyForReleaseStage(releaseStage); if ((configuration.shouldAutoCaptureSessions() || !autoCaptured) && notifyForRelease) { sessionQueue.add(session); sessionStore.write(session); // store session for sending trackedFirstSession = true; } }

Target:
private void trackSessionIfNeeded(boolean autoCaptured, Session session) { String releaseStage = getReleaseStage(); boolean notifyForRelease = configuration.shouldNotifyForReleaseStage(releaseStage); if ((configuration.shouldAutoCaptureSessions() || !autoCaptured) && notifyForRelease) { sessionQueue.add(session); sessionStore.write(session); // store session for sending trackedFirstSession = true; } }
Source:
protected String streamableToString(JsonStream.Streamable streamable) { StringWriter writer = new StringWriter(); JsonStream jsonStream = new JsonStream(writer); try { streamable.toStream(jsonStream); } catch(java.io.IOException e) return writer.toString(); }

Target:
protected String streamableToString(JsonStream.Streamable streamable) throws IOException { StringWriter writer = new StringWriter(); JsonStream jsonStream = new JsonStream(writer); streamable.toStream(jsonStream); return writer.toString(); }
Source:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { // use the english locale to avoid the infamous turkish locale bug final String upperCaseIsolationLevelName = Optional.of(transactionIsolationName.toUpperCase(Locale.ENGLISH)) .orElseThrow(IllegalArgumentException::new); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }

Target:
public static int getTransactionIsolation(final String transactionIsolationName) { if (transactionIsolationName != null) { try { // use the english locale to avoid the infamous turkish locale bug final String upperCaseIsolationLevelName = transactionIsolationName.toUpperCase(Locale.ENGLISH); return IsolationLevel.valueOf(upperCaseIsolationLevelName).getLevelId(); } catch (Exception e) { throw new IllegalArgumentException("Invalid transaction isolation value: " + transactionIsolationName); } } return -1; }
Source:
public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); isAutoCommit = autoCommit; isCommitStateDirty = false; dirtyBits |= DIRTY_BIT_AUTOCOMMIT; }

Target:
public void setAutoCommit(boolean autoCommit) throws SQLException { delegate.setAutoCommit(autoCommit); if (isAutoCommit != autoCommit) { isCommitStateDirty = false; } isAutoCommit = autoCommit; dirtyBits |= DIRTY_BIT_AUTOCOMMIT; }
Source:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry == PoolEntry.MAXED_POOL_MARKER) { return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } // addConnection() failed, so we sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }

Target:
public Boolean call() throws Exception { long sleepBackoff = 200L; do { final PoolEntry poolEntry = createPoolEntry(); if (poolEntry == MAXED_POOL_MARKER) { return Boolean.FALSE; } else if (poolEntry != null) { connectionBag.add(poolEntry); return Boolean.TRUE; } // addConnection() failed, so we sleep and retry quietlySleep(sleepBackoff); sleepBackoff = Math.min(connectionTimeout / 2, (long) (sleepBackoff * 1.3)); } while (true); }
Source:
public <M> List<M> getEnabledModulesByClass(Class<M> moduleClass, M defaultPlugin) { ArrayList<M> pluginClasses = new ArrayList<M>(); if (defaultPlugin != null) { pluginClasses.add(defaultPlugin); } if (manager.getExtensions(moduleClass).size() > 0) { pluginClasses.addAll(manager.getExtensions(moduleClass)); } return pluginClasses; }

Target:
public <M> List<M> getEnabledModulesByClass(Class<M> moduleClass, M defaultPlugin) { ArrayList<M> pluginClasses = new ArrayList<M>(); if (defaultPlugin != null) { pluginClasses.add(defaultPlugin); } pluginClasses.addAll(manager.getExtensions(moduleClass)); return pluginClasses; }
Source:
public Map<String, Set<String>> readClasspathStorages() { Map<String, Set<String>> result = new LinkedHashMap<String, Set<String>>(); return result; }

Target:
public Map<String, Set<String>> readClasspathStorages() { return new LinkedHashMap<String, Set<String>>(); }
Source:
protected PluginClasspath createPluginClasspath() { if (RuntimeMode.DEVELOPMENT.equals(getRuntimeMode())) { return new DevelopmentPluginClasspath(); } return new NGrinderPluginClasspath(); }

Target:
protected PluginClasspath createPluginClasspath() { return new NGrinderPluginClasspath(); }
Source:
public void clearLevel(String loggerName) { java.util.logging.Logger logger = loggers.get(loggerName); if (logger == null) { logger = java.util.logging.Logger.getLogger(loggerName); } logger.setLevel(null); }

Target:
public synchronized void clearLevel(String loggerName) { java.util.logging.Logger logger = loggers.remove(loggerName); if (logger != null) { logger.setLevel(null); } }
Source:
public void testCreateAnnouncementLocation() { URI baseURI = URI.create("http://example.com:8080"); URI baseWithSlash = URI.create("http://example.com:8080/"); String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseURI, nodeId)); assertEquals(expected, HttpDiscoveryAnnouncementClient.createAnnouncementLocation(baseWithSlash, nodeId)); }

Target:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId), expected); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId), expected); }
Source:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId)); assertEquals(expected, createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId)); }

Target:
public void testCreateAnnouncementLocation() { String nodeId = "ffff"; URI expected = URI.create("http://example.com:8080/v1/announcement/" + nodeId); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080"), nodeId), expected); assertEquals(createAnnouncementLocation(URI.create("http://example.com:8080/"), nodeId), expected); }
Source:
DecayTDigest(TDigest digest, double alpha, Ticker ticker) { this(digest, alpha, ticker, TimeUnit.NANOSECONDS.toSeconds(ticker.read())); }

Target:
private DecayTDigest(TDigest digest, double alpha, Ticker ticker) { this(digest, alpha, ticker, TimeUnit.NANOSECONDS.toSeconds(ticker.read())); }
Source:
public void flush() { BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } if (logger.isInfoEnabled()) { logger.info(line); } } catch (IOException e) { throw new Error(e); // should never get here } } getBuffer().setLength(0); }

Target:
public void flush() { BufferedReader in = new BufferedReader(new StringReader(getBuffer().toString())); while (true) { try { String line = in.readLine(); if (line == null) { break; } logger.info(line); } catch (IOException e) { throw new Error(e); // should never get here } } getBuffer().setLength(0); }
Source:
private void setDelta(int bucket, int value) { int slot = bucketToSlot(bucket); // clear the old value byte clearMask = (byte) (BUCKET_MASK << shiftForBucket(bucket)); deltas[slot] &= (byte) ~clearMask; // set the new value byte setMask = (byte) (value << shiftForBucket(bucket)); deltas[slot] |= setMask; }

Target:
private void setDelta(int bucket, int value) { int slot = bucketToSlot(bucket); // clear the old value byte clearMask = (byte) (BUCKET_MASK << shiftForBucket(bucket)); deltas[slot] &= ~clearMask; // set the new value byte setMask = (byte) (value << shiftForBucket(bucket)); deltas[slot] |= setMask; }
Source:
public void close() { try { context.dispose(); loginContext.logout(); } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }

Target:
public void close() { try { try { context.dispose(); } finally { loginContext.logout(); } } catch (GSSException | LoginException e) { throw new AuthenticationException(e); } }
Source:
public boolean isPublic(final Class<? extends T> clazz) { final XKasperPublic annotation = checkNotNull(clazz).getAnnotation(XKasperPublic.class); return null != annotation; }

Target:
public boolean isPublic(final Class<? extends T> clazz) { return (null != checkNotNull(clazz).getAnnotation(XKasperPublic.class)); }
Source:
public HTTPKasperResponse asHttp(){ if (TransportMode.HTTP.equals(getTransportMode()) { return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }

Target:
public HTTPKasperResponse asHttp(){ if (TransportMode.HTTP.equals(getTransportMode())) { return (HTTPKasperResponse) this; } throw new KasperException("Not an HTTP response"); }
Source:
public void testLeftBubblePosition() { Float expectedXLeft = EXPECTED_X_STD_LEFT; Float expectedYLeft = EXPECTED_Y_STD; ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(expectedXLeft, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(expectedYLeft, bubbleActor.calculateImageY(CALC_Y_LEFT)); }

Target:
public void testLeftBubblePosition() { ShowBubbleActor bubbleActor = new ShowBubbleActor(OBJECT_NAME, sprite, Constants.SAY_BRICK); assertEquals(EXPECTED_X_STD_LEFT, bubbleActor.calculateLeftImageX(CALC_X_LEFT)); assertEquals(EXPECTED_Y_STD, bubbleActor.calculateImageY(CALC_Y_LEFT)); }
Source:
public List<UUID> getKeyList(List<? extends UserData> userDataList) { List<UUID> keyList = new ArrayList<>(); for (UserData userData : userDataList) { keyList.add(userData.getDeviceKey()); } return keyList; }

Target:
private List<UUID> getKeyList(List<? extends UserData> userDataList) { List<UUID> keyList = new ArrayList<>(); for (UserData userData : userDataList) { keyList.add(userData.getDeviceKey()); } return keyList; }
Source:
protected void getTags() { GetTagsTask getTagsTask = new GetTagsTask(); getTagsTask.setOnTagsResponseListener(this); getTagsTask.execute(); }

Target:
private void getTags() { GetTagsTask getTagsTask = new GetTagsTask(); getTagsTask.setOnTagsResponseListener(this); getTagsTask.execute(); }
Source:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); assertSame(BRICK_FORMULA_VALUE, cloneBrickFormula.interpretInteger(sprite)); }

Target:
public void testBrickFieldValidValue() throws InterpretationException { assertSame(BRICK_FORMULA_VALUE, brickFormula.interpretInteger(sprite)); }
Source:
public void onActivityResult(int requestCode, int resultCode, Intent data) { //Register your intent with "queueIntent" if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else if (requestCode == REQUEST_EXPORT_EMBROIDERY_FILE) { if (resultCode == RESULT_OK) { Log.d(TAG, "Exported embroidery file"); } } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { //Register your intent with "queueIntent" if (intentListeners.indexOfKey(requestCode) >= 0) { IntentListener asker = intentListeners.get(requestCode); asker.onIntentResult(resultCode, data); intentListeners.remove(requestCode); } else { stageResourceHolder.onActivityResult(requestCode, resultCode, data); } }
Source:
public void setUp() throws Exception { Script startScript = BrickTestUtils.createProjectAndGetStartScript("newDataDialogTest"); variableBrickPosition = 1; listBrickPosition = 2; // "when program starts" brick is the first startScript.addBrick(variableBrickPosition - 1, new SetVariableBrick()); startScript.addBrick(listBrickPosition - 1, new AddItemToUserListBrick()); baseActivityTestRule.launchActivity(); }

Target:
public void setUp() throws Exception { Script startScript = BrickTestUtils.createProjectAndGetStartScript("newDataDialogTest"); variableBrickPosition = 1; listBrickPosition = 2; startScript.addBrick(new SetVariableBrick()); startScript.addBrick(new AddItemToUserListBrick()); baseActivityTestRule.launchActivity(); }
Source:
public void uncaughtException(Thread thread, Throwable exception) { CrashReporter.storeUnhandledException(exception); preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); Log.e(TAG, "uncaughtException: ", exception); exit(); }

Target:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "uncaughtException: ", exception); CrashReporter.storeUnhandledException(exception); preferences.edit().putBoolean(RECOVERED_FROM_CRASH, true).commit(); exit(); }
Source:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { for (int j = 0; j < sprite.getLookDataList().size(); j++) { LookData lookData = sprite.getLookDataList().get(j); lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }

Target:
private void disposeTextures() { for (Scene scene : project.getSceneList()) { for (Sprite sprite : scene.getSpriteList()) { for (LookData lookData : sprite.getLookDataList()) { lookData.getPixmap().dispose(); lookData.getTextureRegion().getTexture().dispose(); } } } }
Source:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled); editor.commit(); if (isEnabled) { CloudMessaging.initialize(context); } }

Target:
public static void setCloudNotificationsEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CLOUD_NOTIFICATIONS, isEnabled).commit(); CloudMessaging.initialize(context); }
Source:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); CrashReporter.initialize(context); }

Target:
public static void setAutoCrashReportingEnabled(Context context, boolean isEnabled) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean(SETTINGS_CRASH_REPORTS, isEnabled); editor.commit(); if (isEnabled) { CrashReporter.initialize(context); } }
Source:
public boolean isRecoveredFromCrash() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(RECOVERED_FROM_CRASH, false); }

Target:
private boolean isRecoveredFromCrash() { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(RECOVERED_FROM_CRASH, false); }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler(this)); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); CrashReporter.sendUnhandledCaughtException(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); titleActionBar = null; returnToProjectsList = false; returnByPressingBackButton = false; Thread.setDefaultUncaughtExceptionHandler(new BaseExceptionHandler()); checkIfCrashRecoveryAndFinishActivity(this); getActionBar().setDisplayHomeAsUpEnabled(true); }
Source:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "unhandled exception", exception); CrashReporter.storeUnhandledException(exception); if (!BuildConfig.DEBUG) { System.exit(EXIT_CODE); android.os.Process.killProcess(android.os.Process.myPid()); } }

Target:
public void uncaughtException(Thread thread, Throwable exception) { Log.e(TAG, "unhandled exception", exception); CrashReporter.storeUnhandledException(exception); System.exit(EXIT_CODE); android.os.Process.killProcess(android.os.Process.myPid()); }
Source:
private void askQuestion() { ArrayList<Object> params = new ArrayList<>(); params.add(this); if (StageActivity.messageHandler == null) { return; } // Check to see if a recognition activity is present Message message = StageActivity.messageHandler.obtainMessage(StageActivity.REGISTER_INTENT, params); message.sendToTarget(); questionAsked = true; }

Target:
private void askQuestion() { if (StageActivity.messageHandler == null) { return; } ArrayList<Object> params = new ArrayList<>(); params.add(this); Message message = StageActivity.messageHandler.obtainMessage(StageActivity.REGISTER_INTENT, params); message.sendToTarget(); questionAsked = true; }
Source:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); return; } }

Target:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) { try { final Class<?> componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway EeLogger.ROOT_LOGGER.debugf(e,"Ignoring failure to handle interceptor annotations for %s", description.getComponentClassName()); } }
Source:
public void destroy() { // add a breakpoint here to check if this method is invoked LOG.info("===================="); LOG.info("Destroyed CountBean"); LOG.info("===================="); TestResultsBean.setPreDestroySessionScoped(true); }

Target:
public void destroy() { LOG.info("Destroyed CountBean"); TestResultsBean.setPreDestroySessionScoped(true); }
Source:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); } catch (Exception e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); }

Target:
private void processComponentConfig(final EEApplicationClasses applicationClasses, final DeploymentReflectionIndex deploymentReflectionIndex, final ComponentDescription description, DeploymentUnit deploymentUnit) throws DeploymentUnitProcessingException { final Class<?> componentClass; try { componentClass = ClassLoadingUtils.loadClass(description.getComponentClassName(), deploymentUnit); } catch (Throwable e) { //just ignore the class for now. //if it is an optional component this is ok, if it is not an optional component //it will fail at configure time anyway return; } handleAnnotations(applicationClasses, deploymentReflectionIndex, componentClass, description); }
Source:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (i <= timeoutCount); runTransaction(isTimeout); } try { return TxTestUtil.getStatusAsString(txn.getStatus()); } catch (SystemException se) { throw new EJBException("Can't get status of transaction", se); } }

Target:
public String testTransaction(int transactionCount, int timeoutCount) throws RemoteException, NamingException, SystemException { TxTestUtil.checkTransactionExists(tm, false); for(int i = 1; i <= transactionCount; i++) { boolean isTimeout = (i <= timeoutCount); runTransaction(isTimeout); } return TxTestUtil.getStatusAsString(txn.getStatus()); }
Source:
public void writeItems(java.util.List<Object> items) throws Exception { for(Object o : items){ LOG.info(o.toString()); } }

Target:
public void writeItems(java.util.List<Object> items) throws Exception { // do nothing - if the items are delivered to writer test passes }
Source:
protected AbstractWebFailoverTestCase(String deploymentName, TransactionMode mode) { this.deploymentName = deploymentName; this.nonOwnerTask = () -> { // If the cache is non-transactional, we need to wait for that replication to finish, otherwise the read can be stale if (mode.isTransactional()) { try { Thread.sleep(GRACE_TIME_TO_REPLICATE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; }

Target:
protected AbstractWebFailoverTestCase(String deploymentName, TransactionMode mode) { this.deploymentName = deploymentName; this.nonOwnerTask = () -> { // If the cache is non-transactional, we need to wait for that replication to finish, otherwise the read can be stale if (!mode.isTransactional()) { try { Thread.sleep(GRACE_TIME_TO_REPLICATE); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }; }
Source:
public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); modelNode.get(OPERATION_HEADERS).get(ALLOW_RESOURCE_SERVICE_RESTART).set(true); ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); }

Target:
public static void setProperty(String name, String value, ModelControllerClient client) { ModelNode modelNode = createOpNode("system-property=" + name, ADD); modelNode.get(VALUE).set(value); ModelNode result = executeOp(modelNode, client); log.debugf("Added property %s, result: %s", name, result); }
Source:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); // Transformers if (context.isRegisterTransformers()) { JSFResourceDefinition.registerTransformers(subsystem); } }

Target:
public void initialize(final ExtensionContext context) { JSFLogger.ROOT_LOGGER.debug("Activating JSF(Mojarra) Extension"); final SubsystemRegistration subsystem = context.registerSubsystem(SUBSYSTEM_NAME, CURRENT_MODEL_VERSION); subsystem.registerSubsystemModel(JSFResourceDefinition.INSTANCE); subsystem.registerXMLElementWriter(JSFSubsystemParser_1_1.INSTANCE); }
Source:
private static boolean isValidBackupDir(Path backupDir) { String backupDirName = backupDir.toFile().getName(); // Check if it of format yyyyMMddHHmm try { DateUtil.getDate(backupDirName); return true; } catch (Exception e) { return false; } }

Target:
private static boolean isValidBackupDir(Path backupDir) { String backupDirName = backupDir.toFile().getName(); // Check if it of format yyyyMMddHHmm return (DateUtil.getDate(backupDirName) != null); }
Source:
public void execute() throws Exception { // If Cassandra is started then only start Snapshot Backup while (!CassandraMonitor.hasCassadraStarted()) { logger.debug( "Cassandra has not yet started, hence Snapshot Backup will start after [" + WAIT_TIME_MS / 1000 + "] secs ..."); sleeper.sleep(WAIT_TIME_MS); } // Do not allow more than one snapshot to run at the same time. This is possible as this // happens on CRON. if (!lock.tryLock()) { logger.error("Snapshot Operation is already running! Try again later."); throw new Exception("Snapshot Operation already running"); } try { executeSnapshot(); } finally { lock.unlock(); } }

Target:
public void execute() throws Exception { // If Cassandra is started then only start Snapshot Backup while (!CassandraMonitor.hasCassadraStarted()) { logger.debug( "Cassandra has not yet started, hence Snapshot Backup will start after [" + WAIT_TIME_MS / 1000 + "] secs ..."); sleeper.sleep(WAIT_TIME_MS); } // Do not allow more than one snapshot to run at the same time. This is possible as this // happens on CRON. if (!lock.tryLock()) { logger.warn("Snapshot Operation is already running! Try again later."); throw new Exception("Snapshot Operation already running"); } try { executeSnapshot(); } finally { lock.unlock(); } }
Source:
public void setUseIntermediateSharedCache(boolean useIntermediateSharedCache) { //Not used by Infinispan 5.1 }

Target:
public boolean setUseIntermediateSharedCache(boolean useIntermediateSharedCache) { return false; }
Source:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); if (vertex.getAverageCoverage() <= minAverageCoverage || vertex.getAverageCoverage() >= maxAverageCoverage) { //broadcase kill self broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); }

Target:
public void detectLowCoverageVertex() { VertexValueWritable vertex = getVertexValue(); if (vertex.getAverageCoverage() < minAverageCoverage || vertex.getAverageCoverage() > maxAverageCoverage) { //broadcase kill self broadcastKillself(); vertex.setState(State.DEAD_NODE); activate(); } else voteToHalt(); }
Source:
private boolean checkedIfValid(ReadHeadInfo readHead, VKmer neighbor) { //if neighbor exist in read table //How to work with a read? //int neighborPositionOnRead = getVertexValue().walk.size() - getVertexValue().index + 1; int neighborPositionOnRead = getVertexValue().walkSize - getVertexValue().index; return readHead.getThisReadSequence().getGeneCodeAtPosition(neighborPositionOnRead) == neighbor .getGeneCodeAtPosition(kmerSize - 1); }

Target:
private boolean checkedIfValid(ReadHeadInfo readHead, VKmer neighbor) { //if neighbor exist in read table //How to work with a read? //int neighborPositionOnRead = getVertexValue().walk.size() - getVertexValue().index + 1; int neighborPositionOnRead = getVertexValue().walkSize - getVertexValue().index; for (int i = 0; i < kmerSize; i++) { if (readHead.getThisReadSequence().getGeneCodeAtPosition(neighborPositionOnRead + i) != neighbor .getGeneCodeAtPosition(i)) { return false; } } return true; }
Source:
public void getPrograms_shouldTestGetProgramsIfCohortIsEmpty() { int i = 0; Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.getMemberIds().clear(); patientPrograms = dao.getPatientPrograms(null, programs); assertEquals(patientPrograms.size(), 4); }

Target:
public void getPrograms_shouldTestGetProgramsIfCohortIsEmpty() { Cohort cohort = new Cohort(); Collection<Program> programs = pws.getAllPrograms(); List<PatientProgram> patientPrograms; cohort.getMemberIds().clear(); patientPrograms = dao.getPatientPrograms(null, programs); assertEquals(patientPrograms.size(), 4); }
Source:
public Concept hydrate(String s) { try { return Context.getConceptService().getConcept(Integer.valueOf(s)); } catch (Exception e) { logger.error("Error", e); } //pass return null; }

Target:
public Concept hydrate(String s) { try { return Context.getConceptService().getConcept(Integer.valueOf(s)); } catch (Exception e) { log.error("Error", e); } //pass return null; }
Source:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { String ORIGINAL_TEXT = "OriginalText"; ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText(ORIGINAL_TEXT); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals(ORIGINAL_TEXT); assertTrue(existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(ORIGINAL_TEXT, savedConceptProposal.getOriginalText()); assertEquals(conceptProposal, savedConceptProposal); }

Target:
public void saveConceptProposal_shouldReturnSavedConceptProposalObject() { final String ORIGINAL_TEXT = "OriginalText"; ConceptProposal conceptProposal = new ConceptProposal(); conceptProposal.setOriginalText(ORIGINAL_TEXT); List<ConceptProposal> existingConceptProposals = conceptService.getConceptProposals(ORIGINAL_TEXT); assertTrue(existingConceptProposals.isEmpty()); ConceptProposal savedConceptProposal = conceptService.saveConceptProposal(conceptProposal); assertEquals(ORIGINAL_TEXT, savedConceptProposal.getOriginalText()); assertEquals(conceptProposal, savedConceptProposal); }
Source:
public void getConceptsByClass_shouldGetConceptsByClass() { // replay List<Concept> actualConcepts = conceptService.getConceptsByClass(new ConceptClass(3)); // verify Assert.assertThat(actualConcepts, containsInAnyOrder(conceptService.getConcept(3), conceptService.getConcept(60), conceptService.getConcept(88), conceptService.getConcept(792))); }

Target:
public void getConceptsByClass_shouldGetConceptsByClass() { // replay List<Concept> actualConcepts = conceptService.getConceptsByClass(new ConceptClass(3)); // verify Assert.assertThat(actualConcepts.size(), is(4)); Assert.assertThat(actualConcepts, containsInAnyOrder(conceptService.getConcept(3), conceptService.getConcept(60), conceptService.getConcept(88), conceptService.getConcept(792))); }
Source:
public boolean isReady() { // TODO Auto-generated method stub return false; }

Target:
public boolean isReady() { return this.isReady(); }
Source:
public Object methodException(Context context, Class claz, String method, Exception e, Info info) { log.debug("Claz: " + claz.getName() + " method: " + method, e); // if formatting a date (and probably getting an "IllegalArgumentException") if ("format".equals(method)) { return null; } // keep the default behavior try { throw e; } catch (Exception x) { x.printStackTrace(); } return info; }

Target:
public Object methodException(Context context, Class claz, String method, Exception e, Info info) { log.debug("Claz: " + claz.getName() + " method: " + method, e); // if formatting a date (and probably getting an "IllegalArgumentException") if ("format".equals(method)) { return null; } return info; }
Source:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { // replay Context.logout(); Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); // verif Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }

Target:
public void authenticate_shouldAuthenticateUserWithAlternateScheme() { // replay Authenticated authenticated = Context.authenticate(new TestUsernameCredentials("admin")); // verif Assert.assertEquals("test-scheme", authenticated.getAuthenticationScheme()); Assert.assertEquals(Context.getAuthenticatedUser().getUuid(), authenticated.getUser().getUuid()); Assert.assertEquals("admin", Context.getAuthenticatedUser().getUsername()); }
Source:
public void equal_shouldReturnFalseIfObjectIsNull() { // A null argument to equal should not lead to an exception CohortMembership cohortMembership = new CohortMembership(12); boolean result = cohortMembership.equals(null); assertFalse(result); }

Target:
public void equal_shouldReturnFalseIfObjectIsNull() { // A null argument to equal should not lead to an exception CohortMembership cohortMembership = new CohortMembership(12); assertFalse(cohortMembership.equals(null)); }
Source:
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) { return diagnosisDAO.getActiveDiagnoses(patient); }

Target:
public List<Diagnosis> getDiagnoses(Patient patient, Date fromDate) { return diagnosisDAO.getActiveDiagnoses(patient, fromDate); }
Source:
public static boolean copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return false; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); return true; } }

Target:
public static void copyFile(InputStream inputStream, OutputStream outputStream) throws IOException { if (inputStream == null || outputStream == null) { if (outputStream != null) { IOUtils.closeQuietly(outputStream); } return; } try { IOUtils.copy(inputStream, outputStream); } finally { IOUtils.closeQuietly(outputStream); } }
Source:
public void expandJar_shouldExpandEntireJarIfNameIsNull() throws IOException { // Arrange final int numberOfFilesInJar = 6; File destinationFolder = this.getEmptyJarDestinationFolder(); // Act ModuleUtil.expandJar(getJarFile(), destinationFolder, null, false); // Assert Assert.assertEquals(numberOfFilesInJar, FileUtils.listFiles(destinationFolder, null, true).size()); // Clean up FileUtils.deleteDirectory(destinationFolder); }

Target:
public void expandJar_shouldExpandEntireJarIfNameIsNull() throws Exception { final int numberOfFilesInJar = 6; File destinationFolder = this.getEmptyJarDestinationFolder(); ModuleUtil.expandJar(getJarFile(), destinationFolder, null, false); Assert.assertEquals(numberOfFilesInJar, FileUtils.listFiles(destinationFolder, null, true).size()); FileUtils.deleteDirectory(destinationFolder); }
Source:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); // make a patient Patient patientToAddThenRemove = new Patient(4); // verify that the patient is not already in the Cohort assertFalse(service.getCohort(2).contains(patientToAddThenRemove.getPatientId())); // try to remove it from the cohort without failing try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }

Target:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); // make a patient Patient patientToAddThenRemove = new Patient(4); // verify that the patient is not already in the Cohort assertFalse(service.getCohort(2).contains(patientToAddThenRemove)); // try to remove it from the cohort without failing try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }
Source:
public static void setStaticUnknownConcept(Concept currentUnknownConcept) { ConceptServiceImpl.unknownConcept = currentUnknownConcept; }

Target:
private static void setStaticUnknownConcept(Concept currentUnknownConcept) { ConceptServiceImpl.unknownConcept = currentUnknownConcept; }
Source:
public static void setStaticHandlers(Map<String, ComplexObsHandler> currentHandlers) { ObsServiceImpl.handlers = currentHandlers; }

Target:
private static void setStaticHandlers(Map<String, ComplexObsHandler> currentHandlers) { ObsServiceImpl.handlers = currentHandlers; }
Source:
public static void setStaticIdentifierValidators( Map<Class<? extends IdentifierValidator>, IdentifierValidator> currentIdentifierValidators) { PatientServiceImpl.identifierValidators = currentIdentifierValidators; }

Target:
private static void setStaticIdentifierValidators( Map<Class<? extends IdentifierValidator>, IdentifierValidator> currentIdentifierValidators) { PatientServiceImpl.identifierValidators = currentIdentifierValidators; }
Source:
public static Thread runInNewDaemonThread(final Runnable runnable) { // make sure we're already in a daemon thread if (!isDaemonThread()) { throw new APIAuthenticationException("Only daemon threads can spawn new daemon threads"); } // we should consider making DaemonThread public, so the caller can access returnedObject and exceptionThrown DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); new Thread(runnable).start(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }

Target:
public static Thread runInNewDaemonThread(final Runnable runnable) { // make sure we're already in a daemon thread if (!isDaemonThread()) { throw new APIAuthenticationException("Only daemon threads can spawn new daemon threads"); } // we should consider making DaemonThread public, so the caller can access returnedObject and exceptionThrown DaemonThread thread = new DaemonThread() { @Override public void run() { isDaemonThread.set(true); try { Context.openSession(); runnable.run(); } finally { Context.closeSession(); } } }; thread.start(); return thread; }
Source:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { // get the current global properties List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); globalProperties.remove(3); // and now add a new one to it and save it globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }

Target:
public void saveGlobalProperties_shouldAssignUuidToAllNewProperties() throws Exception { // get the current global properties List<GlobalProperty> globalProperties = Context.getAdministrationService().getAllGlobalProperties(); // and now add a new one to it and save it globalProperties.add(new GlobalProperty("new prop", "new prop value", "desc")); Context.getAdministrationService().saveGlobalProperties(globalProperties); Assert.assertNotNull(Context.getAdministrationService().getGlobalPropertyObject("new prop").getUuid()); }
Source:
public CustomDatatype.Summary toHtmlSummary(CustomDatatype<T> datatype, String valueReference) { SerializingCustomDatatype<T> dt = (SerializingCustomDatatype<T>) datatype; return new CustomDatatype.Summary(dt.deserialize(valueReference).getName(), true); }

Target:
public CustomDatatype.Summary toHtmlSummary(CustomDatatype<T> datatype, String valueReference) { return toHtmlSummary(datatype, valueReference); }
Source:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { throw new IllegalStateException("throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } throwable.fillInStackTrace(); filter.filter(throwable); throw throwable; }

Target:
public Object answer(InvocationOnMock invocation) throws Throwable { if (throwable == null) { throw new IllegalStateException("throwable is null: " + "you shall not call #answer if #validateFor fails!"); } if (MockUtil.isMock(throwable)) { throw throwable; } Throwable t = throwable.fillInStackTrace(); if (t == null) { //Custom exceptions sometimes return null, see #866 throw throwable; } filter.filter(t); throw t; }
Source:
public void finishMocking() { //Cleaning up the state, we no longer need the listener hooked up //The listener implements MockCreationListener and at this point //we no longer need to listen on mock creation events. We are wrapping up the session Mockito.framework().removeListener(listener); //Emit test finished event so that validation such as strict stubbing can take place listener.testFinished(new TestFinishedEvent() { public Throwable getFailure() { return null; } public Object getTestClassInstance() { return testClassInstances.get(0); } public String getTestMethodName() { return null; } }); //Finally, validate user's misuse of Mockito framework. Mockito.validateMockitoUsage(); }

Target:
public void finishMocking() { finishMocking(null); }
Source:
public List<T> getAllValues() { readLock.lock(); try { return Arrays.asList((T[]) arguments.toArray()); } finally { readLock.unlock(); } }

Target:
public List<T> getAllValues() { readLock.lock(); try { return new ArrayList<T>((List) arguments); } finally { readLock.unlock(); } }
Source:
public void should_call_single_listener_on_verify() throws NoSuchMethodException { //given RememberingListener listener = new RememberingListener(); MockitoFramework mockitoFramework = Mockito.framework(); mockitoFramework.addListener(listener); Method invocationWanted = Foo.class.getDeclaredMethod("doSomething", String.class); Foo foo = mock(Foo.class); //when VerificationMode never = never(); verify(foo, never).doSomething(""); //then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); }

Target:
public void should_call_single_listener_on_verify() { //given Foo foo = mock(Foo.class); //when VerificationMode never = never(); verify(foo, never).doSomething(""); //then assertThat(listener).is(notifiedFor(foo, never, invocationWanted)); }
Source:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(ClassFileVersion.JAVA_V9)); // Change when ByteBuddy has ASM6 MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }

Target:
public void should_create_mock_from_final_class_in_the_JDK() throws Exception { assumeTrue(ClassFileVersion.ofThisVm().isLessThan(JAVA_V9)); // Change when ByteBuddy has ASM6 - see #788 MockCreationSettings<Pattern> settings = settingsFor(Pattern.class); Pattern proxy = mockMaker.createMock(settings, new MockHandlerImpl<Pattern>(settings)); assertThat(proxy.pattern()).isEqualTo("bar"); }
Source:
public void addListener(MockitoListener listener) { assertNotNull(listener); if (listener instanceof MockCreationListener) { mockingProgress().addListener(listener); } }

Target:
public void addListener(MockitoListener listener) { assertNotNull(listener); mockingProgress().addListener(listener); }
Source:
private List<TestResult> filterTests(List<? extends TestResult> failedTests, String regexPattern) { if(regexPattern.length() != 0) { Pattern pattern = Pattern.compile(regexPattern); failedTests = failedTests.stream().filter(t -> pattern.matcher(t.getFullName()).matches()).collect(Collectors.toList()); } return (List<TestResult>)failedTests; }

Target:
private List<? extends TestResult> filterTests(List<? extends TestResult> failedTests, String regexPattern) { if(regexPattern.length() != 0) { Pattern pattern = Pattern.compile(regexPattern); failedTests = failedTests.stream().filter(t -> pattern.matcher(t.getFullName()).matches()).collect(Collectors.toList()); } return failedTests; }
Source:
public boolean equals(final Object obj) { // Eliminate the usual boilerplate because // this inner static class is only used in a generic ConcurrentHashMap // which will not compare against other Object types return obj instanceof MultipartKey && Arrays.equals(keys, ((MultipartKey)obj).keys); }

Target:
public boolean equals(final Object obj) { // Eliminate the usual boilerplate because // this inner static class is only used in a generic ConcurrentHashMap // which will not compare against other Object types return Arrays.equals(keys, ((MultipartKey)obj).keys); }
Source:
public void testToCalendarWithDateNull() { try { DateUtils.toCalendar(null, zone); fail("Expected NullPointerException to be thrown when Date is null"); } catch(final NullPointerException npe) { // expected } }

Target:
public void testToCalendarWithDateNull() { DateUtils.toCalendar(null, zone); }
Source:
public void testToCalendarWithTimeZoneNull() { try { DateUtils.toCalendar(date1, null); fail("Expected NullPointerException to be thrown when TimeZone is null"); } catch(final NullPointerException npe) { // expected } }

Target:
public void testToCalendarWithTimeZoneNull() { DateUtils.toCalendar(date1, null); }
Source:
public void postBuildIndex() throws IOException, ServiceException { if(optimizeEnabled) { // this is required to be at the very very very end after rebuilding the whole index optimizeIndex(solrConfiguration.getReindexCollectionName(), solrConfiguration.getReindexServer()); // Swap the active and the reindex cores if (!solrConfiguration.isSingleCoreMode()) { shs.swapActiveCores(solrConfiguration); } } }

Target:
public void postBuildIndex() throws IOException, ServiceException { if(optimizeEnabled) { // this is required to be at the very very very end after rebuilding the whole index optimizeIndex(solrConfiguration.getReindexCollectionName(), solrConfiguration.getReindexServer()); } // Swap the active and the reindex cores if (!solrConfiguration.isSingleCoreMode()) { shs.swapActiveCores(solrConfiguration); } }
Source:
protected void minify(BufferedReader in, BufferedWriter out, String filename, String type) throws IOException { try { if (JS_TYPE.equals(type)) { jsMinificationService.minifyJs(filename, in, out); } else if (CSS_TYPE.equals(type)) { cssMinificationService.minifyCss(filename, in, out); } else { throw new ResourceMinificationException("Minification is not supported for file: " + filename); } } catch (ResourceMinificationException e) { // We're throwing and catching ResourceMinificationException for backwards compatibility. // In 5.4 this method will throw a ResourceMinificationException throw new RuntimeException(e); } }

Target:
protected void minify(BufferedReader in, BufferedWriter out, String filename, String type) throws IOException { try { if (JS_TYPE.equals(type)) { jsMinificationService.minifyJs(filename, in, out); } else if (CSS_TYPE.equals(type)) { cssMinificationService.minifyCss(filename, in, out); } else { throw new ResourceMinificationException("Minification is not supported for file: " + filename); } } catch (ResourceMinificationException e) { // We're throwing and catching ResourceMinificationException for backwards compatibility. // In 5.4 this method will throw a ResourceMinificationException throw new IOException(e); } }