auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void clear() { <START> if (null != writer) { <END> writer.close(); metadata = null; writer = null; } reset(); }</code><technical_language>This is a bad reference ownership. I feel this class part of TableWriter avoid issues this</technical_language>

Target:
void clear() { if (nCompletedConcurrentTasks.get() < nEnqueuedConcurrentTasks) { LOG.error().$("new block should have been either committed or cancelled [table=").$(writer.getName()).$(']').$(); completePendingConcurrentTasks(true); } metadata = null; writer = null; partWriter = null; for (int i = 0; i < nextPartitionBlockWriterIndex; i++) { partitionBlockWriters.getQuick(i).clear(); } nextPartitionBlockWriterIndex = 0; partitionBlockWriterByTimestamp.clear(); }
Source:
<code>S3Exception(S3ErrorCode error, String message, Throwable cause, Map<String, String> elements) { super(requireNonNull(message), cause); this.error = requireNonNull(error); <START> this.message = message; <END> this.elements = ImmutableMap.copyOf(elements); }</code><technical_language>retrieve this super.getMessage</technical_language>

Target:
S3Exception(S3ErrorCode error, String message, Throwable cause, Map<String, String> elements) { super(requireNonNull(message), cause); this.error = requireNonNull(error); this.elements = ImmutableMap.copyOf(elements); }
Source:
<code>public final FunctionDesc getFunction(final String signature, FunctionType funcType, DataType... paramTypes) throws AmbiguousFunctionException, UndefinedFunctionException { final GetFunctionMetaRequest.Builder builder = GetFunctionMetaRequest.newBuilder(); builder.setSignature(signature); if (funcType != null) { builder.setFunctionType(funcType); } for (DataType type : paramTypes) { builder.addParameterTypes(type); } try { final BlockingInterface stub = getStub(); <START> final FunctionResponse response = stub.getFunctionMeta(null, builder.build()); <END> throwsIfThisError(response.getState(), UndefinedFunctionException.class); throwsIfThisError(response.getState(), AmbiguousFunctionException.class); ensureOk(response.getState()); return new FunctionDesc(response.getFunction()); } catch (ServiceException se) { throw new RuntimeException(se); } catch (ClassNotFoundException e) { throw new TajoInternalError(e); } }</code><technical_language>If functions of name, getFunctionMeta() throws a function nearest argument instead of throwing AmbiguousFunctionException</technical_language>

Target:
public final FunctionDesc getFunction(final String signature, FunctionType funcType, DataType... paramTypes) throws AmbiguousFunctionException, UndefinedFunctionException { final GetFunctionMetaRequest.Builder builder = GetFunctionMetaRequest.newBuilder(); builder.setSignature(signature); if (funcType != null) { builder.setFunctionType(funcType); } for (DataType type : paramTypes) { builder.addParameterTypes(type); } try { final BlockingInterface stub = getStub(); final FunctionResponse response = stub.getFunctionMeta(null, builder.build()); throwsIfThisError(response.getState(), UndefinedFunctionException.class); ensureOk(response.getState()); return new FunctionDesc(response.getFunction()); } catch (ServiceException se) { throw new RuntimeException(se); } catch (ClassNotFoundException e) { throw new TajoInternalError(e); } }
Source:
<code>public void absorb(SolGame game, float dmg, Vector2 pos, SolShip ship, DmgType dmgType) { if (!canAbsorb(dmgType) || dmg <= 0) { throw new AssertionError("illegal call to absorb"); } myIdleTime = 0f; if (dmgType == DmgType.BULLET) { dmg *= bulletDmgFactor; <START> } <END> if (dmgType == DmgType.ENERGY) { dmg *= energyDmgFactor; } if (dmgType == DmgType.EXPLOSION) { dmg *= explosionDmgFactor; } myLife -= myLife < dmg ? myLife : dmg; game.getPartMan().shieldSpark(game, pos, ship.getHull(), myConfig.tex, dmg / myConfig.maxLife); float volMul = SolMath.clamp(4 * dmg / myConfig.maxLife); game.getSoundManager().play(game, myConfig.absorbSound, null, ship, volMul); }</code><technical_language>convert if conditions if else ladder? if (dmgType == DmgType.BULLET) { ... } else if (...) {</technical_language>

Target:
public void absorb(SolGame game, float dmg, Vector2 pos, SolShip ship, DmgType dmgType) { if (!canAbsorb(dmgType) || dmg <= 0) { throw new AssertionError("illegal call to absorb"); } myIdleTime = 0f; if (dmgType == DmgType.BULLET) { dmg *= bulletDmgFactor; } else if (dmgType == DmgType.ENERGY) { dmg *= energyDmgFactor; } else if (dmgType == DmgType.EXPLOSION) { dmg *= explosionDmgFactor; } myLife -= myLife < dmg ? myLife : dmg; game.getPartMan().shieldSpark(game, pos, ship.getHull(), myConfig.tex, dmg / myConfig.maxLife); float volMul = SolMath.clamp(4 * dmg / myConfig.maxLife); game.getSoundManager().play(game, myConfig.absorbSound, null, ship, volMul); }
Source:
<code>public final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) { Contracts.assertNotNull( beanType, MESSAGES.beanTypeCannotBeNull() ); sanityCheckPropertyPath( propertyName ); sanityCheckGroups( groups ); <START> PathImpl pathFromString = PathImpl.createPathFromString( propertyName ); <END> ValidationContext<T> validationContext = getValidationContextBuilder().forValidateValue( beanType, pathFromString ); if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); return validateValueInContext( validationContext, value, pathFromString, validationOrder ); }</code><technical_language>name propertyPath too</technical_language>

Target:
public final <T> Set<ConstraintViolation<T>> validateValue(Class<T> beanType, String propertyName, Object value, Class<?>... groups) { Contracts.assertNotNull( beanType, MESSAGES.beanTypeCannotBeNull() ); sanityCheckPropertyPath( propertyName ); sanityCheckGroups( groups ); PathImpl propertyPath = PathImpl.createPathFromString( propertyName ); BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidateValue( beanType, propertyPath ); if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); return validateValueInContext( validationContext, value, propertyPath, validationOrder ); }
Source:
<code>public <T> T getValue(Attribute<T> key) { <START> return null; <END> }</code><technical_language>is this return null?</technical_language>

Target:
public <T> T getValue(Attribute<T> key) { return attributes.get(key); }
Source:
<code>public ConfigReposControllerV2(ApiAuthenticationHelper authHelper, ConfigRepoService service, EntityHashingService entityHashingService) { <START> super(ApiVersion.v2, EntityType.ConfigRepo.name(), "20.2.0", "20.5.0", ApiVersion.v3); <END> this.authHelper = authHelper; this.service = service; this.entityHashingService = entityHashingService; }</code><technical_language>WDYT annotating class deprecated passing deprecation arguments in a constructor</technical_language>

Target:
public ConfigReposControllerV2(ApiAuthenticationHelper authHelper, ConfigRepoService service, EntityHashingService entityHashingService) { super(ApiVersion.v2); this.authHelper = authHelper; this.service = service; this.entityHashingService = entityHashingService; }
Source:
<code>private void configureJob(Job job, String tableName, String inputQuery, String condition, boolean shouldSplit) throws Exception { try { upsertAndSnapshot(tableName, shouldSplit); result = new ArrayList<>(); job.setMapperClass(TableSnapshotMapper.class); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormatClass(NullOutputFormat.class); Assert.assertTrue(job.waitForCompletion(true)); Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(timestamp)); StringBuilder selectQuery = new StringBuilder("SELECT * FROM " + tableName); if (condition != null) { selectQuery.append(" WHERE " + condition); } if (inputQuery == null) inputQuery = selectQuery.toString(); ResultSet rs = DriverManager.getConnection(getUrl(), props).createStatement().executeQuery(inputQuery); for (List<Object> r : result) { if (rs.next() == false) { <START> System.out.println("Placeholder"); <END> } int i = 0; String field1 = rs.getString(i + 1); assertEquals("Got the incorrect value for field1", r.get(i++), field1); String field2 = rs.getString(i + 1); assertEquals("Got the incorrect value for field2", r.get(i++), field2); int field3 = rs.getInt(i + 1); assertEquals("Got the incorrect value for field3", r.get(i++), field3); } assertFalse("Should only have stored" + result.size() + "rows in the table for the timestamp!", rs.next()); } finally { deleteSnapshot(tableName); } }</code><technical_language>remove</technical_language>

Target:
private void configureJob(Job job, String tableName, String inputQuery, String condition, boolean shouldSplit) throws Exception { try { upsertAndSnapshot(tableName, shouldSplit); result = new ArrayList<>(); job.setMapperClass(TableSnapshotMapper.class); job.setMapOutputKeyClass(ImmutableBytesWritable.class); job.setMapOutputValueClass(NullWritable.class); job.setOutputFormatClass(NullOutputFormat.class); Assert.assertTrue(job.waitForCompletion(true)); Properties props = new Properties(); props.setProperty("CurrentSCN", Long.toString(timestamp)); StringBuilder selectQuery = new StringBuilder("SELECT * FROM " + tableName); if (condition != null) { selectQuery.append(" WHERE " + condition); } if (inputQuery == null) inputQuery = selectQuery.toString(); ResultSet rs = DriverManager.getConnection(getUrl(), props).createStatement().executeQuery(inputQuery); for (List<Object> r : result) { assertTrue("No data stored in the table!", rs.next()); int i = 0; String field1 = rs.getString(i + 1); assertEquals("Got the incorrect value for field1", r.get(i++), field1); String field2 = rs.getString(i + 1); assertEquals("Got the incorrect value for field2", r.get(i++), field2); int field3 = rs.getInt(i + 1); assertEquals("Got the incorrect value for field3", r.get(i++), field3); } assertFalse("Should only have stored" + result.size() + "rows in the table for the timestamp!", rs.next()); } finally { deleteSnapshot(tableName); } }
Source:
<code>private ISymbolProviderPreferencePage[] getProviderPages() { List<ISymbolProviderPreferencePage> pages = new ArrayList<>(); ITmfTrace trace = getTrace(); if (trace != null) { for (ITmfTrace subTrace : getTracesToBuild(trace)) { <START> Collection<ISymbolProvider> providers = fSymbolProviders.get(subTrace); <END> if (!providers.isEmpty()) { for (ISymbolProvider provider : providers) { org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider provider2 = (org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) provider; ISymbolProviderPreferencePage page = provider2.createPreferencePage(); if (page != null) { pages.add(page); } } } } } return pages.toArray(new ISymbolProviderPreferencePage[pages.size()]); }</code><technical_language>this familiar... remove</technical_language>

Target:
private ISymbolProviderPreferencePage[] getProviderPages() { List<ISymbolProviderPreferencePage> pages = new ArrayList<>(); ITmfTrace trace = getTrace(); if (trace != null) { for (ITmfTrace subTrace : getTracesToBuild(trace)) { for (ISymbolProvider provider : fSymbolProviders.get(subTrace)) { if (provider instanceof org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) { org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider provider2 = (org.eclipse.tracecompass.tmf.ui.symbols.ISymbolProvider) provider; ISymbolProviderPreferencePage page = provider2.createPreferencePage(); if (page != null) { pages.add(page); } } } } } return pages.toArray(new ISymbolProviderPreferencePage[pages.size()]); }
Source:
<code>public static List<TurboIssue> getMatchedIssues(List<TurboIssue> issues, String query){ List<String> queries = Arrays.asList(query.split("\\s")); return issues.stream() <START> .filter(i -> Utility.containsIgnoreCaseMultipleWords(i.getTitle() + " " + i.getId(), queries)) <END> .collect(Collectors.toList()); }</code><technical_language>replace this long function name overload instead? Kind of extending contains operation lists</technical_language>

Target:
public static List<TurboIssue> getMatchedIssues(List<TurboIssue> issues, String query){ List<String> queries = Arrays.asList(query.split("\\s")); return issues.stream() .filter(i -> Utility.containsIgnoreCase(i.getTitle() + " " + i.getId(), queries)) .collect(Collectors.toList()); }
Source:
<code>void handleContainerStop(String processorId, String containerId, String preferredHost, int exitStatus, Duration preferredHostRetryDelay, ContainerAllocator containerAllocator) { if (getControlActionMetadata(processorId).isPresent()) { LOG.info("Setting the container with processorId stopped to be true because of existing container placement action", processorId); Object activeContainerStopped = getControlActionMetadata(processorId).get().getActiveContainerStopped(); synchronized (activeContainerStopped) { <START> activeContainerStopped.notifyAll(); <END> } } else if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleContainerStop(processorId, containerId, preferredHost, exitStatus, containerAllocator, preferredHostRetryDelay); } else { containerAllocator.requestResourceWithDelay(processorId, preferredHost, preferredHostRetryDelay); } }</code><technical_language>+1 expose single synchronized methods for reads writes control-action-metadata. accesses control-action-metada methods; optionally add logging in methods</technical_language>

Target:
void handleContainerStop(String processorId, String containerId, String preferredHost, int exitStatus, Duration preferredHostRetryDelay, ContainerAllocator containerAllocator) { if (hasActiveContainerPlacementAction(processorId)) { ContainerPlacementMetadata metadata = getPlacementActionMetadata(processorId).get(); LOG.info("Setting the container state with Processor ID: to be stopped because of existing ContainerPlacement action: {}", processorId, metadata); metadata.setContainerStatus(ContainerPlacementMetadata.ContainerStatus.STOPPED); } else if (standbyContainerManager.isPresent()) { standbyContainerManager.get() .handleContainerStop(processorId, containerId, preferredHost, exitStatus, containerAllocator, preferredHostRetryDelay); } else { containerAllocator.requestResourceWithDelay(processorId, preferredHost, preferredHostRetryDelay); } }
Source:
<code>public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions) { <START> return this.uploadWithResponse(new BlobUploadOptions(data) <END> .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setTier(AccessTier.HOT).setRequestConditions(requestConditions)); }</code><technical_language>I this released</technical_language>

Target:
public Mono<Response<BlockBlobItem>> uploadWithResponse(Flux<ByteBuffer> data, ParallelTransferOptions parallelTransferOptions, BlobHttpHeaders headers, Map<String, String> metadata, AccessTier tier, BlobRequestConditions requestConditions) { return this.uploadWithResponse(new BlobParallelUploadOptions(data) .setParallelTransferOptions(parallelTransferOptions).setHeaders(headers).setMetadata(metadata) .setTier(AccessTier.HOT).setRequestConditions(requestConditions)); }
Source:
<code>public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); final Set<T> retVal = Sets.newHashSet(); final Set<String> extensionNames = Sets.newHashSet(); for (String coordinate : config.getCoordinates()) { <START> log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); <END> try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate, config.getDefaultVersion()); for (T module : ServiceLoader.load(clazz, loader)) { String moduleName = module.getClass().getName(); if (!extensionNames.contains(moduleName)) { log.info("Adding remote extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } catch (Exception e) { throw Throwables.propagate(e); } } if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { String moduleName = module.getClass().getName(); if (!extensionNames.contains(moduleName)) { log.info("Adding local extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } extensionsMap.put(clazz, retVal); return retVal; }</code><technical_language>getCanonicalName clean prevent weird anonymous local classes. means failgracefully if getCanonicalName returns null</technical_language>

Target:
public synchronized static <T> Collection<T> getFromExtensions(ExtensionsConfig config, Class<T> clazz) { final TeslaAether aether = getAetherClient(config); final Set<T> retVal = Sets.newHashSet(); final Set<String> extensionNames = Sets.newHashSet(); for (String coordinate : config.getCoordinates()) { log.info("Loading extension[%s] for class[%s]", coordinate, clazz.getName()); try { URLClassLoader loader = getClassLoaderForCoordinates(aether, coordinate, config.getDefaultVersion()); for (T module : ServiceLoader.load(clazz, loader)) { String moduleName = module.getClass().getCanonicalName(); if (moduleName == null) { log.warn( "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?", module.getClass().getName() ); } else if (!extensionNames.contains(moduleName)) { log.info("Adding remote extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } catch (Exception e) { throw Throwables.propagate(e); } } if (config.searchCurrentClassloader()) { for (T module : ServiceLoader.load(clazz, Initialization.class.getClassLoader())) { String moduleName = module.getClass().getCanonicalName(); if (moduleName == null) { log.warn( "Extension module [%s] was ignored because it doesn't have a canonical name, is it a local or anonymous class?", module.getClass().getName() ); } else if (!extensionNames.contains(moduleName)) { log.info("Adding local extension module[%s] for class[%s]", moduleName, clazz.getName()); extensionNames.add(moduleName); retVal.add(module); } } } extensionsMap.put(clazz, retVal); return retVal; }
Source:
<code>ArrayResult executeOperation() { int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length] [((ArrayInput) this.getReceivedData()).data.length]; for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) { for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) { resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j]; } } ArrayResult result = new ArrayResult(resultData); <START> return result; <END> }</code><technical_language>one-liner</technical_language>

Target:
ArrayResult executeOperation() { int[][] resultData = new int[((ArrayInput) this.getReceivedData()).data[0].length] [((ArrayInput) this.getReceivedData()).data.length]; for (int i = 0; i < ((ArrayInput) this.getReceivedData()).data.length; i++) { for (int j = 0; j < ((ArrayInput) this.getReceivedData()).data[0].length; j++) { resultData[j][i] = ((ArrayInput) this.getReceivedData()).data[i][j]; } } return new ArrayResult(resultData); }
Source:
<code><START> String getComponent(){ <END> return mComponent; }</code><technical_language>Space {</technical_language>

Target:
String getComponent() { return component; }
Source:
<code>private JdbcOptions getJdbcOptions(ReadableConfig readableConfig) { final String url = readableConfig.get(URL); final JdbcOptions.Builder builder = JdbcOptions.builder() .setDBUrl(url) .setTableName(readableConfig.get(TABLE_NAME)) <START> .setConnectionCheckTimeoutSeconds((int) readableConfig.get(MAX_RETRY_TIMEOUT).toMillis()) <END> .setDialect(JdbcDialects.get(url).get()); readableConfig.getOptional(DRIVER).ifPresent(builder::setDriverName); readableConfig.getOptional(USERNAME).ifPresent(builder::setUsername); readableConfig.getOptional(PASSWORD).ifPresent(builder::setPassword); return builder.build(); }</code><technical_language>This is wrong. toMillis() returns milliseconds parameter requires seconds. toSeconds() here</technical_language>

Target:
private JdbcOptions getJdbcOptions(ReadableConfig readableConfig) { final String url = readableConfig.get(URL); final JdbcOptions.Builder builder = JdbcOptions.builder() .setDBUrl(url) .setTableName(readableConfig.get(TABLE_NAME)) .setDialect(JdbcDialects.get(url).get()) .setParallelism(readableConfig.getOptional(FactoryUtil.SINK_PARALLELISM).orElse(null)) .setConnectionCheckTimeoutSeconds((int) readableConfig.get(MAX_RETRY_TIMEOUT).getSeconds()); readableConfig.getOptional(DRIVER).ifPresent(builder::setDriverName); readableConfig.getOptional(USERNAME).ifPresent(builder::setUsername); readableConfig.getOptional(PASSWORD).ifPresent(builder::setPassword); return builder.build(); }
Source:
<code><START> private String enforceNotNullNorEmpty(String str, String propertyName) { <END> checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; }</code><technical_language>![MAJOR](<LINK_1> 'Severity: MAJOR') "enforceNotNullNorEmpty" a "static" method. [![rule](<LINK_2>](<LINK_0></technical_language>

Target:
private static String enforceNotNullNorEmpty(String str, String propertyName) { checkNotNull(str, "%s can't be null", propertyName); checkArgument(!str.isEmpty(), "%s can't be empty", propertyName); return str; }
Source:
<code>public IgniteSemaphore semaphore(final String name, @Nullable AtomicConfiguration cfg, final int cnt, final boolean failoverSafe, final boolean create) throws IgniteCheckedException { return getAtomic(new AtomicAccessor<GridCacheSemaphoreEx>() { @Override public T2<GridCacheSemaphoreEx, AtomicDataStructureValue> get(GridCacheInternalKey key, AtomicDataStructureValue val, IgniteInternalCache cache) throws IgniteCheckedException { GridCacheSemaphoreEx sem = cast(dsMap.get(key), GridCacheSemaphoreEx.class); if (sem != null) { assert val != null; return new T2<>(sem, null); } if (val == null && !create) return null; AtomicDataStructureValue retVal = (val == null ? new GridCacheSemaphoreState(cnt, new HashMap<UUID, Integer>(), failoverSafe, ctx.discovery().gridStartTime()) : null); GridCacheSemaphoreEx sem0 = new GridCacheSemaphoreImpl(name, key, cache); if(val!=null){ <START> ctx.closure().callLocalSafe( <END> new Callable<Object>() { @Override public Object call() throws Exception { GridCacheSemaphoreState semState=(GridCacheSemaphoreState)val; for (UUID nodeId : semState.getWaiters().keySet()) { ClusterNode node = ctx.cluster().get().node(nodeId); if (node == null) { sem0.onNodeRemoved(nodeId); if (log.isDebugEnabled()) log.debug("Removed node found to be waiting which is no longer active: " + nodeId); } } return null; }}, false); } return new T2<>(sem0, retVal); } }, cfg, name, SEMAPHORE, create, GridCacheSemaphoreEx.class); }</code><technical_language>Actually, is need start a new closure here, this method get() is executed transaction started in getAtomic()</technical_language>

Target:
public IgniteSemaphore semaphore(final String name, @Nullable AtomicConfiguration cfg, final int cnt, final boolean failoverSafe, final boolean create) throws IgniteCheckedException { return getAtomic(new AtomicAccessor<GridCacheSemaphoreEx>() { @Override public T2<GridCacheSemaphoreEx, AtomicDataStructureValue> get(GridCacheInternalKey key, AtomicDataStructureValue val, IgniteInternalCache cache) throws IgniteCheckedException { GridCacheSemaphoreEx sem = cast(dsMap.get(key), GridCacheSemaphoreEx.class); if (sem != null) { assert val != null; return new T2<>(sem, null); } if (val == null && !create) return null; AtomicDataStructureValue retVal = (val == null ? new GridCacheSemaphoreState(cnt, new HashMap<UUID, Integer>(), failoverSafe, ctx.discovery().gridStartTime()) : null); GridCacheSemaphoreEx sem0 = new GridCacheSemaphoreImpl(name, key, cache); if (val != null && failoverSafe) { GridCacheSemaphoreState semState = (GridCacheSemaphoreState) val; boolean updated = false; Map<UUID,Integer> waiters = semState.getWaiters(); Integer permit = ((GridCacheSemaphoreState) val).getCount(); for (UUID nodeId : new HashSet<>(waiters.keySet())) { ClusterNode node = ctx.cluster().get().node(nodeId); if (node == null) { permit += waiters.get(nodeId); waiters.remove(nodeId); updated = true; } } if (updated) { semState.setWaiters(waiters); semState.setCount(permit); retVal = semState; } } return new T2<>(sem0, retVal); } }, cfg, name, SEMAPHORE, create, GridCacheSemaphoreEx.class); }
Source:
<code>private String getSubmissionFormMobileHtml(String questionNumberString, String responseNumberString, boolean sessionIsOpen, boolean isExistingResponse, FeedbackRubricResponseDetails frd) { StringBuilder mobileHtml = new StringBuilder(); String mobilePanelTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL; String mobilePanelFragmentTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL_FRAGMENT; for (int i = 0; i < numOfRubricSubQuestions; i++) { StringBuilder panelBody = new StringBuilder(); for (int j = 0; j < numOfRubricChoices; j++) { String panelBodyFragment = Templates.populateTemplate(mobilePanelFragmentTemplate, Slots.QUESTION_INDEX, questionNumberString, Slots.RESPONSE_INDEX, responseNumberString, Slots.COL, Integer.toString(j), Slots.ROW, Integer.toString(i), Slots.DISABLED, sessionIsOpen ? "" : "disabled", "${description}", Sanitizer.sanitizeForHtml(this.getDescription(i, j)), "${checked}", isExistingResponse && frd.getAnswer(i) == j ? "checked" : "", Slots.RUBRIC_CHOICE_VALUE, Sanitizer.sanitizeForHtml(rubricChoices.get(j)), "${Const.ParamsNames.FEEDBACK_QUESTION_RUBRICCHOICE}", Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_CHOICE); panelBody.append(panelBodyFragment); } String panel = Templates.populateTemplate(mobilePanelTemplate, "${panelBody}", panelBody.toString(), "${subQuestion}", StringHelper.integerToLowerCaseAlphabeticalIndex(i + 1) + ") " <START> + Sanitizer.sanitizeForHtml(rubricSubQuestions.get(i))); <END> mobileHtml.append(panel).append(Const.EOL); } return mobileHtml.toString(); }</code><technical_language>revert lines? changed</technical_language>

Target:
private String getSubmissionFormMobileHtml(String questionNumberString, String responseNumberString, boolean sessionIsOpen, boolean isExistingResponse, FeedbackRubricResponseDetails frd) { StringBuilder mobileHtml = new StringBuilder(); String mobilePanelTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL; String mobilePanelFragmentTemplate = FormTemplates.RUBRIC_SUBMISSION_FORM_MOBILE_PANEL_FRAGMENT; for (int i = 0; i < numOfRubricSubQuestions; i++) { StringBuilder panelBody = new StringBuilder(); for (int j = 0; j < numOfRubricChoices; j++) { String panelBodyFragment = Templates.populateTemplate(mobilePanelFragmentTemplate, Slots.QUESTION_INDEX, questionNumberString, Slots.RESPONSE_INDEX, responseNumberString, Slots.COL, Integer.toString(j), Slots.ROW, Integer.toString(i), Slots.DISABLED, sessionIsOpen ? "" : "disabled", Slots.DESCRIPTION, Sanitizer.sanitizeForHtml(this.getDescription(i, j)), Slots.CHECKED, isExistingResponse && frd.getAnswer(i) == j ? "checked" : "", Slots.RUBRIC_CHOICE_VALUE, Sanitizer.sanitizeForHtml(rubricChoices.get(j)), Slots.RUBRIC_PARAM_CHOICE, Const.ParamsNames.FEEDBACK_QUESTION_RUBRIC_CHOICE); panelBody.append(panelBodyFragment); } String panel = Templates.populateTemplate(mobilePanelTemplate, Slots.PANEL_BODY, panelBody.toString(), Slots.SUB_QUESTION, StringHelper.integerToLowerCaseAlphabeticalIndex(i + 1) + ") " + Sanitizer.sanitizeForHtml(rubricSubQuestions.get(i))); mobileHtml.append(panel).append(Const.EOL); } return mobileHtml.toString(); }
Source:
<code>public static String filterAndUpdate(String input, Map<? extends Serializable, ? extends Serializable> variables) { if (input == null || input.isEmpty()) { return input; } String output = input; Map<String, String> substitutes = buildSubstitutes(variables); boolean anyReplacement; int depthCount = 0; do { anyReplacement = false; depthCount++; for (Map.Entry<String, String> replacement : substitutes.entrySet()) { if (replacement.getValue() != null) { String newOutput = output.replace(replacement.getKey(), replacement.getValue()); anyReplacement = anyReplacement || !newOutput.equals(output); output = newOutput; } } <START> } while (anyReplacement && depthCount < 5); <END> return output; }</code><technical_language>5</technical_language>

Target:
public static String filterAndUpdate(String input, Map<? extends Serializable, ? extends Serializable> variables) { if (input == null || input.isEmpty()) { return input; } String output = input; Map<String, String> substitutes = buildSubstitutes(variables); output = replaceRecursively(output, substitutes); return output; }
Source:
<code>public KubernetesNamespace create(String workspaceId) throws InfrastructureException { final String namespaceName; try { namespaceName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( <START> format("Failed to determine the namespace to put the workspace %s to", workspaceId), e); <END> } KubernetesNamespace namespace = doCreateNamespace(workspaceId, namespaceName); namespace.prepare(); if (isCreatingNamespaces(workspaceId) && !isNullOrEmpty(serviceAccountName)) { KubernetesWorkspaceServiceAccount workspaceServiceAccount = doCreateServiceAccount(workspaceId, namespaceName); workspaceServiceAccount.prepare(); } return namespace; }</code><technical_language>error message propagated while be. sense add e.getMessage new error message</technical_language>

Target:
public KubernetesNamespace create(String workspaceId) throws InfrastructureException { final String namespaceName; try { namespaceName = evalNamespaceName(workspaceId, EnvironmentContext.getCurrent().getSubject()); } catch (NotFoundException | ServerException | ConflictException | ValidationException e) { throw new InfrastructureException( format( "Failed to determine the namespace to put the workspace %s to." + " The error message was: %s", workspaceId, e.getMessage()), e); } KubernetesNamespace namespace = doCreateNamespace(workspaceId, namespaceName); namespace.prepare(); if (isCreatingNamespace(workspaceId) && !isNullOrEmpty(serviceAccountName)) { KubernetesWorkspaceServiceAccount workspaceServiceAccount = doCreateServiceAccount(workspaceId, namespaceName); workspaceServiceAccount.prepare(); } return namespace; }
Source:
<code>public void addContactTestWithANullValue() throws XMLStreamException, IOException { Contact contact = getContact(1L, null, "John", "Doe", "5555551212", "Mr."); XMLOutputFactory factory = XMLOutputFactory.newInstance(); StringWriter stringOut = new StringWriter(); XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut); ContactXmlGenerator.addContact(contact, "contact", writer); writer.close(); <START> String expected = "<contact><contactId>1</contactId><firstName>John</firstName><lastName>Doe</lastName><phoneNumber>5555551212</phoneNumber><title>Mr.</title></contact>"; <END> assertEquals(expected, stringOut.toString()); stringOut.close(); }</code><technical_language>This longer expected XML. Note this means changes XSD</technical_language>

Target:
public void addContactTestWithANullValue() throws XMLStreamException, IOException { Contact contact = getContact(1L, null, "John", "Doe", "5555551212", "Mr."); XMLOutputFactory factory = XMLOutputFactory.newInstance(); StringWriter stringOut = new StringWriter(); XMLStreamWriter writer = factory.createXMLStreamWriter(stringOut); ContactXmlGenerator.addContact(contact, "contact", writer); writer.close(); String expected = "<contact><contactId>1</contactId><fullName>John</fullName><friendlyName>Doe</friendlyName><phoneNumber>5555551212</phoneNumber><title>Mr.</title></contact>"; assertEquals(expected, stringOut.toString()); stringOut.close(); }
Source:
<code>private void createAndStartCallPeriodicRunnable( StatsService statsService, CallContext callContext, Call call, AccountID accountID) { String conferenceIDPrefix = accountID.getAccountPropertyString( CS_ACC_PROP_CONFERENCE_PREFIX); int interval = accountID.getAccountPropertyInt( CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL); String conferenceName = callContext.getRoomName(); if (conferenceName.contains("@")) { <START> conferenceName = Util.extractCallIdFromResource(conferenceName); <END> } String subDomain = callContext.getSubDomain(); if (!StringUtils.isNullOrEmpty(subDomain) && conferenceIDPrefix != null) { if (!conferenceIDPrefix.endsWith("/")) { conferenceIDPrefix += "/"; } conferenceIDPrefix += subDomain; } CallPeriodicRunnable cpr = new CallPeriodicRunnable( call, interval, statsService, conferenceName, conferenceIDPrefix, DEFAULT_JIGASI_ID + "-" + originID, this.remoteEndpointID); cpr.start(); statisticsProcessors.put(call, cpr); statisticsExecutor.registerRecurringRunnable(cpr); }</code><technical_language>worth moving this logic a getConferenceName getter CallContext</technical_language>

Target:
private void createAndStartCallPeriodicRunnable( StatsService statsService, CallContext callContext, Call call, AccountID accountID) { String conferenceIDPrefix = accountID.getAccountPropertyString( CS_ACC_PROP_CONFERENCE_PREFIX); int interval = accountID.getAccountPropertyInt( CS_ACC_PROP_STATISTICS_INTERVAL, DEFAULT_STAT_INTERVAL); String subDomain = callContext.getSubDomain(); if (!StringUtils.isNullOrEmpty(subDomain) && conferenceIDPrefix != null) { if (!conferenceIDPrefix.endsWith("/")) { conferenceIDPrefix += "/"; } conferenceIDPrefix += subDomain; } CallPeriodicRunnable cpr = new CallPeriodicRunnable( call, interval, statsService, callContext.getConferenceName(), conferenceIDPrefix, DEFAULT_JIGASI_ID + "-" + originID, this.remoteEndpointID); cpr.start(); statisticsProcessors.put(call, cpr); statisticsExecutor.registerRecurringRunnable(cpr); }
Source:
<code><START> public Optional<Predicate<ItemStackSnapshot>> getIngredientPredicate(int x, int y) { <END> if (x < 0 || x >= recipeWidth || y < 0 || y >= recipeHeight) { return Optional.empty(); } int recipeItemIndex = x + y * recipeWidth; ItemStackSnapshot recipeSnapshot = ItemStackUtil.snapshotOf(recipeItems[recipeItemIndex]); return Optional.of(new MatchCraftingVanillaItemStack(recipeSnapshot)); }</code><technical_language>is this Optional? Sounds bad honest. If anything, predicate</technical_language>

Target:
public Predicate<ItemStackSnapshot> getIngredientPredicate(int x, int y) { if (x < 0 || x >= this.recipeWidth || y < 0 || y >= this.recipeHeight) { throw new IndexOutOfBoundsException("Invalid ingredient predicate location"); } int recipeItemIndex = x + y * this.recipeWidth; ItemStackSnapshot recipeSnapshot = ItemStackUtil.snapshotOf(this.recipeItems[recipeItemIndex]); return new MatchCraftingVanillaItemStack(recipeSnapshot); }
Source:
<code>public static void updateToTable(Connection connection, String tableName, Persistable persistable, int id) { String queryStart = "UPDATE " + tableName + " SET " + DatabaseHelper.DATA_COL + " = ? "; String queryEnd = " WHERE " + DatabaseHelper.ID_COL + " = ?;"; HashMap<String, Object> map = DatabaseHelper.getMetaFieldsAndValues(persistable); String[] fieldNames = map.keySet().toArray(new String[map.keySet().size()]); Object[] values = map.values().toArray(new Object[map.values().size()]); StringBuilder stringBuilder = new StringBuilder(queryStart); for(String fieldName: fieldNames){ <START> stringBuilder.append( ", " + fieldName + " = ?"); <END> } String query = stringBuilder.append(queryEnd).toString(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(query); byte[] blob = org.commcare.modern.database.TableBuilder.toBlob(persistable); preparedStatement.setBinaryStream(1, new ByteArrayInputStream(blob), blob.length); int i = 2; for(Object obj: values){ if (obj instanceof String) { preparedStatement.setString(i, (String)obj); } else if (obj instanceof Blob) { preparedStatement.setBlob(i, (Blob)obj); } else if (obj instanceof Integer) { preparedStatement.setInt(i, (Integer)obj); } else if (obj instanceof byte[]) { preparedStatement.setBinaryStream(i, new ByteArrayInputStream((byte[])obj), ((byte[])obj).length); } else if (obj == null) { preparedStatement.setNull(i, 0); } i++; } preparedStatement.setInt(i, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }</code><technical_language>Lint warning is suggesting .append( ", " + fieldName + " = ?"); changed .append( ", ").append(fieldName).append(" = ?");</technical_language>

Target:
public static void updateToTable(Connection connection, String tableName, Persistable persistable, int id) { String queryStart = "UPDATE " + tableName + " SET " + DatabaseHelper.DATA_COL + " = ? "; String queryEnd = " WHERE " + DatabaseHelper.ID_COL + " = ?;"; HashMap<String, Object> map = DatabaseHelper.getMetaFieldsAndValues(persistable); String[] fieldNames = map.keySet().toArray(new String[map.keySet().size()]); Object[] values = map.values().toArray(new Object[map.values().size()]); StringBuilder stringBuilder = new StringBuilder(queryStart); for(String fieldName: fieldNames){ stringBuilder.append(", ").append(fieldName).append(" = ?"); } String query = stringBuilder.append(queryEnd).toString(); PreparedStatement preparedStatement = null; try { preparedStatement = connection.prepareStatement(query); int lastArgIndex = setPreparedStatementArgs(preparedStatement, persistable, values); preparedStatement.setInt(lastArgIndex, id); preparedStatement.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if (preparedStatement != null) { try { preparedStatement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
Source:
<code>public static MonthView create(ViewGroup parent, LayoutInflater inflater, DateFormat weekdayNameFormat, Listener listener, Calendar today) { final MonthView view = (MonthView) inflater.inflate(R.layout.month, parent, false); final int originalDayOfWeek = today.get(Calendar.DAY_OF_WEEK); int firstDayOfWeek = today.getFirstDayOfWeek(); final CalendarRowView headerRow = (CalendarRowView) view.grid.getChildAt(0); <START> for (int c = Calendar.SUNDAY; c <= Calendar.SATURDAY; c++) { <END> today.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + c - 1); final TextView textView = (TextView) headerRow.getChildAt(c - 1); textView.setText(weekdayNameFormat.format(today.getTime())); } today.set(Calendar.DAY_OF_WEEK, originalDayOfWeek); view.listener = listener; return view; }</code><technical_language>This loop changed [0..7) offset day of week. more clear</technical_language>

Target:
public static MonthView create(ViewGroup parent, LayoutInflater inflater, DateFormat weekdayNameFormat, Listener listener, Calendar today) { final MonthView view = (MonthView) inflater.inflate(R.layout.month, parent, false); final int originalDayOfWeek = today.get(Calendar.DAY_OF_WEEK); int firstDayOfWeek = today.getFirstDayOfWeek(); final CalendarRowView headerRow = (CalendarRowView) view.grid.getChildAt(0); for (int offset = 0; offset < 7; offset++) { today.set(Calendar.DAY_OF_WEEK, firstDayOfWeek + offset); final TextView textView = (TextView) headerRow.getChildAt(offset); textView.setText(weekdayNameFormat.format(today.getTime())); } today.set(Calendar.DAY_OF_WEEK, originalDayOfWeek); view.listener = listener; return view; }
Source:
<code>public Optional<SmeltingRecipe> findMatchingRecipe(ItemStackSnapshot ingredient) { checkNotNull(ingredient, "ingredient"); for (SmeltingRecipe customRecipe : customRecipes) { if (customRecipe.isValid(ingredient)) { return Optional.of(customRecipe); } } ItemStack nativeIngredient = ItemStackUtil.fromSnapshotToNative(ingredient); for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) <START> { <END> ItemStack nativeIngredientPrecise = entry.getKey(); if (compareItemStacks(nativeIngredient, nativeIngredientPrecise)) { ItemStack nativeExemplaryResult = entry.getValue(); ItemStackSnapshot result = ItemStackUtil.snapshotOf(nativeExemplaryResult); ItemStackSnapshot ingredientPrecise = ItemStackUtil.snapshotOf(nativeIngredientPrecise); Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(ingredientPrecise); double experience = this.experienceList.get(nativeExemplaryResult); SmeltingRecipe recipe = new SpongeSmeltingRecipe(result, ingredientPrecise, ingredientPredicate, experience); return Optional.of(recipe); } } return Optional.empty(); }</code><technical_language>Wrong formatting</technical_language>

Target:
public Optional<SmeltingRecipe> findMatchingRecipe(ItemStackSnapshot ingredient) { checkNotNull(ingredient, "ingredient"); for (SmeltingRecipe customRecipe : this.customRecipes) { if (customRecipe.isValid(ingredient)) { return Optional.of(customRecipe); } } ItemStack nativeIngredient = ItemStackUtil.fromSnapshotToNative(ingredient); for (Map.Entry<ItemStack, ItemStack> entry : this.smeltingList.entrySet()) { ItemStack nativeIngredientPrecise = entry.getKey(); if (compareItemStacks(nativeIngredient, nativeIngredientPrecise)) { ItemStack nativeExemplaryResult = entry.getValue(); ItemStackSnapshot result = ItemStackUtil.snapshotOf(nativeExemplaryResult); ItemStackSnapshot ingredientPrecise = ItemStackUtil.snapshotOf(nativeIngredientPrecise); Predicate<ItemStackSnapshot> ingredientPredicate = new MatchSmeltingVanillaItemStack(ingredientPrecise); double experience = this.experienceList.get(nativeExemplaryResult); SmeltingRecipe recipe = new SpongeSmeltingRecipe(result, ingredientPrecise, ingredientPredicate, experience); return Optional.of(recipe); } } return Optional.empty(); }
Source:
<code>private void assignActiveRecords(Vector<UserKeyRecord> migratedRecords) { Map<String, List<UserKeyRecord>> usernamesToRecords = new HashMap<>(); for (UserKeyRecord record : migratedRecords) { String username = record.getUsername(); List<UserKeyRecord> recordsForUsername = usernamesToRecords.get(username); if (recordsForUsername == null) { recordsForUsername = new ArrayList<>(); } recordsForUsername.add(record); <START> usernamesToRecords.put(username, recordsForUsername); <END> } for (String username : usernamesToRecords.keySet()) { List<UserKeyRecord> records = usernamesToRecords.get(username); UserKeyRecord activeRecord; if (records.size() == 1) { activeRecord = records.get(0); } else { Collections.sort(records, new Comparator<UserKeyRecord>() { @Override public int compare(UserKeyRecord lhs, UserKeyRecord rhs) { return lhs.getValidTo().compareTo(rhs.getValidTo()); } }); activeRecord = records.get(0); } activeRecord.setActive(); } }</code><technical_language>put call is needed of recordsForUsername == null, list updated regardless</technical_language>

Target:
private void assignActiveRecords(Vector<UserKeyRecord> migratedRecords) { Map<String, List<UserKeyRecord>> usernamesToRecords = new HashMap<>(); for (UserKeyRecord record : migratedRecords) { String username = record.getUsername(); List<UserKeyRecord> recordsForUsername = usernamesToRecords.get(username); if (recordsForUsername == null) { recordsForUsername = new ArrayList<>(); usernamesToRecords.put(username, recordsForUsername); } recordsForUsername.add(record); } for (String username : usernamesToRecords.keySet()) { List<UserKeyRecord> records = usernamesToRecords.get(username); UserKeyRecord activeRecord; if (records.size() == 1) { activeRecord = records.get(0); } else { Collections.sort(records, new Comparator<UserKeyRecord>() { @Override public int compare(UserKeyRecord lhs, UserKeyRecord rhs) { return lhs.getValidTo().compareTo(rhs.getValidTo()); } }); activeRecord = records.get(0); } activeRecord.setActive(); } }
Source:
<code>protected boolean isMigrationNeeded(Key<FeedbackResponseComment> entity) { FeedbackResponseComment comment = ofy().load().key(entity).now(); <START> return comment.getCommentGiverType() == null; <END> }</code><technical_language>Actually, I curious ![image](<LINK_0> is 17 reflection</technical_language>

Target:
protected boolean isMigrationNeeded(Key<FeedbackResponseComment> entity) { FeedbackResponseComment comment = ofy().load().key(entity).now(); try { Field commentGiverType = comment.getClass().getDeclaredField("commentGiverType"); commentGiverType.setAccessible(true); return commentGiverType.get(comment) == null; } catch (ReflectiveOperationException e) { return true; } }
Source:
<code>protected void setControlEnabled(SWTGridCell gridCell, Control control, boolean enabled) { if (isDisableRenderedAsEditable() && (getVElement().getLabelAlignment() == LabelAlignment.NONE && gridCell.getColumn() == 1 || hasLeftLabelAlignment() && gridCell.getColumn() == 2)) { Control controlToUnset = control; if (isControlUnsettable()) { controlToUnset = Composite.class .cast(Composite.class.cast(Composite.class.cast(control).getChildren()[0]).getChildren()[0]) .getChildren()[0]; } Text.class.cast(controlToUnset).setEditable(enabled); } else { <START> if (gridCell.getColumn() == 2) { <END> super.setControlEnabled(gridCell, Composite.class.cast(control).getChildren()[0], enabled); } else { super.setControlEnabled(gridCell, control, enabled); } } }</code><technical_language>If render label, column for text 1</technical_language>

Target:
protected void setControlEnabled(SWTGridCell gridCell, Control control, boolean enabled) { if (isDisableRenderedAsEditable() && (getVElement().getLabelAlignment() == LabelAlignment.NONE && gridCell.getColumn() == 1 || hasLeftLabelAlignment() && gridCell.getColumn() == 2)) { Control controlToUnset = control; if (isControlUnsettable()) { controlToUnset = Composite.class .cast(Composite.class.cast(Composite.class.cast(control).getChildren()[0]).getChildren()[0]) .getChildren()[0]; } Text.class.cast(controlToUnset).setEditable(enabled); } else { if (getVElement().getLabelAlignment() == LabelAlignment.NONE && gridCell.getColumn() == 1 || hasLeftLabelAlignment() && gridCell.getColumn() == 2) { super.setControlEnabled(gridCell, Composite.class.cast(control).getChildren()[0], enabled); } else { super.setControlEnabled(gridCell, control, enabled); } } }
Source:
<code>public void beginAnalysis() { <START> queryStateTimer.beginAnalysis(); <END> }</code><technical_language>consistent tense, this beginAnalyzing</technical_language>

Target:
public void beginAnalysis() { queryStateTimer.beginAnalyzing(); }
Source:
<code>public void testByteMapsToEnumOutOfOrdinalRange() { <START> mapper = getMapper(new String[] { "enumMapping.xml" }); <END> MyBeanPrimeByte src = new MyBeanPrimeByte(); src.setFirst((byte) 0); src.setSecond((byte) 3); MyBean dest = mapper.map(src, MyBean.class); }</code><technical_language>is need explicitly create array calling method. varargs is provide "enumMapping.xml" argument, code cleaner more readable</technical_language>

Target:
public void testByteMapsToEnumOutOfOrdinalRange() { testExpectedException.expect(MappingException.class); testExpectedException.expectMessage(startsWith("Cannot convert")); mapper = getMapper("mappings/enumMapping.xml"); MyBeanPrimeByte src = new MyBeanPrimeByte(); src.setFirst((byte) 0); src.setSecond((byte) 3); mapper.map(src, MyBean.class); }