auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setHeight(int height) { <START> int oldHeight = this.fHeight; <END> this.fHeight = height; if (oldHeight != height) { getParent().layout(new Control[] { this }); } }</code><technical_language>avoid this local variable if store fHeight if clause, if feel (also, this. unnecessary)</technical_language>

Target:
public void setHeight(int height) { if (fHeight != height) { fHeight = height; getParent().layout(new Control[] { this }); } }
Source:
<code>public void onSave() { boolean isInternal = (Boolean) getIsInternal().getEntity(); if (isInternal) { DiskImage diskImage = getDiskImage(); if (getQuota().getIsAvailable() && getQuota().getSelectedItem() != null) { diskImage.setQuotaId(((Quota) getQuota().getSelectedItem()).getId()); } long sizeToAddInGigabytes = Long.valueOf((String) getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } setDisk(diskImage); } else { LunDisk lunDisk = getLunDisk(); DiskInterface diskInterface = (DiskInterface) getDiskInterface().getSelectedItem(); if (DiskInterface.VirtIO_SCSI.equals(diskInterface)) { lunDisk.setSgio(Boolean.TRUE.equals((Boolean) getIsSgIoUnfiltered().getEntity()) ? ScsiGenericIO.UNFILTERED : ScsiGenericIO.FILTERED); } setDisk(lunDisk); } getDisk().setDiskAlias((String) getAlias().getEntity()); getDisk().setDiskDescription((String) getDescription().getEntity()); getDisk().setDiskInterface((DiskInterface) getDiskInterface().getSelectedItem()); getDisk().setWipeAfterDelete((Boolean) getIsWipeAfterDelete().getEntity()); getDisk().setBoot((Boolean) getIsBootable().getEntity()); getDisk().setShareable((Boolean) getIsShareable().getEntity()); getDisk().setPlugged((Boolean) getIsPlugged().getEntity()); getDisk().setPropagateErrors(PropagateErrors.Off); <START> if (getIsReadOnly().getIsAvailable()) { <END> getDisk().setReadOnly((Boolean) getIsReadOnly().getEntity()); } else { getDisk().setReadOnly(false); } }</code><technical_language>a matter of taste - I prefer ternary if in cases</technical_language>

Target:
public void onSave() { boolean isInternal = (Boolean) getIsInternal().getEntity(); if (isInternal) { DiskImage diskImage = getDiskImage(); if (getQuota().getIsAvailable() && getQuota().getSelectedItem() != null) { diskImage.setQuotaId(((Quota) getQuota().getSelectedItem()).getId()); } long sizeToAddInGigabytes = Long.valueOf((String) getSizeExtend().getEntity()); if (sizeToAddInGigabytes > 0) { diskImage.setSizeInGigabytes(diskImage.getSizeInGigabytes() + sizeToAddInGigabytes); } setDisk(diskImage); } else { LunDisk lunDisk = getLunDisk(); DiskInterface diskInterface = (DiskInterface) getDiskInterface().getSelectedItem(); if (DiskInterface.VirtIO_SCSI.equals(diskInterface)) { lunDisk.setSgio(Boolean.TRUE.equals((Boolean) getIsSgIoUnfiltered().getEntity()) ? ScsiGenericIO.UNFILTERED : ScsiGenericIO.FILTERED); } setDisk(lunDisk); } getDisk().setDiskAlias((String) getAlias().getEntity()); getDisk().setDiskDescription((String) getDescription().getEntity()); getDisk().setDiskInterface((DiskInterface) getDiskInterface().getSelectedItem()); getDisk().setWipeAfterDelete((Boolean) getIsWipeAfterDelete().getEntity()); getDisk().setBoot((Boolean) getIsBootable().getEntity()); getDisk().setShareable((Boolean) getIsShareable().getEntity()); getDisk().setPlugged((Boolean) getIsPlugged().getEntity()); getDisk().setPropagateErrors(PropagateErrors.Off); getDisk().setReadOnly(getIsReadOnly().getIsAvailable() ? (Boolean) getIsReadOnly().getEntity() : null); }
Source:
<code>public Consumer createConsumer(Processor processor) throws Exception { <START> throw new NoSuchEndpointException("Workday producer is not implemented."); <END> }</code><technical_language>meant a consumer I guess</technical_language>

Target:
public Consumer createConsumer(Processor processor) throws Exception { throw new NoSuchEndpointException("Workday consumer is not implemented."); }
Source:
<code>public void onEvent(final PushLinkReceivedEvent event) { <START> if (!isInForeground) { <END> return; } showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.view_button_text), (dialog, which) -> PushLinkManager.INSTANCE.userGrantedPushLinkAction(this, event.getPushLink()), getString(R.string.label_cancel), null ); }</code><technical_language>checking app isInForeground showAlertdialog method</technical_language>

Target:
public void onEvent(final PushLinkReceivedEvent event) { if (event.getPushLink().isDeepLink()) { showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.view_button_text), (dialog, which) -> PushLinkManager.INSTANCE.onPushLinkActionGranted(this, event.getPushLink()), getString(R.string.label_cancel), null ); } else { showAlertDialog(event.getPushLink().getTitle(), event.getPushLink().getBody(), getString(R.string.label_ok), null, getString(R.string.label_cancel), null ); } }
Source:
<code>protected void runTask() { telescopeReporter = OwlTelescopeReporterFactory.getInstance() .getTelescopeReporter( OwlTelescopeReporters.RADIO_TIMES_INGESTER, Event.Type.INGEST); telescopeReporter.startReporting(); String requestUri = feedUrl; if (doCompleteUpdate) { requestUri += "/since?lastUpdated=" + UrlEncoding.encode(dateFormat.print(START_DATE)); } else { requestUri += "/since?lastUpdated=" + UrlEncoding .encode(dateFormat.print(new DateTime(DateTimeZone.UTC).minusDays(3))); } try { reportStatus("Started..."); <START> getAndTransform(feedUrl); <END> } catch (Exception e) { AdapterLogEntry errorRecord = errorEntry() .withCause(e) .withSource(getClass()) .withUri(requestUri) .withDescription("Exception while fetching film feed"); log.record(errorRecord); reportStatus("Failed: " + errorRecord.id()); telescopeReporter.reportFailedEvent("Failed with exception. Ingest stopped abruptly. " + e.getMessage(), EntityType.FILM, requestUri, errorRecord); Throwables.propagate(e); } finally { telescopeReporter.endReporting(); } }</code><technical_language>this requestUri</technical_language>

Target:
protected void runTask() { telescopeReporter = OwlTelescopeReporterFactory.getInstance() .getTelescopeReporter( OwlTelescopeReporters.RADIO_TIMES_INGESTER, Event.Type.INGEST); telescopeReporter.startReporting(); String requestUri = feedUrl; if (doCompleteUpdate) { requestUri += "/since?lastUpdated=" + UrlEncoding.encode(dateFormat.print(START_DATE)); } else { requestUri += "/since?lastUpdated=" + UrlEncoding .encode(dateFormat.print(new DateTime(DateTimeZone.UTC).minusDays(3))); } try { reportStatus("Started..."); getAndTransform(requestUri); } catch (Exception e) { AdapterLogEntry errorRecord = errorEntry() .withCause(e) .withSource(getClass()) .withUri(requestUri) .withDescription("Exception while fetching film feed"); log.record(errorRecord); reportStatus("Failed: " + errorRecord.id()); telescopeReporter.reportFailedEvent("Failed with exception. Ingest stopped abruptly. " + e.getMessage(), EntityType.FILM, requestUri, errorRecord); Throwables.propagate(e); } finally { telescopeReporter.endReporting(); } }
Source:
<code><START> public long getCurrentUidValidity() throws MessagingException { <END> if (isOpen()) { close(); } store.releaseConnection(connection); try { synchronized (this) { connection = store.getConnection(); } String openCommand = "EXAMINE"; String encodedFolderName = folderNameCodec.encode(getPrefixedName()); String escapedFolderName = ImapUtility.encodeString(encodedFolderName); String command = String.format("%s %s", openCommand, escapedFolderName); List<ImapResponse> responses = executeSimpleCommand(command); return SelectOrExamineResponse.extractUidValidity(responses); } catch (IOException ioe) { throw ioExceptionHandler(connection, ioe); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to open connection for " + getLogId(), me); throw me; } }</code><technical_language>this done in easier simply calling open if folder is opened? this open folder, fetches a SelectOrExamineResponse, parse store uidvalidity, in cases folder is opened do server communication</technical_language>

Target:
public long getCurrentUidValidity() throws MessagingException { if (isOpen()) { close(); } try { List<ImapResponse> responses = internalOpen(OPEN_MODE_RO); return SelectOrExamineResponse.extractUidValidity(responses); } catch (MessagingException me) { Log.e(LOG_TAG, "Unable to open connection for " + getLogId(), me); throw me; } }
Source:
<code>public void testSamFileVersion1pt5() throws Exception { final SamReader samReader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(new File(TEST_DATA_DIR, "test_samfile_version_1pt5.bam")); final Histogram<String> results = executeValidation(samReader, null, IndexValidationStringency.EXHAUSTIVE); <START> Assert.assertFalse(results.isEmpty()); <END> }</code><technical_language>Instead of assertFalse() this assert number of results values for expected result, if possible</technical_language>

Target:
public void testSamFileVersion1pt5() throws Exception { final SamReader samReader = SamReaderFactory.makeDefault().validationStringency(ValidationStringency.SILENT).open(new File(TEST_DATA_DIR, "test_samfile_version_1pt5.bam")); final Histogram<String> results = executeValidation(samReader, null, IndexValidationStringency.EXHAUSTIVE); Assert.assertEquals(results.getCount(),2.0); }
Source:
<code>private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; final boolean shouldPerformOpOnVmSnapshots = !diskImage.isShareable(); try { if (shouldPerformOpOnVmSnapshots) { VM vm = getVmForNonShareableDiskImage(diskImage); lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { <START> updatedSnapshots = null; <END> } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); if (updatedSnapshots != null) { for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } } return null; } }); } finally { if (shouldPerformOpOnVmSnapshots){ freeVmSnapshotsLock(); } } }</code><technical_language>optional: Collections.emptyList()</technical_language>

Target:
private void removeImageFromDB() { final DiskImage diskImage = getDiskImage(); final List<Snapshot> updatedSnapshots; final boolean shouldPerformOpOnVmSnapshots = !diskImage.isShareable(); try { if (shouldPerformOpOnVmSnapshots) { VM vm = getVmForNonShareableDiskImage(diskImage); lockVmSnapshotsWithWait(vm); updatedSnapshots = prepareSnapshotConfigWithoutImage(diskImage.getId()); } else { updatedSnapshots = Collections.emptyList(); } TransactionSupport.executeInScope(TransactionScopeOption.Required, new TransactionMethod<Object>() { @Override public Object runInTransaction() { getDiskImageDynamicDAO().remove(diskImage.getImageId()); Guid imageTemplate = diskImage.getit_guid(); Guid currentGuid = diskImage.getImageId(); while (!currentGuid.equals(imageTemplate) && !currentGuid.equals(Guid.Empty)) { RemoveChildren(currentGuid); DiskImage image = getDiskImageDao().getSnapshotById(currentGuid); if (image != null) { RemoveSnapshot(image); currentGuid = image.getParentId(); } else { currentGuid = Guid.Empty; log.warnFormat( "'image' (snapshot of image '{0}') is null, cannot remove it.", diskImage.getImageId()); } } getBaseDiskDao().remove(diskImage.getId()); getVmDeviceDAO().remove(new VmDeviceId(diskImage.getId(), null)); for (Snapshot s : updatedSnapshots) { getSnapshotDao().update(s); } return null; } }); } finally { if (shouldPerformOpOnVmSnapshots) { freeVmSnapshotsLock(); } } }
Source:
<code>protected Map<String, String> getInternalAddressesAndPorts(ContainerInfo containerInfo, String internalHost) { String internalAddressContainer = containerInfo.getNetworkSettings().getIpAddress(); String internalAddress; boolean useExposedPorts = true; <START> if (internalAddressContainer != null && !internalAddressContainer.isEmpty()) { <END> internalAddress = internalAddressContainer; } else { internalAddress = internalHost; useExposedPorts = false; } Map<String, List<PortBinding>> portBindings = containerInfo.getNetworkSettings().getPorts(); Map<String, String> addressesAndPorts = new HashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : portBindings.entrySet()) { String exposedPort = portEntry.getKey().split("/")[0]; String ephemeralPort = portEntry.getValue().get(0).getHostPort(); if (useExposedPorts) { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + exposedPort); } else { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + ephemeralPort); } } return addressesAndPorts; }</code><technical_language>IsNullOrEmpty - code clearer</technical_language>

Target:
protected Map<String, String> getInternalAddressesAndPorts(ContainerInfo containerInfo, String internalHost) { String internalAddressContainer = containerInfo.getNetworkSettings().getIpAddress(); String internalAddress; boolean useExposedPorts = true; if (!isNullOrEmpty(internalAddressContainer)) { internalAddress = internalAddressContainer; } else { internalAddress = internalHost; useExposedPorts = false; } Map<String, List<PortBinding>> portBindings = containerInfo.getNetworkSettings().getPorts(); Map<String, String> addressesAndPorts = new HashMap<>(); for (Map.Entry<String, List<PortBinding>> portEntry : portBindings.entrySet()) { String exposedPort = portEntry.getKey().split("/")[0]; String ephemeralPort = portEntry.getValue().get(0).getHostPort(); if (useExposedPorts) { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + exposedPort); } else { addressesAndPorts.put(portEntry.getKey(), internalAddress + ":" + ephemeralPort); } } return addressesAndPorts; }
Source:
<code><START> private boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) { <END> String requestResource = request.uri().substring(1); if (requestResource.isEmpty()) { requestResource = "index.html"; } URL resourceUrl = getClass().getResource(requestResource); if (resourceUrl == null) { return false; } RandomAccessFile raf; long fileLength; try { raf = new RandomAccessFile(resourceUrl.getFile(), "r"); fileLength = raf.length(); } catch (IOException io) { System.out.println("File not found " + io.getMessage()); return false; } HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK); HttpUtil.setContentLength(response, fileLength); String contentType = "application/octet-stream"; if (requestResource.endsWith("html")) { contentType = "text/html; charset=UTF-8"; } else if (requestResource.endsWith("css")) { contentType = "text/css; charset=UTF-8"; } else if (requestResource.endsWith("js")) { contentType = "application/javascript"; } response.headers().set(CONTENT_TYPE, contentType); sendResponse(response, ctx, false); ctx.writeAndFlush(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); return true; }</code><technical_language>static</technical_language>

Target:
private static boolean sendResource(FullHttpRequest request, ChannelHandlerContext ctx) { if (request.uri().isEmpty() || !request.uri().startsWith("/")) { return false; } String requestResource = request.uri().substring(1); if (requestResource.isEmpty()) { requestResource = "index.html"; } URL resourceUrl = INSTANCE.getClass().getResource(requestResource); if (resourceUrl == null) { return false; } RandomAccessFile raf = null; long fileLength = -1L; try { raf = new RandomAccessFile(resourceUrl.getFile(), "r"); fileLength = raf.length(); } catch (FileNotFoundException fne) { System.out.println("File not found " + fne.getMessage()); return false; } catch (IOException io) { System.out.println("Cannot read file length " + io.getMessage()); return false; } finally { if (fileLength < 0 && raf != null) { try { raf.close(); } catch (IOException io) { } } } HttpResponse response = new DefaultHttpResponse(request.protocolVersion(), OK); HttpUtil.setContentLength(response, fileLength); String contentType = "application/octet-stream"; if (requestResource.endsWith("html")) { contentType = "text/html; charset=UTF-8"; } else if (requestResource.endsWith("css")) { contentType = "text/css; charset=UTF-8"; } else if (requestResource.endsWith("js")) { contentType = "application/javascript"; } response.headers().set(CONTENT_TYPE, contentType); sendResponse(response, ctx, false); ctx.write(new DefaultFileRegion(raf.getChannel(), 0, fileLength)); ctx.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT); return true; }
Source:
<code>public void storeToken(String tokenHash, String randomTokenLink, String accountId, String description) { Integer rowsUpdated = jdbi.withHandle(handle -> handle.insert("INSERT INTO tokens(token_hash, token_link, description, account_id) VALUES (?,?,?,?)", tokenHash, randomTokenLink, description, accountId) ); if (rowsUpdated != 1) { <START> log.error("Unable to store new token for account {}", accountId); <END> throw new RuntimeException(String.format("Unable to store new token for account %s}", accountId)); } }</code><technical_language>log rows inserted get error</technical_language>

Target:
public void storeToken(String tokenHash, String randomTokenLink, String accountId, String description) { Integer rowsUpdated = jdbi.withHandle(handle -> handle.insert("INSERT INTO tokens(token_hash, token_link, description, account_id) VALUES (?,?,?,?)", tokenHash, randomTokenLink, description, accountId) ); if (rowsUpdated != 1) { log.error("Unable to store new token for account '{}'. '{}' rows were updated", accountId, rowsUpdated); throw new RuntimeException(String.format("Unable to store new token for account %s}", accountId)); } }
Source:
<code>public final void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); <START> wasCustomHandlerInvoked = false; <END> }</code><technical_language>this statement is statement. do anything</technical_language>

Target:
public void testExecutorStateEventWithCustomHandler() { ExecutorStateEvent event = new ExecutorStateEvent(executor, leaseCoordinator); event.accept(customHandler); assertTrue(wasCustomHandlerInvoked); }
Source:
<code>public ComponentRef<BackupSender> getBackupSender() { <START> return basicComponentRegistry.getComponent(BackupSender.class); <END> }</code><technical_language>introduced in Beta4 removed</technical_language>

Target:
public ComponentRef<BackupSender> getBackupSender() { return backupSender; }
Source:
<code>public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); <START> kind = ( "desc".equalsIgnoreCase( order ) ) ? Order.DESC : Order.ASC; <END> }</code><technical_language>picking, need extra brackets. keep: kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC;</technical_language>

Target:
public AssociationOrderBy(String expression, String order) { columnName = expression.substring( 1, expression.length() - 1 ); kind = "desc".equalsIgnoreCase( order ) ? Order.DESC : Order.ASC; }
Source:
<code>public boolean update(String path, DataUpdater<T> updater, int options) { T newRecord = null; boolean exceptionDuringUpdater = false; try { newRecord = updater.update(pathToRecords.get(path)); } catch (Exception e) { exceptionDuringUpdater = true; } if (exceptionDuringUpdater) { return false; } else { <START> System.out.println("Updating to store path: " + path + ", record: " + newRecord.toString()); <END> return setAndNotify(path, newRecord); } }</code><technical_language>is a system.out here</technical_language>

Target:
public boolean update(String path, DataUpdater<T> updater, int options) { T newRecord = null; boolean exceptionDuringUpdater = false; try { newRecord = updater.update(pathToRecords.get(path)); } catch (Exception e) { exceptionDuringUpdater = true; } if (exceptionDuringUpdater) { return false; } else { return setAndNotify(path, newRecord); } }
Source:
<code>private Signature createSignature(String encodedHeader, String encodedClaims) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, RealmUnavailableException { Signature signature = Signature.getInstance(resolveAlgorithm(encodedHeader)); Iterator<PemEntry<?>> pemEntryIterator = Pem.parsePemContent(CodePointIterator.ofUtf8Bytes(this.publicKey)); <START> PublicKey publicKey = (PublicKey) pemEntryIterator.next().getEntry(); <END> signature.initVerify(publicKey); signature.update((encodedHeader + "." + encodedClaims).getBytes()); return signature; }</code><technical_language>This be: PublicKey publicKey = pemEntryIterator.next().tryCast(PublicKey.class); if (publicKey == null) throw (some invalid key message);</technical_language>

Target:
private Signature createSignature(String encodedHeader, String encodedClaims) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, RealmUnavailableException { Signature signature = Signature.getInstance(resolveAlgorithm(encodedHeader)); signature.initVerify(this.publicKey); signature.update((encodedHeader + "." + encodedClaims).getBytes()); return signature; }
Source:
<code>private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { <START> return targetTierPrice.multiply(new BigDecimal(targetQuantity)); <END> }</code><technical_language>Nit: BigDecimal.valueOf()</technical_language>

Target:
private static BigDecimal computeAmount(final BigDecimal targetTierPrice, final Integer targetQuantity) { return targetTierPrice.multiply(BigDecimal.valueOf(targetQuantity)); }
Source:
<code>private boolean suggestionEqualsUserEntry(List<String> candidates, String chunk, int suggestionOffset) { if (chunk == null) { return false; } if (suggestionOffset > 0) { <START> return candidates.size() == 1 && chunk.substring(suggestionOffset).equals(candidates.get(0)); <END> } else { return candidates.size() == 1 && chunk.equals(candidates.get(0)); } }</code><technical_language>@spyrkob, excellent! move 2 candidates.size() == 1 a single checkline 496. if(chunk == null || candidates.size() == 1)</technical_language>

Target:
private boolean suggestionEqualsUserEntry(List<String> candidates, String chunk, int suggestionOffset) { if (chunk == null || candidates.size() != 1) { return false; } if (suggestionOffset > 0) { return chunk.substring(suggestionOffset).equals(candidates.get(0)); } else { return chunk.equals(candidates.get(0)); } }
Source:
<code><START> public IMetaStoreClient getMSC() { <END> connectionStats.incrementMetastoreCalls(); return msClient; }</code><technical_language>is this required public? exposing metastore client streaming connection API risky clients mess it</technical_language>

Target:
IMetaStoreClient getMSC() { connectionStats.incrementMetastoreCalls(); return msClient; }
Source:
<code>public void testCanvasCommandUndoWithRows() { relation.getRow().add(new List()); relation.getRow().get(0).getExpression().add(new LiteralExpression()); <START> ((LiteralExpression) relation.getRow().get(0).getExpression().get(0)).setText("value"); <END> uiModel.appendRow(new DMNGridRow()); uiModelMapper.fromDMNModel(0, 1); makeCommand(); final Command<AbstractCanvasHandler, CanvasViolation> cc = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.execute(handler)); reset(command, canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.undo(handler)); assertEquals(2, uiModel.getColumnCount()); assertEquals(uiRowNumberColumn, uiModel.getColumns().get(0)); assertEquals(uiModelColumn, uiModel.getColumns().get(1)); assertEquals(1, uiModel.getRowCount()); assertEquals(1, uiModel.getRows().get(0).getCells().size()); assertEquals("value", uiModel.getCell(0, 1).getValue().getValue()); verify(command).updateParentInformation(); verify(canvasOperation).execute(); }</code><technical_language>This line is hard readable, I if rewrote lines above, get nicer code: java final LiteralExpression literalExpression = new LiteralExpression(); literalExpression.setText("value"); relation.getRow().get(0).getExpression().add(literalExpression);</technical_language>

Target:
public void testCanvasCommandUndoWithRows() { relation.getRow().add(new List()); final LiteralExpression literalExpression = new LiteralExpression(); literalExpression.setText(VALUE); relation.getRow().get(0).getExpression().add(literalExpression); uiModel.appendRow(new DMNGridRow()); uiModelMapper.fromDMNModel(0, 1); makeCommand(); final Command<AbstractCanvasHandler, CanvasViolation> cc = command.newCanvasCommand(handler); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.execute(handler)); reset(command, canvasOperation); assertEquals(CanvasCommandResultBuilder.SUCCESS, cc.undo(handler)); assertEquals(2, uiModel.getColumnCount()); assertEquals(uiRowNumberColumn, uiModel.getColumns().get(0)); assertEquals(uiModelColumn, uiModel.getColumns().get(1)); assertEquals(1, uiModel.getRowCount()); assertEquals(1, uiModel.getRows().get(0).getCells().size()); assertEquals(VALUE, uiModel.getCell(0, 1).getValue().getValue()); verify(command).updateParentInformation(); verify(canvasOperation).execute(); }
Source:
<code>public JsonNode getJson() { if (json == null || json.toString().isEmpty()) { <START> ObjectNode root = JsonNodeFactory.instance.objectNode(); <END> ArrayNode resps = JsonNodeFactory.instance.arrayNode(); for (LightblueResponse resp : responses) { ObjectNode seqNode = JsonNodeFactory.instance.objectNode(); seqNode.set("seq", JsonNodeFactory.instance.numberNode(responses.indexOf(resp))); seqNode.set("response", resp.getJson()); resps.add(seqNode); } root.set("responsess", resps); json = root; } return json; }</code><technical_language>json.toString().isEmpty expensive. null check is ok</technical_language>

Target:
public JsonNode getJson() { if (json == null) { ObjectNode root = JsonNodeFactory.instance.objectNode(); ArrayNode resps = JsonNodeFactory.instance.arrayNode(); for (Entry<Integer, LightblueResponse> resp : responses.entrySet()) { ObjectNode seqNode = JsonNodeFactory.instance.objectNode(); seqNode.set("seq", JsonNodeFactory.instance.numberNode(resp.getKey())); seqNode.set("response", resp.getValue().getJson()); resps.add(seqNode); } root.set("responsess", resps); json = root; } return json; }
Source:
<code>private void submitMergePlan(final MergeNormalizationPlan plan) { final int totalSizeMb; try { final long totalSizeMbLong = plan.getNormalizationTargets() .stream() .mapToLong(NormalizationTarget::getRegionSizeMb) <START> .reduce(0, Math::addExact); <END> totalSizeMb = Math.toIntExact(totalSizeMbLong); } catch (ArithmeticException e) { LOG.debug("Sum of merge request size overflows rate limiter data type. {}", plan); planSkipped(plan.getType()); return; } final RegionInfo[] infos = plan.getNormalizationTargets() .stream() .map(NormalizationTarget::getRegionInfo) .toArray(RegionInfo[]::new); final long rateLimitedSecs = Math.round(rateLimiter.acquire(Math.max(1, totalSizeMb))); LOG.debug("Rate limiting delayed this operation by {}", Duration.ofSeconds(rateLimitedSecs)); final long pid; try { pid = masterServices.mergeRegions( infos, false, HConstants.NO_NONCE, HConstants.NO_NONCE); } catch (IOException e) { LOG.debug("failed to submit plan {}.", plan, e); planSkipped(plan.getType()); return; } mergePlanCount++; LOG.debug("Submitted resulting in pid {}", plan, pid); }</code><technical_language>reduce(0, Math::addExact) is preferred sum() due long overflow. If for regions, get merge request again? (and again.... in subsequent normalizer runs?)</technical_language>

Target:
private void submitMergePlan(final MergeNormalizationPlan plan) { final int totalSizeMb; try { final long totalSizeMbLong = plan.getNormalizationTargets() .stream() .mapToLong(NormalizationTarget::getRegionSizeMb) .reduce(0, Math::addExact); totalSizeMb = Math.toIntExact(totalSizeMbLong); } catch (ArithmeticException e) { LOG.debug("Sum of merge request size overflows rate limiter data type. {}", plan); planSkipped(plan.getType()); return; } final RegionInfo[] infos = plan.getNormalizationTargets() .stream() .map(NormalizationTarget::getRegionInfo) .toArray(RegionInfo[]::new); final long pid; try { pid = masterServices.mergeRegions( infos, false, HConstants.NO_NONCE, HConstants.NO_NONCE); } catch (IOException e) { LOG.info("failed to submit plan {}.", plan, e); planSkipped(plan.getType()); return; } mergePlanCount++; LOG.info("Submitted resulting in pid {}", plan, pid); final long rateLimitedSecs = Math.round(rateLimiter.acquire(Math.max(1, totalSizeMb))); LOG.debug("Rate limiting delayed the worker by {}", Duration.ofSeconds(rateLimitedSecs)); }
Source:
<code>protected <T> CompletableFuture<T> invokeAsync(InvocationContext ctx, VisitableCommand cmd) { CompletableFuture<T> cf; boolean isImplicitTx = ctx.isInTxScope() && ((TxInvocationContext) ctx).isImplicitTransaction(); final Transaction implicitTransaction; try { cf = (CompletableFuture<T>) fmap.chain.invokeAsync(ctx, cmd); if (isImplicitTx) { <START> implicitTransaction = transactionManager.suspend(); <END> } else { implicitTransaction = null; } } catch (SystemException e) { throw new CacheException("Cannot suspend implicit transaction", e); } catch (Throwable t) { if (isImplicitTx) { try { if (transactionManager != null) transactionManager.rollback(); } catch (Throwable t2) { log.trace("Could not rollback", t2); t.addSuppressed(t2); } } throw t; } if (isImplicitTx) { return cf.handle((result, throwable) -> { if (throwable != null) { try { implicitTransaction.rollback(); } catch (SystemException e) { log.trace("Could not rollback", e); throwable.addSuppressed(e); } throw CompletableFutures.asCompletionException(throwable); } try { implicitTransaction.commit(); } catch (Exception e) { log.couldNotCompleteInjectedTransaction(e); throw CompletableFutures.asCompletionException(e); } return result; }); } else { return cf; } }</code><technical_language>here, suspend transaction invoking interceptors</technical_language>

Target:
protected <T> CompletableFuture<T> invokeAsync(InvocationContext ctx, VisitableCommand cmd) { CompletableFuture<T> cf; boolean isImplicitTx = ctx.isInTxScope() && ((TxInvocationContext) ctx).isImplicitTransaction(); final Transaction implicitTransaction; try { if (isImplicitTx) { implicitTransaction = transactionManager.suspend(); assert implicitTransaction != null; } else { implicitTransaction = null; } cf = (CompletableFuture<T>) fmap.chain.invokeAsync(ctx, cmd); } catch (SystemException e) { throw new CacheException("Cannot suspend implicit transaction", e); } catch (Throwable t) { if (isImplicitTx) { try { if (transactionManager != null) transactionManager.rollback(); } catch (Throwable t2) { log.trace("Could not rollback", t2); t.addSuppressed(t2); } } throw t; } if (isImplicitTx) { return cf.handle((result, throwable) -> { if (throwable != null) { try { implicitTransaction.rollback(); } catch (SystemException e) { log.trace("Could not rollback", e); throwable.addSuppressed(e); } throw CompletableFutures.asCompletionException(throwable); } try { implicitTransaction.commit(); } catch (Exception e) { log.couldNotCompleteInjectedTransaction(e); throw CompletableFutures.asCompletionException(e); } return result; }); } else { return cf; } }
Source:
<code>public Mono<Void> downloadToFile(String downloadFilePath, FileRange range) { AsynchronousFileChannel channel = channelSetup(downloadFilePath); return sliceFileRange(range) .flatMap(chunk -> downloadWithProperties(chunk, false) .map(dar -> dar.value().body()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil.bytebufStreamToFile(fbb, channel, chunk.start() - (range == null ? 0 : range.start())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(300)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException)) <START> .doOnTerminate(() -> <END> LOGGER.asInfo().log("Saved " + chunk.toString() + " on thread " + Thread.currentThread().getName()))) .then() .doOnTerminate(() -> channelCleanUp(channel)); }</code><technical_language>Is this log message for testing</technical_language>

Target:
public Mono<Void> downloadToFile(String downloadFilePath, FileRange range) { AsynchronousFileChannel channel = channelSetup(downloadFilePath); return sliceFileRange(range) .flatMap(chunk -> downloadWithProperties(chunk, false) .map(dar -> dar.value().body()) .subscribeOn(Schedulers.elastic()) .flatMap(fbb -> FluxUtil.bytebufStreamToFile(fbb, channel, chunk.start() - (range == null ? 0 : range.start())) .subscribeOn(Schedulers.elastic()) .timeout(Duration.ofSeconds(DOWNLOAD_UPLOAD_CHUNK_TIMEOUT)) .retry(3, throwable -> throwable instanceof IOException || throwable instanceof TimeoutException))) .then() .doOnTerminate(() -> channelCleanUp(channel)); }
Source:
<code>public ResponseEntity<?> getCursors(@PathVariable("subscriptionId") final String subscriptionId, final NativeWebRequest request, final Client client) { if (!featureToggleService.isFeatureEnabled(HIGH_LEVEL_API)) { return new ResponseEntity<>(NOT_IMPLEMENTED); } try { final List<SubscriptionCursor> cursors = cursorsService.getSubscriptionCursors(subscriptionId, client) .stream() <START> .map(cursor -> cursor.withToken(cursorTokenService.generateToken())) <END> .collect(Collectors.toList()); return status(OK).body(new ItemsWrapper<>(cursors)); } catch (final NakadiException e) { return create(e.asProblem(), request); } }</code><technical_language>Strange SubscriptionCursorWithoutToken method withToken. create SubscriptionCursor hear</technical_language>

Target:
public ResponseEntity<?> getCursors(@PathVariable("subscriptionId") final String subscriptionId, final NativeWebRequest request, final Client client) { featureToggleService.checkFeatureOn(HIGH_LEVEL_API); try { final List<SubscriptionCursor> cursors = cursorsService.getSubscriptionCursors(subscriptionId, client) .stream() .map(cursor -> cursor.withToken(cursorTokenService.generateToken())) .collect(Collectors.toList()); return status(OK).body(new ItemsWrapper<>(cursors)); } catch (final NakadiException e) { return create(e.asProblem(), request); } }
Source:
<code><START> public static Path getSomePemFile() { <END> Path pemFile; try { pemFile = Paths.get(Files.createTempFile("private-key_", ".pem").toUri()); File f = new File("test/resources/private-key.pem"); Files.copy(f.toPath(), pemFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { throw new RuntimeException(e); } return pemFile; }</code><technical_language>care of removing files tests end..</technical_language>

Target:
public static Path getSomePemFile() { Path pemFile; try { pemFile = Paths.get(Files.createTempFile("private-key_", ".pem").toUri()); File f = new File("test/resources/private-key.pem"); Files.copy(f.toPath(), pemFile, StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING); pemFile.toFile().deleteOnExit(); } catch (IOException e) { throw new RuntimeException(e); } return pemFile; }
Source:
<code>public void visitMethod(MethodTree method) { if (!method.is(Tree.Kind.CONSTRUCTOR) && returnsOptional(method)) { ModifiersTree modifiers = method.modifiers(); for (AnnotationTree annotation : modifiers.annotations()) { <START> Type type = annotation.annotationType().symbolType(); <END> if (type.is(NULLABLE)) { context.reportIssue(this, annotation, "Methods with an \"Optional\" return type should not be \"@Nullable\"."); } } method.accept(new ReturnNullVisitor()); } super.visitMethod(method); }</code><technical_language>discussed, this visit of annotations generalized catch parameters, field variables. cases raise issues: class A { @Nullable // Noncompliant Optional<String> myField; void foo(@Nullable Optional<String> s) { // Noncompliant - Optional null } }</technical_language>

Target:
public void visitMethod(MethodTree method) { if (!method.is(Tree.Kind.CONSTRUCTOR) && returnsOptional(method)) { checkNullableAnnotation(method.modifiers(), "Methods with an \"Optional\" return type should not be \"@Nullable\"."); method.accept(new ReturnNullVisitor()); } super.visitMethod(method); }
Source:
<code>private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { <START> if ( maxMemoryString.endsWith( "%" ) ) <END> { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); return calculateMaxMemoryFromPercent( percent ); } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }</code><technical_language>need trim user provided string figure out is of</technical_language>

Target:
private static Long parseMaxMemory( String maxMemoryString ) { if ( maxMemoryString != null ) { maxMemoryString = maxMemoryString.trim(); if ( maxMemoryString.endsWith( "%" ) ) { int percent = Integer.parseInt( maxMemoryString.substring( 0, maxMemoryString.length() - 1 ) ); return calculateMaxMemoryFromPercent( percent ); } return Settings.parseLongWithUnit( maxMemoryString ); } return null; }
Source:
<code>public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final ClassLoader initialContextClassLoader = Thread.currentThread().getContextClassLoader(); final Meter errors = errorMeter(method); final Context timerContext = timer(method).time(); try { Thread.currentThread().setContextClassLoader(serviceClass.getClassLoader()); final String serviceInterfaceName = serviceInterface.getSimpleName(); final String methodName = method.getName(); final Profiling<Object> prof = new Profiling<Object>(); <START> final String profilingId = DOT_JOINER.join(serviceInterfaceName, methodName); <END> return prof.executeWithProfiling(ProfilingFeatureType.PLUGIN, profilingId, new WithProfilingCallback() { @Override public Object execute() throws Throwable { return method.invoke(service, args); } }); } catch (final InvocationTargetException e) { errors.mark(); if (e.getCause() != null) { throw e.getCause(); } else { throw new RuntimeException(e); } } finally { timerContext.stop(); Thread.currentThread().setContextClassLoader(initialContextClassLoader); } }</code><technical_language>a cache (each join invocation creates a new char[] StringBuilder)</technical_language>

Target:
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable { final ClassLoader initialContextClassLoader = Thread.currentThread().getContextClassLoader(); final Context timerContext = timer(method).time(); try { Thread.currentThread().setContextClassLoader(serviceClass.getClassLoader()); final String methodName = method.getName(); final Profiling<Object> prof = new Profiling<Object>(); final String profilingId = serviceInterfaceName + "." + methodName; return prof.executeWithProfiling(ProfilingFeatureType.PLUGIN, profilingId, new WithProfilingCallback() { @Override public Object execute() throws Throwable { return method.invoke(service, args); } }); } catch (final InvocationTargetException e) { final Meter errors = errorMeter(method); errors.mark(); if (e.getCause() != null) { throw e.getCause(); } else { throw new RuntimeException(e); } } finally { timerContext.stop(); Thread.currentThread().setContextClassLoader(initialContextClassLoader); } }
Source:
<code><START> public void testSlaveAttributesFromLabel() throws Exception { <END> Mesos.SlaveRequest request = mockSlaveRequestWithSlaveLabelAttributes(Boolean.TRUE, false, null, "testLabelString:docker-container-name"); jenkinsScheduler.requestJenkinsSlave(request, null); ArrayList<Protos.Offer> offers = new ArrayList<Protos.Offer>(); Protos.Offer rejectedOffer = createOfferWithAttributes("rack", "jenkins-master"); offers.add(rejectedOffer); offers.add(createOfferWithAttributes("rack", "jenkins-slave")); List<MesosSlaveInfo> mesosSlaveInfos = mockSlaveInfos(); Mockito.when(mesosCloud.getSlaveInfos()).thenReturn(mesosSlaveInfos); MesosComputer computer = Mockito.mock(MesosComputer.class); Mockito.when(jenkins.getComputers()).thenReturn(new Computer[] { computer }); SchedulerDriver driver = Mockito.mock(SchedulerDriver.class); jenkinsScheduler.setDriver(driver); jenkinsScheduler.resourceOffers(driver, offers); Mockito.verify(driver, Mockito.atLeastOnce()).declineOffer(rejectedOffer.getId(), Protos.Filters.newBuilder().setRefuseSeconds(5).build()); Mockito.verify(driver, Mockito.atLeastOnce()).suppressOffers(); }</code><technical_language>Nice! I wanted ask for tests</technical_language>

Target:
public void testSlaveAttributesFromLabel() throws Exception { Mesos.SlaveRequest request = mockSlaveRequestWithSlaveLabelAttributes(Boolean.TRUE, false, null, "testLabelString:docker-container-name"); jenkinsScheduler.requestJenkinsSlave(request, null); ArrayList<Protos.Offer> offers = new ArrayList<Protos.Offer>(); Protos.Offer rejectedOffer = createOfferWithAttributes("rack", "jenkins-master"); offers.add(rejectedOffer); offers.add(createOfferWithAttributes("rack", "jenkins-slave")); List<MesosSlaveInfo> mesosSlaveInfos = mockSlaveInfos(); Mockito.when(mesosCloud.getSlaveInfos()).thenReturn(mesosSlaveInfos); MesosComputer computer = Mockito.mock(MesosComputer.class); Mockito.when(jenkins.getComputers()).thenReturn(new Computer[] { computer }); SchedulerDriver driver = Mockito.mock(SchedulerDriver.class); jenkinsScheduler.setDriver(driver); jenkinsScheduler.resourceOffers(driver, offers); Mockito.verify(driver, Mockito.atMost(1)).declineOffer(rejectedOffer.getId(), Protos.Filters.newBuilder().setRefuseSeconds(5).build()); Mockito.verify(driver, Mockito.atLeastOnce()).suppressOffers(); assertEquals(0, jenkinsScheduler.getUnmatchedLabels().size()); }
Source:
<code><START> public void nullToEmptyString() { <END> if (this.email == null) { this.email = ""; } if (this.name == null) { this.name = ""; } if (this.googleId == null) { this.googleId = ""; } if (this.team == null) { this.team = ""; } if (this.comments == null) { this.comments = ""; } if (this.section == null) { this.section = ""; } }</code><technical_language>@xpdavid is this right do</technical_language>

Target:
public void nullToEmptyString() { if (this.email == null) { this.email = ""; } if (this.name == null) { this.name = ""; } if (this.googleId == null) { this.googleId = ""; } if (this.comments == null) { this.comments = ""; } }
Source:
<code>public void replaceUnderscores() { String badText = "I think _ on balance _ that people should use dashes. ___________ Never use underscores to separate text."; String cleanText = TextCleaner.replaceUnderscores(badText); boolean isGood = !(cleanText.contains("_")); <START> logger.error(cleanText); <END> assertEquals(true, isGood); }</code><technical_language>this is a test reporting errors, please change logger.info()</technical_language>

Target:
public void replaceUnderscores() { String badText = "I think _ on balance _ that people should use dashes. ___________ Never use underscores to separate text."; String cleanText = TextCleaner.replaceUnderscores(badText); boolean isGood = !(cleanText.contains("_")); logger.info(cleanText); assertEquals(true, isGood); }
Source:
<code>public Action deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null || !jsonElement.isJsonObject()) return null; Map.Entry<String, JsonElement> firstEntry = jsonElement.getAsJsonObject().entrySet().iterator().next(); JsonElement actionValue = firstEntry.getValue(); String fieldName = null; if (this.actionClass.getEnclosingClass() != null && !Modifier.isStatic(this.actionClass.getModifiers())) { throw new JsonParseException("non static inner class is not allowed"); } else if (this.actionClass.getDeclaredFields().length == 1){ fieldName = this.actionClass.getDeclaredFields()[0].getName(); <START> } <END> JsonObject actionJson = new JsonObject(); if (fieldName == null) { throw new JsonParseException("can not find a user defined field"); } if (actionValue.isJsonPrimitive()) { JsonPrimitive primValue = actionValue.getAsJsonPrimitive(); if (primValue.isNumber()) { actionJson.addProperty(fieldName, primValue.getAsNumber()); }else if (primValue.isBoolean()) { actionJson.addProperty(fieldName, primValue.getAsBoolean()); }else if (primValue.isString()) { actionJson.addProperty(fieldName, primValue.getAsString()); } }else{ actionJson.add(fieldName, actionValue); } return new Gson().fromJson(actionJson, this.actionClass); }</code><technical_language>I prefer check actionClass in constructor if ActionAdapter#deserialize() is called twice, checking action process runs twice. is redundant. If prefer check this here, I follow decision:+1:</technical_language>

Target:
public Action deserialize(JsonElement jsonElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (jsonElement == null || !jsonElement.isJsonObject()) return null; Map.Entry<String, JsonElement> firstEntry = jsonElement.getAsJsonObject().entrySet().iterator().next(); JsonElement actionValue = firstEntry.getValue(); String fieldName = this.actionClass.getDeclaredFields()[0].getName(); JsonObject actionJson = new JsonObject(); if (actionValue.isJsonPrimitive()) { JsonPrimitive primValue = actionValue.getAsJsonPrimitive(); if (primValue.isNumber()) { actionJson.addProperty(fieldName, primValue.getAsNumber()); }else if (primValue.isBoolean()) { actionJson.addProperty(fieldName, primValue.getAsBoolean()); }else if (primValue.isString()) { actionJson.addProperty(fieldName, primValue.getAsString()); } }else{ actionJson.add(fieldName, actionValue); } return new Gson().fromJson(actionJson, this.actionClass); }
Source:
<code>public void testReadUUIDMissingLogicalTypeUnsafe() throws IOException { <START> System.clearProperty("avro.disable.unsafe"); <END> Assume.assumeTrue( ReflectionUtil.getFieldAccess() instanceof FieldAccessUnsafe); Schema uuidSchema = SchemaBuilder.record(RecordWithUUID.class.getName()) .fields().requiredString("uuid").endRecord(); LogicalTypes.uuid().addToSchema(uuidSchema.getField("uuid").schema()); UUID u1 = UUID.randomUUID(); RecordWithStringUUID r1 = new RecordWithStringUUID(); r1.uuid = u1.toString(); File test = write( ReflectData.get().getSchema(RecordWithStringUUID.class), r1); RecordWithUUID datum = (RecordWithUUID) read( ReflectData.get().createDatumReader(uuidSchema), test).get(0); Object uuid = datum.uuid; Assert.assertTrue("UUID should be a String (unsafe)", uuid instanceof String); }</code><technical_language>This property restored end of test</technical_language>

Target:
public void testReadUUIDMissingLogicalTypeUnsafe() throws IOException { String unsafeValue = System.getProperty("avro.disable.unsafe"); try { System.clearProperty("avro.disable.unsafe"); Assume.assumeTrue( ReflectionUtil.getFieldAccess() instanceof FieldAccessUnsafe); Schema uuidSchema = SchemaBuilder.record(RecordWithUUID.class.getName()) .fields().requiredString("uuid").endRecord(); LogicalTypes.uuid().addToSchema(uuidSchema.getField("uuid").schema()); UUID u1 = UUID.randomUUID(); RecordWithStringUUID r1 = new RecordWithStringUUID(); r1.uuid = u1.toString(); File test = write( ReflectData.get().getSchema(RecordWithStringUUID.class), r1); RecordWithUUID datum = (RecordWithUUID) read( ReflectData.get().createDatumReader(uuidSchema), test).get(0); Object uuid = datum.uuid; Assert.assertTrue("UUID should be a String (unsafe)", uuid instanceof String); } finally { if (unsafeValue != null) { System.setProperty("avro.disable.unsafe", unsafeValue); } } }