auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public AuthenticationResult authenticateJDBCContext(Map<String, Object> context) { String user = (String) context.get("user"); String password = (String) context.get("password"); if (user == null || password == null) { return null; } if (checkCredentials(user, password.toCharArray())) { <START> return new AuthenticationResult(user, name, name, null); <END> } else { return null; } }</code><technical_language>change this to: return new AuthenticationResult(user, authorizerName, name, null); error introduced in this PR, "name" for authorizerName parameter is a bug</technical_language>

Target:
public AuthenticationResult authenticateJDBCContext(Map<String, Object> context) { String user = (String) context.get("user"); String password = (String) context.get("password"); if (user == null || password == null) { return null; } if (checkCredentials(user, password.toCharArray())) { return new AuthenticationResult(user, authorizerName, name, null); } else { return null; } }
Source:
<code>public void testCaseWithoutLineWrapping() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NoLineWrapCheck.class); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; <START> verify(checkConfig, getPath("InputnolinewrapGood.java"), expected); <END> }</code><technical_language>name of check is NoLineWrap. lowercase check's name</technical_language>

Target:
public void testCaseWithoutLineWrapping() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(NoLineWrapCheck.class); final String[] expected = CommonUtils.EMPTY_STRING_ARRAY; verify(checkConfig, getPath("InputNoLineWrapGood.java"), expected); }
Source:
<code>protected String[] getPropertyAliases(Loadable persister, int j) { String[] propertyColumnNames = persister.getPropertyColumnNames(j); <START> if (propertyColumnNames!=null && propertyColumnNames.length==1 && propertyColumnNames[0]==null) { <END> return new String[]{ persister.getPropertyNames()[j] }; } return propertyColumnNames; }</code><technical_language>great space chars consistently existing coding format if ( propertyColumnNames != null && propertyColumnNames.length == 1 && propertyColumnNames[0] == null )</technical_language>

Target:
protected String[] getPropertyAliases(Loadable persister, int j) { String[] propertyColumnNames = persister.getPropertyColumnNames(j); if ( Arrays.equals( propertyColumnNames, new String[] { null } ) ) { return new String[]{ persister.getPropertyNames()[j] }; } return propertyColumnNames; }
Source:
<code>public void close() throws IOException { <START> if (resultHTable != null) { <END> resultHTable.close(); } }</code><technical_language>Check for indexHtable close too</technical_language>

Target:
public void close() throws IOException { if (resultTable != null) { resultTable.close(); } if (indexTable != null) { indexTable.close(); } }
Source:
<code>public SimpleFeatureCollection parse(File file, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws ServiceException { OGRDataStoreFactory factory = new BridjOGRDataStoreFactory(); if (!factory.isAvailable()) { throw new ServiceException("GDAL library is not found for GPX import"); } Map<String, String> connectionParams = new HashMap<>(); connectionParams.put("DriverName", "GPX"); connectionParams.put("DatasourceName", file.getAbsolutePath()); DataStore store = null; try { store = factory.createDataStore(connectionParams); for (String typeName : store.getTypeNames()) { if ("track_points".equals(typeName)) { continue; } <START> sourceCRS = CRS.decode("EPSG:4326", true); <END> SimpleFeatureSource source = store.getFeatureSource(typeName); return FeatureCollectionParsers.read(source, sourceCRS, targetCRS); } throw new ServiceException("Could not find any usable typeNames from GPX file"); } catch (FactoryException e) { throw new ServiceException("Failed to decode EPSG:4326"); } catch (Exception e) { throw new ServiceException("GPX parsing failed", e); } finally { if (store != null) { store.dispose(); } } }</code><technical_language>Do this of loop connectionParams</technical_language>

Target:
public SimpleFeatureCollection parse(File file, CoordinateReferenceSystem sourceCRS, CoordinateReferenceSystem targetCRS) throws ServiceException { OGRDataStoreFactory factory = new BridjOGRDataStoreFactory(); if (!factory.isAvailable()) { throw new ServiceException("GDAL library is not found for GPX import"); } try { sourceCRS = CRS.decode("EPSG:4326", true); } catch (FactoryException e) { throw new ServiceException("Failed to decode EPSG:4326"); } Map<String, String> connectionParams = new HashMap<>(); connectionParams.put("DriverName", "GPX"); connectionParams.put("DatasourceName", file.getAbsolutePath()); DataStore store = null; try { store = factory.createDataStore(connectionParams); for (String typeName : store.getTypeNames()) { if ("track_points".equals(typeName)) { continue; } SimpleFeatureSource source = store.getFeatureSource(typeName); return FeatureCollectionParsers.read(source, sourceCRS, targetCRS); } throw new ServiceException("Could not find any usable typeNames from GPX file"); } catch (Exception e) { throw new ServiceException("GPX parsing failed", e); } finally { if (store != null) { store.dispose(); } } }
Source:
<code>public Diagnosis unvoidDiagnosis(Diagnosis diagnosis) throws APIException { <START> if (diagnosis.getVoided()) { <END> diagnosis.setVoided(false); diagnosis.setVoidedBy(null); diagnosis.setDateVoided(null); diagnosis.setVoidReason(null); } return save(diagnosis); }</code><technical_language>get a chance unvoidObs in ObsServiceImpl</technical_language>

Target:
public Diagnosis unvoidDiagnosis(Diagnosis diagnosis) throws APIException { return Context.getDiagnosisService().save(diagnosis); }
Source:
<code>public void append(JsonParser parser, BlockBuilder blockBuilder) throws IOException { Boolean result = castTokenAsBoolean(parser); <START> if (result == null) { <END> blockBuilder.appendNull(); } else { BOOLEAN.writeBoolean(blockBuilder, result); } }</code><technical_language>JsonUtil is supposed a set of Utils. I separate this class 3 parts (reader/writer/util) this pull request is merged</technical_language>

Target:
public void append(JsonParser parser, BlockBuilder blockBuilder) throws IOException { Boolean result = currentTokenAsBoolean(parser); if (result == null) { blockBuilder.appendNull(); } else { BOOLEAN.writeBoolean(blockBuilder, result); } }
Source:
<code>public List<FactMappingValidationError> validate(Simulation simulation, KieContainer kieContainer) { List<FactMappingValidationError> errors = new ArrayList<>(); String dmnFilePath = simulation.getSimulationDescriptor().getDmnFilePath(); DMNModel dmnModel = getDMNModel(kieContainer, dmnFilePath); for (FactMapping factMapping : simulation.getSimulationDescriptor().getFactMappings()) { if (isToSkip(factMapping)) { continue; } String nodeName = factMapping.getFactIdentifier().getName(); DMNType rootDMNType; try { rootDMNType = dmnModel.getDecisionByName(nodeName) != null ? dmnModel.getDecisionByName(nodeName).getResultType() : dmnModel.getInputByName(nodeName).getType(); } catch (NullPointerException e) { errors.add(createNodeChangedError(factMapping, "node not found")); continue; } List<String> steps = expressionElementToString(factMapping); Type rootType = getRootType((BaseDMNTypeImpl) rootDMNType); <START> if (!CONTEXT.equals(rootType) && steps.size() == 0 && rootDMNType.isComposite()) { <END> errors.add(createNodeChangedError(factMapping, rootDMNType.getName())); continue; } try { DMNType fieldType = navigateDMNType(rootDMNType, steps); if (!isDMNFactMappingValid(factMapping.getClassName(), factMapping, fieldType)) { errors.add(createFieldChangedError(factMapping, fieldType.getName())); } } catch (IllegalStateException e) { errors.add(createGenericError(factMapping, e.getMessage())); } } return errors; }</code><technical_language>steps.isEmpty() do in RULEScenarioValidation</technical_language>

Target:
public List<FactMappingValidationError> validate(Simulation simulation, KieContainer kieContainer) { List<FactMappingValidationError> errors = new ArrayList<>(); String dmnFilePath = simulation.getSimulationDescriptor().getDmnFilePath(); DMNModel dmnModel = getDMNModel(kieContainer, dmnFilePath); for (FactMapping factMapping : simulation.getSimulationDescriptor().getFactMappings()) { if (isToSkip(factMapping)) { continue; } String nodeName = factMapping.getFactIdentifier().getName(); DMNType rootDMNType; try { rootDMNType = dmnModel.getDecisionByName(nodeName) != null ? dmnModel.getDecisionByName(nodeName).getResultType() : dmnModel.getInputByName(nodeName).getType(); } catch (NullPointerException e) { errors.add(createNodeChangedError(factMapping, "node not found")); continue; } List<String> steps = expressionElementToString(factMapping); Type rootType = getRootType((BaseDMNTypeImpl) rootDMNType); if (!CONTEXT.equals(rootType) && steps.isEmpty() && rootDMNType.isComposite()) { errors.add(createNodeChangedError(factMapping, rootDMNType.getName())); continue; } try { DMNType fieldType = navigateDMNType(rootDMNType, steps); if (!isDMNFactMappingValid(factMapping.getClassName(), factMapping, fieldType)) { errors.add(createFieldChangedError(factMapping, fieldType.getName())); } } catch (IllegalStateException e) { errors.add(createGenericError(factMapping, e.getMessage())); } } return errors; }
Source:
<code>private void checkForPluginUpdate(File pluginsFolder, File pluginFile) { File updateFolder = new File( pluginsFolder, "update" ); if ( !updateFolder.isDirectory() ) { return; } File pluginUpdateFile = new File( updateFolder, pluginFile.getName() ); if ( pluginUpdateFile.isFile() ) { try ( FileInputStream fis = new FileInputStream( pluginUpdateFile ); FileOutputStream fos = new FileOutputStream( pluginFile ) ) { fos.getChannel().transferFrom( fis.getChannel(), 0, Long.MAX_VALUE ); } <START> catch ( IOException e ) <END> { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Failed to update plugin " + pluginFile, e ); } pluginUpdateFile.delete(); } }</code><technical_language>ex</technical_language>

Target:
private void checkForPluginUpdate(File pluginsFolder, File pluginFile) { File updateFolder = new File( pluginsFolder, "update" ); if ( !updateFolder.isDirectory() ) { return; } File pluginUpdateFile = new File( updateFolder, pluginFile.getName() ); if ( pluginUpdateFile.isFile() ) { try { Files.copy( pluginUpdateFile.toPath(), pluginFile.toPath() ); } catch ( IOException ex ) { ProxyServer.getInstance().getLogger().log( Level.WARNING, "Failed to update plugin " + pluginFile, ex ); } pluginUpdateFile.delete(); } }
Source:
<code><START> @Test public void replaceKeepsOriginals() { <END> Screen able = new Screen("Able"); Screen baker = new Screen("Baker"); Backstack backstack = Backstack.emptyBuilder() .addAll(Arrays.<Object>asList(able, baker)) .build(); Flow flow = new Flow(backstack, new FlowListener()); assertThat(backstack.size()).isEqualTo(2); Object charlie = new HasParent<Screen>() { @Override public Screen getParent() { return new Screen("Able"); } }; flow.replaceTo(charlie); assertThat(lastStack.size()).isEqualTo(2); assertThat(lastStack.current().getScreen()).isSameAs(charlie); flow.goBack(); assertThat(lastStack.size()).isEqualTo(1); assertThat(lastStack.current().getScreen()).isSameAs(able); }</code><technical_language>tests covering of lines 146, 151, 153 159</technical_language>

Target:
@Test public void replaceKeepsOriginals() { Screen able = new Able(); Screen baker = new Baker(); Screen charlie = new Charlie(); Screen delta = new Screen("Delta"); Backstack backstack = Backstack.emptyBuilder() .addAll(Arrays.<Object>asList(able, baker, charlie, delta)) .build(); Flow flow = new Flow(backstack, new FlowListener()); assertThat(backstack.size()).isEqualTo(4); Screen foxtrot = new Foxtrot(); flow.replaceTo(foxtrot); assertThat(lastStack.size()).isEqualTo(4); assertThat(lastStack.current().getScreen()).isSameAs(foxtrot); flow.goBack(); assertThat(lastStack.size()).isEqualTo(3); assertThat(lastStack.current().getScreen()).isEqualTo(new Echo()); flow.goBack(); assertThat(lastStack.size()).isEqualTo(2); assertThat(lastStack.current().getScreen()).isSameAs(baker); flow.goBack(); assertThat(lastStack.size()).isEqualTo(1); assertThat(lastStack.current().getScreen()).isSameAs(able); }
Source:
<code>public void storeWorkerMetrics(final String workerId, final WorkerMetrics metrics) { final DataInfo dataInfo = new DataInfoImpl(metrics.getNumDataBlocks()); final EvaluatorParameters evaluatorParameters = new WorkerEvaluatorParameters(workerId, dataInfo, metrics); workerEvalParams.add(evaluatorParameters); try { final URL obj = new URL(this.dolphinURL); final HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.setDoInput(true); con.connect(); final OutputStream os = con.getOutputStream(); final String param = "serverid=-1&workerid=" + workerId; System.out.println("request with " + param); os.write((param).getBytes()); os.flush(); os.close(); final BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream()) ); String inputLine; final StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch (Exception e) { <START> System.out.println(e); <END> } }</code><technical_language>Again, prefer logger System.out. Please leave a log in WARNING level. - narrow type of Exception IOException (i.e., catch (IOException e))</technical_language>

Target:
public void storeWorkerMetrics(final String workerId, final WorkerMetrics metrics) { final DataInfo dataInfo = new DataInfoImpl(metrics.getNumDataBlocks()); final EvaluatorParameters evaluatorParameters = new WorkerEvaluatorParameters(workerId, dataInfo, metrics); workerEvalParams.add(evaluatorParameters); if (this.dashboardEnabled) { sendMetrics(workerId, metrics.toString()); } }
Source:
<code>public void VisualEditorEditing_005_switchToSourceMode() { String articleName2 = PageContent.ARTICLE_NAME_PREFIX + base.getTimeStamp(); VisualEditorPageObject ve = base.openVEOnArticle(wikiURL, articleName2); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve = ve.typeInSourceEditor(text); VisualEditorSaveChangesDialog saveDialog = ve.clickPublishButton(); VisualEditorReviewChangesDialog reviewDialog = saveDialog.clickReviewYourChanges(); reviewDialog.verifyAddedDiffs(firstSourceEditText); ve = reviewDialog.closeDialog(); <START> ve.verifyVEToolBarPresent(); <END> ve.verifyEditorSurfacePresent(); ve = ve.typeInSourceEditor(text); saveDialog = ve.clickPublishButton(); reviewDialog = saveDialog.clickReviewYourChanges(); reviewDialog.verifyAddedDiffs(secondSourceEditText); saveDialog = reviewDialog.clickReturnToSaveFormButton(); ArticlePageObject article = saveDialog.savePage(); article.verifyVEPublishComplete(); }</code><technical_language>verify if content publish is ok</technical_language>

Target:
public void VisualEditorEditing_005_switchToSourceMode() { String articleName2 = PageContent.ARTICLE_NAME_PREFIX + base.getTimeStamp(); VisualEditorPageObject ve = base.openVEOnArticle(wikiURL, articleName2); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve = ve.typeInSourceEditor(text); VisualEditorSaveChangesDialog saveDialog = ve.clickPublishButton(); VisualEditorReviewChangesDialog reviewDialog = saveDialog.clickReviewYourChanges(); reviewDialog.verifyAddedDiffs(firstSourceEditText); ve = reviewDialog.closeDialog(); ve.verifyVEToolBarPresent(); ve.verifyEditorSurfacePresent(); ve = ve.typeInSourceEditor(text); saveDialog = ve.clickPublishButton(); reviewDialog = saveDialog.clickReviewYourChanges(); reviewDialog.verifyAddedDiffs(secondSourceEditText); saveDialog = reviewDialog.clickReturnToSaveFormButton(); ArticlePageObject article = saveDialog.savePage(); article.verifyVEPublishComplete(); article.verifyContent(text); }
Source:
<code>public void drop() throws IOException { closeTree(); <START> fileSystem.deleteFile( storeFile ); <END> }</code><technical_language>fileSystem.deleteFileOrThrow underneath</technical_language>

Target:
public void drop() throws IOException { closeTree(); fileSystem.deleteFileOrThrow( storeFile ); }
Source:
<code>protected String generateHelpMessage() { StringBuilder sb = new StringBuilder(); sb.append( "Fake News Categories (example: !fakenews canada):" ); sb.append( "\n" ); sb.append( " { canada }" ); sb.append( " { usa }" ); sb.append( " { belgium }" ); sb.append( " { france }" ); sb.append( " { russia }" ); sb.append( " { serbia }" ); sb.append( " { venezuela }" ); sb.append( " { newzealand }" ); <START> sb.append( " { india }" ); <END> return sb.toString(); }</code><technical_language>countries map (here loop keys)</technical_language>

Target:
protected String generateHelpMessage() { StringBuilder sb = new StringBuilder(); sb.append( "Fake News Categories (example: !fakenews canada):" ); sb.append( "\n" ); for ( String category : fakeNewsFeedsByCategory.keySet() ) { sb.append( " { " + category + " }" ); } return sb.toString(); }
Source:
<code>protected void validateAssertion(final SamlAssertionWrapper assertion) throws WSSecurityException { if (assertion.getSaml1() != null) { assertion.validateSignatureAgainstProfile(); } else if (assertion.getSaml2() != null) { final Issuer issuer = assertion.getSaml2().getIssuer(); validateIssuer(issuer); try { for (final Saml2ExchangeAuthFrameworkValidator validator : getSaml2SpecValidators()) { validator.validateAssertion(assertion); } } catch (final WSSecurityException e) { <START> LOG.error("Saml Validation error: " + e.getMessage(), e); <END> throw new WSSecurityException(ErrorCode.FAILED_CHECK, "invalidSAMLsecurity"); } } }</code><technical_language>Follow logging standard LOG.error("Saml Validation error: {}" , e.getMessage(), e);</technical_language>

Target:
protected void validateAssertion(final SamlAssertionWrapper assertion) throws WSSecurityException { if (assertion.getSaml1() != null) { assertion.validateSignatureAgainstProfile(); } else if (assertion.getSaml2() != null) { final Issuer issuer = assertion.getSaml2().getIssuer(); validateIssuer(issuer); try { for (final Saml2ExchangeAuthFrameworkValidator validator : getSaml2SpecValidators()) { validator.validateAssertion(assertion); } } catch (final WSSecurityException e) { LOG.error("Saml Validation error: {}", e.getLocalizedMessage(), e); throw new WSSecurityException(ErrorCode.FAILED_CHECK, "invalidSAMLsecurity"); } } }
Source:
<code>protected PsiFile createFile(String name, @NotNull String templateName, @NotNull PsiDirectory dir) { FileTemplate template = FileTemplateManager.getInstance(dir.getProject()).getInternalTemplate(templateName); Properties properties = new Properties(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir); <START> String packageName = packages.isEmpty() ? GoPsiImplUtil.makePackageNameValid(ContainerUtil.getLastItem(StringUtil.split(dir.getName(), "-"))) : ArrayUtil.toStringArray(packages)[0]; <END> if (name.endsWith(GoConstants.TEST_SUFFIX_WITH_EXTENSION) || name.endsWith(GoConstants.TEST_SUFFIX)) { packageName += GoConstants.TEST_SUFFIX; } properties.setProperty(PACKAGE, packageName); try { PsiElement element = FileTemplateUtil.createFromTemplate(template, name, properties, dir); if (element instanceof PsiFile) return (PsiFile)element; } catch (Exception e) { LOG.warn(e); return null; } return super.createFile(name, templateName, dir); }</code><technical_language>do need split directory name? makePackageNameValid do for you</technical_language>

Target:
protected PsiFile createFile(String name, @NotNull String templateName, @NotNull PsiDirectory dir) { FileTemplate template = FileTemplateManager.getInstance(dir.getProject()).getInternalTemplate(templateName); Properties properties = new Properties(); Collection<String> packages = GoUtil.getAllPackagesInDirectory(dir); String packageName = packages.isEmpty() ? GoPsiImplUtil.getLocalPackageName(dir.getName()) : ContainerUtil.getFirstItem(packages); if (name.endsWith(GoConstants.TEST_SUFFIX) || name.endsWith(GoConstants.TEST_SUFFIX_WITH_EXTENSION)) { packageName += GoConstants.TEST_SUFFIX; } properties.setProperty(PACKAGE, packageName); try { PsiElement element = FileTemplateUtil.createFromTemplate(template, name, properties, dir); if (element instanceof PsiFile) return (PsiFile)element; } catch (Exception e) { LOG.warn(e); return null; } return super.createFile(name, templateName, dir); }
Source:
<code>private boolean consumeOne(final byte[] body) { try { maybePrepareToCommitConsumerOffsets(); final FutureReporter.Context consumptionContext = reporter.reportConsumption(); final AsyncFuture<Void> future = schema.consume(body); threadLocalSequenceNumber++; final Long sequenceNumber = new Long(threadLocalSequenceNumber); if (enablePeriodicCommit) { outstandingConsumptionRequests.add(sequenceNumber); } future.onFinished(() -> { <START> if (enablePeriodicCommit) { <END> outstandingConsumptionRequests.remove(sequenceNumber); if (outstandingConsumptionRequests.size() == 0) { coordinator.commitConsumerOffsets(); } } }); future.onDone(consumptionContext); reporter.reportMessageSize(body.length); consumed.increment(); return false; } catch (final ConsumerSchemaValidationException e) { reporter.reportConsumerSchemaError(); return false; } catch (final Exception e) { errors.incrementAndGet(); log.error("{}: Failed to consume", name, e); reporter.reportMessageError(); return true; } }</code><technical_language>check if-statement of assigning future avoid overhead if disabled</technical_language>

Target:
private boolean consumeOne(final byte[] body) { try { maybePrepareToCommitConsumerOffsets(); final FutureReporter.Context consumptionContext = reporter.reportConsumption(); final AsyncFuture<Void> future = schema.consume(body); if (enablePeriodicCommit) { final Long sequenceNumber = ++threadLocalSequenceNumber; outstandingConsumptionRequests.put(sequenceNumber, true); future.onFinished(() -> { outstandingConsumptionRequests.remove(sequenceNumber); if (outstandingConsumptionRequests.size() == 0) { coordinator.commitConsumerOffsets(); } }); } future.onDone(consumptionContext); reporter.reportMessageSize(body.length); consumed.increment(); return false; } catch (final ConsumerSchemaValidationException e) { reporter.reportConsumerSchemaError(); return false; } catch (final Exception e) { errors.incrementAndGet(); log.error("{}: Failed to consume", name, e); reporter.reportMessageError(); return true; } }
Source:
<code>public InfluxdbEmitter(InfluxdbEmitterConfig influxdbEmitterConfig) { this.influxdbEmitterConfig = influxdbEmitterConfig; this.influxdbClient = HttpClientBuilder.create().build(); this.eventsQueue = new LinkedBlockingQueue<>(influxdbEmitterConfig.getMaxQueueSize()); this.dimensionWhiteList = ImmutableSet.of( "dataSource", "type", "numMetrics", "numDimensions", "threshold", "dimension", "taskType", "taskStatus", "tier" ); <START> log.info("constructing influxdb emitter"); <END> }</code><technical_language>suggestion log.info("constructed influxdb emitter");</technical_language>

Target:
public InfluxdbEmitter(InfluxdbEmitterConfig influxdbEmitterConfig) { this.influxdbEmitterConfig = influxdbEmitterConfig; this.influxdbClient = HttpClientBuilder.create().build(); this.eventsQueue = new LinkedBlockingQueue<>(influxdbEmitterConfig.getMaxQueueSize()); this.dimensionWhiteList = influxdbEmitterConfig.getDimensionWhitelist(); log.info("constructed influxdb emitter"); }
Source:
<code>public void build_createANewRadiologyOrderSearchCriteriaInstanceWithFromEffectiveStartDateIfFromEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date fromEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withFromEffectiveStartDate(fromEffectiveStartDate) .build(); <START> assertTrue(radiologyOrderSearchCriteria.getFromEffectiveStartDate() <END> .equals(fromEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }</code><technical_language>@bgeVam assertThat(,is())</technical_language>

Target:
public void build_createANewRadiologyOrderSearchCriteriaInstanceWithFromEffectiveStartDateIfFromEffectiveStartDateIsSet() throws Exception { DateFormat format = new SimpleDateFormat("yyyy-MM-dd"); Date fromEffectiveStartDate = format.parse("2016-05-01"); radiologyOrderSearchCriteria = new RadiologyOrderSearchCriteria.Builder().withFromEffectiveStartDate(fromEffectiveStartDate) .build(); assertThat(radiologyOrderSearchCriteria.getFromEffectiveStartDate(), is(fromEffectiveStartDate)); assertNull(radiologyOrderSearchCriteria.getPatient()); assertFalse(radiologyOrderSearchCriteria.getIncludeVoided()); assertNull(radiologyOrderSearchCriteria.getUrgency()); assertNull(radiologyOrderSearchCriteria.getToEffectiveStartDate()); }
Source:
<code>public static void setupBeforeClass() { <START> Map<String, String> config = new HashMap<>(); <END> rangerAuthorizer = new RangerAuthorizer(null, null, false, null); }</code><technical_language>I remove this line</technical_language>

Target:
public static void setupBeforeClass() { rangerAuthorizer = new RangerAuthorizer(null, null, false, new Configuration()); }
Source:
<code>private void clientInvalidated(ClientDescriptor clientDescriptor, int invalidationId) { InvalidationHolder invalidationHolder = clientsWaitingForInvalidation.get(invalidationId); if (stores.get(invalidationHolder.cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder.clientsHavingToInvalidate.remove(clientDescriptor); <START> if (invalidationHolder.clientsHavingToInvalidate.isEmpty()) { <END> clientsWaitingForInvalidation.remove(invalidationId); try { clientCommunicator.sendNoResponse(invalidationHolder.clientDescriptorWaitingForInvalidation, EhcacheEntityResponse.invalidationDone(invalidationHolder.cacheId, invalidationHolder.key)); LOGGER.debug("SERVER: notifying originating client that all other clients invalidated key in cache from (ID {})", invalidationHolder.key, invalidationHolder.cacheId, clientDescriptor, invalidationId); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } } }</code><technical_language>Is this racy in case invalidations happen close other? is protected a higher level</technical_language>

Target:
private void clientInvalidated(ClientDescriptor clientDescriptor, int invalidationId) { InvalidationHolder invalidationHolder = clientsWaitingForInvalidation.get(invalidationId); if (stores.get(invalidationHolder.cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder.clientsHavingToInvalidate.remove(clientDescriptor); if (invalidationHolder.clientsHavingToInvalidate.isEmpty()) { if (clientsWaitingForInvalidation.remove(invalidationId) != null) { try { clientCommunicator.sendNoResponse(invalidationHolder.clientDescriptorWaitingForInvalidation, EhcacheEntityResponse.invalidationDone(invalidationHolder.cacheId, invalidationHolder.key)); LOGGER.debug("SERVER: notifying originating client that all other clients invalidated key in cache from (ID {})", invalidationHolder.key, invalidationHolder.cacheId, clientDescriptor, invalidationId); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } } } }
Source:
<code>private HostScore calculateHostScore(HostState host, double clusterMaxMeanActive, double clusterMaxDiskUsed) { double score = 0; double meanActive = host.getMeanActiveTasks(); double usedDiskPercent = getUsedDiskPercent(host); <START> long diskFreeBytes = host.getMax().getDisk() - host.getUsed().getDisk(); <END> if (clusterMaxMeanActive <= 0) { meanActive = 1; clusterMaxMeanActive = 1; } if (clusterMaxDiskUsed <= 0) { usedDiskPercent = 1; clusterMaxDiskUsed = 1; } int activeTaskWeight = config.getActiveTaskWeight(); int diskUsedWeight = config.getDiskUsedWeight(); score += activeTaskWeight * Math.pow(meanActive / clusterMaxMeanActive, 2.5); score += diskUsedWeight * Math.pow(usedDiskPercent / clusterMaxDiskUsed, 2.5); score = Math.max(score, (activeTaskWeight + diskUsedWeight) * usedDiskPercent); return new HostScore(meanActive, usedDiskPercent, diskFreeBytes, score); }</code><technical_language>Add a new helper method HostState.getDiskFreeBytes() do this</technical_language>

Target:
private HostScore calculateHostScore(HostState host, double clusterMaxMeanActive, double clusterMaxDiskUsed) { double score = 0; double meanActive = host.getMeanActiveTasks(); double usedDiskPercent = getUsedDiskPercent(host); if (clusterMaxMeanActive <= 0) { meanActive = 1; clusterMaxMeanActive = 1; } if (clusterMaxDiskUsed <= 0) { usedDiskPercent = 1; clusterMaxDiskUsed = 1; } int activeTaskWeight = config.getActiveTaskWeight(); int diskUsedWeight = config.getDiskUsedWeight(); score += activeTaskWeight * Math.pow(meanActive / clusterMaxMeanActive, 2.5); score += diskUsedWeight * Math.pow(usedDiskPercent / clusterMaxDiskUsed, 2.5); score = Math.max(score, (activeTaskWeight + diskUsedWeight) * usedDiskPercent); return new HostScore(meanActive, usedDiskPercent, score); }
Source:
<code>public void customize() { List<String> commands = Lists.newLinkedList(); String gitRepoUrl = getEntity().getConfig(NodeJsWebAppService.APP_GIT_REPOSITORY_URL); String archiveUrl = getEntity().getConfig(NodeJsWebAppService.APP_ARCHIVE_URL); String appName = getEntity().getConfig(NodeJsWebAppService.APP_NAME); if (Strings.isNonBlank(gitRepoUrl) && Strings.isNonBlank(archiveUrl)) { <START> throw new IllegalStateException("Only one of Git or archive URL must be set"); <END> } else if (Strings.isNonBlank(gitRepoUrl)) { commands.add(String.format("git clone %s %s", gitRepoUrl, appName)); } else if (Strings.isNonBlank(archiveUrl)) { ArchiveUtils.deploy(archiveUrl, getMachine(), getRunDir()); } else { throw new IllegalStateException("At least one of Git or archive URL must be set"); } newScript(CUSTOMIZING) .body.append(commands) .execute(); }</code><technical_language>Include entity this is in exception (and gitRepoUrl archiveUrl are). e.g. throw new IllegalStateException("Only of Git archive URL set for "+entity+"; repo "+gitRepoUrl+" archive "+archiveUrl); for other exception thrown below</technical_language>

Target:
public void customize() { List<String> commands = Lists.newLinkedList(); String gitRepoUrl = getEntity().getConfig(NodeJsWebAppService.APP_GIT_REPOSITORY_URL); String archiveUrl = getEntity().getConfig(NodeJsWebAppService.APP_ARCHIVE_URL); String appName = getEntity().getConfig(NodeJsWebAppService.APP_NAME); if (Strings.isNonBlank(gitRepoUrl) && Strings.isNonBlank(archiveUrl)) { throw new IllegalStateException("Only one of Git or archive URL must be set for " + getEntity()); } else if (Strings.isNonBlank(gitRepoUrl)) { commands.add(String.format("git clone %s %s", gitRepoUrl, appName)); } else if (Strings.isNonBlank(archiveUrl)) { ArchiveUtils.deploy(archiveUrl, getMachine(), getRunDir()); } else { throw new IllegalStateException("At least one of Git or archive URL must be set for " + getEntity()); } newScript(CUSTOMIZING) .body.append(commands) .execute(); }
Source:
<code>public AccessToken(String token, OffsetDateTime expiresAt) { this.token = token; <START> this.expiresAt = expiresAt; <END> }</code><technical_language>This a breaking change for developers Identity library this class core for custom credentials</technical_language>

Target:
public AccessToken(String token, OffsetDateTime expiresAt) { this.token = token; this.expiresAt = expiresAt.minusMinutes(2); }
Source:
<code>private void onActivePhoneSwitch() { for (HashMap.Entry<NetworkRequest, Integer> entry : mNetworkRequests.entrySet()) { NetworkRequest networkRequest = entry.getKey(); boolean applied = entry.getValue() != <START> -1; <END> boolean shouldApply = mPhoneSwitcher.shouldApplyNetworkRequest( networkRequest, mPhone.getPhoneId()); int action = getAction(applied, shouldApply); if (action == ACTION_NO_OP) continue; String logStr = "onActivePhoneSwitch: " + ((action == ACTION_REQUEST) ? "Requesting" : "Releasing") + " network request " + networkRequest; mLocalLog.log(logStr); int transportType = getTransportTypeFromNetworkRequest(networkRequest); if (action == ACTION_REQUEST) { requestNetworkInternal(networkRequest, DcTracker.REQUEST_TYPE_NORMAL, getTransportTypeFromNetworkRequest(networkRequest)); } else if (action == ACTION_RELEASE) { int transport = getTransportTypeFromNetworkRequest(networkRequest); releaseNetworkInternal(networkRequest, DcTracker.RELEASE_TYPE_DETACH, transport); } mNetworkRequests.put(networkRequest, shouldApply ? transportType : -1); } }</code><technical_language>define constant for -1</technical_language>

Target:
private void onActivePhoneSwitch() { for (HashMap.Entry<NetworkRequest, Integer> entry : mNetworkRequests.entrySet()) { NetworkRequest networkRequest = entry.getKey(); boolean applied = entry.getValue() != TransportType.INVALID; boolean shouldApply = mPhoneSwitcher.shouldApplyNetworkRequest( networkRequest, mPhone.getPhoneId()); int action = getAction(applied, shouldApply); if (action == ACTION_NO_OP) continue; String logStr = "onActivePhoneSwitch: " + ((action == ACTION_REQUEST) ? "Requesting" : "Releasing") + " network request " + networkRequest; mLocalLog.log(logStr); int transportType = getTransportTypeFromNetworkRequest(networkRequest); if (action == ACTION_REQUEST) { requestNetworkInternal(networkRequest, DcTracker.REQUEST_TYPE_NORMAL, getTransportTypeFromNetworkRequest(networkRequest), null); } else if (action == ACTION_RELEASE) { int transport = getTransportTypeFromNetworkRequest(networkRequest); releaseNetworkInternal(networkRequest, DcTracker.RELEASE_TYPE_DETACH, transport); } mNetworkRequests.put(networkRequest, shouldApply ? transportType : TransportType.INVALID); } }
Source:
<code>public void publish(JSONObject transcript) { String uglyJSON = transcript.toJSONString(); String prettyJSOn = new GsonBuilder().setPrettyPrinting().create(). toJson(new JsonParser().parse(uglyJSON)); <START> <END> new LocalTxtTranscriptHandler().publish(prettyJSOn); }</code><technical_language>Oh, is purpose add whitespace for prettier formatting? If so, remove - -we'll do handling in client</technical_language>

Target:
public void publish(JSONObject transcript) { new LocalTxtTranscriptHandler().publish(transcript.toString()); }
Source:
<code>public void onSupportActionModeStarted(ActionMode mode) { <START> boolean wasCabOpen = isCabOpen(); <END> currentActionMode = new CompatActionMode(mode, wasCabOpen); if (currentActionMode.shouldInjectCustomMenu(PageActivity.this)) { currentActionMode.injectCustomMenu(PageActivity.this); } prepareActionMode(); super.onSupportActionModeStarted(mode); }</code><technical_language>Is this block of code identical in onActionModeStarted()? If so, I complicated enough demand a DRY method</technical_language>

Target:
public void onSupportActionModeStarted(ActionMode mode) { if (!isCabOpen()) { conditionallyInjectCustomCabMenu(mode); } freezeToolbar(); super.onSupportActionModeStarted(mode); }
Source:
<code><START> public static InstallationChecker getInstance() throws ProvisionException { <END> if (INSTANCE == null) { INSTANCE = new InstallationChecker(); } return INSTANCE; }</code><technical_language>prefer Initialization Demand Holder pattern cope singletons <LINK_0></technical_language>

Target:
public synchronized static InstallationChecker getInstance() throws ProvisionException { if (INSTANCE == null) { INSTANCE = new InstallationChecker(); } return INSTANCE; }
Source:
<code>public void run() { LogManager.logDebug("Start run", this); IWorkbench wb = PlatformUI.getWorkbench(); ISelection incoming = viewer.getViewer().getSelection(); IStructuredSelection selection = (IStructuredSelection)incoming; Object o = selection.getFirstElement(); if(o instanceof TreeNode) { TreeNode t = (TreeNode)o; if(t.isClickable()) { IFileStore fs = (IFileStore)t.getData(); if (fs != null) { IEditorInput input= createEditorInput(fs); String editorId= getEditorId(fs); try { IEditorPart editor = wb.getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if(editor instanceof STPEditor) IDESessionSettings.setActiveSTPEditor((STPEditor) editor); wb.getActiveWorkbenchWindow().getActivePage().openEditor(input, editorId); LogManager.logDebug("Editor opened", this); } catch (PartInitException e) { <START> LogManager.logCritical("PartInitException run: " + e.getMessage(), this); END> e.printStackTrace(); } } } else { expandAction.run(); } } LogManager.logDebug("End run", this); }</code><technical_language>Printing stack trace is a good practice. is hard find start eclipse console console switch</technical_language>

Target:
public void run() { LogManager.logDebug("Start run", this); IWorkbench wb = PlatformUI.getWorkbench(); ISelection incoming = viewer.getViewer().getSelection(); IStructuredSelection selection = (IStructuredSelection)incoming; Object o = selection.getFirstElement(); if(o instanceof TreeNode) { TreeNode t = (TreeNode)o; if(t.isClickable()) { IFileStore fs = (IFileStore)t.getData(); if (fs != null) { IEditorInput input= createEditorInput(fs); try { IEditorPart editor = wb.getActiveWorkbenchWindow().getActivePage().getActiveEditor(); if(editor instanceof STPEditor) IDESessionSettings.activeSTPEditor = (STPEditor)editor; wb.getActiveWorkbenchWindow().getActivePage().openEditor(input, CEditor.ID); LogManager.logDebug("Editor opened", this); } catch (PartInitException e) { LogManager.logCritical("PartInitException run: " + e.getMessage(), this); } } } else { expandAction.run(); } } LogManager.logDebug("End run", this); }
Source:
<code>public void withBothFirstResultAndFirstResultExpressionPresent() { try { this.context = new ClassPathXmlApplicationContext("JpaInvalidOutboundGatewayParserTests.xml", getClass()); } catch (BeanDefinitionStoreException e) { assertTrue(e.getMessage().startsWith("Configuration problem: Only one of 'first-result' or 'first-result-expression' is allowed")); return; } <START> assertTrue(false); <END> }</code><technical_language>smile: prefer fail("BeanDefinitionStoreException expeted.") try...catch</technical_language>

Target:
public void withBothFirstResultAndFirstResultExpressionPresent() { try { this.context = new ClassPathXmlApplicationContext("JpaInvalidOutboundGatewayParserTests.xml", getClass()); } catch (BeanDefinitionStoreException e) { assertTrue(e.getMessage().startsWith("Configuration problem: Only one of 'first-result' or 'first-result-expression' is allowed")); return; } fail("BeanDefinitionStoreException expected."); }
Source:
<code>public Object[] getParameters() { switch (control) { case START_SEND: case FINISH_SEND: case CANCEL_SEND: return new Object[]{control.toByte(), siteName}; } <START> return new Object[]{control.toByte()}; <END> }</code><technical_language>I over-optimizing a bit here, XSiteStateTransferControlCommands **very** rare, a simple return new Object[]{control, siteName} fine</technical_language>

Target:
public Object[] getParameters() { return new Object[]{control, siteName}; }
Source:
<code><START> public void setVms(ListModel<Pair<String, VM>> vms) { <END> this.vms = vms; }</code><technical_language>I this private</technical_language>

Target:
private void setVms(ListModel<Pair<String, VM>> vms) { this.vms = vms; }
Source:
<code>private JAXBElement<RegistryObjectType> createIdentifiable(RegistryObjectType registryObjectType) { <START> JAXBElement<RegistryObjectType> i = new JAXBElement<>(new QName( <END> "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, registryObjectType); return i; }</code><technical_language>create immediately return, do return in-line</technical_language>

Target:
private JAXBElement<RegistryObjectType> createIdentifiable(RegistryObjectType registryObjectType) { return new JAXBElement<>(new QName( "urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0", "Identifiable"), RegistryObjectType.class, registryObjectType); }
Source:
<code>private synchronized void createGroupIfNecessary(ResourceGroupId id, QueryExecution queryExecution, Executor executor) { Session session = queryExecution.getSession(); SelectionContext context = new SelectionContext(session.getIdentity().getPrincipal().isPresent(), <START> session.getUser(), session.getSource(), getQueryPriority(session), queryExecution instanceof DataDefinitionExecution); <END> if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(id.getParent().get(), queryExecution, executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); group = parent.getOrCreateSubGroup(id.getLastSegment()); } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }</code><technical_language>argument line</technical_language>

Target:
private synchronized void createGroupIfNecessary(ResourceGroupId id, QueryExecution queryExecution, Executor executor) { Session session = queryExecution.getSession(); SelectionContext context = new SelectionContext( session.getIdentity().getPrincipal().isPresent(), session.getUser(), session.getSource(), getQueryPriority(session), determineQueryType(queryExecution)); if (!groups.containsKey(id)) { InternalResourceGroup group; if (id.getParent().isPresent()) { createGroupIfNecessary(id.getParent().get(), queryExecution, executor); InternalResourceGroup parent = groups.get(id.getParent().get()); requireNonNull(parent, "parent is null"); group = parent.getOrCreateSubGroup(id.getLastSegment()); } else { RootInternalResourceGroup root = new RootInternalResourceGroup(id.getSegments().get(0), this::exportGroup, executor); group = root; rootGroups.add(root); } configurationManager.get().configure(group, context); checkState(groups.put(id, group) == null, "Unexpected existing resource group"); } }
Source:
<code>public SimpleFieldSet getFieldSet() { SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("Total", event.totalBlocks); fs.put("Required", event.minSuccessfulBlocks); fs.put("Failed", event.failedBlocks); fs.put("FatallyFailed", event.fatallyFailedBlocks); <START> fs.put("LatestFailure", event.latestFailure != null ? event.latestFailure.getTime() : 0); <END> fs.put("Succeeded",event.succeedBlocks); fs.put("LatestSuccess", event.latestSuccess != null ? event.latestSuccess.getTime() : 0); fs.put("FinalizedTotal", event.finalizedTotal); if(event.minSuccessFetchBlocks != 0) fs.put("MinSuccessFetchBlocks", event.minSuccessFetchBlocks); fs.putSingle("Identifier", ident); fs.put("Global", global); return fs; }</code><technical_language>Whitespace is inconsistent - added spaces tabs here</technical_language>

Target:
public SimpleFieldSet getFieldSet() { SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("Total", event.totalBlocks); fs.put("Required", event.minSuccessfulBlocks); fs.put("Failed", event.failedBlocks); fs.put("FatallyFailed", event.fatallyFailedBlocks); fs.put("Succeeded",event.succeedBlocks); fs.put("LastProgress", event.latestSuccess != null ? event.latestSuccess.getTime() : 0); fs.put("FinalizedTotal", event.finalizedTotal); if(event.minSuccessFetchBlocks != 0) fs.put("MinSuccessFetchBlocks", event.minSuccessFetchBlocks); fs.putSingle("Identifier", ident); fs.put("Global", global); return fs; }
Source:
<code>public void putNext(Tuple t) throws IOException { if (t == null) { <START> log.warn("Null tuple found; Skipping tuple"); <END> return; } Preconditions.checkArgument(2 <= t.size(), "Expected tuple size >= 2 but found size %s", t.size()); Object pigKey = t.get(0); if (pigKey == null) { log.warn("Null key found; Skipping tuple"); return; } Object pigValue = t.get(1); if (pigValue == null) { log.warn("Null value found; Skipping tuple"); return; } K key = keyConverter.toWritable(pigKey); V value = valueConverter.toWritable(pigValue); try { writer.write(key, value); } catch (InterruptedException e) { throw new IOException(e); } }</code><technical_language>I is a common practice null key interested in sequence of values. blow logs. I limit log log if is error. increment a counter, is more accessible users</technical_language>

Target:
public void putNext(Tuple t) throws IOException { if (t == null) { counterHelper.incrCounter(Error.NULL_TUPLE, 1); return; } K key = keyConverter.toWritable(t.get(0)); if (key == null) { counterHelper.incrCounter(Error.NULL_KEY, 1); return; } V value = valueConverter.toWritable(t.get(1)); if (value == null) { counterHelper.incrCounter(Error.NULL_VALUE, 1); return; } try { writer.write(key, value); } catch (InterruptedException e) { throw new IOException(e); } }
Source:
<code>private int numberOfEntries(ByteBuffer mmap) { return <START> (mmap.capacity() - INDEX_SIZE_EXCLUDING_ENTRIES - (version == (short) 1 ? (resetKey.getFirst().sizeInBytes() + <END> RESET_KEY_TYPE_FIELD_LENGTH + LAST_MODIFIED_TIME_FIELD_LENGTH) : 0)) / (keySize + valueSize); }</code><technical_language>making INDEX_SIZE_EXCLUDING_ENTRIES a class variable simplify this code</technical_language>

Target:
private int numberOfEntries(ByteBuffer mmap) { return (mmap.capacity() - indexSizeExcludingEntries) / (keySize + valueSize); }
Source:
<code>protected boolean isDocument(HttpResponseHeader responseHeader) { <START> return responseHeader.getHeaders().stream() <END> .filter(header -> "Content-Type".equalsIgnoreCase(header.getName())) .anyMatch( header -> header.getValue().startsWith("text/html") || header.getValue().startsWith("application/xml")); }</code><technical_language>Prefer getHeader(HttpHeader.CONTENT_TYPE) (or getHeaderValues), require traverse headers again</technical_language>

Target:
protected boolean isDocument(HttpResponseHeader responseHeader) { return responseHeader.getHeaderValues(HttpHeader.CONTENT_TYPE).stream() .anyMatch( header -> header.startsWith("text/html") || header.startsWith("application/xml")); }
Source:
<code>public <T> boolean putMapping(Class<T> clazz) { if (clazz.isAnnotationPresent(Mapping.class)) { String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath(); if (!StringUtils.isEmpty(mappingPath)) { String mappings = readFileFromClasspath(mappingPath); if (!StringUtils.isEmpty(mappings)) { return putMapping(clazz, mappings); } } else { LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); } } try { <START> final MappingBuilder mappingBuilder = new MappingBuilder(elasticsearchConverter); <END> return putMapping(clazz, mappingBuilder.buildMapping(clazz)); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } }</code><technical_language>Nit: need for final variables</technical_language>

Target:
public <T> boolean putMapping(Class<T> clazz) { if (clazz.isAnnotationPresent(Mapping.class)) { String mappingPath = clazz.getAnnotation(Mapping.class).mappingPath(); if (!StringUtils.isEmpty(mappingPath)) { String mappings = readFileFromClasspath(mappingPath); if (!StringUtils.isEmpty(mappings)) { return putMapping(clazz, mappings); } } else { LOGGER.info("mappingPath in @Mapping has to be defined. Building mappings using @Field"); } } try { MappingBuilder mappingBuilder = new MappingBuilder(elasticsearchConverter); return putMapping(clazz, mappingBuilder.buildMapping(clazz)); } catch (Exception e) { throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e); } }