auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void saveValue(String metricId, Number value, long timeStamp) { LogWriter logWriter = context.getService(LogWriter.class); try { metricId = URLEncoder.encode(metricId, "UTF-8"); logWriter.log(sessionId, taskId + File.separatorChar + METRIC_MARKER + File.separatorChar + metricId, context.getId().getIdentifier(), new MetricLogEntry(timeStamp, metricId, value)); } catch (UnsupportedEncodingException e) { log.error("Can't save metric value with id="+metricId, e); } }

Target:
public void saveValue(String metricId, Number value, long timeStamp) { LogWriter logWriter = context.getService(LogWriter.class); try { metricId = URLEncoder.encode(metricId, "UTF-8"); logWriter.log(sessionId, taskId + File.separatorChar + METRIC_MARKER + File.separatorChar + metricId, context.getId().getIdentifier(), new MetricLogEntry(timeStamp, metricId, value)); } catch (UnsupportedEncodingException e) { log.error("Can't save metric value with id={}", metricId, e); } }
Source:
public static void restoreSystemProperties() { System.setProperty("org.uberfire.nio.git.daemon.enabled", gitDaemonEnabled); System.setProperty("org.uberfire.nio.git.ssh.enabled", gitSshEnabled); }

Target:
public static void restoreSystemProperties() { System.clearProperty("org.uberfire.nio.git.daemon.enabled"); System.clearProperty("org.uberfire.nio.git.ssh.enabled"); }
Source:
public Future<Void> send(final ByteBuffer buffer) { LOG.info("Sending"); LOG.info("local address {}", session.channel().localAddress()); LOG.info("remote address {}", session.channel().remoteAddress()); final BinaryWebSocketFrame frame = new BinaryWebSocketFrame(Unpooled.copiedBuffer(buffer)); LOG.info("Frame: {}", frame); final ChannelFuture future = session.channel().write(frame); future.addListener(new GenericProgressiveFutureListener<ProgressiveFuture<Void>>() { @SuppressWarnings("PMD.CommentRequired") @Override public void operationProgressed(final ProgressiveFuture future, final long progress, final long total) { LOG.info("huh? {}, {}", progress, total); } @Override public void operationComplete(final ProgressiveFuture future) { LOG.info("COMPELTE"); } }); return future; }

Target:
public Future<Void> send(final ByteBuffer buffer) { LOG.info("Sending"); LOG.info("local address {}", session.channel().localAddress()); LOG.info("remote address {}", session.channel().remoteAddress()); final BinaryWebSocketFrame frame = new BinaryWebSocketFrame(Unpooled.copiedBuffer(buffer)); LOG.info("Frame: {}", frame); final ChannelFuture future = session.channel().write(frame); future.addListener(new GenericProgressiveFutureListener<ProgressiveFuture<Void>>() { @SuppressWarnings("PMD.CommentRequired") @Override public void operationProgressed(final ProgressiveFuture future, final long progress, final long total) { LOG.info("current progress in sending message {}, {}", progress, total); } @Override public void operationComplete(final ProgressiveFuture future) { LOG.info("COMPELTE"); } }); return future; }
Source:
public Long getPropertyLongObject(String propertyFileName, String propertyName, Long defaultValue) throws PropertyAccessException { PropertiesConfiguration properties = propertyFilesHashmap.get(propertyFileName); if (properties != null && properties.containsKey(propertyName)) { try { return properties.getLong(propertyName, defaultValue); } catch (ConversionException ex) { throw new PropertyAccessException("Could not convert property value to long for: " + propertyName, ex); } } throw new PropertyAccessException(getErrorMessage(propertyFileName, propertyName)); }

Target:
public Long getPropertyLongObject(String propertyFileName, String propertyName, Long defaultValue) { PropertiesConfiguration properties = propertyFilesHashmap.get(propertyFileName); if (properties != null && properties.containsKey(propertyName)) { try { return properties.getLong(propertyName, defaultValue); } catch (ConversionException ex) { LOG.error("Could not convert property value to long for: ", propertyName, ex); } } return defaultValue; }
Source:
public String getDescription(Object element) { StringBuilder result = new StringBuilder(getText(element)); if (element instanceof RefNode) { Ref ref = ((RefNode) element).getObject(); String branchName = Repository.shortenRefName(ref.getName()); result = new StringBuilder(branchName); } if (element instanceof RepositoryGroupNode) { RepositoryGroup group = ((RepositoryGroupNode) element).getGroup(); result.append(" (").append(group.getRepositoryDirectories().size()) .append(")"); } else if (element instanceof RepositoryTreeNode) { if (((RepositoryTreeNode) element) .getType() != RepositoryTreeNodeType.REPO) { Repository repo = ((RepositoryTreeNode) element) .getRepository(); result.append(" [").append(GitLabels.getPlainShortLabel(repo)) .append(']'); } } return result.toString(); }

Target:
public String getDescription(Object element) { StringBuilder result = new StringBuilder(getText(element)); if (element instanceof RefNode) { Ref ref = ((RefNode) element).getObject(); String branchName = Repository.shortenRefName(ref.getName()); result = new StringBuilder(branchName); } if (element instanceof RepositoryGroupNode) { RepositoryGroup group = ((RepositoryGroupNode) element).getGroup(); result.append(" (").append(group.getRepositoryDirectories().size()) .append(')'); } else if (element instanceof RepositoryTreeNode) { if (((RepositoryTreeNode) element) .getType() != RepositoryTreeNodeType.REPO) { Repository repo = ((RepositoryTreeNode) element) .getRepository(); result.append(" [").append(GitLabels.getPlainShortLabel(repo)) .append(']'); } } return result.toString(); }
Source:
public void stop() { if (manager != null) { manager.stop(); manager = null; sysInjector = null; sshInjector = null; httpInjector = null; if (webPluginDir != null) { try { FileUtils.delete(webPluginDir, FileUtils.RECURSIVE); } catch (IOException e) { } } } }

Target:
public void stop() { if (manager != null) { manager.stop(); manager = null; sysInjector = null; sshInjector = null; httpInjector = null; } }
Source:
private static void updateJsonArrayDataNodesRackAware(JSONArray dataNodeJsonArray, int dataNodeCount, String hostname, int basePort, int sslPort, int numRacks, HardwareState hardwareState, JSONArray disks) throws JSONException { for (int i = dataNodeJsonArray.length(); i < dataNodeCount; ++i) { dataNodeJsonArray.put( getJsonDataNode(hostname, basePort + i, sslPort + i, i % numRacks, 64, hardwareState, disks)); } }

Target:
private static void updateJsonArrayDataNodesRackAware(JSONArray dataNodeJsonArray, int dataNodeCount, String hostname, int basePort, int sslPort, int numRacks, HardwareState hardwareState, JSONArray disks) throws JSONException { for (int i = dataNodeJsonArray.length(); i < dataNodeCount; ++i) { dataNodeJsonArray.put( getJsonDataNode(hostname, basePort + i, sslPort + i, i % numRacks, DEFAULT_XID, hardwareState, disks)); } }
Source:
public void testGetAlertCountWithMultipleAlert() throws JsonProcessingException { Assert.assertEquals(0, alertRepo.getAlertCount()); final Transaction transaction = Ebean.beginTransaction(); try { final models.ebean.Alert ebeanAlert1 = new models.ebean.Alert(); ebeanAlert1.setNagiosExtension(TEST_NAGIOS_EXTENSIONS); ebeanAlert1.setName(TEST_NAME); ebeanAlert1.setOperator(TEST_OPERATOR); ebeanAlert1.setPeriod(TEST_PERIOD_IN_SECONDS); ebeanAlert1.setStatistic(TEST_STATISTIC); ebeanAlert1.setQuantityValue(TEST_QUANTITY_VALUE); ebeanAlert1.setQuantityUnit(TEST_QUANTITY_UNIT); ebeanAlert1.setCluster(TEST_CLUSTER); ebeanAlert1.setUuid(UUID.randomUUID()); ebeanAlert1.setMetric(TEST_METRIC); ebeanAlert1.setContext(TEST_CONTEXT); ebeanAlert1.setService(TEST_SERVICE); Ebean.save(ebeanAlert1); final models.ebean.Alert ebeanAlert2 = new models.ebean.Alert(); ebeanAlert2.setNagiosExtension(TEST_NAGIOS_EXTENSIONS); ebeanAlert2.setName(TEST_NAME); ebeanAlert2.setOperator(TEST_OPERATOR); ebeanAlert2.setPeriod(TEST_PERIOD_IN_SECONDS); ebeanAlert2.setStatistic(TEST_STATISTIC); ebeanAlert2.setQuantityValue(TEST_QUANTITY_VALUE); ebeanAlert2.setQuantityUnit(TEST_QUANTITY_UNIT); ebeanAlert2.setCluster(TEST_CLUSTER); ebeanAlert2.setUuid(UUID.randomUUID()); ebeanAlert2.setMetric(TEST_METRIC); ebeanAlert2.setContext(TEST_CONTEXT); ebeanAlert2.setService(TEST_SERVICE); Ebean.save(ebeanAlert2); transaction.commit(); } finally { transaction.end(); } Assert.assertEquals(2, alertRepo.getAlertCount()); }

Target:
public void testGetAlertCountWithMultipleAlert() throws JsonProcessingException { Assert.assertEquals(0, alertRepo.getAlertCount()); final Transaction transaction = Ebean.beginTransaction(); try { final models.ebean.Alert ebeanAlert1 = TestBeanFactory.createEbeanAlert(); ebeanAlert1.setUuid(UUID.randomUUID()); Ebean.save(ebeanAlert1); final models.ebean.Alert ebeanAlert2 = TestBeanFactory.createEbeanAlert(); ebeanAlert2.setUuid(UUID.randomUUID()); Ebean.save(ebeanAlert2); transaction.commit(); } finally { transaction.end(); } Assert.assertEquals(2, alertRepo.getAlertCount()); }
Source:
private static SerialPort connect(String portName, int baudRate) { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if ( portIdentifier.isCurrentlyOwned() ) { System.err.println("Error: Port currently in use"); } else { CommPort commPort = portIdentifier.open(portName, 2000); if ( commPort instanceof SerialPort ) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); return serialPort; } } } catch (Exception e) { System.err.println("Error: Unable to connect to port" + portName); } return null; }

Target:
private static SerialPort connect(String portName, int baudRate) { try { CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName); if ( portIdentifier.isCurrentlyOwned() ) { System.err.println("Error: Port currently in use"); } else { CommPort commPort = portIdentifier.open(portName, TIMEOUT); if ( commPort instanceof SerialPort ) { SerialPort serialPort = (SerialPort) commPort; serialPort.setSerialPortParams(baudRate,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE); return serialPort; } } } catch (Exception e) { System.err.println("Error: Unable to connect to port" + portName); } return null; }
Source:
public double calculateStandardizedValue(final long meterValue, final ScalerUnitResponse scalerUnitResponse) { final ScalerUnit scalerUnit = scalerUnitResponse.getScalerUnit(); final double multiplier = this.getMultiplierToOsgpUnit(scalerUnit.getDlmsUnit()); final double power = scalerUnit.getScaler() == 0 ? 1 : Math.pow(10, scalerUnit.getScaler()); final double calculated = round((meterValue / power) * multiplier, this.fraction_digits); LOGGER.debug(String.format("calcualted %s from %s using %s", calculated, meterValue, scalerUnit)); return calculated; }

Target:
public double calculateStandardizedValue(final long meterValue, final ScalerUnitResponse scalerUnitResponse) { final ScalerUnit scalerUnit = scalerUnitResponse.getScalerUnit(); final double multiplier = this.getMultiplierToOsgpUnit(scalerUnit.getDlmsUnit()); final double power = scalerUnit.getScaler() == 0 ? 1 : Math.pow(10, scalerUnit.getScaler()); final double calculated = round((meterValue / power) * multiplier, this.fractionDigits); LOGGER.debug(String.format("calculated %s from %s using %s", calculated, meterValue, scalerUnit)); return calculated; }
Source:
protected void handleMessageInternal(Message<?> message) throws Exception { StreamHolder inputStreamHolder = this.payloadToInputStream(message); if (inputStreamHolder != null) { Session<F> session = this.sessionFactory.getSession(); String fileName = inputStreamHolder.name; try { String remoteDirectory = this.directoryExpressionProcessor.processMessage(message); String temporaryRemoteDirectory = remoteDirectory; if (this.temporaryDirectoryExpressionProcessor != null){ temporaryRemoteDirectory = this.temporaryDirectoryExpressionProcessor.processMessage(message); } fileName = this.fileNameGenerator.generateFileName(message); this.sendFileToRemoteDirectory(inputStreamHolder.stream, temporaryRemoteDirectory, remoteDirectory, fileName, session); } catch (FileNotFoundException e) { throw new MessageDeliveryException(message, "File [" + inputStreamHolder.name + "] not found in local working directory; it was moved or deleted unexpectedly.", e); } catch (IOException e) { throw new MessageDeliveryException(message, "Failed to transfer file [" + inputStreamHolder.name + "->" + fileName + "] from local directory to remote directory.", e); } catch (Exception e) { throw new MessageDeliveryException(message, "Error handling message for file [" + inputStreamHolder.name + "->" + fileName + "]", e); } finally { if (session != null) { session.close(); } } } }

Target:
protected void handleMessageInternal(Message<?> message) throws Exception { StreamHolder inputStreamHolder = this.payloadToInputStream(message); if (inputStreamHolder != null) { Session<F> session = this.sessionFactory.getSession(); String fileName = inputStreamHolder.getName(); try { String remoteDirectory = this.directoryExpressionProcessor.processMessage(message); String temporaryRemoteDirectory = remoteDirectory; if (this.temporaryDirectoryExpressionProcessor != null){ temporaryRemoteDirectory = this.temporaryDirectoryExpressionProcessor.processMessage(message); } fileName = this.fileNameGenerator.generateFileName(message); this.sendFileToRemoteDirectory(inputStreamHolder.getStream(), temporaryRemoteDirectory, remoteDirectory, fileName, session); } catch (FileNotFoundException e) { throw new MessageDeliveryException(message, "File [" + inputStreamHolder.getName() + "] not found in local working directory; it was moved or deleted unexpectedly.", e); } catch (IOException e) { throw new MessageDeliveryException(message, "Failed to transfer file [" + inputStreamHolder.getName() + "->" + fileName + "] from local directory to remote directory.", e); } catch (Exception e) { throw new MessageDeliveryException(message, "Error handling message for file [" + inputStreamHolder.getName() + "->" + fileName + "]", e); } finally { if (session != null) { session.close(); } } } else { if (logger.isWarnEnabled()) { logger.warn("File " + message.getPayload() + " does not exist"); } } }
Source:
public void attributeChanged(TaskAttribute attribute) { if (attribute.getParentAttribute() != getTaskData().getRoot()) { throw new RuntimeException( "Editing is only supported for attributes that are attached to the root of task data"); } unsavedChangedAttributes.add(attribute); if (this.listeners != null) { final TaskDataModelEvent event = new TaskDataModelEvent(this, EventKind.CHANGED, attribute); TaskDataModelListener[] listeners = this.listeners.toArray(new TaskDataModelListener[0]); for (final TaskDataModelListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable e) { StatusHandler .log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Listener failed", e)); } public void run() throws Exception { listener.attributeChanged(event); } }); } } String changedAttribute = attribute.getId(); for (TaskAttribute taskAttribute : attribute.getTaskData().getRoot().getAttributes().values()) { if (changedAttribute.equals(taskAttribute.getMetaData().getDependsOn())) { attributeChanged(taskAttribute); } } }

Target:
public void attributeChanged(TaskAttribute attribute) { if (attribute.getParentAttribute() != getTaskData().getRoot()) { throw new RuntimeException( "Editing is only supported for attributes that are attached to the root of task data"); } unsavedChangedAttributes.add(attribute); if (this.listeners != null) { final TaskDataModelEvent event = new TaskDataModelEvent(this, EventKind.CHANGED, attribute); TaskDataModelListener[] listeners = this.listeners.toArray(new TaskDataModelListener[0]); for (final TaskDataModelListener listener : listeners) { SafeRunner.run(new ISafeRunnable() { public void handleException(Throwable e) { StatusHandler .log(new Status(IStatus.ERROR, ITasksCoreConstants.ID_PLUGIN, "Listener failed", e)); } public void run() throws Exception { listener.attributeChanged(event); } }); } } }
Source:
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(CoreUtils.bomAwareToString(bodyBytes, getHeaderValue("Content-Type"))); }

Target:
public Mono<String> getBodyAsString(Charset charset) { Objects.requireNonNull(charset, "'charset' cannot be null."); return bodyBytes == null ? Mono.empty() : Mono.just(new String(bodyBytes, charset)); }
Source:
public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted() || result.used()) { return null; } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); }

Target:
public <T> T forwardTo(final Class<T> type) { return proxifier.proxify(type, new MethodInvocation<T>() { @Override public Object intercept(T proxy, Method method, Object[] args, SuperMethod superMethod) { try { logger.debug("Executing {}", method); ControllerMethod old = methodInfo.getControllerMethod(); methodInfo.setControllerMethod(DefaultControllerMethod.instanceFor(type, method)); Object methodResult = method.invoke(container.instanceFor(type), args); methodInfo.setControllerMethod(old); Type returnType = method.getGenericReturnType(); if (!(returnType == void.class)) { request.setAttribute(extractor.nameFor(returnType), methodResult); } if (response.isCommitted() || result.used()) { logger.debug("Response already commited, not forwarding."); return null; } String path = resolver.pathFor(DefaultControllerMethod.instanceFor(type, method)); logger.debug("Forwarding to {}", path); request.getRequestDispatcher(path).forward(request, response); return null; } catch (InvocationTargetException e) { propagateIfPossible(e.getCause()); throw new ProxyInvocationException(e); } catch (Exception e) { throw new ProxyInvocationException(e); } } }); }
Source:
protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { this.localConversation = (SwrveBaseConversation) extras.getSerializable("conversation"); this.hideToolbar = extras.getBoolean("hide_toolbar"); } } if (!hideToolbar) { setTheme(R.style.Theme_ConversationsWithToolbar); } try { if (localConversation != null) { conversationFragment = ConversationFragment.create(localConversation); conversationFragment.commitConversationFragment(getSupportFragmentManager()); } else { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity. No SwrveConversation was detected"); this.finish(); } } catch (Exception ge) { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity.", ge); this.finish(); } }

Target:
protected void onCreate(Bundle savedInstanceState) { getWindow().requestFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); Intent intent = getIntent(); if (intent != null) { Bundle extras = intent.getExtras(); if (extras != null) { this.localConversation = (SwrveBaseConversation) extras.getSerializable(CONVERSATION_KEY); this.hideToolbar = extras.getBoolean(HIDE_TOOLBAR_KEY); } } if (!hideToolbar) { setTheme(R.style.Theme_ConversationsWithToolbar); } try { if (localConversation != null) { conversationFragment = ConversationFragment.create(localConversation); conversationFragment.commitConversationFragment(getSupportFragmentManager()); } else { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity. No SwrveConversation was detected"); this.finish(); } } catch (Exception ge) { SwrveLogger.e(LOG_TAG, "Could not render ConversationActivity.", ge); this.finish(); } }
Source:
public TaskReport ingestServiceData(PluginTask task, RecordImporter recordImporter, int taskIndex, PageBuilder pageBuilder) { if (task.getQueryBy().isPresent() && task.getQueryBy().get() == QueryBy.DATE_RANGE && task.getIncremental() && !Exec.isPreview()) { OffsetDateTime latestUpdateAt = task.getLatestUpdatedAt().isPresent() ? task.getLatestUpdatedAt().get().toInstant().atOffset(ZoneOffset.UTC) : OffsetDateTime.now(ZoneOffset.UTC); OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); if (latestUpdateAt.isAfter(now)) { logger.warn("`latest_updated_at` ({}) preceded current time ({}). Will try to import next run", latestUpdateAt.format(DATE_FORMATTER), now.format(DATE_FORMATTER)); OffsetDateTime earliest = task.getEarliestUpdatedAt().isPresent() ? task.getEarliestUpdatedAt().get().toInstant().atOffset(ZoneOffset.UTC) : OffsetDateTime.now(ZoneOffset.UTC); TaskReport taskReport = Exec.newTaskReport(); taskReport.set("earliest_updated_at", earliest.format(DATE_FORMATTER)); if (task.getReportDuration().isPresent()) { taskReport.set("report_duration", task.getReportDuration().get()); } return taskReport; } } return super.ingestServiceData(task, recordImporter, taskIndex, pageBuilder); }

Target:
public TaskReport ingestServiceData(PluginTask task, RecordImporter recordImporter, int taskIndex, PageBuilder pageBuilder) { if (task.getQueryBy().isPresent() && task.getQueryBy().get() == QueryBy.DATE_RANGE && task.getIncremental() && !Exec.isPreview()) { OffsetDateTime latestUpdateAt = OffsetDateTime.ofInstant(task.getLatestUpdatedAt().get().toInstant(), ZoneOffset.UTC); OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC); if (latestUpdateAt.isAfter(now)) { logger.warn("`latest_updated_at` ({}) preceded current time ({}). Will try to import next run", latestUpdateAt.format(DATE_FORMATTER), now.format(DATE_FORMATTER)); OffsetDateTime earliest = OffsetDateTime.ofInstant(task.getEarliestUpdatedAt().get().toInstant(), ZoneOffset.UTC); TaskReport taskReport = Exec.newTaskReport(); taskReport.set("earliest_updated_at", earliest.format(DATE_FORMATTER)); if (task.getReportDuration().isPresent()) { taskReport.set("report_duration", task.getReportDuration().get()); } return taskReport; } } return super.ingestServiceData(task, recordImporter, taskIndex, pageBuilder); }
Source:
public JavaWriter beginMethod(String returnType, String name, Set<Modifier> modifiers, List<String> parameters, List<String> throwsTypes) throws IOException { indent(); emitModifiers(modifiers); if (returnType != null) { emitCompressedType(returnType); out.write(" "); out.write(name); } else { emitCompressedType(name); } out.write("("); if (parameters != null) { for (int p = 0; p < parameters.size();) { if (p != 0) { out.write(", "); } emitCompressedType(parameters.get(p++)); out.write(" "); emitCompressedType(parameters.get(p++)); } } out.write(")"); if (throwsTypes != null && throwsTypes.size() > 0) { out.write("\n"); indent(); out.write(" throws "); for (int i = 0; i < throwsTypes.size(); i++) { if (i != 0) { out.write(", "); } emitCompressedType(throwsTypes.get(i)); } } if (modifiers.contains(ABSTRACT) || Scope.INTERFACE_DECLARATION.equals(scopes.getFirst())) { out.write(";\n"); scopes.push(Scope.ABSTRACT_METHOD); } else { out.write(" {\n"); scopes.push(returnType == null ? Scope.CONSTRUCTOR : Scope.NON_ABSTRACT_METHOD); } return this; }

Target:
public JavaWriter beginMethod(String returnType, String name, Set<Modifier> modifiers, List<String> parameters, List<String> throwsTypes) throws IOException { indent(); emitModifiers(modifiers); if (returnType != null) { emitCompressedType(returnType); out.write(" "); out.write(name); } else { emitCompressedType(name); } out.write("("); if (parameters != null) { for (int p = 0; p < parameters.size();) { if (p != 0) { out.write(", "); } emitCompressedType(parameters.get(p++)); out.write(" "); emitCompressedType(parameters.get(p++)); } } out.write(")"); if (throwsTypes != null && throwsTypes.size() > 0) { out.write("\n"); indent(); out.write(" throws "); for (int i = 0; i < throwsTypes.size(); i++) { if (i != 0) { out.write(", "); } emitCompressedType(throwsTypes.get(i)); } } if (modifiers.contains(ABSTRACT) || Scope.INTERFACE_DECLARATION.equals(scopes.peek())) { out.write(";\n"); scopes.push(Scope.ABSTRACT_METHOD); } else { out.write(" {\n"); scopes.push(returnType == null ? Scope.CONSTRUCTOR : Scope.NON_ABSTRACT_METHOD); } return this; }
Source:
private void waitForVdsUp(Guid vdsGuid) { VdsStatusListener vdsStatusListener = new VdsStatusListener() { @Override public void vdsStatusChanged() { synchronized(HostSetupNetworksCommand.this){ HostSetupNetworksCommand.this.notify(); } } }; try{ synchronized(this){ vdsEventListener.addVdsUpListener(vdsStatusListener); if (resourceManager.getVdsManager(vdsGuid).getCopyVds().getStatus() != VDSStatus.Up){ this.wait(WAIT_FOR_UPSTATUS_TIMEOUT); } } } catch(InterruptedException e) { } finally { vdsEventListener.removeVdsUpListener(vdsStatusListener); } }

Target:
private void waitForVdsUp(Guid vdsGuid) { VdsStatusListener vdsStatusListener = new VdsStatusListener() { @Override public void vdsStatusChanged() { synchronized(HostSetupNetworksCommand.this){ HostSetupNetworksCommand.this.notify(); } } }; try{ synchronized(this){ vdsEventListener.addVdsUpListener(vdsStatusListener); if (resourceManager.getVdsManager(vdsGuid).getCopyVds().getStatus() != VDSStatus.Up){ logMonitorLockReleased("Waiting for host to move to the Up state"); this.wait(WAIT_FOR_UPSTATUS_TIMEOUT); } } } catch(InterruptedException e) { } finally { vdsEventListener.removeVdsUpListener(vdsStatusListener); } }
Source:
static String toString(int flags) { StringBuilder result = new StringBuilder(); if ((flags & FLAG_DEBUG) == FLAG_DEBUG) { result.append("DEBUG"); } else if ((flags & FLAG_SAMPLED_SET) == FLAG_SAMPLED_SET) { if ((flags & FLAG_SAMPLED) == FLAG_SAMPLED) { result.append("SAMPLED"); } else { result.append("NOT_SAMPLED"); } } if ((flags & FLAG_SAMPLED_LOCAL) == FLAG_SAMPLED_LOCAL) { if (result.length() > 0) result.append('|'); result.append("SAMPLED_LOCAL"); } return result.toString(); }

Target:
static String toString(int flags) { StringBuilder result = new StringBuilder(); if ((flags & FLAG_DEBUG) == FLAG_DEBUG) { result.append("DEBUG"); } else if ((flags & FLAG_SAMPLED_SET) == FLAG_SAMPLED_SET) { if ((flags & FLAG_SAMPLED) == FLAG_SAMPLED) { result.append("SAMPLED_REMOTE"); } else { result.append("NOT_SAMPLED_REMOTE"); } } if ((flags & FLAG_SAMPLED_LOCAL) == FLAG_SAMPLED_LOCAL) { if (result.length() > 0) result.append('|'); result.append("SAMPLED_LOCAL"); } return result.toString(); }
Source:
protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); TransactionService transactionService = services.getTransactionService(); ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e) { printer.error("Found a row in the transactions table that didn't have 1" + " and only 1 column value: start={}", SafeArg.of("startTs", startTs)); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= timestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs)); transactionService.putUnlessExists(startTs, TransactionConstants.FAILED_COMMIT_TS); } printer.info("Rollback of transactions completed."); return 0; }

Target:
protected int executeTimestampCommand(AtlasDbServices services) { KeyValueService kvs = services.getKeyValueService(); ClosableIterator<RowResult<Value>> range = kvs.getRange( TransactionConstants.TRANSACTION_TABLE, RangeRequest.all(), Long.MAX_VALUE); Map<Cell, byte[]> txTableValuesToWrite = new HashMap<>(); while (range.hasNext()) { RowResult<Value> row = range.next(); byte[] rowName = row.getRowName(); long startTs = TransactionConstants.getTimestampForValue(rowName); Value value; try { value = row.getOnlyColumnValue(); } catch (IllegalStateException e) { printer.error("Found a row in the transactions table that didn't have 1" + " and only 1 column value: start={}", SafeArg.of("startTs", startTs)); continue; } long commitTs = TransactionConstants.getTimestampForValue(value.getContents()); if (commitTs <= timestamp) { continue; } printer.info("Found and cleaning possibly inconsistent transaction: [start={}, commit={}]", SafeArg.of("startTs", startTs), SafeArg.of("commitTs", commitTs)); Cell key = Cell.create(rowName, TransactionConstants.COMMIT_TS_COLUMN); byte[] valueForRollbackTimestamp = TransactionConstants.getValueForTimestamp(TransactionConstants.FAILED_COMMIT_TS); txTableValuesToWrite.put(key, valueForRollbackTimestamp); } if (!txTableValuesToWrite.isEmpty()) { Map<TableReference, Map<Cell, byte[]>> valuesToPut = new HashMap<>(); valuesToPut.put(TransactionConstants.TRANSACTION_TABLE, txTableValuesToWrite); kvs.put(TransactionConstants.TRANSACTION_TABLE, txTableValuesToWrite, services.getTimestampService().getFreshTimestamp()); printer.info("Completed rollback of transactions after the given timestamp."); } else { printer.info("Found no transactions after the given timestamp to rollback."); } return 0; }
Source:
public static SerializableTransactionManager create(KeyValueService keyValueService, TimelockService timelockService, LockService lockService, TransactionService transactionService, Supplier<AtlasDbConstraintCheckingMode> constraintModeSupplier, ConflictDetectionManager conflictDetectionManager, SweepStrategyManager sweepStrategyManager, Cleaner cleaner, Supplier<Boolean> initializationPrerequisite, boolean allowHiddenTableAccess, Supplier<Long> lockAcquireTimeoutMs, int concurrentGetRangesThreadPoolSize, int defaultGetRangesConcurrency, boolean initializeAsync, Supplier<Long> timestampCacheSize) { TimestampTracker timestampTracker = TimestampTrackerImpl.createWithDefaultTrackers( timelockService, cleaner, initializeAsync); SerializableTransactionManager serializableTransactionManager = new SerializableTransactionManager( keyValueService, timelockService, lockService, transactionService, constraintModeSupplier, conflictDetectionManager, sweepStrategyManager, cleaner, allowHiddenTableAccess, lockAcquireTimeoutMs, timestampTracker, concurrentGetRangesThreadPoolSize, defaultGetRangesConcurrency, timestampCacheSize); return initializeAsync ? new InitializeCheckingWrapper(serializableTransactionManager, initializationPrerequisite) : serializableTransactionManager; }

Target:
public static SerializableTransactionManager create(KeyValueService keyValueService, TimelockService timelockService, LockService lockService, TransactionService transactionService, Supplier<AtlasDbConstraintCheckingMode> constraintModeSupplier, ConflictDetectionManager conflictDetectionManager, SweepStrategyManager sweepStrategyManager, Cleaner cleaner, Supplier<Boolean> initializationPrerequisite, boolean allowHiddenTableAccess, Supplier<Long> lockAcquireTimeoutMs, int concurrentGetRangesThreadPoolSize, int defaultGetRangesConcurrency, boolean initializeAsync, Supplier<Long> timestampCacheSize) { TimestampTracker timestampTracker = TimestampTrackerImpl.createWithDefaultTrackers( timelockService, cleaner, initializeAsync); SerializableTransactionManager serializableTransactionManager = new SerializableTransactionManager( keyValueService, timelockService, lockService, transactionService, constraintModeSupplier, conflictDetectionManager, sweepStrategyManager, cleaner, timestampTracker, timestampCacheSize, allowHiddenTableAccess, lockAcquireTimeoutMs, concurrentGetRangesThreadPoolSize, defaultGetRangesConcurrency); return initializeAsync ? new InitializeCheckingWrapper(serializableTransactionManager, initializationPrerequisite) : serializableTransactionManager; }
Source:
public MessageIdTracker(final NetworkConfig config) { exchangeLifetime = config.getLong(NetworkConfig.Keys.EXCHANGE_LIFETIME); boolean useRandomFirstMID = config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START); if (useRandomFirstMID) { counter = new AtomicInteger(new SecureRandom().nextInt(1 << 10)); } else { counter = new AtomicInteger(0); } messageIds = new HashMap<>(TOTAL_NO_OF_MIDS); }

Target:
public MessageIdTracker(final NetworkConfig config) { exchangeLifetime = config.getLong(NetworkConfig.Keys.EXCHANGE_LIFETIME); boolean useRandomFirstMID = config.getBoolean(NetworkConfig.Keys.USE_RANDOM_MID_START); if (useRandomFirstMID) { counter = new AtomicInteger(new Random().nextInt(1 << 10)); } else { counter = new AtomicInteger(0); } messageIds = new HashMap<>(TOTAL_NO_OF_MIDS); }
Source:
protected void setupVelocityContext() { String rl = "resource.loader"; String pkg = "org.apache.velocity.runtime.resource.loader"; Properties p = new Properties(); p.setProperty(rl, "file, class"); p.setProperty("file." + rl + ".class", pkg + ".FileResourceLoader"); p.setProperty("file." + rl + ".path", args.site.mail_dir.getAbsolutePath()); p.setProperty("class." + rl + ".class", pkg + ".ClasspathResourceLoader"); p.setProperty(org.apache.velocity.runtime.RuntimeConstants.RUNTIME_LOG, new File(args.site.logs_dir, "error_log").getAbsolutePath()); try { Velocity.init(p); } catch(Exception e) { } velocityContext = new VelocityContext(); velocityContext.put("email", this); velocityContext.put("messageClass", messageClass); velocityContext.put("StringUtils", StringUtils.class); }

Target:
protected void setupVelocityContext() { velocityContext = new VelocityContext(); velocityContext.put("email", this); velocityContext.put("messageClass", messageClass); velocityContext.put("StringUtils", StringUtils.class); }
Source:
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisQueueOutboundGateway.class); builder.addConstructorArgValue(element.getAttribute("control-queue")); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel","outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "extract-payload"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "serializer"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "requires-reply"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "order"); return builder; }

Target:
protected BeanDefinitionBuilder parseHandler(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(RedisQueueOutboundGateway.class); builder.addConstructorArgValue(element.getAttribute("control-queue")); String connectionFactory = element.getAttribute("connection-factory"); if (!StringUtils.hasText(connectionFactory)) { connectionFactory = "redisConnectionFactory"; } builder.addConstructorArgReference(connectionFactory); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "reply-channel","outputChannel"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "expect-message"); IntegrationNamespaceUtils.setReferenceIfAttributeDefined(builder, element, "serializer"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "reply-timeout", "timeout"); IntegrationNamespaceUtils.setValueIfAttributeDefined(builder, element, "requires-reply"); return builder; }
Source:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { CacheEntry entry = preferredEntry != null ? preferredEntry : (CacheEntry) otherEntries.get(0); entry.setValue(MERGE_RESULT); return entry; }; }

Target:
public IndependentClustersMergeTest() { this.numMembersInCluster = 2; this.mergePolicy = (preferredEntry, otherEntries) -> { CacheEntry<String, String> entry = preferredEntry != null ? preferredEntry : otherEntries.get(0); entry.setValue(MERGE_RESULT); return entry; }; }
Source:
public JSONObject createContent() { Map<String, String> security = new TreeMap<>(); putBoolean(security, "hudson.ConsoleNote.INSECURE", false); putBoolean(security, "hudson.model.ParametersAction.keepUndefinedParameters", false); putBoolean(security, "hudson.model.User.allowNonExistentUserToLogin", false); putBoolean(security, "hudson.model.User.allowUserCreationViaUrl", false); putBoolean(security, "hudson.model.User.SECURITY_243_FULL_DEFENSE", true); putStringInfo(security, "hudson.model.ParametersAction.safeParameters"); putStringInfo(security, "hudson.model.DirectoryBrowserSupport.CSP"); Map<String, Object> info = new TreeMap<>(); info.put("core", Jenkins.getVersion().toString()); info.put("clientDate", clientDateString()); info.put("properties", security); return JSONObject.fromObject(info); }

Target:
public JSONObject createContent() { Map<String, String> security = new TreeMap<>(); putBoolean(security, "hudson.ConsoleNote.INSECURE", false); putBoolean(security, "hudson.model.ParametersAction.keepUndefinedParameters", false); putBoolean(security, "hudson.model.User.allowNonExistentUserToLogin", false); putBoolean(security, "hudson.model.User.allowUserCreationViaUrl", false); putBoolean(security, "hudson.model.User.SECURITY_243_FULL_DEFENSE", true); putBoolean(security, "hudson.remoting.URLDeserializationHelper.avoidUrlWrapping", false); putBoolean(security, "jenkins.security.ClassFilterImpl.SUPPRESS_WHITELIST", false); putBoolean(security, "jenkins.security.ClassFilterImpl.SUPPRESS_ALL", false); putStringInfo(security, "hudson.model.ParametersAction.safeParameters"); putStringInfo(security, "hudson.model.DirectoryBrowserSupport.CSP"); putStringInfo(security, "hudson.security.HudsonPrivateSecurityRealm.ID_REGEX"); Map<String, Object> info = new TreeMap<>(); info.put("core", Jenkins.getVersion().toString()); info.put("clientDate", clientDateString()); info.put("properties", security); return JSONObject.fromObject(info); }
Source:
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); this.nameText.setText("newName"); this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { if (!CharMatcher.whitespace().matchesAnyOf(RenameInputWizardPage.this.nameText.getText())) { setPageComplete(true); } } }); this.nameText.selectAll(); this.setPageComplete(true); this.setControl(composite); }

Target:
public void createControl(Composite parent) { Composite composite = new Composite(parent, SWT.NONE); composite.setLayout(new GridLayout(2, false)); composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true)); composite.setFont(parent.getFont()); Label label = new Label(composite, SWT.NONE); label.setLayoutData(new GridData()); label.setText(Messages.rename_label); this.nameText = new Text(composite, SWT.BORDER); this.nameText.setText("newName"); this.nameText.setFont(composite.getFont()); this.nameText.setLayoutData(new GridData(GridData.FILL, GridData.BEGINNING, true, false)); this.nameText.addModifyListener(new ModifyListener() { @Override public void modifyText(ModifyEvent e) { validatePage(); } }); this.nameText.selectAll(); this.setControl(composite); validatePage(); }
Source:
public void stopClient() throws JMSException { if (null != connection && null != session && null != sender) { try { long threadID = Thread.currentThread().getId(); log.info("Closing publisher | ThreadID : " + threadID); this.sender.close(); this.session.close(); this.connection.close(); this.sender = null; this.session = null; this.connection = null; log.info("Publisher closed | ThreadID : " + threadID); } catch (JMSException e) { log.error("Error while stopping the publisher.", e); throw e; } } else { throw new NullPointerException("The connection, session and message sender is not assigned."); } }

Target:
public void stopClient() throws JMSException { if (null != connection && null != session && null != sender) { long threadID = Thread.currentThread().getId(); log.info("Closing publisher | ThreadID : " + threadID); this.sender.close(); this.session.close(); this.connection.close(); this.sender = null; this.session = null; this.connection = null; log.info("Publisher closed | ThreadID : " + threadID); } }
Source:
public void started() { IdgenTask.setEnabled(true); createLocationPrefixAttributeType(); log.info("Idgen Module Started..."); }

Target:
public void started() { IdgenTask.setEnabled(true); log.info("Idgen Module Started..."); }
Source:
private ProblemMarkerFilterManager() { IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = reg .getConfigurationElementsFor(PROBLEM_MARKER_FILTER_EXTENSION_POINT); for (int i = 0; i < extensions.length; i++) { IConfigurationElement element = extensions[i]; try { IProblemMarkerFilter filter = (IProblemMarkerFilter) element.createExecutableExtension("class"); filters.add(filter); } catch (CoreException e) { CCorePlugin.log(e); } } }

Target:
private ProblemMarkerFilterManager() { IExtensionRegistry reg = Platform.getExtensionRegistry(); IConfigurationElement[] extensions = reg .getConfigurationElementsFor(CCorePlugin.PLUGIN_ID, EXTENSION_POINT); for (int i = 0; i < extensions.length; i++) { IConfigurationElement element = extensions[i]; ProblemMarkerFilterDesc filterDesc = new ProblemMarkerFilterDesc(element); filters.add(filterDesc); } }
Source:
public void render(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.render(rowView, viewCache, value.getSectionHeader()); return; } itemRenderer.render(rowView, viewCache, value.getData()); }

Target:
public void render(View rowView, ListRowViewCache viewCache, SectionListItem<H, I> value) { if (value.isSectionHeader()) { headerRenderer.render(rowView, viewCache, value.getSectionHeader()); } else { itemRenderer.render(rowView, viewCache, value.getData()); } }
Source:
List<MetricFamilySamples> fromCounter(String name, Counter counter) { MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); return Arrays.asList(new MetricFamilySamples(name, Type.COUNTER, GENERIC_HELP_MESSAGE, Arrays.asList(sample))); }

Target:
List<MetricFamilySamples> fromCounter(String name, Counter counter) { MetricFamilySamples.Sample sample = new MetricFamilySamples.Sample(name, new ArrayList<String>(), new ArrayList<String>(), new Long(counter.getCount()).doubleValue()); return Arrays.asList(new MetricFamilySamples(name, Type.GAUGE, getHelpMessage(name, counter), Arrays.asList(sample))); }
Source:
public DocumentClone(String content, String[] lineDelimiters) { super(); setTextStore(new StringTextStore(content)); boolean hasDefaultDelims= true; if (lineDelimiters != null && DefaultLineTracker.DELIMITERS.length == lineDelimiters.length) { hasDefaultDelims= true; for (int i= 0; i < lineDelimiters.length; i++) { if (DefaultLineTracker.DELIMITERS[i] != lineDelimiters[i]) { hasDefaultDelims= false; break; } } } ILineTracker tracker= hasDefaultDelims ? new DefaultLineTracker() : new ConfigurableLineTracker(lineDelimiters); setLineTracker(tracker); getTracker().set(content); completeInitialization(); }

Target:
public DocumentClone(String content, String[] lineDelimiters) { super(); setTextStore(new StringTextStore(content)); boolean hasDefaultDelims= Arrays.equals(lineDelimiters, DefaultLineTracker.DELIMITERS); ILineTracker tracker= hasDefaultDelims ? new DefaultLineTracker() : new ConfigurableLineTracker(lineDelimiters); setLineTracker(tracker); getTracker().set(content); completeInitialization(); }
Source:
public void setClassName_throwOnLongClassName() { Realm realm = Realm.getInstance(configFactory.createConfigurationBuilder().build()); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.getSchema().create(MigrationPrimaryKey.CLASS_NAME); } }); realm.close(); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema() .get(MigrationPrimaryKey.CLASS_NAME) .setClassName("MigrationNameIsLongerThan56charThisShouldThrowAnException"); } }; RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(1) .migration(migration) .build(); try { Realm.getInstance(realmConfig); fail(); } catch (IllegalArgumentException expected) { assertEquals("Class name is to long. Limit is 57 characters: 'MigrationNameIsLongerThan56charThisShouldThrowAnException' (57)", expected.getMessage()); } }

Target:
public void setClassName_throwOnLongClassName() { Realm realm = Realm.getInstance(configFactory.createConfigurationBuilder().build()); realm.executeTransaction(new Realm.Transaction() { @Override public void execute(Realm realm) { realm.getSchema().create(MigrationPrimaryKey.CLASS_NAME); } }); realm.close(); RealmMigration migration = new RealmMigration() { @Override public void migrate(DynamicRealm realm, long oldVersion, long newVersion) { realm.getSchema() .get(MigrationPrimaryKey.CLASS_NAME) .setClassName("MigrationNameIsLongerThan56charThisShouldThrowAnException"); } }; RealmConfiguration realmConfig = configFactory.createConfigurationBuilder() .schemaVersion(1) .migration(migration) .build(); try { Realm.getInstance(realmConfig); fail(); } catch (IllegalArgumentException expected) { assertEquals("Class name is to long. Limit is 56 characters: 'MigrationNameIsLongerThan56charThisShouldThrowAnException' (57)", expected.getMessage()); } }
Source:
} catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { try { Class.forName("junit.framework.ComparisonFailure"); theFactory = new ExceptionFactoryImpl() { @Override public AssertionError create(String message, String wanted, String actual) { return new org.mockito.exceptions.verification.junit.ArgumentsAreDifferent(message, wanted, actual); } }; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }

Target:
} catch (ClassNotFoundException onlyIfOpenTestIsNotAvailable) { try { Class.forName("junit.framework.ComparisonFailure"); theFactory = org.mockito.exceptions.verification.junit.ArgumentsAreDifferent::new; } catch (ClassNotFoundException onlyIfJUnitIsNotAvailable) { } }