auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private void initializeDatasource(Annotation storeAnnotation) { Properties connectionProperties = new Properties(); String poolPropertyString = storeAnnotation.getElement(ANNOTATION_ELEMENT_POOL_PROPERTIES); String url = storeAnnotation.getElement(ANNOTATION_ELEMENT_URL); String username = storeAnnotation.getElement(ANNOTATION_ELEMENT_USERNAME); String password = storeAnnotation.getElement(ANNOTATION_ELEMENT_PASSWORD); if (RDBMSTableUtils.isEmpty(url) || RDBMSTableUtils.isEmpty(username) || RDBMSTableUtils.isEmpty(password)) { throw new RDBMSTableException("Required parameter(s) for DB connectivity cannot be empty."); } connectionProperties.setProperty("jdbcUrl", url); connectionProperties.setProperty("dataSource.user", username); connectionProperties.setProperty("dataSource.password", password); if (poolPropertyString != null) { List<String[]> poolProps = RDBMSTableUtils.processKeyValuePairs(poolPropertyString); poolProps.forEach(pair -> connectionProperties.setProperty(pair[0], pair[1])); } HikariConfig config = new HikariConfig(connectionProperties); this.dataSource = new HikariDataSource(config); }

Target:
private void initializeDatasource(Annotation storeAnnotation) { Properties connectionProperties = new Properties(); String poolPropertyString = storeAnnotation.getElement(ANNOTATION_ELEMENT_POOL_PROPERTIES); String url = storeAnnotation.getElement(ANNOTATION_ELEMENT_URL); String username = storeAnnotation.getElement(ANNOTATION_ELEMENT_USERNAME); String password = storeAnnotation.getElement(ANNOTATION_ELEMENT_PASSWORD); if (RDBMSTableUtils.isEmpty(url)) { throw new RDBMSTableException("Required parameter '" + ANNOTATION_ELEMENT_URL + "' for DB " + "connectivity cannot be empty."); } if (RDBMSTableUtils.isEmpty(username)) { throw new RDBMSTableException("Required parameter '" + ANNOTATION_ELEMENT_USERNAME + "' for DB " + "connectivity cannot be empty."); } if (RDBMSTableUtils.isEmpty(password)) { throw new RDBMSTableException("Required parameter '" + ANNOTATION_ELEMENT_PASSWORD + "' for DB " + "connectivity cannot be empty."); } connectionProperties.setProperty("jdbcUrl", url); connectionProperties.setProperty("dataSource.user", username); connectionProperties.setProperty("dataSource.password", password); if (poolPropertyString != null) { List<String[]> poolProps = RDBMSTableUtils.processKeyValuePairs(poolPropertyString); poolProps.forEach(pair -> connectionProperties.setProperty(pair[0], pair[1])); } HikariConfig config = new HikariConfig(connectionProperties); this.dataSource = new HikariDataSource(config); }
Source:
public Object getNegotiatedProperty(String propName) { assertComplete(); switch (propName) { case Sasl.QOP: return selectedQop.getName(); case Sasl.MAX_BUFFER: return Integer.toString(actualMaxReceiveBuffer != 0 ? actualMaxReceiveBuffer : configuredMaxReceiveBuffer); case Sasl.RAW_SEND_SIZE: return Integer.toString(maxBuffer); } return super.getNegotiatedProperty(propName); }

Target:
public Object getNegotiatedProperty(String propName) { assertComplete(); switch (propName) { case Sasl.QOP: return selectedQop.getName(); case Sasl.MAX_BUFFER: return Integer.toString(actualMaxReceiveBuffer != 0 ? actualMaxReceiveBuffer : configuredMaxReceiveBuffer); case Sasl.RAW_SEND_SIZE: return Integer.toString(maxBuffer); } return null; }
Source:
public static void fromMetastoreApiStorageDescriptor(StorageDescriptor storageDescriptor, Storage.Builder builder, String tablePartitionName) { SerDeInfo serdeInfo = storageDescriptor.getSerdeInfo(); if (serdeInfo == null) { throw new PrestoException(HIVE_INVALID_METADATA, "Table storage descriptor is missing SerDe info"); } builder.setStorageFormat(StorageFormat.createNullable(serdeInfo.getSerializationLib(), storageDescriptor.getInputFormat(), storageDescriptor.getOutputFormat())) .setLocation(nullToEmpty(storageDescriptor.getLocation())) .setBucketProperty(HiveBucketProperty.fromStorageDescriptor(storageDescriptor, tablePartitionName)) .setSkewed(storageDescriptor.isSetSkewedInfo() && storageDescriptor.getSkewedInfo().isSetSkewedColNames() && !storageDescriptor.getSkewedInfo().getSkewedColNames().isEmpty()) .setSerdeParameters(serdeInfo.getParameters() == null ? ImmutableMap.of() : serdeInfo.getParameters()) .setParameters(storageDescriptor.getParameters()); }

Target:
public static void fromMetastoreApiStorageDescriptor(StorageDescriptor storageDescriptor, Storage.Builder builder, String tablePartitionName) { SerDeInfo serdeInfo = storageDescriptor.getSerdeInfo(); if (serdeInfo == null) { throw new PrestoException(HIVE_INVALID_METADATA, "Table storage descriptor is missing SerDe info"); } builder.setStorageFormat(StorageFormat.createNullable(serdeInfo.getSerializationLib(), storageDescriptor.getInputFormat(), storageDescriptor.getOutputFormat())) .setLocation(nullToEmpty(storageDescriptor.getLocation())) .setBucketProperty(HiveBucketProperty.fromStorageDescriptor(storageDescriptor, tablePartitionName)) .setSkewed(storageDescriptor.isSetSkewedInfo() && storageDescriptor.getSkewedInfo().isSetSkewedColNames() && !storageDescriptor.getSkewedInfo().getSkewedColNames().isEmpty()) .setSerdeParameters(serdeInfo.getParameters() == null ? ImmutableMap.of() : serdeInfo.getParameters()) .setParameters(storageDescriptor.getParameters() == null ? ImmutableMap.of() : storageDescriptor.getParameters()); }
Source:
public ExpiredObject getExpiredObject(String key) { String expiredObjectType = (String) redisProvider.get(key); if(!Strings.isNullOrEmpty(expiredObjectType)){ ExpiredObject expiredObject = new ExpiredObject(); expiredObject.setKey(key); expiredObject.setValue(key); expiredObject.setType(ExpiredObjectType.fromValue(expiredObjectType)); return expiredObject; } return null; }

Target:
public ExpiredObject getExpiredObject(String key) { String value = (String) redisProvider.get(key); if (!Strings.isNullOrEmpty(value)) { ExpiredObject expiredObjectFromDb = null; try { expiredObjectFromDb = Jackson2.createJsonMapper().readValue(value, ExpiredObject.class); } catch (IOException e) { LOG.error("Error in assigning json value to ExpiredObject value attribute.", e); expiredObjectFromDb = new ExpiredObject(); } ExpiredObject expiredObject = new ExpiredObject(key, expiredObjectFromDb.getType(), expiredObjectFromDb.getCreatedAt(), expiredObjectFromDb.getExpiredAt()); return expiredObject; } return null; }
Source:
protected void writeEntityBody(Annotation entity, JsonGenerator jg) throws IOException { jg.writeStringField("id", entity.getId()); jg.writeStringField("color", entity.getColor()); String date = null; if (entity.getDate() != null) { date = entity.getDate().toInstant().toString(); } jg.writeStringField("date", date); jg.writeStringField("flags", entity.getFlags()); jg.writeStringField("name", entity.getName()); jg.writeStringField("documentId", entity.getDocumentId()); jg.writeStringField("xpath", entity.getXpath()); jg.writeStringField("lastModifier", entity.getLastModifier()); jg.writeNumberField("page", entity.getPage()); jg.writeStringField("position", entity.getPosition()); String creationDate = null; if (entity.getCreationDate() != null) { creationDate = entity.getCreationDate().toInstant().toString(); } jg.writeStringField("creationDate", creationDate); jg.writeNumberField("opacity", entity.getOpacity()); jg.writeStringField("subject", entity.getSubject()); jg.writeStringField("security", entity.getSecurity()); }

Target:
protected void writeEntityBody(Annotation entity, JsonGenerator jg) throws IOException { jg.writeStringField(ANNOTATION_ID, entity.getId()); jg.writeStringField(ANNOTATION_COLOR, entity.getColor()); String date = null; if (entity.getDate() != null) { date = entity.getDate().toInstant().toString(); } jg.writeStringField(ANNOTATION_DATE, date); jg.writeStringField(ANNOTATION_FLAGS, entity.getFlags()); jg.writeStringField(ANNOTATION_NAME, entity.getName()); jg.writeStringField(ANNOTATION_DOCUMENT_ID, entity.getDocumentId()); jg.writeStringField(ANNOTATION_XPATH, entity.getXpath()); jg.writeStringField(ANNOTATION_LAST_MODIFIER, entity.getLastModifier()); jg.writeNumberField(ANNOTATION_PAGE, entity.getPage()); jg.writeStringField(ANNOTATION_POSITION, entity.getPosition()); String creationDate = null; if (entity.getCreationDate() != null) { creationDate = entity.getCreationDate().toInstant().toString(); } jg.writeStringField(ANNOTATION_CREATION_DATE, creationDate); jg.writeNumberField(ANNOTATION_OPACITY, entity.getOpacity()); jg.writeStringField(ANNOTATION_SUBJECT, entity.getSubject()); jg.writeStringField(ANNOTATION_SECURITY, entity.getSecurity()); }
Source:
public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 || (a ^ naiveSum) >= 0) { return naiveSum; } return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); }

Target:
public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { return naiveSum; } return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); }
Source:
public String getUrl() { return client.url(); }

Target:
public URL getUrl() { try { return new URL(client.url()); } catch (MalformedURLException ex) { throw new IllegalStateException("Queue URL is malformed"); } }
Source:
public static void loadDclassSharedObject() throws IOException { try { if (OS.contains("mac")) { System.load("/usr/local/lib/libdclassjni.0.dylib"); } else if (OS.contains("nix") || OS.contains("nux") || OS.contains("aix")) { try { System.loadLibrary("dclassjni"); } catch(Exception e) { System.err.println("Error: " + e); System.exit(-1); }; } else { System.err.println("OS not supported."); System.exit(-1); } } catch (UnsatisfiedLinkError e) { File f = new File("/usr/lib/libdclassjni.so"); System.err.println("/usr/lib/libdclassjni.so exists: " + f.exists()); System.err.println("/usr/lib/libdclassjni.so is readable: " + f.canRead()); System.err.println("Native code library failed to load.\n" + e); e.printStackTrace(); } }

Target:
public static void loadDclassSharedObject() throws IOException { try { if (OS.contains("mac")) { System.load("/usr/local/lib/libdclassjni.0.dylib"); } else if (OS.contains("nix") || OS.contains("nux") || OS.contains("aix")) { try { System.loadLibrary("dclassjni"); } catch(Exception e) { System.err.println("Error: " + e); System.exit(-1); }; } else { System.err.println("OS not supported."); System.exit(-1); } } catch (UnsatisfiedLinkError e) { System.err.println("Native code library failed to load.\n" + e); e.printStackTrace(); } }
Source:
public ResponseEntity<Problem> handleInvalidStreamId(final InvalidStreamIdException ex, final NativeWebRequest request) { LOG.warn("Stream id is not found", ex.getStreamId(), ex.getMessage()); return Responses.create(MoreStatus.UNPROCESSABLE_ENTITY, ex.getMessage(), request); }

Target:
public ResponseEntity<Problem> handleInvalidStreamId(final InvalidStreamIdException ex, final NativeWebRequest request) { LOG.warn("Stream id is not found: {}", ex.getStreamId(), ex.getMessage()); return Responses.create(MoreStatus.UNPROCESSABLE_ENTITY, ex.getMessage(), request); }
Source:
public UUID createRule(UUID chainId, short ethertype) { try { UUID randId = UUID.randomUUID(); Topology.Rule r = Topology.Rule.getDefaultInstance() .toBuilder() .setId(UUIDUtil.toProto(randId)) .setAction(Topology.Rule.Action.ACCEPT) .setChainId(UUIDUtil.toProto(chainId)) .setDlType(ethertype) .build(); backend.store().create(r); return randId; } catch (Exception e) { throw new RuntimeException("Failed to create chain"); } }

Target:
public UUID createRule(UUID chainId, short ethertype) { try { UUID randId = UUID.randomUUID(); Topology.Rule r = Topology.Rule.getDefaultInstance() .toBuilder() .setId(UUIDUtil.toProto(randId)) .setType(Topology.Rule.Type.LITERAL_RULE) .setAction(Topology.Rule.Action.ACCEPT) .setChainId(UUIDUtil.toProto(chainId)) .setDlType(ethertype) .build(); backend.store().create(r); return randId; } catch (Exception e) { throw new RuntimeException("Failed to create chain"); } }
Source:
private boolean passesGithubAuthenticationCheck(TriggerEvent event, Trigger trigger) { boolean triggerHasSecret = StringUtils.isNotEmpty(trigger.getSecret()); boolean eventHasSignature = event.getDetails().getRequestHeaders().containsKey(GITHUB_SECURE_SIGNATURE_HEADER); if (triggerHasSecret && !eventHasSignature) { log.warn("Received GitEvent from Github without secure signature, for trigger configured with a secret"); return false; } if (!triggerHasSecret && eventHasSignature) { log.warn("Received GitEvent from Github with secure signature, but trigger did not contain the secret"); return false; } if (!triggerHasSecret) { return true; } return hasValidGitHubSecureSignature(event, trigger); }

Target:
private boolean passesGithubAuthenticationCheck(TriggerEvent event, Trigger trigger) { boolean triggerHasSecret = StringUtils.isNotEmpty(trigger.getSecret()); boolean eventHasSignature = event.getDetails().getRequestHeaders().containsKey(GITHUB_SECURE_SIGNATURE_HEADER); if (triggerHasSecret && !eventHasSignature) { log.warn("Received GitEvent from Github without secure signature for trigger configured with a secret"); return false; } if (!triggerHasSecret && eventHasSignature) { log.warn("Received GitEvent from Github with secure signature, but trigger did not contain the secret"); return false; } if (!triggerHasSecret) { return true; } return hasValidGitHubSecureSignature(event, trigger); }
Source:
public WSResponse sendAndReceiveRequestsFromSolver() { this.solverInstances = new ArrayList<>(); WSResponse response = null; String resultJson; TextAnnotation processedInstance; for (TextAnnotation ta : unprocessedInstances) { response = solver.processRequest(ta); try{ resultJson = response.getBody(); processedInstance = SerializationHelper.deserializeFromJson(resultJson); } catch(Exception e){ break; } solverInstances.add(processedInstance); } return response; }

Target:
public WSResponse sendAndReceiveRequestsFromSolver() { this.solverInstances = new ArrayList<>(); WSResponse response = null; String resultJson; TextAnnotation processedInstance; for (TextAnnotation ta : unprocessedInstances) { response = learnerInterface.processRequest(ta); try{ resultJson = response.getBody(); processedInstance = SerializationHelper.deserializeFromJson(resultJson); } catch(Exception e){ break; } solverInstances.add(processedInstance); } return response; }
Source:
void cancelScheduleMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int enqueDelayInSec = 3; StepVerifier.create(sender.scheduleMessage(message, Instant.now().plusSeconds(enqueDelayInSec)) .doOnSuccess(seqNumber -> sender.cancelScheduledMessage(seqNumber)) .delaySubscription(Duration.ofSeconds(enqueDelayInSec + 1)) .thenMany(receiver.receive().take(1))) .expectNoEvent(Duration.ofSeconds(5)) .verifyComplete(); }

Target:
void cancelScheduleMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); final Instant scheduledEnqueueTime = Instant.now().plusSeconds(10); final Duration delayDuration = Duration.ofSeconds(3); final Long sequenceNumber = sender.scheduleMessage(message, scheduledEnqueueTime).block(); logger.verbose("Scheduled the message, sequence number {}.", sequenceNumber); Mono.delay(delayDuration) .then(sender.cancelScheduledMessage(sequenceNumber.longValue())) .block(); logger.verbose("Cancelled the scheduled message, sequence number {}.", sequenceNumber); StepVerifier.create(receiver.receive().take(1)) .expectNoEvent(Duration.ofSeconds(5)) .verifyComplete(); }
Source:
protected void importResources(File file) { if (file.exists()) { File[] files = file.listFiles(); if (files != null) { for (File f : files) { importResources(f); } } else { try { URL url = file.toURI().toURL(); String parserType = getParserType(url); importFile(parserType, url); } catch (MalformedURLException e) { } } } }

Target:
public void importResources(File file) { if (file.exists()) { File[] files = file.listFiles(); if (files != null) { for (File f : files) { importResources(f); } } else { try { URL url = file.toURI().toURL(); String parserType = getParserType(url); importFile(parserType, url); } catch (MalformedURLException e) { logger.debug("Can't create a URL", e); } } } }
Source:
public void recordRequest(HttpServletRequest request, boolean enabled) { if (Telemetry.isDisabled()) { return; } if (!isActivePeriod()) { return; } HttpSession session = request.getSession(false); if (session != null) { String sessionId = session.getId(); sessionsBySetting.putIfAbsent(enabled, new HashSet<>()); sessionsBySetting.get(enabled).add(sessionId); } }

Target:
public void recordRequest(HttpServletRequest request, boolean enabled) { if (Telemetry.isDisabled()) { return; } if (!isActivePeriod()) { return; } HttpSession session = request.getSession(false); if (session != null) { String sessionId = session.getId(); if (enabled) { synchronized (sessionsWithAutoRefresh) { sessionsWithAutoRefresh.add(sessionId); } } else { synchronized (sessionsWithoutAutoRefresh) { sessionsWithoutAutoRefresh.add(sessionId); } } } }
Source:
private PageId getPageId(Path path) { Path parent = Preconditions.checkNotNull(path.getParent()); if (!Paths.get(mRoot).equals(parent.getParent())) { return null; } try { Path fileName = Preconditions.checkNotNull(path.getFileName()); Path parentName = Preconditions.checkNotNull(parent.getFileName()); long pageIndex = Long.parseLong(fileName.toString()); long fileId = Long.parseLong(parentName.toString()); return new PageId(fileId, pageIndex); } catch (NumberFormatException e) { return null; } }

Target:
private PageId getPageId(Path path) { Matcher matcher = mPagePattern.matcher(path.toString()); if (!matcher.matches()) { return null; } try { String parentName = Preconditions.checkNotNull(matcher.group(1)); String fileName = Preconditions.checkNotNull(matcher.group(2)); long fileId = Long.parseLong(parentName); long pageIndex = Long.parseLong(fileName); return new PageId(fileId, pageIndex); } catch (NumberFormatException e) { return null; } }
Source:
private void updateFeedbackParticipantComments(List<FeedbackResponseCommentAttributes> commentsToUpdate) throws EntityDoesNotExistException { for (FeedbackResponseCommentAttributes feedbackResponseComment : commentsToUpdate) { try { FeedbackResponseCommentAttributes updatedComment = logic.updateFeedbackResponseComment(feedbackResponseComment); logic.putDocument(updatedComment); statusToAdmin += this.getClass().getName() + ":<br>" + "Editing feedback response comment: " + feedbackResponseComment.getId() + "<br>" + "in course/feedback session: " + feedbackResponseComment.courseId + "/" + feedbackResponseComment.feedbackSessionName + "<br>" + "by: " + feedbackResponseComment.commentGiver + "<br>" + "comment text: " + feedbackResponseComment.commentText.getValue(); } catch (InvalidParametersException e) { setStatusForException(e); isError = true; } } }

Target:
private void updateFeedbackParticipantComments(List<FeedbackResponseCommentAttributes> commentsToUpdate) throws EntityDoesNotExistException { for (FeedbackResponseCommentAttributes feedbackResponseComment : commentsToUpdate) { try { FeedbackResponseCommentAttributes updatedComment = logic.updateFeedbackResponseComment(feedbackResponseComment); logic.putDocument(updatedComment); statusToAdmin += this.getClass().getName() + ":<br>" + "Editing feedback response comment: " + feedbackResponseComment.getId() + "<br>" + "in course/feedback session: " + feedbackResponseComment.courseId + "/" + feedbackResponseComment.feedbackSessionName + "<br>" + "by: " + feedbackResponseComment.commentGiver + "<br>" + "comment text: " + feedbackResponseComment.commentText.getValue(); } catch (InvalidParametersException e) { setStatusForException(e); } } }
Source:
public void simpleRequest() throws Exception { Map<String, String> s = new HashMap<>(); s.put("url", "http://localhost:" + wireMockRule.port()); s.put("database", "test-db"); stubFor(post(urlPathEqualTo("/write")).willReturn(aResponse().withStatus(200))); InfluxDbOutputWriter writer = new InfluxDbOutputWriter(new FakeClock()); writer.postConstruct(s); writer.writeQueryResult("foo", null, 1); writer.postCollect(); verify(postRequestedFor(urlPathEqualTo("/write")) .withQueryParam("db", equalTo("test-db")) .withQueryParam("precision", equalTo("ms")) .withRequestBody(equalTo("foo value=1i 1234"))); }

Target:
public void simpleRequest() throws Exception { Map<String, String> s = new HashMap<>(); s.put("url", "http://localhost:" + wireMockRule.port()); s.put("database", "test-db"); stubFor(post(urlPathEqualTo("/write")).willReturn(aResponse().withStatus(200))); InfluxDbOutputWriter writer = new InfluxDbOutputWriter(FAKE_CLOCK); writer.postConstruct(s); writer.writeQueryResult("foo", null, 1); writer.postCollect(); verify(postRequestedFor(urlPathEqualTo("/write")) .withQueryParam("db", equalTo("test-db")) .withQueryParam("precision", equalTo("ms")) .withRequestBody(equalTo("foo value=1i 1234"))); }
Source:
public Folder findParentFolder(final Treeable asset, final User user, final boolean respectFrontEndPermissions) throws DotIdentifierStateException, DotDataException, DotSecurityException { Identifier id = APILocator.getIdentifierAPI().find(asset.getIdentifier()); if(id==null) return null; if(id.getParentPath()==null || ROOT_PATH.equals(id.getParentPath()) || SYSTEM_FOLDER_PATH.equals(id.getParentPath())){ return null; } Host host = APILocator.getHostAPI().find(id.getHostId(), user, respectFrontEndPermissions); Folder f = folderFactory.findFolderByPath(id.getParentPath(), host); if(f == null || !UtilMethods.isSet(f.getInode())) return null; if (!permissionAPI.doesUserHavePermission(f, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { final String userId = user.getUserId() != null ? user.getUserId(): ""; final String path = f.getPath() != null ? f.getPath() : id.getParentPath(); Logger.error(this, "User " + userId + " does not have permission to read Folder " + path + " Please check the folder exists."); throw new DotSecurityException("User " + userId + " does not have permission to read Folder " + path); } return f; }

Target:
public Folder findParentFolder(final Treeable asset, final User user, final boolean respectFrontEndPermissions) throws DotIdentifierStateException, DotDataException, DotSecurityException { Identifier id = APILocator.getIdentifierAPI().find(asset.getIdentifier()); if(id==null || id.getParentPath()==null || ROOT_PATH.equals(id.getParentPath()) || SYSTEM_FOLDER_PATH.equals(id.getParentPath())){ return null; } Host host = APILocator.getHostAPI().find(id.getHostId(), user, respectFrontEndPermissions); final Folder folder = folderFactory.findFolderByPath(id.getParentPath(), host); if(folder == null || !UtilMethods.isSet(folder.getInode())){ return null; } if (!doesUserHavePermissions(folder, PermissionAPI.PERMISSION_READ, user, respectFrontEndPermissions)) { final String userId = user.getUserId() != null ? user.getUserId(): ""; final String path = folder.getPath() != null ? folder.getPath() : id.getParentPath(); Logger.error(this, "User " + userId + " does not have permission to read Folder " + path + " Please check the folder exists."); throw new DotSecurityException("User " + userId + " does not have permission to read Folder " + path); } return folder; }
Source:
public InputStream open() throws IOException { final String bucket = uri.getAuthority(); final String key = GoogleUtils.extractGoogleCloudStorageObjectKey(uri); final GoogleByteSource byteSource = new GoogleByteSource(storage, bucket, key); return CompressionUtils.decompress(byteSource.openStream(), uri.toString()); }

Target:
public InputStream open() throws IOException { final String bucket = uri.getAuthority(); final String key = GoogleUtils.extractGoogleCloudStorageObjectKey(uri); final GoogleByteSource byteSource = new GoogleByteSource(storage, bucket, key); return CompressionUtils.decompress(byteSource.openStream(), uri.getPath()); }
Source:
public String getErrorMessage() { return null; }

Target:
public String getErrorMessage() { return errorMessage; }
Source:
public static ConversionResult getResult(int error) { switch (error) { case 0: return CONVERSION_OK; case 1: return ILLEGAL_SEQUENCE; case 2: return OUTPUT_BUFFER_TOO_SMALL; case 3: return INCOMPLETE_SEQUENCE; case 4: return ERROR_METHOD_ID; case 5: return ERROR_ARRAY_FUNCTION_CALL; case 6: return ERROR_DESCRIPTOR; default: return WEIRD_ERROR; } }

Target:
public static ConversionResult getResult(int error) { switch (error) { case 0: return CONVERSION_OK; case 1: return ILLEGAL_SEQUENCE; case 2: return OUTPUT_BUFFER_TOO_SMALL; case 3: return INCOMPLETE_SEQUENCE; default: throw new IllegalArgumentException(); } }
Source:
public static Collection<Tile> parseTileMetrics(final File tileMetricsOutFile, final Map<Integer, File> phasingMetricsFiles, final ReadStructure readStructure, final ValidationStringency validationStringency) throws FileNotFoundException { TileMetricsOutReader tileMetricsIterator = new TileMetricsOutReader (tileMetricsOutFile, 3); final Collection<IlluminaTileMetrics> tileMetrics = determineLastValueForLaneTileMetricsCode(tileMetricsIterator); final Map<String, ? extends Collection<IlluminaTileMetrics>> locationToMetricsMap = partitionTileMetricsByLocation(tileMetrics); final Collection<Tile> tiles = new LinkedList<>(); for (final Map.Entry<String, ? extends Collection<IlluminaTileMetrics>> entry : locationToMetricsMap.entrySet()) { final Collection<IlluminaTileMetrics> tileRecords = entry.getValue(); final IlluminaTileMetrics record = CollectionUtil.getSoleElement(tileRecords); if (record.isClusterRecord()) { final Collection<TilePhasingValue> tilePhasingValues = getTilePhasingValues(record.getLaneTileCode(), phasingMetricsFiles, readStructure, validationStringency); tiles.add(new Tile(record.getLaneNumber(), record.getTileNumber(), tileMetricsIterator.getDensity(), record.getMetricValue(), tilePhasingValues.toArray(new TilePhasingValue[tilePhasingValues.size()]))); } } return Collections.unmodifiableCollection(tiles); }

Target:
public static Collection<Tile> parseTileMetrics(final File tileMetricsOutFile, final Map<Integer, File> phasingMetricsFiles, final ReadStructure readStructure, final ValidationStringency validationStringency) throws FileNotFoundException { TileMetricsOutReader tileMetricsIterator = new TileMetricsOutReader(tileMetricsOutFile, TileMetricsOutReader.TileMetricsVersion.THREE); final Collection<IlluminaTileMetrics> tileMetrics = determineLastValueForLaneTileMetricsCode(tileMetricsIterator); final Map<String, ? extends Collection<IlluminaTileMetrics>> locationToMetricsMap = partitionTileMetricsByLocation(tileMetrics); final Collection<Tile> tiles = new LinkedList<>(); for (final Map.Entry<String, ? extends Collection<IlluminaTileMetrics>> entry : locationToMetricsMap.entrySet()) { final Collection<IlluminaTileMetrics> tileRecords = entry.getValue(); final IlluminaTileMetrics record = CollectionUtil.getSoleElement(tileRecords); if (record.isClusterRecord()) { final Collection<TilePhasingValue> tilePhasingValues = getTilePhasingValues(record.getLaneTileCode(), phasingMetricsFiles, readStructure, validationStringency); tiles.add(new Tile(record.getLaneNumber(), record.getTileNumber(), tileMetricsIterator.getDensity(), record.getMetricValue(), tilePhasingValues.toArray(new TilePhasingValue[tilePhasingValues.size()]))); } } return Collections.unmodifiableCollection(tiles); }
Source:
public void test() { Client client = new Client(); long result = client.useService(10); assertTrue(result == 100 || result == -1); }

Target:
public void test() { Client client = new Client(); long result = client.useService(10); assertTrue(result == 100 || result == RemoteService.FAILURE); }
Source:
private MessageHandlerNode handlerNode(String name, IntegrationConsumer consumer) { MessageChannel outputChannel = consumer.getOutputChannel(); String outputChannelName = outputChannel == null ? null : outputChannel.toString(); MessageHandler handler = consumer.getHandler(); return handler instanceof CompositeMessageHandler ? compositeHandler(name, consumer, (CompositeMessageHandler) handler, outputChannelName, null, false) : handler instanceof DiscardingMessageHandler ? discardingHandler(name, consumer, (DiscardingMessageHandler) handler, outputChannelName, null, false) : handler instanceof MappingMessageRouterManagement ? routingHandler(name, consumer, handler, (MappingMessageRouterManagement) handler, outputChannelName, null, false) : handler instanceof RecipientListRouterManagement ? recipientListRoutingHandler(name, consumer, handler, (RecipientListRouterManagement) handler, outputChannelName, null, false) : new MessageHandlerNode(this.nodeId.incrementAndGet(), name, handler, consumer.getInputChannel().toString(), outputChannelName); }

Target:
private MessageHandlerNode handlerNode(String name, IntegrationConsumer consumer) { MessageChannel outputChannel = consumer.getOutputChannel(); String outputChannelName = outputChannel == null ? null : outputChannel.toString(); MessageHandler handler = consumer.getHandler(); if (handler instanceof CompositeMessageHandler) { return compositeHandler(name, consumer, (CompositeMessageHandler) handler, outputChannelName, null, false); } else if (handler instanceof DiscardingMessageHandler) { return discardingHandler(name, consumer, (DiscardingMessageHandler) handler, outputChannelName, null, false); } else if (handler instanceof MappingMessageRouterManagement) { return routingHandler(name, consumer, handler, (MappingMessageRouterManagement) handler, outputChannelName, null, false); } else if (handler instanceof RecipientListRouterManagement) { return recipientListRoutingHandler(name, consumer, handler, (RecipientListRouterManagement) handler, outputChannelName, null, false); } else { return new MessageHandlerNode(this.nodeId.incrementAndGet(), name, handler, consumer.getInputChannel().toString(), outputChannelName); } }
Source:
public static File writeToTempFile(Iterator<Tweet> iterator) throws IOException { File srcFile = File.createTempFile("tweets", "txt"); srcFile.deleteOnExit(); FileWriter fw = new FileWriter(srcFile); try { BufferedWriter bw = new BufferedWriter(fw); try { while (iterator.hasNext()) { bw.write(GSON.toJson(iterator.next())); bw.newLine(); } } finally { bw.close(); } } finally { fw.close(); } return srcFile; }

Target:
public static File writeToTempFile(Iterator<Tweet> iterator) throws IOException { File srcFile = File.createTempFile("tweets", "txt"); srcFile.deleteOnExit(); BufferedWriter writer = Files.newWriter(srcFile, Charsets.UTF_8); try { while (iterator.hasNext()) { writer.write(GSON.toJson(iterator.next())); writer.newLine(); } } finally { writer.close(); } return srcFile; }
Source:
public Long getUuid() { return new Long(0); }

Target:
public Long getUuid() { return 0L; }
Source:
@Override public void parseArguments(CommandArgIterator argIter) { String s = argIter.nextArg("New cluster state not found."); try { state = ClusterState.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Can't parse new cluster state. State: " + s, e); } if (argIter.hasNextArg()) { String arg = argIter.peekNextArg(); if ("--force".equalsIgnoreCase(arg)) { force = true; argIter.nextArg(""); } } }

Target:
@Override public void parseArguments(CommandArgIterator argIter) { String s = argIter.nextArg("New cluster state not found."); try { state = ClusterState.valueOf(s.toUpperCase()); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Can't parse new cluster state. State: " + s, e); } if (argIter.hasNextArg()) { String arg = argIter.peekNextArg(); if (FORCE_COMMAND.equalsIgnoreCase(arg)) { force = true; argIter.nextArg(""); } } }
Source:
public static Archive<?> createTestArchive() { Archive<?> beanValidationJarWithMissingProvider = IntegrationTestUtil.createCustomBeanValidationProviderJar(); Node providerClass = beanValidationJarWithMissingProvider.delete( "org/hibernate/validator/integration/util/MyValidationProvider.class" ); if ( providerClass == null ) { fail( "MyValidationProvider was not as expected in the custom jar" ); } return ShrinkWrap.create( WebArchive.class, WAR_FILE_NAME ) .addClasses( MyValidatorCreator.class ) .addAsLibraries( IntegrationTestUtil.bundleHibernateValidatorWithDependencies( true ) ) .addAsLibrary( beanValidationJarWithMissingProvider ) .addAsResource( "log4j.properties" ) .addAsWebInfResource( EmptyAsset.INSTANCE, ArchivePaths.create( "beans.xml" ) ) .addAsWebInfResource( "jboss-deployment-structure.xml" ); }

Target:
public static Archive<?> createTestArchive() { Archive<?> beanValidationJarWithMissingProvider = IntegrationTestUtil.createCustomBeanValidationProviderJar(); Node providerClass = beanValidationJarWithMissingProvider.delete( "org/hibernate/validator/integration/util/MyValidationProvider.class" ); if ( providerClass == null ) { fail( "MyValidationProvider was not as expected in the custom jar" ); } return ShrinkWrap.create( WebArchive.class, WAR_FILE_NAME ) .addAsLibraries( IntegrationTestUtil.bundleHibernateValidatorWithDependencies( true ) ) .addAsLibrary( beanValidationJarWithMissingProvider ) .addAsResource( "log4j.properties" ) .addAsWebInfResource( "jboss-deployment-structure.xml" ); }
Source:
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layout, SplitSchedulingStrategy splitSchedulingStrategy) { ElasticsearchTableLayoutHandle layoutHandle = (ElasticsearchTableLayoutHandle) layout; ElasticsearchTableHandle tableHandle = layoutHandle.getTable(); ElasticsearchTableDescription table = client.getTable(tableHandle.getSchemaName(), tableHandle.getTableName()); checkState(table != null, "Table %s no longer exists", tableHandle.toString()); List<String> indices = client.getIndices(table); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (String index : indices) { ClusterSearchShardsResponse response = client.getSearchShards(index, table); DiscoveryNode[] nodes = response.getNodes(); for (ClusterSearchShardsGroup group : response.getGroups()) { int nodeIndex = group.getShardId().getId() % nodes.length; ElasticsearchSplit split = new ElasticsearchSplit(table, index, group.getShardId().getId(), nodes[nodeIndex].getHostName(), nodes[nodeIndex].getAddress().getPort(), layoutHandle.getTupleDomain()); splits.add(split); } } return new FixedSplitSource(splits.build()); }

Target:
public ConnectorSplitSource getSplits(ConnectorTransactionHandle transactionHandle, ConnectorSession session, ConnectorTableLayoutHandle layout, SplitSchedulingStrategy splitSchedulingStrategy) { ElasticsearchTableLayoutHandle layoutHandle = (ElasticsearchTableLayoutHandle) layout; ElasticsearchTableHandle tableHandle = layoutHandle.getTable(); ElasticsearchTableDescription table = client.getTable(tableHandle.getSchemaName(), tableHandle.getTableName()); verify(table != null, "Table no longer exists: %s", tableHandle.toString()); List<String> indices = client.getIndices(table); ImmutableList.Builder<ConnectorSplit> splits = ImmutableList.builder(); for (String index : indices) { ClusterSearchShardsResponse response = client.getSearchShards(index, table); DiscoveryNode[] nodes = response.getNodes(); for (ClusterSearchShardsGroup group : response.getGroups()) { int nodeIndex = group.getShardId().getId() % nodes.length; ElasticsearchSplit split = new ElasticsearchSplit(table, index, group.getShardId().getId(), nodes[nodeIndex].getHostName(), nodes[nodeIndex].getAddress().getPort(), layoutHandle.getTupleDomain()); splits.add(split); } } return new FixedSplitSource(splits.build()); }
Source:
private String validateModel(String name, InputStream inputStream) throws IOException { Resource resource = resourceSet.createResource(URI.createURI("tmp_" + name)); try { resource.load(inputStream, Collections.EMPTY_MAP); StringBuilder criticalErrors = new StringBuilder(); StringBuilder warnings = new StringBuilder(); if (resource != null && !resource.getContents().isEmpty()) { for (Diagnostic diagnostic : resource.getErrors()) { criticalErrors.append(MessageFormat.format("[{0},{1}]: {2}\n", diagnostic.getLine(), diagnostic.getColumn(), diagnostic.getMessage())); } if (criticalErrors.length() > 0) { return criticalErrors.toString(); } org.eclipse.emf.common.util.Diagnostic diagnostic = Diagnostician.INSTANCE .validate(resource.getContents().get(0)); for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) { warnings.append(d.getMessage()); warnings.append("\n"); } if (warnings.length() > 0) { logger.warn("Validation error(s) in configuration model '{}':\n {}", name, warnings.toString()); } } } finally { resourceSet.getResources().remove(resource); } return null; }

Target:
private String validateModel(String name, InputStream inputStream) throws IOException { Resource resource = resourceSet.createResource(URI.createURI("tmp_" + name)); try { resource.load(inputStream, Collections.EMPTY_MAP); StringBuilder criticalErrors = new StringBuilder(); StringBuilder warnings = new StringBuilder(); if (resource != null && !resource.getContents().isEmpty()) { for (Diagnostic diagnostic : resource.getErrors()) { criticalErrors.append(MessageFormat.format("[{0},{1}]: {2}\n", diagnostic.getLine(), diagnostic.getColumn(), diagnostic.getMessage())); } if (criticalErrors.length() > 0) { return criticalErrors.toString(); } org.eclipse.emf.common.util.Diagnostic diagnostic = Diagnostician.INSTANCE .validate(resource.getContents().get(0)); for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) { warnings.append(d.getMessage()); warnings.append("\n"); } if (warnings.length() > 0) { logger.warn("Validation error(s) in configuration model '{}':\n {}", name, warnings); } } } finally { resourceSet.getResources().remove(resource); } return null; }
Source:
void insertVariables(final int id, final int actionId, Map<String, String> stateVariables, Map<String, String> originalStateVariables) { Map<String, String> changedStateVariables = changedStateVariables(stateVariables, originalStateVariables); if (changedStateVariables.isEmpty()) { return; } if (sqlVariants.useBatchUpdate()) { final Iterator<Entry<String, String>> variables = changedStateVariables.entrySet().iterator(); int[] updateStatus = jdbc.batchUpdate(insertWorkflowInstanceStateSql() + " values (?,?,?,?)", new AbstractInterruptibleBatchPreparedStatementSetter() { @Override protected boolean setValuesIfAvailable(PreparedStatement ps, int i) throws SQLException { if (!variables.hasNext()) { return false; } Entry<String, String> var = variables.next(); ps.setInt(1, id); ps.setInt(2, actionId); ps.setString(3, var.getKey()); ps.setString(4, var.getValue()); return true; } }); int updatedRows = 0; boolean unknownResults = false; for (int i = 0; i < updateStatus.length; ++i) { if (updateStatus[i] == Statement.SUCCESS_NO_INFO) { unknownResults = true; continue; } if (updateStatus[i] == Statement.EXECUTE_FAILED) { throw new IllegalStateException("Failed to insert/update state variables"); } updatedRows += updateStatus[i]; } if (!unknownResults && updatedRows != changedStateVariables.size()) { throw new IllegalStateException("Failed to insert/update state variables, expected update count " + changedStateVariables.size() + ", actual " + updatedRows); } } else { for (Entry<String, String> entry : changedStateVariables.entrySet()) { int updated = jdbc.update(insertWorkflowInstanceStateSql() + " values (?,?,?,?)", id, actionId, entry.getKey(), entry.getValue()); if (updated != 1) { throw new IllegalStateException("Failed to insert state variable " + entry.getKey()); } } } }

Target:
void insertVariables(final int id, final int actionId, Map<String, String> stateVariables, Map<String, String> originalStateVariables) { Map<String, String> changedStateVariables = changedStateVariables(stateVariables, originalStateVariables); if (changedStateVariables.isEmpty()) { return; } if (sqlVariants.useBatchUpdate()) { insertVariablesWithBatchUpdate(id, actionId, changedStateVariables); } else { insertVariablesWithMultipleUpdates(id, actionId, changedStateVariables); } }
Source:
public static <T> T removeLast(List<T> self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot pop() an empty List"); } return self.remove(self.size() - 1); }

Target:
public static <T> T removeLast(List<T> self) { if (self.isEmpty()) { throw new NoSuchElementException("Cannot removeLast() an empty List"); } return self.remove(self.size() - 1); }
Source:
protected String[] getTopologyConf(PackingPlan packing) { config = Config.newBuilder() .putAll(config) .put(Key.TOPOLOGY_BINARY_FILE, FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() .iterator().next().getRequiredResource(); String[] deploymentConfs = new String[Ints.checkedCast(Runtime.numContainers(runtime))]; for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(KubernetesConstants.API_VERSION, KubernetesConstants.API_VERSION_1); instance.put(KubernetesConstants.API_KIND, KubernetesConstants.API_POD); instance.set(KubernetesConstants.API_METADATA, getMetadata(mapper, i)); instance.set(KubernetesConstants.API_SPEC, getContainerSpec(mapper, i, containerResource)); deploymentConfs[i] = instance.toString(); } return deploymentConfs; }

Target:
protected String[] getTopologyConf(PackingPlan packing) { config = Config.newBuilder() .putAll(config) .put(Key.TOPOLOGY_BINARY_FILE, FileUtils.getBaseName(Context.topologyBinaryFile(config))) .build(); ObjectMapper mapper = new ObjectMapper(); PackingPlan updatedPackingPlan = packing.cloneWithHomogeneousScheduledResource(); SchedulerUtils.persistUpdatedPackingPlan(Runtime.topologyName(runtime), updatedPackingPlan, Runtime.schedulerStateManagerAdaptor(runtime)); Resource containerResource = updatedPackingPlan.getContainers() .iterator().next().getScheduledResource().get(); String[] deploymentConfs = new String[Ints.checkedCast(Runtime.numContainers(runtime))]; for (int i = 0; i < Runtime.numContainers(runtime); i++) { ObjectNode instance = mapper.createObjectNode(); instance.put(KubernetesConstants.API_VERSION, KubernetesConstants.API_VERSION_1); instance.put(KubernetesConstants.API_KIND, KubernetesConstants.API_POD); instance.set(KubernetesConstants.API_METADATA, getMetadata(mapper, i)); instance.set(KubernetesConstants.API_SPEC, getContainerSpec(mapper, i, containerResource)); deploymentConfs[i] = instance.toString(); } return deploymentConfs; }
Source:
public FileChooserDialog(Skin skin, String selectString, String cancelString, FileChooserListener fileChooserListener) { super(skin); this.fileChooserListener = fileChooserListener; root(files = new FilesListWidget(skin)); button(selectString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(files .getSelectedFile().path(), FileChooserListener.Result.SUCCESS); } }); button(cancelString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(null, null); } }); }

Target:
public FileChooserDialog(Skin skin, String selectString, String cancelString, FileChooserListener fileChooserListener) { super(skin); this.fileChooserListener = fileChooserListener; root(files = new FilesListWidget(skin)); button(selectString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(files .getSelectedFile().path(), FileChooserListener.Result.SUCCESS); } }); button(cancelString).addListener(new ClickListener() { @Override public void clicked(InputEvent event, float x, float y) { FileChooserDialog.this.fileChooserListener.fileChosen(null, FileChooserListener.Result.CANCELLED); } }); }
Source:
public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } final Map<Long, T> idValueMap = new HashMap<>(); for (int index = 0; index < ids.size(); index++) { if (!router.isLocal(ids.get(index))) { LOG.log(Level.INFO, "This id is not local: {0}", ids.get(index)); } else { idValueMap.put(ids.get(index), values.get(index)); } } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } final Map<Long, Object> innerMap = dataMap.get(dataType); innerMap.putAll(idValueMap); } finally { readWriteLock.writeLock().unlock(); } }

Target:
public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } final Map<Long, T> idValueMap = new HashMap<>(); for (int index = 0; index < ids.size(); index++) { if (!router.isLocal(ids.get(index))) { LOG.log(Level.WARNING, "This id is not local: {0}", ids.get(index)); } else { idValueMap.put(ids.get(index), values.get(index)); } } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } final Map<Long, Object> innerMap = dataMap.get(dataType); innerMap.putAll(idValueMap); } finally { readWriteLock.writeLock().unlock(); } }
Source:
public <B> Eval<B> flatMap(final F<A, Eval<B>> f) { return bind(f); }

Target:
public final <B> Eval<B> flatMap(final F<A, Eval<B>> f) { return bind(f); }
Source:
public void executeTransactionAsync_cancelTransactionInside() throws Throwable { final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(LogLevel.DEBUG); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.where(Owner.class).count()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { assertTrue(testLogger.message.contains( "Exception has been throw: Can't commit a non-existing write transaction")); assertTrue(error instanceof IllegalStateException); RealmLog.remove(testLogger); looperThread.testComplete(); } }); }

Target:
public void executeTransactionAsync_cancelTransactionInside() throws Throwable { final TestHelper.TestLogger testLogger = new TestHelper.TestLogger(LogLevel.DEBUG); RealmLog.add(testLogger); final Realm realm = looperThread.realm; assertEquals(0, realm.where(Owner.class).count()); realm.executeTransactionAsync(new Realm.Transaction() { @Override public void execute(Realm realm) { Owner owner = realm.createObject(Owner.class); owner.setName("Owner"); realm.cancelTransaction(); } }, new Realm.Transaction.OnSuccess() { @Override public void onSuccess() { fail("Should not reach success if runtime exception is thrown in callback."); } }, new Realm.Transaction.OnError() { @Override public void onError(Throwable error) { assertTrue(testLogger.message.contains( "Exception has been thrown: Can't commit a non-existing write transaction")); assertTrue(error instanceof IllegalStateException); RealmLog.remove(testLogger); looperThread.testComplete(); } }); }