auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void applyProjectsVolumes(List<PodData> podsData, List<HasMetadata> componentObjects) { if (componentObjects .stream() .noneMatch( hasMeta -> hasMeta instanceof PersistentVolumeClaim && hasMeta.getMetadata().getName().equals(PROJECTS_VOLUME_NAME))) { PersistentVolumeClaim volumeClaim = newPVC( PROJECTS_VOLUME_NAME, defaultPVCAccessMode, defaultProjectPVCSize, pvcStorageClassName); componentObjects.add(volumeClaim); } for (PodData podData : podsData) { <START> final String podVolumeName = PROJECTS_VOLUME_NAME + "-" + podData.getMetadata().getName(); <END> if (podData .getSpec() .getVolumes() .stream() .noneMatch(volume -> volume.getName().equals(PROJECTS_VOLUME_NAME))) { Volume volume = newVolume(podVolumeName, PROJECTS_VOLUME_NAME); podData.getSpec().getVolumes().add(volume); } for (Container container : podData.getSpec().getContainers()) { if (container .getVolumeMounts() .stream() .noneMatch(mount -> mount.getName().equals(PROJECTS_VOLUME_NAME))) { VolumeMount volumeMount = newVolumeMount(podVolumeName, projectFolderPath, null); container.getVolumeMounts().add(volumeMount); } } } }</code><technical_language>hit some name length limit this</technical_language>

Target:
private void applyProjectsVolumes(List<PodData> podsData, List<HasMetadata> componentObjects) { if (componentObjects .stream() .noneMatch( hasMeta -> hasMeta instanceof PersistentVolumeClaim && hasMeta.getMetadata().getName().equals(PROJECTS_VOLUME_NAME))) { PersistentVolumeClaim volumeClaim = newPVC( PROJECTS_VOLUME_NAME, defaultPVCAccessMode, defaultProjectPVCSize, pvcStorageClassName); componentObjects.add(volumeClaim); } for (PodData podData : podsData) { if (podData .getSpec() .getVolumes() .stream() .noneMatch(volume -> volume.getName().equals(PROJECTS_VOLUME_NAME))) { Volume volume = newVolume(PROJECTS_VOLUME_NAME, PROJECTS_VOLUME_NAME); podData.getSpec().getVolumes().add(volume); } for (Container container : podData.getSpec().getContainers()) { if (container .getVolumeMounts() .stream() .noneMatch(mount -> mount.getName().equals(PROJECTS_VOLUME_NAME))) { VolumeMount volumeMount = newVolumeMount(PROJECTS_VOLUME_NAME, projectFolderPath, null); container.getVolumeMounts().add(volumeMount); } } } }
Source:
<code>public void visitMethod(MethodTree tree) { boolean isUnitTest = isUnitTest(tree); inUnitTest.push(isUnitTest); <START> methodContainsAssertion.push(Boolean.FALSE); <END> super.visitMethod(tree); inUnitTest.pop(); if (isUnitTest && !methodContainsAssertion.pop()) { context.addIssue(tree, this, "Add at least one assertion to this test case."); } }</code><technical_language>matter of taste rely autoboxing</technical_language>

Target:
public void visitMethod(MethodTree tree) { boolean isUnitTest = isUnitTest(tree); inUnitTest.push(isUnitTest); methodContainsAssertion.push(false); super.visitMethod(tree); inUnitTest.pop(); if (isUnitTest && !methodContainsAssertion.pop()) { context.addIssue(tree, this, "Add at least one assertion to this test case."); } }
Source:
<code>protected DependentTypesHelper createDependentTypesHelper() { return new DependentTypesHelper(this) { @Override protected void reportErrors(Tree errorTree, List<DependentTypesError> errors) { List<DependentTypesError> superErrors = new ArrayList<>(); for (DependentTypesError error : errors) { if (error.error.equals(NOT_EFFECTIVELY_FINAL)) { checker.reportError( errorTree, "lock.expression.not.final", error.expression); } else { superErrors.add(error); } } super.reportErrors(errorTree, superErrors); } @Override protected String standardizeString( String expression, FlowExpressionContext context, TreePath localScope, boolean useLocalScope, boolean removeErroneousExpressions) { if (DependentTypesError.isExpressionError(expression)) { <START> return null; <END> } if (LockVisitor.SELF_RECEIVER_PATTERN.matcher(expression).matches()) { return expression; } try { Receiver result = FlowExpressionParseUtil.parse( expression, context, localScope, useLocalScope); if (result == null) { if (removeErroneousExpressions) { return null; } else { return new DependentTypesError(expression, " ").toString(); } } if (!isExpressionEffectivelyFinal(result)) { if (removeErroneousExpressions) { return null; } else { return new DependentTypesError(expression, NOT_EFFECTIVELY_FINAL) .toString(); } } return result.toString(); } catch (FlowExpressionParseUtil.FlowExpressionParseException e) { if (removeErroneousExpressions) { return null; } else { return new DependentTypesError(expression, e).toString(); } } } }; }</code><technical_language>This return null if removeErroneousExpressions is true</technical_language>

Target:
protected DependentTypesHelper createDependentTypesHelper() { return new DependentTypesHelper(this) { @Override protected void reportErrors(Tree errorTree, List<DependentTypesError> errors) { List<DependentTypesError> superErrors = new ArrayList<>(); for (DependentTypesError error : errors) { if (error.error.equals(NOT_EFFECTIVELY_FINAL)) { checker.reportError( errorTree, "lock.expression.not.final", error.expression); } else { superErrors.add(error); } } super.reportErrors(errorTree, superErrors); } @Override protected String standardizeString( String expression, FlowExpressionContext context, TreePath localScope, boolean useLocalScope) { if (DependentTypesError.isExpressionError(expression)) { return expression; } if (LockVisitor.SELF_RECEIVER_PATTERN.matcher(expression).matches()) { return expression; } try { Receiver result = FlowExpressionParseUtil.parse( expression, context, localScope, useLocalScope); if (result == null) { return new DependentTypesError(expression, " ").toString(); } if (!isExpressionEffectivelyFinal(result)) { return new DependentTypesError(expression, NOT_EFFECTIVELY_FINAL) .toString(); } return result.toString(); } catch (FlowExpressionParseUtil.FlowExpressionParseException e) { return new DependentTypesError(expression, e).toString(); } } }; }
Source:
<code>public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { HttpRequest httpRequest = context.getHttpRequest(); if ("http".equals(httpRequest.getUrl().getProtocol())) { return Mono.error(new IllegalStateException( "Shared access signature credentials require HTTPS to prevent leaking the shared access signature.")); } String signature = credential.getSignature(); if (signature.startsWith("?")) { signature = signature.substring(1); } String query = httpRequest.getUrl().getQuery(); String url = httpRequest.getUrl().toString(); if (query == null || query.isEmpty()) { url = url + "?" + signature; <START> } else if (!query.contains(signature)) { <END> url = url + "&" + signature; } httpRequest.setUrl(url); return next.process(); }</code><technical_language>Based this this policy implement <LINK_0> PER_CALL? this logic positional change another route well, explicitly prevent duplicate SAS parameters</technical_language>

Target:
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { HttpRequest httpRequest = context.getHttpRequest(); if ("http".equals(httpRequest.getUrl().getProtocol())) { return Mono.error(new IllegalStateException( "Shared access signature credentials require HTTPS to prevent leaking the shared access signature.")); } String signature = credential.getSignature(); if (signature.startsWith("?")) { signature = signature.substring(1); } String query = httpRequest.getUrl().getQuery(); String url = httpRequest.getUrl().toString(); if (query == null || query.isEmpty()) { if (url.endsWith("?")) { url = url + signature; } else { url = url + "?" + signature; } } else if (!query.contains(signature)) { url = url + "&" + signature; } httpRequest.setUrl(url); return next.process(); }
Source:
<code>public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); if (target == null) target = "/"; try { response.setContentType(JSON_CONTENT_TYPE); if (VoltDB.instance().getHttpAdminListener().m_jsonEnabled) { if (target.equals("/")) { httpClientInterface.process((Request )request, response); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println("Resource not found"); } } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("JSON API IS CURRENTLY DISABLED"); } } catch (Exception ex) { <START> m_log.info("Not servicing url: " + target + " Details: " + ex.getMessage(), ex); <END> } }</code><technical_language>Is this enough</technical_language>

Target:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { super.doGet(request, response); String target = request.getPathInfo(); if (target == null) target = "/"; try { response.setContentType(JSON_CONTENT_TYPE); if (VoltDB.instance().getHttpAdminListener().m_jsonEnabled) { if (target.equals("/")) { httpClientInterface.process((Request )request, response); } else { response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.getWriter().println("Resource not found"); } } else { response.setStatus(HttpServletResponse.SC_FORBIDDEN); response.getWriter().println("JSON API IS CURRENTLY DISABLED"); } } catch (Exception ex) { rateLimitedLogWarn("Not servicing url: %s Details: ", target, ex.getMessage()); response.setStatus(HttpServletResponse.SC_BAD_REQUEST); response.getWriter().print(buildClientResponse(null, ClientResponse.UNEXPECTED_FAILURE, Throwables.getStackTraceAsString(ex))); } }
Source:
<code>public AeroGearGCMPushJsonConfiguration loadConfigJson(Context context) { try { InputStream fileStream = context.getResources().getAssets().open(getFileName()); int size = fileStream.available(); byte[] buffer = new byte[size]; fileStream.read(buffer); fileStream.close(); String json = new String(buffer); JSONObject pushConfig = new JSONObject(json); JSONObject pushAndroidConfig = pushConfig.getJSONObject("android"); this.pushConfig.setPushServerURI(new URI(pushConfig.getString("pushServerURL"))); this.pushConfig.addSenderId(pushAndroidConfig.getString("senderID")); this.pushConfig.setVariantID(pushAndroidConfig.getString("variantID")); <START> this.pushConfig.setSecret(pushAndroidConfig.getString("variantSecret")); <END> } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return this; }</code><technical_language>args passed getString constants well</technical_language>

Target:
public AeroGearGCMPushJsonConfiguration loadConfigJson(Context context) { InputStream fileStream = null; try { fileStream = context.getResources().getAssets().open(getFileName()); int size = fileStream.available(); byte[] buffer = new byte[size]; fileStream.read(buffer); fileStream.close(); String json = new String(buffer); JSONObject pushConfig = new JSONObject(json); JSONObject pushAndroidConfig = pushConfig.getJSONObject(JSON_OBJECT); this.pushConfig.setPushServerURI(new URI(pushConfig.getString(JSON_URL))); this.pushConfig.addSenderId(pushAndroidConfig.getString(JSON_SENDER_ID)); this.pushConfig.setVariantID(pushAndroidConfig.getString(JSON_VARIANT_ID)); this.pushConfig.setSecret(pushAndroidConfig.getString(JSON_VARIANT_SECRET)); } catch (URISyntaxException e) { Log.e(TAG, e.getMessage(), e); } catch (JSONException e) { Log.e(TAG, e.getMessage(), e); throw new RuntimeException("An error occurred while parsing the " + getFileName() + ". Please check the file format"); } catch (IOException e) { Log.e(TAG, e.getMessage(), e); throw new RuntimeException("An error occurred while parsing the " + getFileName() + ". Please check if the file exists"); } finally { if (fileStream != null) { try { fileStream.close(); } catch (IOException e) { } } } return this; }
Source:
<code><START> public List<TypeMirror> uses() { <END> List<TypeMirror> result = new ArrayList<TypeMirror>(); Set<TypeMirror> alreadyAdded = new HashSet<TypeMirror>(); addAllOnce( result, alreadyAdded, mapperPrism.uses() ); if ( mapperConfigPrism != null ) { addAllOnce( result, alreadyAdded, mapperConfigPrism.uses() ); } return result; }</code><technical_language>a LinkedHashSet do trick, avoiding manual "add-all-once" handling while guaranteeing a stable iteration order</technical_language>

Target:
public List<TypeMirror> uses() { Set<TypeMirror> uses = new LinkedHashSet<TypeMirror>( mapperPrism.uses() ); if ( mapperConfigPrism != null ) { uses.addAll( mapperConfigPrism.uses() ); } return new ArrayList<TypeMirror>( uses ); }
Source:
<code>public PEMWriter(@Nonnull File file) throws IOException { targetFile = file; <START> tmpFile = File.createTempFile("jack-server", file.getName(), file.getParentFile()); <END> if (!tmpFile.exists()) { if (!tmpFile.createNewFile()) { throw new IOException("Failed to create temp file '" + tmpFile.getPath() + "'"); } if (!(tmpFile.setExecutable(false, false) && tmpFile.setWritable(false, false) && tmpFile.setReadable(false, false) && tmpFile.setWritable(true, true) && tmpFile.setReadable(true, true))) { throw new IOException("Failed to set permission of '" + tmpFile.getPath() + "'"); } } out = new OutputStreamWriter(new FileOutputStream(tmpFile), CHARSET); }</code><technical_language>I decided SchedLib tools for in server? Is right? If yes, add missing tooling in SchedLib. Prefix is 'jack-server-' in other place</technical_language>

Target:
public PEMWriter(@Nonnull File file) throws IOException { targetFile = file; tmpFile = File.createTempFile("jackserver-", file.getName(), file.getParentFile()); if (!tmpFile.exists()) { if (!tmpFile.createNewFile()) { throw new IOException("Failed to create temp file '" + tmpFile.getPath() + "'"); } if (!(tmpFile.setExecutable(false, false) && tmpFile.setWritable(false, false) && tmpFile.setReadable(false, false) && tmpFile.setWritable(true, true) && tmpFile.setReadable(true, true))) { throw new IOException("Failed to set permission of '" + tmpFile.getPath() + "'"); } } out = new OutputStreamWriter(new FileOutputStream(tmpFile), CHARSET); }
Source:
<code>public static void main(String[] args) throws IOException { String ddfListUrl = "<LINK_0>"; String ddfFilesPath = Ddf2JsonGenerator.DEFAULT_DDF_FILES_PATH; if (args.length >= 1) ddfFilesPath = args[0]; if (args.length >= 2) ddfListUrl = args[1]; new DdfList2JsonGenerator().processDdfList(ddfListUrl, ddfFilesPath); LOG.debug("DDF list processed to {}, proceeding with JSON generation", ddfListUrl, ddfFilesPath); <START> Ddf2JsonGenerator.main(new String[] { ddfFilesPath }); <END> }</code><technical_language>add a parameter for path of json output path : java // generate object spec file Ddf2JsonGenerator ddfJsonGenerator = new Ddf2JsonGenerator(); try (FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) { ddfJsonGenerator.generate(new File(ddfFilesPath), fileOutputStream); } instead of : java Ddf2JsonGenerator.main(new String[] { ddfFilesPath });</technical_language>

Target:
public static void main(String[] args) throws IOException { String ddfFilesPath = Ddf2JsonGenerator.DEFAULT_DDF_FILES_PATH; String outputPath = Ddf2JsonGenerator.DEFAULT_OUTPUT_PATH; String ddfListUrl = "<LINK_0>"; if (args.length >= 1) ddfFilesPath = args[0]; if (args.length >= 2) outputPath = args[1]; if (args.length >= 3) ddfListUrl = args[2]; new DdfList2JsonGenerator().processDdfList(ddfListUrl, ddfFilesPath); LOG.debug("DDF list processed to {}, proceeding with JSON generation", ddfListUrl, ddfFilesPath); Ddf2JsonGenerator ddfJsonGenerator = new Ddf2JsonGenerator(); try (FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) { ddfJsonGenerator.generate(new File(ddfFilesPath), fileOutputStream); } }
Source:
<code>public <S extends TargetState> S getTargetState( @NonNull String alias) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (!this.stateTypes.containsKey(alias)) { <START> throw new IllegalArgumentException("Unknown alias: " + alias); <END> } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states/aliases/{2}", this.app.getAppID(), this.target.getTypedID().toString(), alias); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); JsonObject object = new JsonParser().parse(responseBody.toString()).getAsJsonObject(); return (S)this.gson.fromJson(object, this.stateTypes.get(alias)); }</code><technical_language>throw UnregisteredAliasException</technical_language>

Target:
public <S extends TargetState> S getTargetState( @NonNull String alias) throws ThingIFException { if (this.target == null) { throw new IllegalStateException("Can not perform this action before onboarding"); } if (!this.stateTypes.containsKey(alias)) { throw new UnregisteredAliasException(alias, false); } String path = MessageFormat.format("/thing-if/apps/{0}/targets/{1}/states/aliases/{2}", this.app.getAppID(), this.target.getTypedID().toString(), alias); String url = Path.combine(this.app.getBaseUrl(), path); Map<String, String> headers = this.newHeader(); IoTRestRequest request = new IoTRestRequest(url, IoTRestRequest.Method.GET, headers); JSONObject responseBody = this.restClient.sendRequest(request); JsonObject object = new JsonParser().parse(responseBody.toString()).getAsJsonObject(); return (S)this.gson.fromJson(object, this.stateTypes.get(alias)); }
Source:
<code>public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, NON_CANCELLING, <START> ""); <END> }</code><technical_language>suggestion EMPTY_VALUE);</technical_language>

Target:
public void testUnmarshallSubprocessLevelEventEmptyProperties() throws Exception { Diagram<Graph, Metadata> diagram = unmarshall(marshaller, BPMN_CATCHING_INTERMEDIATE_EVENT_FILE_PATH); assertDiagram(diagram, AMOUNT_OF_NODES_IN_DIAGRAM); IntermediateConditionalEvent emptySubprocessEvent = getCatchingIntermediateNodeById(diagram, EMPTY_SUBPROCESS_LEVEL_EVENT_ID, HAS_NO_INCOME_EDGE, HAS_NO_OUTGOING_EDGE); assertGeneralSet(emptySubprocessEvent.getGeneral(), EMPTY_VALUE, EMPTY_VALUE); assertConditionalEventExecutionSet(emptySubprocessEvent.getExecutionSet(), CONDITION_EXPRESSION_SCRIPT_DEFAULT_VALUE, CONDITION_EXPRESSION_LANGUAGE, CONDITION_ERPRESSION_TYPE, NON_CANCELLING, EMPTY_VALUE); }
Source:
<code>private String createFormattedRemittanceIdTextBasedOnPresenceOfInvoiceDataForDv(String invoiceNumber, Date invoiceDate, String customerPaymentDocumentNumber) { <START> StringBuffer formattedRemittanceIdText = new StringBuffer(""); <END> if (StringUtils.isNotBlank(invoiceNumber) && ObjectUtils.isNotNull(invoiceDate)) { formattedRemittanceIdText.append(invoiceNumber); formattedRemittanceIdText.append(" Doc No:"); formattedRemittanceIdText.append(customerPaymentDocumentNumber); } else if (StringUtils.isNotBlank(customerPaymentDocumentNumber)) { formattedRemittanceIdText.append("Doc No:"); formattedRemittanceIdText.append(customerPaymentDocumentNumber); } return formattedRemittanceIdText.toString(); }</code><technical_language>I suggest a StringBuilder instead for efficiency. builder defaults empty, need explicitly empty string initial value</technical_language>

Target:
private String createFormattedRemittanceIdTextBasedOnPresenceOfInvoiceDataForDv(String invoiceNumber, Date invoiceDate, String customerPaymentDocumentNumber) { StringBuilder formattedRemittanceIdText = new StringBuilder(""); if (StringUtils.isNotBlank(invoiceNumber) && ObjectUtils.isNotNull(invoiceDate)) { formattedRemittanceIdText.append(invoiceNumber); formattedRemittanceIdText.append(" Doc:"); formattedRemittanceIdText.append(customerPaymentDocumentNumber); } else if (StringUtils.isNotBlank(customerPaymentDocumentNumber)) { formattedRemittanceIdText.append("Doc:"); formattedRemittanceIdText.append(customerPaymentDocumentNumber); } return formattedRemittanceIdText.toString(); }
Source:
<code>public void registerSingleFileToLongleaf() throws Exception { Bag workBag = addContainerObject(depBag, Cdr.Work); Resource fileResc = addFileObject(workBag, FILE_CONTENT1, true); fileResc.addProperty(CdrDeposit.storageUri, LOC2_ID); workBag.addProperty(Cdr.primaryObject, fileResc); job.closeModel(); job.run(); String registrationArguments = "register -f " + LOC2_ID + " --checksums 'md5:" + MD5 + "' --force"; <START> File file = new File(outputPath); <END> BufferedReader br = new BufferedReader(new FileReader(file)); String output = br.readLine(); assertEquals(registrationArguments, output); }</code><technical_language>do FileUtils.readFileToString(file, encoding) a shortcut for reading output file</technical_language>

Target:
public void registerSingleFileToLongleaf() throws Exception { Bag workBag = addContainerObject(depBag, Cdr.Work); Resource fileResc = addFileObject(workBag, FILE_CONTENT1, true); fileResc.addProperty(CdrDeposit.storageUri, FILE_SCHEME + LOC2_ID + "/original_file"); workBag.addProperty(Cdr.primaryObject, fileResc); job.closeModel(); job.run(); String output = FileUtils.readFileToString(new File(outputPath), StandardCharsets.UTF_8); assertRegisterCalled(LOC1_ID + "/event_log", 3, output); assertRegisterCalled(LOC2_ID + "/original_file --checksums \"md5:" + MD5 + "\"", 1, output); }
Source:
<code>public ResolvedOvernightFutureTrade resolve(ReferenceData refData) { ResolvedOvernightFuture resolved = getProduct().resolve(refData); TradedPrice tradedPrice = info.getTradeDate() .map(tradeDate -> TradedPrice.of(tradeDate, price)) <START> .orElse(null); <END> return new ResolvedOvernightFutureTrade(info, resolved, quantity, tradedPrice); }</code><technical_language>Trade date required for trade. Position Trade, 'Trade', trade date is required. This changed (see for example BondFutureTrade). OvernightFuture aligned changes</technical_language>

Target:
public ResolvedOvernightFutureTrade resolve(ReferenceData refData) { if (!info.getTradeDate().isPresent()) { throw new IllegalArgumentException("Trade date on TradeInfo must be present"); } ResolvedOvernightFuture resolved = getProduct().resolve(refData); TradedPrice tradedPrice = TradedPrice.of(info.getTradeDate().get(), price); return new ResolvedOvernightFutureTrade(info, resolved, quantity, tradedPrice); }
Source:
<code>public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (!Context.getPermissionsManager().isAdmin(getUserId())) { AttributeAlias attrbuteAlias = Context.getAliasesManager().getAttributeAliasById(id); Context.getPermissionsManager().checkDevice(getUserId(), <START> attrbuteAlias != null ? attrbuteAlias.getDeviceId() : 0); <END> } Context.getAliasesManager().removeArrtibuteAlias(id); return Response.noContent().build(); }</code><technical_language>I need null check here. crash</technical_language>

Target:
public Response remove(@PathParam("id") long id) throws SQLException { Context.getPermissionsManager().checkReadonly(getUserId()); if (!Context.getPermissionsManager().isAdmin(getUserId())) { AttributeAlias entity = Context.getAliasesManager().getAttributeAlias(id); Context.getPermissionsManager().checkDevice(getUserId(), entity.getDeviceId()); } Context.getAliasesManager().removeArrtibuteAlias(id); return Response.noContent().build(); }
Source:
<code>public ModelAndView loadCandidate(@PathVariable(value = "candidateId") Long candidateId) throws CandidateNotFoundException { ModelAndView modelAndView = new ModelAndView(VIEW_NAME); CandidateDTO candidate = candidateService.getCandidate(candidateId); if (candidate == null) <START> throw new CandidateNotFoundException(); <END> modelAndView.addObject(CANDIDATE_OBJECT_KEY, candidate); return modelAndView; }</code><technical_language>Please add technical details exception, referenced candidateId useful exception. If future need find out 404 errors users, candidate found, candidates id referenced</technical_language>

Target:
public ModelAndView loadCandidate(@PathVariable(value = "candidateId") Long candidateId) { ModelAndView modelAndView = new ModelAndView(VIEW_NAME); CandidateDTO candidate = candidateService.getCandidate(candidateId); if (candidate == null) { throw new CandidateNotFoundException(candidateId); } modelAndView.addObject(CANDIDATE_OBJECT_KEY, candidate); return modelAndView; }
Source:
<code>private void onSessionStateChange(SessionState state, Exception exception) { if (exception != null) { if (loginContext != null) { handleError(exception, loginContext); } } else { final Session session = Session.getActiveSession(); <START> if (state.isOpened()) { <END> if (loginContext != null) { getUserInfo(session); } else if (graphContext != null) { makeGraphCall(); } } } }</code><technical_language>PR this develop branch I added a checkActiveSession method re-use here</technical_language>

Target:
private void onSessionStateChange(SessionState state, Exception exception) { if (exception != null && exception instanceof FacebookOperationCanceledException) { Log.e(TAG, "exception:" + exception.toString()); handleError(exception, loginContext); } else { final Session session = Session.getActiveSession(); if (state.isOpened()) { if (loginContext != null) { getUserInfo(session); } else if (graphContext != null) { makeGraphCall(); } } } }
Source:
<code>public Response getExtensions() { JSONArray results; try { List<String> extensions = STORE.getExtensions(); results = buildEnumerateResult(extensions); } catch (StoreAccessException e) { <START> LOG.error("Enumerate extensions failed", e); <END> throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } catch (FalconException e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } try { JSONObject response = new JSONObject(); response.put(RESULTS, results); response.put(TOTAL_RESULTS, results.length()); return Response.ok(response).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }</code><technical_language>a log message specific this type of exception if want distinguish this exception others, e.g. Failed accessing extension store</technical_language>

Target:
public Response getExtensions() { JSONArray results; try { List<String> extensions = STORE.getExtensions(); results = buildEnumerateResult(extensions); } catch (StoreAccessException e) { LOG.error("Failed when accessing extension store.", e); throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } catch (FalconException e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } try { JSONObject response = new JSONObject(); response.put(EXTENSION_RESULTS, results); response.put(TOTAL_RESULTS, results.length()); return Response.ok(response).build(); } catch (Throwable e) { throw FalconWebException.newAPIException(e, Response.Status.INTERNAL_SERVER_ERROR); } }
Source:
<code><START> private void fireExpireEntityEventTargetItem (final CallbackInfo ci) { <END> try (CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); ExpireEntityEvent.TargetItem event = SpongeEventFactory.createExpireEntityEventTargetItem(Sponge.getCauseStackManager().getCurrentCause(), (Item) this); SpongeImpl.postEvent(event); } }</code><technical_language>I hate complain formatting... This method name needs prefixed spongeImpl$ consistent class (though, @gabizou, [I thought policy prefix impl$, spongeImpl$](<LINK_0> Also, nitpicky, while there, remove space method name parameters, space method name</technical_language>

Target:
private void impl$fireExpireEntityEventTargetItem(final CallbackInfo ci) { if (!SpongeImplHooks.isMainThread() || this.getItem().isEmpty()) { return; } try (final CauseStackManager.StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame()) { frame.pushCause(this); final ExpireEntityEvent.TargetItem event = SpongeEventFactory.createExpireEntityEventTargetItem(frame.getCurrentCause(), (Item) this); SpongeImpl.postEvent(event); } }
Source:
<code>public void processTuple(byte[] tuple) { if (tuple == null) { <START> if (err.isConnected()) { <END> err.emit(new KeyValPair<String, String>(null, "Blank/null tuple")); } errorTupleCount++; return; } String incomingString = new String(tuple); if (StringUtils.isBlank(incomingString) || StringUtils.equals(incomingString, header)) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, "Blank/header tuple")); } errorTupleCount++; return; } try { if (parsedOutput.isConnected()) { csvStringReader.open(incomingString); Map<String, Object> map = csvMapReader.read(nameMapping, processors); parsedOutput.emit(map); parsedOutputCount++; } if (out.isConnected() && clazz != null) { csvStringReader.open(incomingString); Object obj = csvBeanReader.read(clazz, nameMapping, processors); out.emit(obj); emittedObjectCount++; } } catch (SuperCsvException e) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, e.getMessage())); } errorTupleCount++; logger.error("Tuple could not be parsed. Reason {}", e.getMessage()); } catch (IOException e) { logger.error("Exception in process method {}", e.getMessage()); DTThrowable.rethrow(e); } }</code><technical_language>If condition of err.isConnected is required action is emit. default connected Sink.BLACKHOLE put object do anything</technical_language>

Target:
public void processTuple(byte[] tuple) { if (tuple == null) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(null, "Blank/null tuple")); } errorTupleCount++; return; } String incomingString = new String(tuple); if (StringUtils.isBlank(incomingString) || StringUtils.equals(incomingString, header)) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, "Blank/header tuple")); } errorTupleCount++; return; } try { if (parsedOutput.isConnected()) { csvStringReader.open(incomingString); Map<String, Object> map = csvMapReader.read(nameMapping, processors); parsedOutput.emit(map); parsedOutputCount++; } if (out.isConnected() && clazz != null) { csvStringReader.open(incomingString); Object obj = csvBeanReader.read(clazz, nameMapping, processors); out.emit(obj); emittedObjectCount++; } } catch (SuperCsvException | IOException e) { if (err.isConnected()) { err.emit(new KeyValPair<String, String>(incomingString, e.getMessage())); } errorTupleCount++; logger.error("Tuple could not be parsed. Reason {}", e.getMessage()); } }
Source:
<code>protected void doGet(final CloudletTopic reqTopic, final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload) { logger.info(message.cloudGETReqReceiving()); if ("assets".equals(reqTopic.getResources()[0])) { this.findAssets(); if (reqTopic.getResources().length == 1) { this.getAllAssets(respPayload); return; } <START> if (reqTopic.getResources().length != 2) { <END> respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } final Asset asset = this.assets.get(reqTopic.getResources()[1].trim()); if (asset == null) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } final String channelName = extractChannelName(reqPayload); if (channelName == null) { getChannelMetadata(respPayload, asset); } else if (channelName.indexOf(ALL_CHANNELS_WILDCARD) != -1) { readAllChannels(respPayload, asset); } else { readChannels(respPayload, asset, channelName); } } else { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); } logger.info(message.cloudGETReqReceived()); }</code><technical_language>extract reqTopic.getResources() a variable need call thereafter</technical_language>

Target:
protected void doGet(final CloudletTopic reqTopic, final KuraRequestPayload reqPayload, final KuraResponsePayload respPayload) { final String[] resources = reqTopic.getResources(); logger.info(message.cloudGETReqReceiving()); if ("assets".equals(resources[0])) { this.findAssets(); if (resources.length == 1) { this.getAllAssets(respPayload); return; } if (resources.length != 2) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); return; } final Asset asset = this.assets.get(resources[1].trim()); if (asset == null) { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_NOTFOUND); return; } final String channelName = extractChannelName(reqPayload); if (channelName == null) { getChannelMetadata(respPayload, asset); } else if (channelName.indexOf(ALL_CHANNELS_WILDCARD) != -1) { readAllChannels(respPayload, asset); } else { readChannels(respPayload, asset, channelName); } } else { respPayload.setResponseCode(KuraResponsePayload.RESPONSE_CODE_BAD_REQUEST); } logger.info(message.cloudGETReqReceived()); }
Source:
<code>public String getStatusFor(final String issueKey) throws IssueTrackerUpdateException { try { Optional<IssueSummary> issue = jiraConnection.getRestJiraClient().loadByKey(issueKey); <START> return issue.get().getStatus(); <END> } catch (JSONException e) { throw new IssueTrackerUpdateException(e.getMessage(),e); } }</code><technical_language>getRestJiraClient() returns Optional<>, get() assuming issue found. exception odd. more sense throw some special exception (e.g. IssueNotFoundException) in case easier troubleshoot</technical_language>

Target:
public String getStatusFor(final String issueKey) throws IssueTrackerUpdateException { try { Optional<IssueSummary> issue = jiraConnection.getRestJiraClient().loadByKey(issueKey); if(issue.isPresent()) { return issue.get().getStatus(); } else { logJiraIssueNotFound(issueKey); throw new IssueTrackerUpdateException("Issue not found " + issueKey, new NoSuchIssueException(issueKey)); } } catch (JSONException e) { throw new IssueTrackerUpdateException(e.getMessage(),e); } }
Source:
<code>public Map<String, String> getJobMessageProperties() { if (jobProperties == null) { jobProperties = new HashMap<String, String>(); List<PermissionSubject> subjects = getPermissionCheckSubjects(); <START> if (subjects != null) { <END> if (!subjects.isEmpty()) { VdcObjectType entityType; Guid entityId; String value; for (PermissionSubject permSubject : subjects) { entityType = permSubject.getObjectType(); entityId = permSubject.getObjectId(); if (entityType != null && entityId != null) { value = DbFacade.getInstance().getEntityNameByIdAndType(entityId, entityType); if (value == null) { value = entityId.toString(); } jobProperties.put(entityType.name().toLowerCase(), value); } } } } } return jobProperties; }</code><technical_language>avoid level of nesting (subjects != null & !subjects.isEmpty())</technical_language>

Target:
public Map<String, String> getJobMessageProperties() { jobProperties = new HashMap<String, String>(); List<PermissionSubject> subjects = getPermissionCheckSubjects(); if (jobProperties == null && subjects != null) { if (!subjects.isEmpty()) { VdcObjectType entityType; Guid entityId; String value; for (PermissionSubject permSubject : subjects) { entityType = permSubject.getObjectType(); entityId = permSubject.getObjectId(); if (entityType != null && entityId != null) { value = DbFacade.getInstance().getEntityNameByIdAndType(entityId, entityType); if (value == null) { value = entityId.toString(); } jobProperties.put(entityType.name().toLowerCase(), value); } } } } return jobProperties; }
Source:
<code>protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("user"); User currentUser = sessionUser.get(); try { <START> Boolean password_hashed = (req.getParameter("password_hashed") == null ? false : (req.getParameter("password_hashed").equals("1") ? true : false) ); <END> if (currentUser == null) { dataService.login(username, req.getParameter("password"), password_hashed); } String locale = req.getParameter("locale"); resp.sendRedirect("/" + (locale == null ? "" : ("?locale=" + locale))); } catch (Exception ex) { resp.getWriter().println("Authentication failed"); } }</code><technical_language>I guess approach result in easier (just boolean arithmetic): java boolean password_hashed = req.getParameter("password_hashed") != null && req.getParameter("password_hashed").equals("1"); I name variables in camel-case (like in code). password_hashed passwordHashed</technical_language>

Target:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String username = req.getParameter("user"); User currentUser = sessionUser.get(); try { boolean passwordHashed = req.getParameter("password_hashed") != null && req.getParameter("password_hashed").equals("1"); if (currentUser == null) { dataService.login(username, req.getParameter("password"), passwordHashed); } String locale = req.getParameter("locale"); resp.sendRedirect("/" + (locale == null ? "" : ("?locale=" + locale))); } catch (Exception ex) { resp.getWriter().println("Authentication failed"); } }
Source:
<code>public IDebugViewHelper getDebugViewHelper() { <START> return this.debugViewHelpers.get(oldJobType); <END> }</code><technical_language>add oldJobType blank check here</technical_language>

Target:
public IDebugViewHelper getDebugViewHelper() { return lastDebugType != null && debugViewHelpers.get(lastDebugType) != null ? debugViewHelpers.get(lastDebugType) : debugViewHelpers.get(EDebugProcessType.DI); }
Source:
<code>private void testBinaryNumeric() throws SQLException { if (!getPgJdbcDriver()) { return; } Server server = createPgServer( "-ifNotExists", "-pgPort", "5535", "-pgDaemon", "-key", "pgserver", "mem:pgserver"); supportedBinaryOids.add(1700); try { Properties props = new Properties(); props.setProperty("user", "sa"); props.setProperty("password", "sa"); props.setProperty("prepareThreshold", "-1"); Connection conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5535/pgserver", props); Statement stat = conn.createStatement(); <START> try (ResultSet rs = stat.executeQuery("SELECT 1E-16383, 1E-16384, 1E+1")) { rs.next(); assertEquals(new BigDecimal("1E-16383"), rs.getBigDecimal(1)); for (int i = 2; i <= 3; i ++) { try { rs.getBigDecimal(i); fail(); } catch (IllegalArgumentException e) { } } } <END> conn.close(); } finally { supportedBinaryOids.remove(1700); server.stop(); } }</code><technical_language>SELECT 1E1 works PostgreSQL/PgJDBC well, getBigDecimal() returns 10 expected. I need normalize scale in implementation too</technical_language>

Target:
private void testBinaryNumeric() throws SQLException { if (!getPgJdbcDriver()) { return; } Server server = createPgServer( "-ifNotExists", "-pgPort", "5535", "-pgDaemon", "-key", "pgserver", "mem:pgserver"); supportedBinaryOids.add(1700); try { Properties props = new Properties(); props.setProperty("user", "sa"); props.setProperty("password", "sa"); props.setProperty("prepareThreshold", "-1"); Connection conn = DriverManager.getConnection( "jdbc:postgresql://localhost:5535/pgserver", props); Statement stat = conn.createStatement(); try (ResultSet rs = stat.executeQuery("SELECT 1E-16383, 1E+1, 1E+89, 1E-16384")) { rs.next(); assertEquals(new BigDecimal("1E-16383"), rs.getBigDecimal(1)); assertEquals(new BigDecimal("10"), rs.getBigDecimal(2)); assertEquals(new BigDecimal("10").pow(89), rs.getBigDecimal(3)); try { rs.getBigDecimal(4); fail(); } catch (IllegalArgumentException e) { } } try (ResultSet rs = stat.executeQuery("SELECT 1E-32768")) { fail(); } catch (SQLException e) { assertEquals("22003", e.getSQLState()); } try (ResultSet rs = stat.executeQuery("SELECT 1E+131072")) { fail(); } catch (SQLException e) { assertEquals("22003", e.getSQLState()); } conn.close(); } finally { supportedBinaryOids.remove(1700); server.stop(); } }
Source:
<code>public boolean insertAmenityIntoPoi(Amenity amenity) throws SQLException { assert IndexConstants.POI_TABLE != null : "use constants here to show table usage "; poiPreparedStatement.setLong(1, amenity.getId()); poiPreparedStatement.setInt(2, MapUtils.get31TileNumberX(amenity.getLocation().getLongitude())); poiPreparedStatement.setInt(3, MapUtils.get31TileNumberY(amenity.getLocation().getLatitude())); poiPreparedStatement.setString(4, amenity.getType().getKeyName()); poiPreparedStatement.setString(5, amenity.getSubType()); poiPreparedStatement.setString(6, encodeAdditionalInfo(amenity, amenity.getAdditionalInfo(), amenity.getName(), amenity.getEnName(false))); try { addBatch(poiPreparedStatement); return true; } catch (SQLException e) { <START> if (e.getMessage().contains("UNIQUE constraint failed: ")) { <END> log.info("Duplicate poi is not inserted: " + amenity.toString()); } else { throw e; } return false; } }</code><technical_language>This here. catch, swallow exception this is a bad practice</technical_language>

Target:
public void insertAmenityIntoPoi(Amenity amenity) throws SQLException { assert IndexConstants.POI_TABLE != null : "use constants here to show table usage "; poiPreparedStatement.setLong(1, amenity.getId()); poiPreparedStatement.setInt(2, MapUtils.get31TileNumberX(amenity.getLocation().getLongitude())); poiPreparedStatement.setInt(3, MapUtils.get31TileNumberY(amenity.getLocation().getLatitude())); poiPreparedStatement.setString(4, amenity.getType().getKeyName()); poiPreparedStatement.setString(5, amenity.getSubType()); poiPreparedStatement.setString(6, encodeAdditionalInfo(amenity, amenity.getAdditionalInfo(), amenity.getName(), amenity.getEnName(false))); addBatch(poiPreparedStatement); }
Source:
<code>boolean boxedEqual3(Boolean B, Boolean V) { <START> return B == V; END> }</code><technical_language>is this Noncompliant</technical_language>

Target:
void boxedEqual3(Boolean B, Boolean V) { if (B == V) { foo(); } else { bar(); } }
Source:
<code>public ModListScreen(Screen mainMenu) { super(new TranslationTextComponent("fml.menu.mods.title")); this.mainMenu = mainMenu; <START> this.mods = Collections.unmodifiableList(net.minecraftforge.fml.ModList.get().getMods()); <END> this.unsortedMods = Collections.unmodifiableList(this.mods); }</code><technical_language>this import instead of a fully qualified reference</technical_language>

Target:
public ModListScreen(Screen mainMenu) { super(new TranslationTextComponent("fml.menu.mods.title")); this.mainMenu = mainMenu; this.mods = Collections.unmodifiableList(ModList.get().getMods()); this.unsortedMods = Collections.unmodifiableList(this.mods); }
Source:
<code>public void receivingGetAllOrganizationsRequest(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { ScenarioContext.Current().put(Keys.KEY_ORGANIZATION_IDENTIFICATION, getString(settings, Keys.KEY_ORGANIZATION_IDENTIFICATION, Defaults.DEFAULT_ORGANIZATION_IDENTIFICATION)); try { ScenarioContext.Current().put(Keys.RESPONSE, this.client.findAllOrganizations(new FindAllOrganisationsRequest())); } catch (final SoapFaultClientException e) { ScenarioContext.Current().put(Keys.RESPONSE, e); } final Object obj = ScenarioContext.Current().get(Keys.RESPONSE); <START> System.out.println(obj); <END> }</code><technical_language>Remove lines, for testing purposes only...</technical_language>

Target:
public void receivingGetAllOrganizationsRequest(final Map<String, String> settings) throws WebServiceSecurityException, GeneralSecurityException, IOException { ScenarioContext.Current().put(Keys.KEY_ORGANIZATION_IDENTIFICATION, getString(settings, Keys.KEY_ORGANIZATION_IDENTIFICATION, Defaults.DEFAULT_ORGANIZATION_IDENTIFICATION)); try { ScenarioContext.Current().put(Keys.RESPONSE, this.client.findAllOrganizations(new FindAllOrganisationsRequest())); } catch (final SoapFaultClientException e) { ScenarioContext.Current().put(Keys.RESPONSE, e); } }
Source:
<code>private void repopulateBufferIfNeeded() { if (_exhaustedSource) { return; } if (_buffer.hasNext()) { return; } <START> synchronized (this) { <END> final List<? extends E> results = _getPage.apply(_offset); _buffer = results.iterator(); _offset += results.size(); } _exhaustedSource = !_buffer.hasNext(); }</code><technical_language>If this is expected thread safe not, return for multiple threads is element in underlying store (not threads claim instance)</technical_language>

Target:
private void repopulateBufferIfNeeded() { if (_exhaustedSource) { return; } if (!_buffer.isEmpty()) { return; } final List<? extends E> results = _getPage.apply(_offset); _buffer.addAll(results); _offset += results.size(); _exhaustedSource = _buffer.isEmpty(); }
Source:
<code>public void testGetFileContentWithNonAsciiPath() throws Exception { <START> final GHContent fileContent = gitHub.getRepository("hub4j-test-org/GHContentIntegrationTest") .getFileContent("ghcontent-ro/a-file-with-\u00F6"); assertThat(IOUtils.readLines(fileContent.read(), StandardCharsets.UTF_8), hasItems("test")); <END> }</code><technical_language>for a test this (I run locally): suggestion final GHRepository repo = gitHub.getRepository("hub4j-test-org/GHContentIntegrationTest"); final GHContent fileContent = repo.getFileContent("ghcontent-ro/a-file-with-\u00F6"); assertThat(IOUtils.readLines(fileContent.read(), StandardCharsets.UTF_8), hasItems("test")); final GHContent fileContent2 = repo.getFileContent(fileContent.getPath()); assertThat(IOUtils.readLines(fileContent2.read(), StandardCharsets.UTF_8), hasItems("test"));</technical_language>

Target:
public void testGetFileContentWithNonAsciiPath() throws Exception { final GHRepository repo = gitHub.getRepository("hub4j-test-org/GHContentIntegrationTest"); final GHContent fileContent = repo.getFileContent("ghcontent-ro/a-file-with-\u00F6"); assertThat(IOUtils.readLines(fileContent.read(), StandardCharsets.UTF_8), hasItems("test")); final GHContent fileContent2 = repo.getFileContent(fileContent.getPath()); assertThat(IOUtils.readLines(fileContent2.read(), StandardCharsets.UTF_8), hasItems("test")); }
Source:
<code>public Set<Contract.Postcondition> getPostconditions(ExecutableElement executableElement) { Set<Contract.Postcondition> result = super.getPostconditions(executableElement); if (declarationFromElement(executableElement) != null) { <START> if (executableElement.getSimpleName().contentEquals("<init>")) { <END> String[] fieldsToInitialize = fieldsToInitialize( (TypeElement) executableElement.getEnclosingElement()); if (fieldsToInitialize.length != 0) { AnnotationMirror initializedFieldsAnno; { AnnotationBuilder builder = new AnnotationBuilder( processingEnv, InitializedFields.class.getCanonicalName()); builder.setValue("value", fieldsToInitialize); initializedFieldsAnno = builder.build(); } AnnotationMirror ensuresAnno; { AnnotationBuilder builder = new AnnotationBuilder( processingEnv, EnsuresInitializedFields.class.getCanonicalName()); builder.setValue("value", new String[] {"this"}); builder.setValue("fields", fieldsToInitialize); ensuresAnno = builder.build(); } Contract.Postcondition ensuresContract = new Contract.Postcondition( "this", initializedFieldsAnno, ensuresAnno); result.add(ensuresContract); } } } return result; }</code><technical_language>I replace this executableElement.getKind() == ElementKind.CONSTRUCTOR avoid string comparison</technical_language>

Target:
public Set<Contract.Postcondition> getPostconditions(ExecutableElement executableElement) { Set<Contract.Postcondition> result = super.getPostconditions(executableElement); if (declarationFromElement(executableElement) != null) { if (executableElement.getKind() == ElementKind.CONSTRUCTOR) { String[] fieldsToInitialize = fieldsToInitialize( (TypeElement) executableElement.getEnclosingElement()); if (fieldsToInitialize.length != 0) { AnnotationMirror initializedFieldsAnno; { AnnotationBuilder builder = new AnnotationBuilder( processingEnv, InitializedFields.class.getCanonicalName()); builder.setValue("value", fieldsToInitialize); initializedFieldsAnno = builder.build(); } AnnotationMirror ensuresAnno; { AnnotationBuilder builder = new AnnotationBuilder( processingEnv, EnsuresInitializedFields.class.getCanonicalName()); builder.setValue("value", "this"); builder.setValue("fields", fieldsToInitialize); ensuresAnno = builder.build(); } Contract.Postcondition ensuresContract = new Contract.Postcondition( "this", initializedFieldsAnno, ensuresAnno); result.add(ensuresContract); } } } return result; }