instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public InventoryLineHU convertQuantities(@NonNull final UnaryOperator<Quantity> qtyConverter) { return toBuilder() .qtyCount(qtyConverter.apply(getQtyCount())) .qtyBook(qtyConverter.apply(getQtyBook())) .build(); } public InventoryLineHU updatingFrom(@NonNull final InventoryLineCountRequest request) { return toBuilder().updatingFrom(request).build(); } public static InventoryLineHU of(@NonNull final InventoryLineCountRequest request) { return builder().updatingFrom(request).build(); } // // // // ------------------------------------------------------------------------- // // // @SuppressWarnings("unused") public static class InventoryLineHUBuilder
{ InventoryLineHUBuilder updatingFrom(@NonNull final InventoryLineCountRequest request) { return huId(request.getHuId()) .huQRCode(HuId.equals(this.huId, request.getHuId()) ? this.huQRCode : null) .qtyInternalUse(null) .qtyBook(request.getQtyBook()) .qtyCount(request.getQtyCount()) .isCounted(true) .asiId(request.getAsiId()) ; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryLineHU.java
1
请完成以下Java代码
public double getRotation() { return rotation; } public void setRotation(double rotation) { this.rotation = rotation; } public boolean equals(GraphicInfo ginfo) { if (this.getX() != ginfo.getX()) { return false; } if (this.getY() != ginfo.getY()) { return false; } if (this.getHeight() != ginfo.getHeight()) { return false; } if (this.getWidth() != ginfo.getWidth()) { return false; } if (this.getRotation() != ginfo.getRotation()) {
return false; } // check for zero value in case we are comparing model value to BPMN DI value // model values do not have xml location information if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) { return false; } if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) { return false; } // only check for elements that support this value if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) { return false; } return true; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\GraphicInfo.java
1
请在Spring Boot框架中完成以下Java代码
private String getRootUrl(){ return "http://localhost:" + port; } @Test public void contextLoads(){ } // @Test // public void testGetAllDevelopers(){ // HttpHeaders headers = new HttpHeaders(); // HttpEntity<String> entity = new HttpEntity<String>(null, headers); // // ResponseEntity<String> response = restTemplate.exchange(getRootUrl() + "/users", HttpMethod.GET, entity, String.class); // // assertNotNull(response.getBody()); // } @Test public void testGetDeveloperById() { // Developer developer = restTemplate.getForObject(getRootUrl() + "/dev/1", Developer.class); System.out.println(developer.getFirstName()); assertNotNull(developer); } @Test public void testCreateDeveloper(){ Developer developer = new Developer(); developer.setEmailId("hamdamboy.urunov@gmail.com"); developer.setFirstName("Hamdamboy"); developer.setLastName("Urunov"); // developer.setCreateAt(null); // developer.setUpdatedAt(null); ResponseEntity<Developer> postResponse = restTemplate.postForEntity(getRootUrl() + "/devs", developer, Developer.class); assertNotNull(postResponse); assertNotNull(postResponse.getBody()); }
@Test public void testUpdatePost(){ int id = 1; Developer developer = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class); developer.setFirstName("hamdambek"); developer.setLastName("urunov"); restTemplate.put(getRootUrl() + "/developer/" + id, developer); Developer updateDevelop = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class); assertNotNull(updateDevelop); } @Test public void testDeletePost(){ // int id = 2; Developer developer = restTemplate.getForObject(getRootUrl() + "/developers/" + id, Developer.class); assertNotNull(developer); restTemplate.delete(getRootUrl() + "/developers/" + id); try { developer = restTemplate.getForObject(getRootUrl() + "/developer/" + id, Developer.class); } catch (final HttpClientErrorException e){ assertEquals(e.getStatusCode(), HttpStatus.NOT_FOUND); } } }
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringMySQL\src\main\java\spring\restapi\service\SpringBootCrudRestApplicationTests.java
2
请完成以下Java代码
public Quantity getSingleQuantity() { return getSingleGroup().getQty(); } @Value public static class Group { public enum Type { ATTRIBUTE_SET, OTHER_STORAGE_KEYS, ALL_STORAGE_KEYS } ProductId productId; Quantity qty; Type type;
ImmutableAttributeSet attributes; @Builder public Group( @NonNull final Group.Type type, @NonNull final ProductId productId, @NonNull final Quantity qty, @Nullable final ImmutableAttributeSet attributes) { this.type = type; this.productId = productId; this.qty = qty; this.attributes = CoalesceUtil.coalesce(attributes, ImmutableAttributeSet.EMPTY); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailabilityInfoResultForWebui.java
1
请完成以下Java代码
public class FilterUtils { public static <T> Optional<T> findUniqueElementMatchingPredicate_WithReduction(Stream<T> elements, Predicate<T> predicate) { return elements.filter(predicate) .collect(Collectors.reducing((a, b) -> null)); } public static <T> T getUniqueElementMatchingPredicate_WithReduction(Stream<T> elements, Predicate<T> predicate) { return elements.filter(predicate) .reduce((a, b) -> { throw new IllegalStateException("Too many elements match the predicate"); }) .orElseThrow(() -> new IllegalStateException("No element matches the predicate")); } public static <T> Optional<T> findUniqueElementMatchingPredicate_WithCollectingAndThen(Stream<T> elements, Predicate<T> predicate) { return elements.filter(predicate) .collect(Collectors.collectingAndThen(Collectors.toList(), list -> Optional.ofNullable(findUniqueElement(list)))); } private static <T> T findUniqueElement(List<T> elements) { if (elements.size() == 1) { return elements.get(0); }
return null; } public static <T> T getUniqueElementMatchingPredicate_WithCollectingAndThen(Stream<T> elements, Predicate<T> predicate) { return elements.filter(predicate) .collect(Collectors.collectingAndThen(Collectors.toList(), FilterUtils::getUniqueElement)); } private static <T> T getUniqueElement(List<T> elements) { if (elements.size() > 1) { throw new IllegalStateException("Too many elements match the predicate"); } else if (elements.size() == 0) { throw new IllegalStateException("No element matches the predicate"); } return elements.get(0); } }
repos\tutorials-master\core-java-modules\core-java-streams-4\src\main\java\com\baeldung\streams\filteronlyoneelement\FilterUtils.java
1
请完成以下Java代码
public void loadPreference(final Properties ctx) { final int adUserId = Env.getAD_User_ID(ctx); loadPreference(adUserId); } /** * Set Property * * @param key Key * @param value Value */ public void setProperty(final String key, final String value) { if (props == null) { props = new Properties(); } if (value == null) { props.setProperty(key, ""); } else { props.setProperty(key, value); } } /** * Set Property * * @param key Key * @param value Value */ public void setProperty(final String key, final Boolean value) { setProperty(key, DisplayType.toBooleanString(value)); } /** * Set Property * * @param key Key * @param value Value */ public void setProperty(final String key, final int value) { setProperty(key, String.valueOf(value)); }
/** * Get Property * * @param key Key * @return Value */ public String getProperty(final String key) { if (key == null) { return ""; } if (props == null) { return ""; } final String value = props.getProperty(key, ""); if (Check.isEmpty(value)) { return ""; } return value; } /** * Get Property as Boolean * * @param key Key * @return Value */ public boolean isPropertyBool(final String key) { final String value = getProperty(key); return DisplayType.toBooleanNonNull(value, false); } public void updateContext(final Properties ctx) { Env.setContext(ctx, "#ShowTrl", true); Env.setContext(ctx, "#ShowAdvanced", true); Env.setAutoCommit(ctx, isPropertyBool(P_AUTO_COMMIT)); Env.setAutoNew(ctx, isPropertyBool(P_AUTO_NEW)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserPreference.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getTimerLockForceAcquireAfter() { return timerLockForceAcquireAfter; } public void setTimerLockForceAcquireAfter(Duration timerLockForceAcquireAfter) { this.timerLockForceAcquireAfter = timerLockForceAcquireAfter; } public Duration getResetExpiredJobsInterval() { return resetExpiredJobsInterval; } public void setResetExpiredJobsInterval(Duration resetExpiredJobsInterval) { this.resetExpiredJobsInterval = resetExpiredJobsInterval; } public int getResetExpiredJobsPageSize() { return resetExpiredJobsPageSize;
} public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { this.resetExpiredJobsPageSize = resetExpiredJobsPageSize; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AsyncJobExecutorConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public void deleteArticle(User me, @PathVariable String slug) { articleService.deleteArticle(me, slug); } @PreAuthorize("isAuthenticated()") @GetMapping("/api/articles/feed") public MultipleArticlesResponse getFeedArticles( User me, @RequestParam(value = "limit", required = false, defaultValue = "20") int limit, @RequestParam(value = "offset", required = false, defaultValue = "0") int offset) { ArticleFacets facets = new ArticleFacets(null, null, null, offset, limit); List<ArticleVO> articles = articleService.getFeedArticles(me, facets); return new MultipleArticlesResponse(articles); } @PostMapping("/api/articles/{slug}/comments") public SingleCommentResponse createComment( User me, @PathVariable String slug, @RequestBody CreateCommentRequest request) { CommentVO comment = articleService.createComment(me, slug, request); return new SingleCommentResponse(comment); } @GetMapping("/api/articles/{slug}/comments") public MultipleCommentsResponse getComments(User me, @PathVariable String slug) { List<CommentVO> comments = articleService.getArticleComments(me, slug); return new MultipleCommentsResponse(comments); }
@DeleteMapping("/api/articles/{slug}/comments/{id}") public void deleteComment(User me, @PathVariable String slug, @PathVariable int id) { articleService.deleteComment(me, id); } @PostMapping("/api/articles/{slug}/favorite") public SingleArticleResponse favoriteArticle(User me, @PathVariable String slug) { ArticleVO article = articleService.favoriteArticle(me, slug); return new SingleArticleResponse(article); } @DeleteMapping("/api/articles/{slug}/favorite") public SingleArticleResponse unfavoriteArticle(User me, @PathVariable String slug) { ArticleVO article = articleService.unfavoriteArticle(me, slug); return new SingleArticleResponse(article); } }
repos\realworld-spring-boot-native-master\src\main\java\com\softwaremill\realworld\application\article\controller\ArticleController.java
2
请完成以下Java代码
private static class SingletonHolder { public static final SerializableCloneableSingleton instance = new SerializableCloneableSingleton(); } public static SerializableCloneableSingleton getInstance() { return SingletonHolder.instance; } @Override public String describeMe() { throw new UnsupportedOperationException("Not Supported Here"); } @Override public String passOnLocks(MyLock lock) { throw new UnsupportedOperationException("Not Supported Here"); } @Override public void increment() {
this.state++; } public int getState() { return state; } private Object readResolve() throws ObjectStreamException { return SingletonHolder.instance; } public Object cloneObject() throws CloneNotSupportedException { return this.clone(); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\staticsingletondifference\SerializableCloneableSingleton.java
1
请完成以下Spring Boot application配置
spring: boot: admin: ui: theme: color: "#4A1420" palette: 50: "#F8EBE4" 100: "#F2D7CC" 200: "#E5AC9C" 300: "#D87B6C" 400: "#CB463B" 500: "#9F2A2
A" 600: "#83232A" 700: "#661B26" 800: "#4A1420" 900: "#2E0C16"
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\resources\application-themed.yml
2
请完成以下Java代码
private void mapEditorAction(int keyCode, int modifiers, Action a) { final KeyStroke ks = KeyStroke.getKeyStroke(keyCode, modifiers); // editor.getKeymap().removeKeyStrokeBinding(ks); // editor.getKeymap().addActionForKeyStroke(ks, a); // String name = (String)a.getValue(Action.SHORT_DESCRIPTION); if (name == null) name = a.toString(); editor.getEditorActionMap().put(name, a); editor.getEditorInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, name); } public void setHtmlText(String htmlText) { editor.setText(htmlText); } public String getHtmlText() { try { StringWriter sw = new StringWriter(); new AltHTMLWriter(sw, editor.getDocument()).write(); // new HTMLWriter(sw, editor.document).write(); String html = sw.toString(); return html; } catch (Exception e) { e.printStackTrace(); } return null; } /** * Compatible with CTextArea * * @param text * @see #setHtmlText(String) */ public void setText(String text) { if (!isHtml(text)) { setHtmlText(convertToHtml(text)); } else { setHtmlText(text); } } /** * Compatible with CTextArea * * @return html text * @see #getHtmlText() */ public String getText() { return getHtmlText(); } /** * Compatible with CTextArea * * @param position */ public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public BoilerPlateContext getAttributes() { return boilerPlateMenu.getAttributes(); } public void setAttributes(final BoilerPlateContext attributes) { boilerPlateMenu.setAttributes(attributes); } public File getPDF(String fileNamePrefix) { throw new UnsupportedOperationException(); } private void actionPreview() { // final ReportEngine re = getReportEngine(); // ReportCtl.preview(re); File pdf = getPDF(null); if (pdf != null) { Env.startBrowser(pdf.toURI().toString()); } } private Dialog getParentDialog() {
Dialog parent = null; Container e = getParent(); while (e != null) { if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() { throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null) return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText) { if (plainText == null) return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请完成以下Java代码
protected void prepare() { final ProcessInfoParameter[] para = getParametersAsArray(); for (ProcessInfoParameter element : para) { final String name = element.getParameterName(); if (element.getParameter() == null) { // do nothing } else if (CreateCreditMemoFromInvoice.PARA_C_DocType_ID.equals(name)) { final BigDecimal bdC_DocType_ID = element.getParameterAsBigDecimal(); C_DocType_ID = bdC_DocType_ID.intValue(); } else if (CreateCreditMemoFromInvoice.PARA_CompleteIt.equals(name)) { completeIt = element.getParameterAsBoolean(); } else if (CreateCreditMemoFromInvoice.PARA_IsReferenceOriginalOrder.equals(name)) { referenceOriginalOrder = element.getParameterAsBoolean(); }
else if (CreateCreditMemoFromInvoice.PARA_IsReferenceInvoice.equals(name)) { referenceInvoice = element.getParameterAsBoolean(); } else if (CreateCreditMemoFromInvoice.PARA_IsCreditedInvoiceReinvoicable.equals(name)) { creditedInvoiceReinvoicable = element.getParameterAsBoolean(); } else { log.error("Unknown Parameter: " + name); } } } @Override protected void postProcess(boolean success) { if (creditMemo == null || creditMemo.isProcessed()) { // not zooming to the credit memo, because there is nothing more to change return; } AEnv.zoom(AD_Table_ID, Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\invoice\process\CreateCreditMemoFromInvoice.java
1
请完成以下Java代码
public class ActiveOrHistoricCurrencyAndAmount { @XmlValue protected BigDecimal value; @XmlAttribute(name = "Ccy", required = true) protected String ccy; /** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } *
*/ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public void setCcy(String value) { this.ccy = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ActiveOrHistoricCurrencyAndAmount.java
1
请完成以下Java代码
public int getLoadCount() { return loadCount; } public final String getTrxName() { return _trxName; } public final String setTrxName(final String trxName) { final String trxNameOld = _trxName; _trxName = trxName; return trxNameOld; } public final boolean isOldValues() { return useOldValues; } public static final boolean isOldValues(final Object model) { return getWrapper(model).isOldValues(); } public Evaluatee2 asEvaluatee() { return new Evaluatee2() { @Override public String get_ValueAsString(final String variableName) { if (!has_Variable(variableName)) { return ""; } final Object value = POJOWrapper.this.getValuesMap().get(variableName); return value == null ? "" : value.toString(); } @Override public boolean has_Variable(final String variableName) { return POJOWrapper.this.hasColumnName(variableName); } @Override public String get_ValueOldAsString(final String variableName) { throw new UnsupportedOperationException("not implemented");
} }; } public IModelInternalAccessor getModelInternalAccessor() { if (_modelInternalAccessor == null) { _modelInternalAccessor = new POJOModelInternalAccessor(this); } return _modelInternalAccessor; } POJOModelInternalAccessor _modelInternalAccessor = null; public static IModelInternalAccessor getModelInternalAccessor(final Object model) { final POJOWrapper wrapper = getWrapper(model); if (wrapper == null) { return null; } return wrapper.getModelInternalAccessor(); } public boolean isProcessed() { return hasColumnName("Processed") ? StringUtils.toBoolean(getValue("Processed", Object.class)) : false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOWrapper.java
1
请完成以下Java代码
public RequestTypeId retrieveOrgChangeRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_OrgSwitch); } @Override public RequestTypeId retrieveBPartnerCreatedFromAnotherOrgRequestTypeId() { return retrieveRequestTypeIdByInternalName(InternalName_C_BPartner_CreatedFromAnotherOrg); } @Override public RequestTypeId retrieveRequestTypeIdByInternalName(final String internalName) { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_InternalName, internalName) .create() .firstIdOnly(RequestTypeId::ofRepoIdOrNull); // covered by unique index if (requestTypeId == null) { throw new AdempiereException("@NotFound@ @R_RequestType_ID@ (@InternalName@: " + internalName); } return requestTypeId; } @Override public RequestTypeId retrieveDefaultRequestTypeIdOrFirstActive() { return Optionals.firstPresentOfSuppliers( this::retrieveDefaultRequestTypeId, this::retrieveFirstActiveRequestTypeId) .orElseThrow(() -> new AdempiereException("@NotFound@ @R_RequestType_ID@").markAsUserValidationError()); } private Optional<RequestTypeId> retrieveDefaultRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_R_RequestType.COLUMNNAME_IsDefault, true) .create()
.firstIdOnly(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } private Optional<RequestTypeId> retrieveFirstActiveRequestTypeId() { final RequestTypeId requestTypeId = queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addOnlyActiveRecordsFilter() .orderBy(I_R_RequestType.COLUMNNAME_R_RequestType_ID) .create() .firstId(RequestTypeId::ofRepoIdOrNull); return Optional.ofNullable(requestTypeId); } @Override public I_R_RequestType getById(@NonNull final RequestTypeId requestTypeId) { return queryBL.createQueryBuilderOutOfTrx(I_R_RequestType.class) .addEqualsFilter(I_R_RequestType.COLUMNNAME_R_RequestType_ID, requestTypeId) .create() .firstOnlyNotNull(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\request\api\impl\RequestTypeDAO.java
1
请在Spring Boot框架中完成以下Java代码
public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "oneEvent") public String getKey() { return key; } public void setKey(String key) { this.key = key; } @ApiModelProperty(example = "1") public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } @ApiModelProperty(example = "The One Event") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "2") public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2") public String getDeploymentUrl() { return deploymentUrl; } public void setDeploymentUrl(String deploymentUrl) { this.deploymentUrl = deploymentUrl; } @ApiModelProperty(example = "Examples") public String getCategory() { return category; } public void setCategory(String category) {
this.category = category; } @ApiModelProperty(example = "oneEvent.event") public String getResourceName() { return resourceName; } public void setResourceName(String resourceName) { this.resourceName = resourceName; } public void setResource(String resource) { this.resource = resource; } @ApiModelProperty(example = "http://localhost:8182/event-registry-repository/deployments/2/resources/oneEvent.event", value = "Contains the actual deployed event definition JSON.") public String getResource() { return resource; } @ApiModelProperty(example = "This is an event definition for testing purposes") public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\EventDefinitionResponse.java
2
请完成以下Java代码
public I_C_OrderLine getCreated_OrderLine() { return get_ValueAsPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class); } @Override public void setCreated_OrderLine(final I_C_OrderLine Created_OrderLine) { set_ValueFromPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class, Created_OrderLine); } @Override public void setCreated_OrderLine_ID (final int Created_OrderLine_ID) { if (Created_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, Created_OrderLine_ID); } @Override public int getCreated_OrderLine_ID() { return get_ValueAsInt(COLUMNNAME_Created_OrderLine_ID); } @Override public void setIsSOTrx (final boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx()
{ return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public I_M_CostElement getM_CostElement() { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class); } @Override public void setM_CostElement(final I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement); } @Override public void setM_CostElement_ID (final int M_CostElement_ID) { if (M_CostElement_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID); } @Override public int getM_CostElement_ID() { return get_ValueAsInt(COLUMNNAME_M_CostElement_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost.java
1
请在Spring Boot框架中完成以下Java代码
public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static Map<String, Map<String, Object>> toMap() { CardTypeEnum[] ary = CardTypeEnum.values(); Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>(); for (int num = 0; num < ary.length; num++) { Map<String, Object> map = new HashMap<String, Object>(); String key = ary[num].name(); map.put("desc", ary[num].getDesc()); map.put("name", ary[num].name()); enumMap.put(key, map); } return enumMap; } @SuppressWarnings({ "rawtypes", "unchecked" }) public static List toList() { CardTypeEnum[] ary = CardTypeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); list.add(map); } return list;
} public static CardTypeEnum getEnum(String enumName) { CardTypeEnum resultEnum = null; CardTypeEnum[] enumAry = CardTypeEnum.values(); for (int i = 0; i < enumAry.length; i++) { if (enumAry[i].name().equals(enumName)) { resultEnum = enumAry[i]; break; } } return resultEnum; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\CardTypeEnum.java
2
请完成以下Java代码
public <T extends ReferenceListAwareEnum> T getParameterValueAsRefListOrNull(@NonNull final String parameterName, @NonNull final Function<String, T> mapper) { final DocumentFilterParam param = getParameterOrNull(parameterName); if (param == null) { return null; } return param.getValueAsRefListOrNull(mapper); } @Nullable public <T> T getParameterValueAs(@NonNull final String parameterName) { final DocumentFilterParam param = getParameterOrNull(parameterName); if (param == null) { return null; } @SuppressWarnings("unchecked") final T value = (T)param.getValue(); return value; } // // // // // public static final class DocumentFilterBuilder { public DocumentFilterBuilder setFilterId(final String filterId) { return filterId(filterId); } public DocumentFilterBuilder setCaption(@NonNull final ITranslatableString caption) { return caption(caption); } public DocumentFilterBuilder setCaption(@NonNull final String caption) { return caption(TranslatableStrings.constant(caption)); }
public DocumentFilterBuilder setFacetFilter(final boolean facetFilter) { return facetFilter(facetFilter); } public boolean hasParameters() { return !Check.isEmpty(parameters) || !Check.isEmpty(internalParameterNames); } public DocumentFilterBuilder setParameters(@NonNull final List<DocumentFilterParam> parameters) { return parameters(parameters); } public DocumentFilterBuilder addParameter(@NonNull final DocumentFilterParam parameter) { return parameter(parameter); } public DocumentFilterBuilder addInternalParameter(@NonNull final DocumentFilterParam parameter) { parameter(parameter); internalParameterName(parameter.getFieldName()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilter.java
1
请完成以下Java代码
public int getM_AttributeSet_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID); } @Override public void setM_PricingSystem_ID (final int M_PricingSystem_ID) { if (M_PricingSystem_ID < 1) set_Value (COLUMNNAME_M_PricingSystem_ID, null); else set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID); } @Override public int getM_PricingSystem_ID() { return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } @Override public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setName (final java.lang.String Name) {
set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * PaymentRule AD_Reference_ID=195 * Reference name: _Payment Rule */ public static final int PAYMENTRULE_AD_Reference_ID=195; /** Cash = B */ public static final String PAYMENTRULE_Cash = "B"; /** CreditCard = K */ public static final String PAYMENTRULE_CreditCard = "K"; /** DirectDeposit = T */ public static final String PAYMENTRULE_DirectDeposit = "T"; /** Check = S */ public static final String PAYMENTRULE_Check = "S"; /** OnCredit = P */ public static final String PAYMENTRULE_OnCredit = "P"; /** DirectDebit = D */ public static final String PAYMENTRULE_DirectDebit = "D"; /** Mixed = M */ public static final String PAYMENTRULE_Mixed = "M"; /** PayPal = L */ public static final String PAYMENTRULE_PayPal = "L"; /** Rückerstattung = E */ public static final String PAYMENTRULE_Reimbursement = "E"; /** Verrechnung = F */ public static final String PAYMENTRULE_Settlement = "F"; @Override public void setPaymentRule (final java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } @Override public java.lang.String getPaymentRule() { return get_ValueAsString(COLUMNNAME_PaymentRule); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandProcessor.java
1
请完成以下Java代码
public void deactivateLineQtys(final I_C_RfQResponseLine responseLine) { if (!responseLine.isActive()) { final IRfqDAO rfqDAO = Services.get(IRfqDAO.class); for (final I_C_RfQResponseLineQty qty : rfqDAO.retrieveResponseQtys(responseLine)) { if (qty.isActive()) { qty.setIsActive(false); InterfaceWrapperHelper.save(qty); } } } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void preventDeleteIfThereAreReportedQuantities(final I_C_RfQResponseLine rfqResponseLine) { if(rfqResponseLine.getPrice().signum() != 0) { throw new RfQResponseLineHasReportedPriceException(rfqResponseLine); } final IRfqDAO rfqDAO = Services.get(IRfqDAO.class); if (rfqDAO.hasResponseQtys(rfqResponseLine)) { throw new RfQResponseLineHasReportedQtysException(rfqResponseLine); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\model\interceptor\C_RfQResponseLine.java
1
请在Spring Boot框架中完成以下Java代码
public class Document { @XmlElement(name = "Xlief4h", required = true) protected List<Xlief4H> xlief4H; /** * Gets the value of the xlief4H property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the xlief4H property. * * <p> * For example, to add a new item, do as follows: * <pre> * getXlief4H().add(newItem); * </pre> *
* * <p> * Objects of the following type(s) are allowed in the list * {@link Xlief4H } * * */ public List<Xlief4H> getXlief4H() { if (xlief4H == null) { xlief4H = new ArrayList<Xlief4H>(); } return this.xlief4H; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\Document.java
2
请完成以下Java代码
public static Rabbit createRabbitUsingClassForName() throws InstantiationException, IllegalAccessException, ClassNotFoundException { Rabbit rabbit = (Rabbit) Class.forName("com.baeldung.objectcreation.objects.Rabbit").newInstance(); return rabbit; } public static Rabbit createRabbitUsingClassNewInstance() throws InstantiationException, IllegalAccessException { Rabbit rabbit = Rabbit.class.newInstance(); return rabbit; } public static Rabbit createRabbitUsingConstructorNewInstance() throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException { Rabbit rabbit = Rabbit.class.getConstructor().newInstance(); return rabbit; } public static ClonableRabbit createRabbitUsingClone(ClonableRabbit originalRabbit) throws CloneNotSupportedException { ClonableRabbit clonedRabbit = (ClonableRabbit) originalRabbit.clone(); return clonedRabbit; } public static SerializableRabbit createRabbitUsingDeserialization(File file) throws IOException, ClassNotFoundException { try (FileInputStream fis = new FileInputStream(file); ObjectInputStream ois = new ObjectInputStream(fis);) {
return (SerializableRabbit) ois.readObject(); } } public static Rabbit createRabbitUsingSupplier() { Supplier<Rabbit> rabbitSupplier = Rabbit::new; Rabbit rabbit = rabbitSupplier.get(); return rabbit; } public static Rabbit[] createRabbitArray() { Rabbit[] rabbitArray = new Rabbit[10]; return rabbitArray; } public static RabbitType createRabbitTypeEnum() { return RabbitType.PET; //any RabbitType could be returned here, PET is just an example. } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-constructors-2\src\main\java\com\baeldung\objectcreation\utils\CreateRabbits.java
1
请在Spring Boot框架中完成以下Java代码
public class SecondJpaConfig { static final String REPOSITORY_PACKAGE = "com.xkcoding.multi.datasource.jpa.repository.second"; private static final String ENTITY_PACKAGE = "com.xkcoding.multi.datasource.jpa.entity.second"; /** * 扫描spring.jpa.second开头的配置信息 * * @return jpa配置信息 */ @Bean(name = "secondJpaProperties") @ConfigurationProperties(prefix = "spring.jpa.second") public JpaProperties jpaProperties() { return new JpaProperties(); } /** * 获取主库实体管理工厂对象 * * @param secondDataSource 注入名为secondDataSource的数据源 * @param jpaProperties 注入名为secondJpaProperties的jpa配置信息 * @param builder 注入EntityManagerFactoryBuilder * @return 实体管理工厂对象 */ @Bean(name = "secondEntityManagerFactory") public LocalContainerEntityManagerFactoryBean entityManagerFactory(@Qualifier("secondDataSource") DataSource secondDataSource, @Qualifier("secondJpaProperties") JpaProperties jpaProperties, EntityManagerFactoryBuilder builder) { return builder // 设置数据源 .dataSource(secondDataSource) // 设置jpa配置 .properties(jpaProperties.getProperties()) // 设置实体包名 .packages(ENTITY_PACKAGE)
// 设置持久化单元名,用于@PersistenceContext注解获取EntityManager时指定数据源 .persistenceUnit("secondPersistenceUnit").build(); } /** * 获取实体管理对象 * * @param factory 注入名为secondEntityManagerFactory的bean * @return 实体管理对象 */ @Bean(name = "secondEntityManager") public EntityManager entityManager(@Qualifier("secondEntityManagerFactory") EntityManagerFactory factory) { return factory.createEntityManager(); } /** * 获取主库事务管理对象 * * @param factory 注入名为secondEntityManagerFactory的bean * @return 事务管理对象 */ @Bean(name = "secondTransactionManager") public PlatformTransactionManager transactionManager(@Qualifier("secondEntityManagerFactory") EntityManagerFactory factory) { return new JpaTransactionManager(factory); } }
repos\spring-boot-demo-master\demo-multi-datasource-jpa\src\main\java\com\xkcoding\multi\datasource\jpa\config\SecondJpaConfig.java
2
请在Spring Boot框架中完成以下Java代码
public SentinelResourceAspect sentinelResourceAspect() { return new SentinelResourceAspect(); } @PostConstruct public void init() { initFlowRules(); initDegradeRules(); initSystemProtectionRules(); } private void initFlowRules() { List<FlowRule> flowRules = new ArrayList<>(); FlowRule flowRule = new FlowRule(); // Defined resource flowRule.setResource(RESOURCE_NAME); flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS); // number of requests that QPS can pass in a second flowRule.setCount(1); flowRules.add(flowRule); FlowRuleManager.loadRules(flowRules); } private void initDegradeRules() { List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule(); rule.setResource(RESOURCE_NAME); rule.setCount(10); rule.setTimeWindow(10); rules.add(rule); DegradeRuleManager.loadRules(rules); } private void initSystemProtectionRules() { List<SystemRule> rules = new ArrayList<>(); SystemRule rule = new SystemRule(); rule.setHighestSystemLoad(10); rules.add(rule); SystemRuleManager.loadRules(rules); } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-sentinel\src\main\java\com\baeldung\spring\cloud\sentinel\config\SentinelAspectConfiguration.java
2
请完成以下Java代码
public void addedChild(Resource child) { } @Override public void removedChild(Resource child) { } @Override public void addedObserveRelation(ObserveRelation relation) { Request request = relation.getExchange().getRequest(); String token = getTokenFromRequest(request); clients.registerObserveRelation(token, relation); log.trace("Added Observe relation for token: {}", token); } @Override public void removedObserveRelation(ObserveRelation relation) { Request request = relation.getExchange().getRequest(); String token = getTokenFromRequest(request); clients.deregisterObserveRelation(token); log.trace("Relation removed for token: {}", token); } } private TbCoapDtlsSessionInfo getCoapDtlsSessionInfo(EndpointContext endpointContext) { InetSocketAddress peerAddress = endpointContext.getPeerAddress(); String certPemStr = getCertPem(endpointContext); TbCoapDtlsSessionKey tbCoapDtlsSessionKey = StringUtils.isNotBlank(certPemStr) ? new TbCoapDtlsSessionKey(peerAddress, certPemStr) : null; TbCoapDtlsSessionInfo tbCoapDtlsSessionInfo; if (tbCoapDtlsSessionKey != null) { tbCoapDtlsSessionInfo = dtlsSessionsMap .computeIfPresent(tbCoapDtlsSessionKey, (dtlsSessionIdStr, dtlsSessionInfo) -> { dtlsSessionInfo.setLastActivityTime(System.currentTimeMillis());
return dtlsSessionInfo; }); } else { tbCoapDtlsSessionInfo = null; } return tbCoapDtlsSessionInfo; } private String getCertPem(EndpointContext endpointContext) { try { X509CertPath certPath = (X509CertPath) endpointContext.getPeerIdentity(); X509Certificate x509Certificate = (X509Certificate) certPath.getPath().getCertificates().get(0); return Base64.getEncoder().encodeToString(x509Certificate.getEncoded()); } catch (Exception e) { log.error("Failed to get cert PEM: [{}]", endpointContext.getPeerAddress(), e); return null; } } }
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\CoapTransportResource.java
1
请在Spring Boot框架中完成以下Java代码
public final class DataWebAutoConfiguration { private final DataWebProperties properties; DataWebAutoConfiguration(DataWebProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean PageableHandlerMethodArgumentResolverCustomizer pageableCustomizer() { return (resolver) -> { Pageable pageable = this.properties.getPageable(); resolver.setPageParameterName(pageable.getPageParameter()); resolver.setSizeParameterName(pageable.getSizeParameter()); resolver.setOneIndexedParameters(pageable.isOneIndexedParameters()); resolver.setPrefix(pageable.getPrefix()); resolver.setQualifierDelimiter(pageable.getQualifierDelimiter()); resolver.setFallbackPageable(PageRequest.of(0, pageable.getDefaultPageSize())); resolver.setMaxPageSize(pageable.getMaxPageSize());
}; } @Bean @ConditionalOnMissingBean SortHandlerMethodArgumentResolverCustomizer sortCustomizer() { return (resolver) -> resolver.setSortParameter(this.properties.getSort().getSortParameter()); } @Bean @ConditionalOnMissingBean SpringDataWebSettings springDataWebSettings() { return new SpringDataWebSettings(this.properties.getPageable().getSerializationMode()); } }
repos\spring-boot-4.0.1\module\spring-boot-data-commons\src\main\java\org\springframework\boot\data\autoconfigure\web\DataWebAutoConfiguration.java
2
请完成以下Java代码
public class PersonRequest { private int id; private String firstName; private String lastName; private int age; private String address; public static void main(String[] args) { PersonRequest personRequest = new PersonRequest(); personRequest.setId(1); personRequest.setFirstName("John"); personRequest.setLastName("Doe"); personRequest.setAge(30); personRequest.setAddress("United States"); System.out.println(personRequest); } public String toString() { final Gson gson = new GsonBuilder().setPrettyPrinting().create(); return gson.toJson(this); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; }
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
repos\tutorials-master\aws-modules\aws-lambda-modules\lambda-function\src\main\java\com\baeldung\lambda\dynamodb\bean\PersonRequest.java
1
请完成以下Java代码
private PartyIdentificationSEPA3 convertPartyIdentificationSEPA3(@NonNull final I_SEPA_Export sepaHeader) { final PartyIdentificationSEPA3 partyIdCopy = new PartyIdentificationSEPA3(); final PartySEPA2 partySEPA = new PartySEPA2(); partyIdCopy.setId(partySEPA); final PersonIdentificationSEPA2 prvtId = new PersonIdentificationSEPA2(); partySEPA.setPrvtId(prvtId); final RestrictedPersonIdentificationSEPA othr = new RestrictedPersonIdentificationSEPA(); prvtId.setOthr(othr); final RestrictedPersonIdentificationSchemeNameSEPA schemeNm = new RestrictedPersonIdentificationSchemeNameSEPA(); othr.setId(sepaHeader.getSEPA_CreditorIdentifier()); // it's not mandatory, but we made sure that it was set for SEPA_Exports with this protocol othr.setSchmeNm(schemeNm); schemeNm.setPrtry(IdentificationSchemeNameSEPA.valueOf("SEPA")); // NOTE: address is not mandatory // FIXME: copy address if exists return partyIdCopy; }
private String getSEPA_MandateRefNo(final I_SEPA_Export_Line line) { return CoalesceUtil.coalesceSuppliers( () -> line.getSEPA_MandateRefNo(), () -> getBPartnerValueById(line.getC_BPartner_ID()) + "-1"); } private String getBPartnerValueById(final int bpartnerRepoId) { return bpartnerService.getBPartnerValue(BPartnerId.ofRepoIdOrNull(bpartnerRepoId)).trim(); } private String getBPartnerNameById(final int bpartnerRepoId) { return bpartnerService.getBPartnerName(BPartnerId.ofRepoIdOrNull(bpartnerRepoId)).trim(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\sepamarshaller\impl\SEPACustomerDirectDebitMarshaler_Pain_008_003_02.java
1
请在Spring Boot框架中完成以下Java代码
public class BPartnerAttribute { private static final Interner<BPartnerAttribute> interner = Interners.newStrongInterner(); @NonNull String code; private BPartnerAttribute(@NonNull final String code) { this.code = code; } public static BPartnerAttribute ofCode(@NonNull final String code) { final BPartnerAttribute attribute = ofNullableCode(code); if (attribute == null) { throw new AdempiereException("Invalid code: `" + code + "`"); } return attribute; } @JsonCreator @Nullable public static BPartnerAttribute ofNullableCode(@Nullable final String code) { final String codeNorm = StringUtils.trimBlankToNull(code); return codeNorm != null ? interner.intern(new BPartnerAttribute(code))
: null; } @Override @Deprecated public String toString() { return getCode(); } @JsonValue public @NonNull String getCode() { return code; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\attributes\BPartnerAttribute.java
2
请完成以下Java代码
public void setIsRentalEquipment (final boolean IsRentalEquipment) { set_Value (COLUMNNAME_IsRentalEquipment, IsRentalEquipment); } @Override public boolean isRentalEquipment() { return get_ValueAsBoolean(COLUMNNAME_IsRentalEquipment); } @Override public void setSalesLineId (final @Nullable String SalesLineId) { set_Value (COLUMNNAME_SalesLineId, SalesLineId); } @Override public String getSalesLineId() { return get_ValueAsString(COLUMNNAME_SalesLineId); } @Override public void setTimePeriod (final @Nullable BigDecimal TimePeriod) { set_Value (COLUMNNAME_TimePeriod, TimePeriod); } @Override public BigDecimal getTimePeriod() {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TimePeriod); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUnit (final @Nullable String Unit) { set_Value (COLUMNNAME_Unit, Unit); } @Override public String getUnit() { return get_ValueAsString(COLUMNNAME_Unit); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_OrderedArticleLine.java
1
请在Spring Boot框架中完成以下Java代码
public Page<Map<String, Object>> queryHitByPage(int pageNo,int pageSize, String keyword, String indexName, String... fieldNames) { // 构造查询条件,使用标准分词器. QueryBuilder matchQuery = createQueryBuilder(keyword,fieldNames); // 设置高亮,使用默认的highlighter高亮器 HighlightBuilder highlightBuilder = createHighlightBuilder(fieldNames); // 设置查询字段 SearchResponse response = elasticsearchTemplate.getClient().prepareSearch(indexName) .setQuery(matchQuery) .highlighter(highlightBuilder) .setFrom((pageNo-1) * pageSize) .setSize(pageNo * pageSize) // 设置一次返回的文档数量,最大值:10000 .get(); // 返回搜索结果 SearchHits hits = response.getHits(); Long totalCount = hits.getTotalHits(); Page<Map<String, Object>> page = new Page<>(pageNo,pageSize,totalCount.intValue()); page.setList(getHitList(hits)); return page; } /** * 构造查询条件 * @auther: zhoudong * @date: 2018/12/18 10:42 */ private QueryBuilder createQueryBuilder(String keyword, String... fieldNames){ // 构造查询条件,使用标准分词器. return QueryBuilders.multiMatchQuery(keyword,fieldNames) // matchQuery(),单字段搜索 .analyzer("ik_max_word") .operator(Operator.OR); } /** * 构造高亮器 * @auther: zhoudong * @date: 2018/12/18 10:44 */ private HighlightBuilder createHighlightBuilder(String... fieldNames){ // 设置高亮,使用默认的highlighter高亮器 HighlightBuilder highlightBuilder = new HighlightBuilder() // .field("productName") .preTags("<span style='color:red'>") .postTags("</span>");
// 设置高亮字段 for (String fieldName: fieldNames) highlightBuilder.field(fieldName); return highlightBuilder; } /** * 处理高亮结果 * @auther: zhoudong * @date: 2018/12/18 10:48 */ private List<Map<String,Object>> getHitList(SearchHits hits){ List<Map<String,Object>> list = new ArrayList<>(); Map<String,Object> map; for(SearchHit searchHit : hits){ map = new HashMap<>(); // 处理源数据 map.put("source",searchHit.getSourceAsMap()); // 处理高亮数据 Map<String,Object> hitMap = new HashMap<>(); searchHit.getHighlightFields().forEach((k,v) -> { String hight = ""; for(Text text : v.getFragments()) hight += text.string(); hitMap.put(v.getName(),hight); }); map.put("highlight",hitMap); list.add(map); } return list; } @Override public void deleteIndex(String indexName) { elasticsearchTemplate.deleteIndex(indexName); } }
repos\springboot-demo-master\elasticsearch\src\main\java\demo\et59\elaticsearch\service\impl\BaseSearchServiceImpl.java
2
请完成以下Java代码
public int getValue() { return value; } public int setValue(int v) { int value = getLeafValue(v); setBase(currentBase + UNUSED_CHAR_VALUE, value); this.value = v; return v; } @Override public boolean hasNext() { return index < size; } @Override public KeyValuePair next() { if (index >= size) { throw new NoSuchElementException(); } else if (index == 0) { } else { while (path.size() > 0) { int charPoint = path.pop(); int base = path.getLast(); int n = getNext(base, charPoint); if (n != -1) break; path.removeLast(); } } ++index; return this; } @Override public void remove() { throw new UnsupportedOperationException(); } /** * 遍历下一个终止路径 * * @param parent 父节点 * @param charPoint 子节点的char * @return */ private int getNext(int parent, int charPoint) { int startChar = charPoint + 1; int baseParent = getBase(parent); int from = parent; for (int i = startChar; i < charMap.getCharsetSize(); i++) { int to = baseParent + i;
if (check.size() > to && check.get(to) == from) { path.append(i); from = to; path.append(from); baseParent = base.get(from); if (getCheck(baseParent + UNUSED_CHAR_VALUE) == from) { value = getLeafValue(getBase(baseParent + UNUSED_CHAR_VALUE)); int[] ids = new int[path.size() / 2]; for (int k = 0, j = 1; j < path.size(); ++k, j += 2) { ids[k] = path.get(j); } key = charMap.toString(ids); path.append(UNUSED_CHAR_VALUE); currentBase = baseParent; return from; } else { return getNext(from, 0); } } } return -1; } @Override public String toString() { return key + '=' + value; } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrieInteger.java
1
请在Spring Boot框架中完成以下Java代码
static MethodInterceptor jsr250AuthorizationMethodInterceptor( ObjectProvider<Jsr250MethodSecurityConfiguration> _jsr250MethodSecurityConfiguration) { Supplier<AuthorizationManagerBeforeMethodInterceptor> supplier = () -> { Jsr250MethodSecurityConfiguration configuration = _jsr250MethodSecurityConfiguration.getObject(); return configuration.methodInterceptor; }; return new DeferringMethodInterceptor<>(pointcut, supplier); } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize(); this.methodInterceptor.setOrder(this.methodInterceptor.getOrder() + annotation.offset()); } @Autowired(required = false) void setGrantedAuthorityDefaults(GrantedAuthorityDefaults defaults) { this.authorizationManager.setRolePrefix(defaults.getRolePrefix()); }
@Autowired(required = false) void setRoleHierarchy(RoleHierarchy roleHierarchy) { AuthoritiesAuthorizationManager authoritiesAuthorizationManager = new AuthoritiesAuthorizationManager(); authoritiesAuthorizationManager.setRoleHierarchy(roleHierarchy); this.authorizationManager.setAuthoritiesAuthorizationManager(authoritiesAuthorizationManager); } @Autowired(required = false) void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) { this.methodInterceptor.setSecurityContextHolderStrategy(securityContextHolderStrategy); } @Autowired(required = false) void setEventPublisher(AuthorizationEventPublisher eventPublisher) { this.methodInterceptor.setAuthorizationEventPublisher(eventPublisher); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\Jsr250MethodSecurityConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class ReconciliationEntityVo { /** 对账批次号 **/ private String accountCheckBatchNo; /** 账单日期 **/ private Date billDate; /** 银行类型 WEIXIN ALIPAY **/ private String bankType; /** 下单时间 **/ private Date orderTime; /** 银行交易时间 **/ private Date bankTradeTime; /** 银行订单号 **/ private String bankOrderNo; /** 银行流水号 **/ private String bankTrxNo; /** 银行交易状态 **/ private String bankTradeStatus; /** 银行交易金额 **/ private BigDecimal bankAmount; /** 银行退款金额 **/ private BigDecimal bankRefundAmount; /** 银行手续费 **/ private BigDecimal bankFee; public String getAccountCheckBatchNo() { return accountCheckBatchNo; } public void setAccountCheckBatchNo(String accountCheckBatchNo) { this.accountCheckBatchNo = accountCheckBatchNo; } public Date getBillDate() { return billDate; } public void setBillDate(Date billDate) { this.billDate = billDate; } public String getBankType() { return bankType; } public void setBankType(String bankType) { this.bankType = bankType; } public Date getOrderTime() { return orderTime; } public void setOrderTime(Date orderTime) { this.orderTime = orderTime; } public Date getBankTradeTime() { return bankTradeTime; } public void setBankTradeTime(Date bankTradeTime) { this.bankTradeTime = bankTradeTime; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } public String getBankTrxNo() { return bankTrxNo; }
public void setBankTrxNo(String bankTrxNo) { this.bankTrxNo = bankTrxNo; } public String getBankTradeStatus() { return bankTradeStatus; } public void setBankTradeStatus(String bankTradeStatus) { this.bankTradeStatus = bankTradeStatus; } public BigDecimal getBankAmount() { return bankAmount; } public void setBankAmount(BigDecimal bankAmount) { this.bankAmount = bankAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\vo\ReconciliationEntityVo.java
2
请完成以下Java代码
public BPartnerCustomerAccounts getCustomerAccounts( @NonNull final BPartnerId bpartnerId, @NonNull final AcctSchemaId acctSchemaId) { final ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> map = customerAccountsCache.getOrLoad(bpartnerId, this::retrieveCustomerAccounts); final BPartnerCustomerAccounts accounts = map.get(acctSchemaId); if (accounts == null) { throw new AdempiereException("No customer accounts defined for " + bpartnerId + " and " + acctSchemaId); } return accounts; } private ImmutableMap<AcctSchemaId, BPartnerCustomerAccounts> retrieveCustomerAccounts(final BPartnerId bpartnerId) { return queryBL.createQueryBuilder(I_C_BP_Customer_Acct.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Customer_Acct.COLUMNNAME_C_BPartner_ID, bpartnerId)
.create() .stream() .map(BPartnerAccountsRepository::fromRecord) .collect(ImmutableMap.toImmutableMap(BPartnerCustomerAccounts::getAcctSchemaId, accts -> accts)); } @NonNull private static BPartnerCustomerAccounts fromRecord(@NonNull final I_C_BP_Customer_Acct record) { return BPartnerCustomerAccounts.builder() .acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID())) .C_Receivable_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Acct()), BPartnerCustomerAccountType.C_Receivable)) .C_Receivable_Services_Acct(Account.of(AccountId.ofRepoId(record.getC_Receivable_Services_Acct()), BPartnerCustomerAccountType.C_Receivable_Services)) .C_Prepayment_Acct(Account.of(AccountId.ofRepoId(record.getC_Prepayment_Acct()), BPartnerCustomerAccountType.C_Prepayment)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\BPartnerAccountsRepository.java
1
请完成以下Java代码
public void actionPerformed(ActionEvent e) { replaceChB_actionPerformed(e); } }); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 4; gbc.insets = new Insets(5, 10, 5, 10); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(chkReplace, gbc); txtReplace.setPreferredSize(new Dimension(300, 25)); txtReplace.setEnabled(false); gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 5; gbc.gridwidth = 2; gbc.fill = GridBagConstraints.HORIZONTAL; gbc.insets = new Insets(5, 10, 10, 10); gbc.anchor = GridBagConstraints.WEST; areaPanel.add(txtReplace, gbc); areaPanel.setBorder(BorderFactory.createEtchedBorder( Color.white, new Color(142, 142, 142))); this.getContentPane().add(areaPanel, BorderLayout.CENTER); // Initialize buttons cancelB.setMaximumSize(new Dimension(100, 26)); cancelB.setMinimumSize(new Dimension(100, 26)); cancelB.setPreferredSize(new Dimension(100, 26)); cancelB.setText(Local.getString("Cancel")); cancelB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { cancelB_actionPerformed(e); } }); okB.setMaximumSize(new Dimension(100, 26)); okB.setMinimumSize(new Dimension(100, 26)); okB.setPreferredSize(new Dimension(100, 26)); okB.setText(Local.getString("Find")); okB.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(ActionEvent e) { okB_actionPerformed(e); } });
this.getRootPane().setDefaultButton(okB); // build button-panel buttonsPanel.add(okB); buttonsPanel.add(cancelB); getContentPane().add(buttonsPanel, BorderLayout.SOUTH); } void okB_actionPerformed(ActionEvent e) { this.dispose(); } void cancelB_actionPerformed(ActionEvent e) { CANCELLED = true; this.dispose(); } void replaceChB_actionPerformed(ActionEvent e) { txtReplace.setEnabled(chkReplace.isSelected()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\FindDialog.java
1
请完成以下Java代码
private Stream<AdArchive> streamArchivesForLogIds(final ImmutableList<DocOutboundLogId> logIds) { return docOutboundDAO.streamByIdsInOrder(logIds) .filter(I_C_Doc_Outbound_Log::isActive) .map(log -> getLastArchive(log).orElse(null)) .filter(Objects::nonNull); } @NonNull private Optional<AdArchive> getLastArchive(final I_C_Doc_Outbound_Log log) { return archiveBL.getLastArchive(TableRecordReference.ofReferenced(log)); } private void appendCurrentPdf(final PdfCopy targetPdf, final AdArchive currentLog, final Collection<ArchiveId> printedIds, final AtomicInteger errorCount) { PdfReader pdfReaderToAdd = null; try { pdfReaderToAdd = new PdfReader(currentLog.getArchiveStream());
for (int page = 0; page < pdfReaderToAdd.getNumberOfPages(); ) { targetPdf.addPage(targetPdf.getImportedPage(pdfReaderToAdd, ++page)); } targetPdf.freeReader(pdfReaderToAdd); } catch (final BadPdfFormatException | IOException e) { errorCount.incrementAndGet(); } finally { if (pdfReaderToAdd != null) { pdfReaderToAdd.close(); } printedIds.add(currentLog.getId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.webui\src\main\java\de\metas\archive\process\MassConcatenateOutboundPdfs.java
1
请完成以下Java代码
protected final void invalidateView() { final IView view = getView(); invalidateView(view.getViewId()); } protected final void invalidateParentView() { final IView view = getView(); final ViewId parentViewId = view.getParentViewId(); if (parentViewId != null) { invalidateView(parentViewId); } } protected final boolean isSingleSelectedRow() { return getSelectedRowIds().isSingleDocumentId(); } protected final DocumentIdsSelection getSelectedRowIds() { final ViewRowIdsSelection viewRowIdsSelection = Check.assumeNotNull(_viewRowIdsSelection, "View loaded"); return viewRowIdsSelection.getRowIds(); } protected final <ID extends RepoIdAware> ImmutableSet<ID> getSelectedIds(@NonNull final IntFunction<ID> idMapper, @NonNull final QueryLimit limit) { final DocumentIdsSelection selectedRowsIds = getSelectedRowIds(); if (selectedRowsIds.isAll()) { return streamSelectedRows() .limit(limit.toIntOr(Integer.MAX_VALUE)) .map(row -> row.getId().toId(idMapper)) .collect(ImmutableSet.toImmutableSet()); } else { return selectedRowsIds.toIdsFromInt(idMapper); } } @OverridingMethodsMustInvokeSuper protected IViewRow getSingleSelectedRow() {
final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); final DocumentId documentId = selectedRowIds.getSingleDocumentId(); return getView().getById(documentId); } @OverridingMethodsMustInvokeSuper protected Stream<? extends IViewRow> streamSelectedRows() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); return getView().streamByIds(selectedRowIds); } protected final ViewRowIdsSelection getParentViewRowIdsSelection() { return _parentViewRowIdsSelection; } protected final ViewRowIdsSelection getChildViewRowIdsSelection() { return _childViewRowIdsSelection; } @SuppressWarnings("SameParameterValue") protected final <T extends IView> T getChildView(@NonNull final Class<T> viewType) { final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection(); Check.assumeNotNull(childViewRowIdsSelection, "child view is set"); final IView childView = viewsRepo.getView(childViewRowIdsSelection.getViewId()); return viewType.cast(childView); } protected final DocumentIdsSelection getChildViewSelectedRowIds() { final ViewRowIdsSelection childViewRowIdsSelection = getChildViewRowIdsSelection(); return childViewRowIdsSelection != null ? childViewRowIdsSelection.getRowIds() : DocumentIdsSelection.EMPTY; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ViewBasedProcessTemplate.java
1
请完成以下Java代码
public int getM_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set MKTG_ContactPerson_Attribute. @param MKTG_ContactPerson_Attribute_ID MKTG_ContactPerson_Attribute */ @Override public void setMKTG_ContactPerson_Attribute_ID (int MKTG_ContactPerson_Attribute_ID) { if (MKTG_ContactPerson_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, Integer.valueOf(MKTG_ContactPerson_Attribute_ID)); } /** Get MKTG_ContactPerson_Attribute. @return MKTG_ContactPerson_Attribute */ @Override public int getMKTG_ContactPerson_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class); }
@Override public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson) { set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson); } /** Set MKTG_ContactPerson. @param MKTG_ContactPerson_ID MKTG_ContactPerson */ @Override public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID) { if (MKTG_ContactPerson_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID)); } /** Get MKTG_ContactPerson. @return MKTG_ContactPerson */ @Override public int getMKTG_ContactPerson_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public static class JsonInsertIntoImportTable { String fromResource; String toImportTableName; String importFormatName; DataImportConfigId dataImportConfigId; String duration; DataImportRunId dataImportRunId; int countTotalRows; int countValidRows; @JsonInclude(JsonInclude.Include.NON_EMPTY) List<JsonErrorItem> errors; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonInsertIntoImportTable insertIntoImportTable; @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonImportRecordsValidation { String importTableName; String duration; int countImportRecordsDeleted; int countErrors; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonImportRecordsValidation importRecordsValidation; @Value
@Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonActualImport { String importTableName; String targetTableName; int countImportRecordsConsidered; int countInsertsIntoTargetTable; int countUpdatesIntoTargetTable; @JsonInclude(JsonInclude.Include.NON_EMPTY) List<JsonErrorItem> errors; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonActualImport actualImport; @Value @Builder @JsonAutoDetect(fieldVisibility = Visibility.ANY, getterVisibility = Visibility.NONE, isGetterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE) public static class JsonActualImportAsync { int workpackageId; } @JsonInclude(JsonInclude.Include.NON_EMPTY) JsonActualImportAsync actualImportAsync; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\data_import\JsonDataImportResponse.java
2
请完成以下Java代码
public ResponseEntity<JsonResponseContact> retrieveContact( @ApiParam(required = true, value = CONTACT_IDENTIFIER_DOC) // @PathVariable("contactIdentifier") // @NonNull final String contactIdentifierStr) { final IdentifierString contactIdentifier = IdentifierString.of(contactIdentifierStr); final Optional<JsonResponseContact> contact = bpartnerEndpointService.retrieveContact(contactIdentifier); return toResponseEntity(contact); } @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved contact(s)"), @ApiResponse(code = 401, message = "You are not authorized to view the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden"), @ApiResponse(code = 404, message = "There is no page for the given 'next' value") }) @GetMapping public ResponseEntity<JsonResponseContactList> retrieveContactsSince( @ApiParam(value = SINCE_DOC, allowEmptyValue = true) // @RequestParam(name = "since", required = false) // @Nullable final Long epochTimestampMillis, @ApiParam(value = NEXT_DOC, allowEmptyValue = true) // @RequestParam(name = "next", required = false) // @Nullable final String next) { final Optional<JsonResponseContactList> list = bpartnerEndpointService.retrieveContactsSince(epochTimestampMillis, next); return toResponseEntity(list); } @ApiResponses(value = { @ApiResponse(code = 201, message = "Successfully created or updated contact"), @ApiResponse(code = 401, message = "You are not authorized to create or update the resource"), @ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden") }) @ApiOperation("Create of update a contact for a particular bpartner. If the contact exists, then the properties that are *not* specified are left untouched.") @PutMapping public ResponseEntity<JsonResponseUpsert> createOrUpdateContact( @RequestBody @NonNull final JsonRequestContactUpsert contacts) { final JsonResponseUpsertBuilder response = JsonResponseUpsert.builder(); final SyncAdvise syncAdvise = SyncAdvise.builder().ifExists(IfExists.UPDATE_MERGE).ifNotExists(IfNotExists.CREATE).build();
final JsonPersisterService persister = jsonServiceFactory.createPersister(); jsonRequestConsolidateService.consolidateWithIdentifier(contacts); for (final JsonRequestContactUpsertItem requestItem : contacts.getRequestItems()) { final JsonResponseUpsertItem responseItem = persister.persist( IdentifierString.of(requestItem.getContactIdentifier()), requestItem.getContact(), syncAdvise); response.responseItem(responseItem); } return new ResponseEntity<>(response.build(), HttpStatus.CREATED); } private static <T> ResponseEntity<T> toResponseEntity(@NonNull final Optional<T> optionalResult) { return optionalResult .map(ResponseEntity::ok) .orElseGet(() -> ResponseEntity.notFound().build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\bpartner\ContactRestController.java
1
请完成以下Java代码
public static List getWayList(String way) { PayTypeEnum[] ary = PayTypeEnum.values(); List list = new ArrayList(); for (int i = 0; i < ary.length; i++) { if(ary[i].way.equals(way)){ Map<String, String> map = new HashMap<String, String>(); map.put("desc", ary[i].getDesc()); map.put("name", ary[i].name()); list.add(map); } } return list; } /** * 取枚举的json字符串
* * @return */ public static String getJsonStr() { PayTypeEnum[] enums = PayTypeEnum.values(); StringBuffer jsonStr = new StringBuffer("["); for (PayTypeEnum senum : enums) { if (!"[".equals(jsonStr.toString())) { jsonStr.append(","); } jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}"); } jsonStr.append("]"); return jsonStr.toString(); } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\enums\PayTypeEnum.java
1
请完成以下Java代码
private Set<InvoiceCandidateId> voidAndReturnInvoiceCandIds(final I_C_Invoice invoice) { // NOTE: we have to separate voidAndReturnInvoiceCandIds and enqueueForInvoicing in 2 transactions because // InvoiceCandidateEnqueuer is calling updateSelectionBeforeEnqueueing in a new transaction (for some reason?!?) // and that is introducing a deadlock in case we are also changing C_Invoice_Candidate table here. trxManager.assertThreadInheritedTrxNotExists(); return trxManager.callInNewTrx(() -> invoiceCandBL.voidAndReturnInvoiceCandIds(invoice)); } private void enqueueForInvoicing(final Set<InvoiceCandidateId> invoiceCandIds, final @NonNull I_C_Async_Batch asyncBatch) { trxManager.assertThreadInheritedTrxNotExists(); invoiceCandBL.enqueueForInvoicing() .setContext(getCtx()) .setAsyncBatchId(AsyncBatchId.ofRepoId(asyncBatch.getC_Async_Batch_ID())) .setInvoicingParams(getIInvoicingParams()) .setFailIfNothingEnqueued(true) .enqueueInvoiceCandidateIds(invoiceCandIds); } @NonNull private Iterator<I_C_Invoice> retrieveSelection(@NonNull final PInstanceId pinstanceId) { return queryBL .createQueryBuilder(I_C_Invoice.class) .setOnlySelection(pinstanceId) .create() .iterate(I_C_Invoice.class); } private boolean canVoidPaidInvoice(@NonNull final I_C_Invoice invoice) { final I_C_Invoice inv = InterfaceWrapperHelper.create(invoice, I_C_Invoice.class); if (hasAnyNonPaymentAllocations(inv)) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .contentADMessage(MSG_SKIPPED_INVOICE_NON_PAYMENT_ALLOC_INVOLVED) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build(); notificationBL.send(userNotificationRequest); return false; } if (commissionTriggerService.isContainsCommissionTriggers(InvoiceId.ofRepoId(invoice.getC_Invoice_ID()))) { final UserNotificationRequest userNotificationRequest = UserNotificationRequest.builder() .contentADMessage(MSG_SKIPPED_INVOICE_DUE_TO_COMMISSION) .contentADMessageParam(inv.getDocumentNo()) .recipientUserId(Env.getLoggedUserId()) .build();
notificationBL.send(userNotificationRequest); return false; } return true; } @NonNull private IInvoicingParams getIInvoicingParams() { final PlainInvoicingParams invoicingParams = new PlainInvoicingParams(); invoicingParams.setUpdateLocationAndContactForInvoice(true); invoicingParams.setIgnoreInvoiceSchedule(false); return invoicingParams; } private boolean hasAnyNonPaymentAllocations(@NonNull final I_C_Invoice invoice) { final List<I_C_AllocationLine> availableAllocationLines = allocationDAO.retrieveAllocationLines(invoice); return availableAllocationLines.stream() .anyMatch(allocationLine -> allocationLine.getC_Payment_ID() <= 0); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\async\spi\impl\RecreateInvoiceWorkpackageProcessor.java
1
请完成以下Java代码
public void execute(Runnable runnable) { // 获取父线程MDC中的内容,必须在run方法之前,否则等异步线程执行的时候有可能MDC里面的值已经被清空了,这个时候就会返回null Map<String, String> context = MDC.getCopyOfContextMap(); super.execute(() -> run(runnable, context)); } /** * 子线程委托的执行方法 * * @param runnable {@link Runnable} * @param context 父线程MDC内容 */ private void run(Runnable runnable, Map<String, String> context) { // 将父线程的MDC内容传给子线程 if (context != null) {
try { MDC.setContextMap(context); } catch (Exception e) { logger.error(e.getMessage(), e); } } try { // 执行异步操作 runnable.run(); } finally { // 清空MDC内容 MDC.clear(); } } }
repos\spring-boot-student-master\spring-boot-student-log\src\main\java\com\xiaolyuh\utils\MdcThreadPoolTaskExecutor.java
1
请完成以下Java代码
public class RemoveElementFromAnArray { public int[] removeAnElementWithAGivenIndex(int[] array, int index) { return ArrayUtils.remove(array, index); } public int[] removeAllElementsWithGivenIndices(int[] array, int... indices) { return ArrayUtils.removeAll(array, indices); } public int[] removeFirstOccurrenceOfGivenElement(int[] array, int element) { return ArrayUtils.removeElement(array, element); } public int[] removeAllGivenElements(int[] array, int... elements) { return ArrayUtils.removeElements(array, elements); } public int[] removeLastElementUsingCopyOfMethod(int[] array) { return Arrays.copyOf(array, array.length - 1); }
public int[] removeLastElementUsingCopyOfRangeMethod(int[] array) { return Arrays.copyOfRange(array, 0, array.length - 1); } public int[] removeLastElementUsingArrayCopyMethod(int[] array, int[] resultArray) { System.arraycopy(array, 0, resultArray, 0, array.length-1); return resultArray; } public int[] removeLastElementUsingIntStreamRange(int[] array) { return IntStream.range(0, array.length - 1) .map(i -> array[i]) .toArray(); } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-basic-3\src\main\java\com\baeldung\array\remove\RemoveElementFromAnArray.java
1
请在Spring Boot框架中完成以下Java代码
public void persistTwoBooks() { Book ar = new Book(); ar.setIsbn("001-AR"); ar.setTitle("Ancient Rome"); ar.setPrice(25); Book rh = new Book(); rh.setIsbn("001-RH"); rh.setTitle("Rush Hour"); rh.setPrice(31); bookRepository.save(ar); bookRepository.save(rh); }
// cache List<Book> in "books" @Cacheable(cacheNames = "books") public List<Book> fetchBookByPrice() { List<Book> books = bookRepository.fetchByPrice(30); return books; } // evict cache "books" @CacheEvict(cacheNames="books", allEntries=true) public void deleteBooks() { bookRepository.deleteAllInBatch(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSpringCacheEhCacheKickoff\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setMKTG_Campaign_ID (int MKTG_Campaign_ID) { if (MKTG_Campaign_ID < 1) set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ID, null); else set_ValueNoCheck (COLUMNNAME_MKTG_Campaign_ID, Integer.valueOf(MKTG_Campaign_ID)); } /** Get MKTG_Campaign. @return MKTG_Campaign */ @Override public int getMKTG_Campaign_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Campaign_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.marketing.base.model.I_MKTG_Platform getMKTG_Platform() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class); } @Override public void setMKTG_Platform(de.metas.marketing.base.model.I_MKTG_Platform MKTG_Platform) { set_ValueFromPO(COLUMNNAME_MKTG_Platform_ID, de.metas.marketing.base.model.I_MKTG_Platform.class, MKTG_Platform); } /** Set MKTG_Platform. @param MKTG_Platform_ID MKTG_Platform */ @Override public void setMKTG_Platform_ID (int MKTG_Platform_ID) { if (MKTG_Platform_ID < 1) set_Value (COLUMNNAME_MKTG_Platform_ID, null); else set_Value (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID)); } /** Get MKTG_Platform. @return MKTG_Platform */ @Override public int getMKTG_Platform_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); }
/** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Externe Datensatz-ID. @param RemoteRecordId Externe Datensatz-ID */ @Override public void setRemoteRecordId (java.lang.String RemoteRecordId) { set_Value (COLUMNNAME_RemoteRecordId, RemoteRecordId); } /** Get Externe Datensatz-ID. @return Externe Datensatz-ID */ @Override public java.lang.String getRemoteRecordId () { return (java.lang.String)get_Value(COLUMNNAME_RemoteRecordId); } /** Set Anfangsdatum. @param StartDate First effective day (inclusive) */ @Override public void setStartDate (java.sql.Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Anfangsdatum. @return First effective day (inclusive) */ @Override public java.sql.Timestamp getStartDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Campaign.java
1
请完成以下Java代码
public final class AddHoursQueryFilterModifier implements IQueryFilterModifier { private static final String SQL_FUNC_AddHours = "addHours"; private final String hoursColumnSql; /** * * @param hoursColumn model column which contains the hours to add */ public AddHoursQueryFilterModifier(final String hoursColumnName) { Check.assumeNotEmpty(hoursColumnName, "hoursColumnName not empty"); this.hoursColumnSql = hoursColumnName; } public AddHoursQueryFilterModifier(@NonNull final ModelColumn<?, ?> hoursColumn) { this.hoursColumnSql = hoursColumn.getColumnName(); } @Override public @NonNull String getColumnSql(@NonNull String columnName) { final StringBuilder sb = new StringBuilder(); sb.append(SQL_FUNC_AddHours).append("("); sb.append(columnName); // Param 1: Date Column sb.append(", "); sb.append(hoursColumnSql); // Param 2: Hours Column sb.append(")"); return sb.toString(); } @Override public String getValueSql(Object value, List<Object> params) { return NullQueryFilterModifier.instance.getValueSql(value, params); } @Nullable @Override public Object convertValue(@Nullable final String columnName, @Nullable Object value, final @Nullable Object model) { // // Constant: don't change the value // because this is the second operand with which we are comparing...
if (columnName == null || columnName == COLUMNNAME_Constant) { return value; } // // ColumnName: add Hours to it else { final Date dateTime = toDate(value); if (dateTime == null) { return null; } final int hoursToAdd = getHours(model); return TimeUtil.addHours(dateTime, hoursToAdd); } } private int getHours(final Object model) { final Optional<Number> hours = InterfaceWrapperHelper.getValue(model, hoursColumnSql); if (!hours.isPresent()) { return 0; } return hours.get().intValue(); } private Date toDate(final Object value) { final Date date = (Date)value; return date; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\AddHoursQueryFilterModifier.java
1
请完成以下Java代码
public boolean isSOTrx() { final I_C_Invoice invoice = getInvoice(); return invoice.isSOTrx(); } @Override public I_C_Country getC_Country() { final I_C_Invoice invoice = getInvoice(); if (invoice.getC_BPartner_Location_ID() <= 0) { return null; } final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final I_C_BPartner_Location bPartnerLocationRecord = bpartnerDAO.getBPartnerLocationByIdEvenInactive(BPartnerLocationId.ofRepoId(invoice.getC_BPartner_ID(), invoice.getC_BPartner_Location_ID()));
return bPartnerLocationRecord.getC_Location().getC_Country(); } private I_C_Invoice getInvoice() { final I_C_Invoice invoice = invoiceLine.getC_Invoice(); if (invoice == null) { throw new AdempiereException("Invoice not set for" + invoiceLine); } return invoice; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\mm\attributes\countryattribute\impl\InvoiceLineCountryAware.java
1
请在Spring Boot框架中完成以下Java代码
public void customize(WebServiceTemplate webServiceTemplate) { webServiceTemplate.setCheckConnectionForFault(this.checkConnectionFault); } } /** * {@link WebServiceTemplateCustomizer} to set * {@link WebServiceTemplate#setCheckConnectionForError(boolean) * checkConnectionForError}. */ private static final class CheckConnectionForErrorCustomizer implements WebServiceTemplateCustomizer { private final boolean checkConnectionForError; private CheckConnectionForErrorCustomizer(boolean checkConnectionForError) { this.checkConnectionForError = checkConnectionForError; } @Override public void customize(WebServiceTemplate webServiceTemplate) { webServiceTemplate.setCheckConnectionForError(this.checkConnectionForError); } } /** * {@link WebServiceTemplateCustomizer} to set * {@link WebServiceTemplate#setFaultMessageResolver(FaultMessageResolver)
* faultMessageResolver}. */ private static final class FaultMessageResolverCustomizer implements WebServiceTemplateCustomizer { private final FaultMessageResolver faultMessageResolver; private FaultMessageResolverCustomizer(FaultMessageResolver faultMessageResolver) { this.faultMessageResolver = faultMessageResolver; } @Override public void customize(WebServiceTemplate webServiceTemplate) { webServiceTemplate.setFaultMessageResolver(this.faultMessageResolver); } } }
repos\spring-boot-4.0.1\module\spring-boot-webservices\src\main\java\org\springframework\boot\webservices\client\WebServiceTemplateBuilder.java
2
请完成以下Java代码
public String getDbHostname() { return getProperty(PROP_DB_SERVER, "localhost"); } public String getDbPort() { return getProperty(PROP_DB_PORT, "5432"); } public String getDbPassword() { return getProperty(PROP_DB_PASSWORD, // Default value is null because in case is not configured we shall use other auth methods IDatabase.PASSWORD_NA); } @Override public String toString()
{ final HashMap<Object, Object> result = new HashMap<>(properties); result.put(PROP_DB_PASSWORD, "******"); return result.toString(); } public DBConnectionSettings toDBConnectionSettings() { return DBConnectionSettings.builder() .dbHostname(getDbHostname()) .dbPort(getDbPort()) .dbName(getDbName()) .dbUser(getDbUser()) .dbPassword(getDbPassword()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\DBConnectionSettingProperties.java
1
请完成以下Java代码
public ProcessEngineException shellExecutionException(Throwable cause) { return new ProcessEngineException(exceptionMessage("034", "Could not execute shell command."), cause); } public void errorPropagationException(String activityId, Throwable cause) { logError("035", "Caught an exception while propagate error in activity with id '{}'", activityId, cause); } public void debugConcurrentScopeIsPruned(PvmExecutionImpl execution) { logDebug( "036", "Concurrent scope is pruned {}", execution); } public void debugCancelConcurrentScopeExecution(PvmExecutionImpl execution) { logDebug( "037", "Cancel concurrent scope execution {}", execution); } public void destroyConcurrentScopeExecution(PvmExecutionImpl execution) { logDebug( "038", "Destroy concurrent scope execution", execution); } public void completeNonScopeEventSubprocess() { logDebug( "039", "Destroy non-socpe event subprocess"); } public void endConcurrentExecutionInEventSubprocess() { logDebug( "040", "End concurrent execution in event subprocess"); } public ProcessEngineException missingDelegateVariableMappingParentClassException(String className, String delegateVarMapping) { return new ProcessEngineException( exceptionMessage("041", "Class '{}' doesn't implement '{}'.", className, delegateVarMapping)); } public ProcessEngineException missingBoundaryCatchEventError(String executionId, String errorCode, String errorMessage) { return new ProcessEngineException( exceptionMessage(
"042", "Execution with id '{}' throws an error event with errorCode '{}' and errorMessage '{}', but no error handler was defined. ", executionId, errorCode, errorMessage)); } public ProcessEngineException missingBoundaryCatchEventEscalation(String executionId, String escalationCode) { return new ProcessEngineException( exceptionMessage( "043", "Execution with id '{}' throws an escalation event with escalationCode '{}', but no escalation handler was defined. ", executionId, escalationCode)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnBehaviorLogger.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_CycleStep[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Cycle getC_Cycle() throws RuntimeException { return (I_C_Cycle)MTable.get(getCtx(), I_C_Cycle.Table_Name) .getPO(getC_Cycle_ID(), get_TrxName()); } /** Set Project Cycle. @param C_Cycle_ID Identifier for this Project Reporting Cycle */ public void setC_Cycle_ID (int C_Cycle_ID) { if (C_Cycle_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Cycle_ID, Integer.valueOf(C_Cycle_ID)); } /** Get Project Cycle. @return Identifier for this Project Reporting Cycle */ public int getC_Cycle_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Cycle_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Cycle Step. @param C_CycleStep_ID The step for this Cycle */ public void setC_CycleStep_ID (int C_CycleStep_ID) { if (C_CycleStep_ID < 1) set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null); else set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID)); } /** Get Cycle Step. @return The step for this Cycle */ public int getC_CycleStep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Relative Weight.
@param RelativeWeight Relative weight of this step (0 = ignored) */ public void setRelativeWeight (BigDecimal RelativeWeight) { set_Value (COLUMNNAME_RelativeWeight, RelativeWeight); } /** Get Relative Weight. @return Relative weight of this step (0 = ignored) */ public BigDecimal getRelativeWeight () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativeWeight); if (bd == null) return Env.ZERO; return bd; } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CycleStep.java
1
请完成以下Java代码
public void setIp(String ip) { this.ip = ip; } @Override public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public String getLimitApp() { return limitApp; } public void setLimitApp(String limitApp) {
this.limitApp = limitApp; } public String getResource() { return resource; } public void setResource(String resource) { this.resource = resource; } @Override public Rule toRule() { ParamFlowRule rule = new ParamFlowRule(); return rule; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\entity\ParamFlowRuleCorrectEntity.java
1
请完成以下Java代码
public final C_AllocationLine_Builder paymentId(@Nullable final PaymentId paymentId) { return paymentId(PaymentId.toRepoId(paymentId)); } public final C_AllocationLine_Builder paymentId(final int paymentId) { allocLine.setC_Payment_ID(paymentId); return this; } public final C_AllocationLine_Builder amount(final BigDecimal amt) { allocLine.setAmount(amt); return this; } public final C_AllocationLine_Builder discountAmt(final BigDecimal discountAmt) { allocLine.setDiscountAmt(discountAmt); return this; } public final C_AllocationLine_Builder writeOffAmt(final BigDecimal writeOffAmt) { allocLine.setWriteOffAmt(writeOffAmt); return this; } public final C_AllocationLine_Builder overUnderAmt(final BigDecimal overUnderAmt) { allocLine.setOverUnderAmt(overUnderAmt); return this; } public C_AllocationLine_Builder paymentWriteOffAmt(final BigDecimal paymentWriteOffAmt) { allocLine.setPaymentWriteOffAmt(paymentWriteOffAmt); return this; } public final C_AllocationLine_Builder skipIfAllAmountsAreZero() { this.skipIfAllAmountsAreZero = true; return this; } private boolean isSkipBecauseAllAmountsAreZero() { if (!skipIfAllAmountsAreZero) { return false; } // NOTE: don't check the OverUnderAmt because that amount is not affecting allocation, // so an allocation is Zero with our without the over/under amount. return allocLine.getAmount().signum() == 0 && allocLine.getDiscountAmt().signum() == 0 && allocLine.getWriteOffAmt().signum() == 0 //
&& allocLine.getPaymentWriteOffAmt().signum() == 0; } public final C_AllocationHdr_Builder lineDone() { return parent; } /** * @param allocHdrSupplier allocation header supplier which will provide the allocation header created & saved, just in time, so call it ONLY if you are really gonna create an allocation line. * @return created {@link I_C_AllocationLine} or <code>null</code> if it was not needed. */ @Nullable final I_C_AllocationLine create(@NonNull final Supplier<I_C_AllocationHdr> allocHdrSupplier) { if (isSkipBecauseAllAmountsAreZero()) { return null; } // // Get the allocation header, created & saved. final I_C_AllocationHdr allocHdr = allocHdrSupplier.get(); Check.assumeNotNull(allocHdr, "Param 'allocHdr' not null"); Check.assume(allocHdr.getC_AllocationHdr_ID() > 0, "Param 'allocHdr' has C_AllocationHdr_ID>0"); allocLine.setC_AllocationHdr(allocHdr); allocLine.setAD_Org_ID(allocHdr.getAD_Org_ID()); allocationDAO.save(allocLine); return allocLine; } public final C_AllocationHdr_Builder getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\allocation\api\C_AllocationLine_Builder.java
1
请在Spring Boot框架中完成以下Java代码
public String getById(@PathVariable String id) throws Exception { SolrDocument document = solrService.getById(db_core,id); System.out.println(document); return document.toString(); } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("search/{q}") public SolrDocumentList search(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(db_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) { e.printStackTrace(); } return results; } /** * 文件创建索引 */ @RequestMapping("doc/dataimport") public String dataimport(){ // 1、清空索引,生产环境不建议这样使用,可以保存文件新建及更新时间,增量创建索引 try { solrService.deleteAll(file_core); } catch (Exception e) { e.printStackTrace(); }
// 2、创建索引 Mono<String> result = WebClient.create(solrHost) .get() .uri(fileDataImport) .retrieve() .bodyToMono(String.class); System.out.println(result.block()); return "success"; } /** * 综合查询: 在综合查询中, 有按条件查询, 条件过滤, 排序, 分页, 高亮显示, 获取部分域信息 * @return */ @RequestMapping("doc/search/{q}") public SolrDocumentList docSearch(@PathVariable String q){ SolrDocumentList results = null; try { results = solrService.querySolr(file_core,q,"keyword"); } catch (IOException e) { e.printStackTrace(); } catch (SolrServerException e) { e.printStackTrace(); } return results; } }
repos\springboot-demo-master\solr\src\main\java\demo\et59\solr\controller\SolrController.java
2
请在Spring Boot框架中完成以下Java代码
public int size() { return this.loaders.size(); } @Override public boolean isEmpty() { return this.loaders.isEmpty(); } @Override public boolean containsKey(Object key) { return this.loaders.containsKey(key); } @Override public Set<K> keySet() { return this.loaders.keySet(); } @Override public V get(Object key) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.computeIfAbsent((K) key, (k) -> this.loaders.get(k).get()); } @Override public V put(K key, V value) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.put(key, value); } @Override public V remove(Object key) { if (!this.loaders.containsKey(key)) { throw new IllegalArgumentException( "This map only supports the following keys: " + this.loaders.keySet()); } return this.loaded.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Map.Entry<? extends K, ? extends V> entry : m.entrySet()) { put(entry.getKey(), entry.getValue()); }
} @Override public void clear() { this.loaded.clear(); } @Override public boolean containsValue(Object value) { return this.loaded.containsValue(value); } @Override public Collection<V> values() { return this.loaded.values(); } @Override public Set<Entry<K, V>> entrySet() { return this.loaded.entrySet(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LoadingMap<?, ?> that = (LoadingMap<?, ?>) o; return this.loaded.equals(that.loaded); } @Override public int hashCode() { return this.loaded.hashCode(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configuration\SecurityReactorContextConfiguration.java
2
请完成以下Java代码
default @Nullable Integer getIdle() { return null; } /** * Return the maximum number of active connections that can be allocated at the same * time or {@code -1} if there is no limit. Can also return {@code null} if that * information is not available. * @return the maximum number of active connections or {@code null} */ @Nullable Integer getMax(); /** * Return the minimum number of idle connections in the pool or {@code null} if that * information is not available. * @return the minimum number of active connections or {@code null} */ @Nullable Integer getMin();
/** * Return the query to use to validate that a connection is valid or {@code null} if * that information is not available. * @return the validation query or {@code null} */ @Nullable String getValidationQuery(); /** * The default auto-commit state of connections created by this pool. If not set * ({@code null}), default is JDBC driver default (If set to null then the * java.sql.Connection.setAutoCommit(boolean) method will not be called.) * @return the default auto-commit state or {@code null} */ @Nullable Boolean getDefaultAutoCommit(); }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\metadata\DataSourcePoolMetadata.java
1
请完成以下Java代码
public Builder notBefore(Instant notBefore) { return claim(OAuth2TokenClaimNames.NBF, notBefore); } /** * Sets the issued at {@code (iat)} claim, which identifies the time at which the * OAuth 2.0 Token was issued. * @param issuedAt the time at which the OAuth 2.0 Token was issued * @return the {@link Builder} */ public Builder issuedAt(Instant issuedAt) { return claim(OAuth2TokenClaimNames.IAT, issuedAt); } /** * Sets the ID {@code (jti)} claim, which provides a unique identifier for the * OAuth 2.0 Token. * @param jti the unique identifier for the OAuth 2.0 Token * @return the {@link Builder} */ public Builder id(String jti) { return claim(OAuth2TokenClaimNames.JTI, jti); } /** * Sets the claim. * @param name the claim name * @param value the claim value * @return the {@link Builder} */ public Builder claim(String name, Object value) { Assert.hasText(name, "name cannot be empty"); Assert.notNull(value, "value cannot be null"); this.claims.put(name, value); return this; } /**
* A {@code Consumer} to be provided access to the claims allowing the ability to * add, replace, or remove. * @param claimsConsumer a {@code Consumer} of the claims * @return the {@link Builder} */ public Builder claims(Consumer<Map<String, Object>> claimsConsumer) { claimsConsumer.accept(this.claims); return this; } /** * Builds a new {@link OAuth2TokenClaimsSet}. * @return a {@link OAuth2TokenClaimsSet} */ public OAuth2TokenClaimsSet build() { Assert.notEmpty(this.claims, "claims cannot be empty"); // The value of the 'iss' claim is a String or URL (StringOrURI). // Attempt to convert to URL. Object issuer = this.claims.get(OAuth2TokenClaimNames.ISS); if (issuer != null) { URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class); if (convertedValue != null) { this.claims.put(OAuth2TokenClaimNames.ISS, convertedValue); } } return new OAuth2TokenClaimsSet(this.claims); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsSet.java
1
请完成以下Java代码
public class UsingOptional { public static final String DEFAULT_VALUE = "Default Value"; public Optional<Object> process(boolean processed) { String response = doSomething(processed); return Optional.ofNullable(response); } public String findFirst() { return getList() .stream() .findFirst() .orElse(DEFAULT_VALUE); } public Optional<String> findOptionalFirst() { return getList() .stream() .findFirst(); } private List<String> getList() { return emptyList(); } public Optional<String> optionalListFirst() { return getOptionalList()
.flatMap(list -> list.stream().findFirst()); } private Optional<List<String>> getOptionalList() { return Optional.of(getList()); } private String doSomething(boolean processed) { if (processed) { return "passed"; } else { return null; } } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral\src\main\java\com\baeldung\nulls\UsingOptional.java
1
请完成以下Java代码
public class MigratingCalledCaseInstance implements MigratingInstance { public static final MigrationLogger MIGRATION_LOGGER = ProcessEngineLogger.MIGRATION_LOGGER; protected CaseExecutionEntity caseInstance; public MigratingCalledCaseInstance(CaseExecutionEntity caseInstance) { this.caseInstance = caseInstance; } @Override public boolean isDetached() { return caseInstance.getSuperExecutionId() == null; } @Override public void detachState() { caseInstance.setSuperExecution(null); } @Override public void attachState(MigratingScopeInstance targetActivityInstance) { caseInstance.setSuperExecution(targetActivityInstance.resolveRepresentativeExecution()); }
@Override public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } @Override public void migrateState() { // nothing to do } @Override public void migrateDependentEntities() { // nothing to do } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingCalledCaseInstance.java
1
请完成以下Java代码
public abstract class InfoQueryCriteriaBPRadiusAbstract implements IInfoQueryCriteria { public static final String SYSCONFIG_DefaultRadius = "de.metas.radiussearch.DefaultRadius"; protected String locationTableAlias = "a"; private IInfoSimple parent; private I_AD_InfoColumn infoColumn; @Override public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText) { this.parent = parent; this.infoColumn = infoColumn; } @Override public I_AD_InfoColumn getAD_InfoColumn() { return infoColumn; } @Override public int getParameterCount() { return 2; } @Override public String getLabel(int index) { if (index == 0) return Msg.translate(Env.getCtx(), "NearCity"); else if (index == 1) return Msg.translate(Env.getCtx(), "RadiusKM"); else return null; }
@Override public Object getParameterToComponent(int index) { return null; } @Override public Object getParameterValue(int index, boolean returnValueTo) { return null; } public IInfoSimple getParent() { return parent; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPRadiusAbstract.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getType() { return this.type; } public void setType(@Nullable String type) { this.type = type; } public @Nullable String getProvider() { return this.provider; } public void setProvider(@Nullable String provider) { this.provider = provider; } public @Nullable String getLocation() {
return this.location; } public void setLocation(@Nullable String location) { this.location = location; } public @Nullable String getPassword() { return this.password; } public void setPassword(@Nullable String password) { this.password = password; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\ssl\JksSslBundleProperties.java
2
请完成以下Java代码
public java.math.BigDecimal getOpenItems () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenItems); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Kredit gewährt. @param SO_CreditUsed Gegenwärtiger Aussenstand */ @Override public void setSO_CreditUsed (java.math.BigDecimal SO_CreditUsed) { set_Value (COLUMNNAME_SO_CreditUsed, SO_CreditUsed); } /** Get Kredit gewährt. @return Gegenwärtiger Aussenstand */ @Override public java.math.BigDecimal getSO_CreditUsed () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SO_CreditUsed); if (bd == null) return BigDecimal.ZERO; return bd; } /** * SOCreditStatus AD_Reference_ID=289 * Reference name: C_BPartner SOCreditStatus */
public static final int SOCREDITSTATUS_AD_Reference_ID=289; /** CreditStop = S */ public static final String SOCREDITSTATUS_CreditStop = "S"; /** CreditHold = H */ public static final String SOCREDITSTATUS_CreditHold = "H"; /** CreditWatch = W */ public static final String SOCREDITSTATUS_CreditWatch = "W"; /** NoCreditCheck = X */ public static final String SOCREDITSTATUS_NoCreditCheck = "X"; /** CreditOK = O */ public static final String SOCREDITSTATUS_CreditOK = "O"; /** NurEineRechnung = I */ public static final String SOCREDITSTATUS_NurEineRechnung = "I"; /** Set Kreditstatus. @param SOCreditStatus Kreditstatus des Geschäftspartners */ @Override public void setSOCreditStatus (java.lang.String SOCreditStatus) { set_Value (COLUMNNAME_SOCreditStatus, SOCreditStatus); } /** Get Kreditstatus. @return Kreditstatus des Geschäftspartners */ @Override public java.lang.String getSOCreditStatus () { return (java.lang.String)get_Value(COLUMNNAME_SOCreditStatus); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Stats.java
1
请完成以下Spring Boot application配置
server.port=8088 #rabbitmq spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=admin spring.rabbitmq.password=admin spring.rabbitmq.virtual-host=my_vhost man
agement.endpoints.web.exposure.include=* management.endpoint.shutdown.enabled=true
repos\springboot-demo-master\rabbitmq\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
private void removeFromStarred(UserDashboardsInfo stored, DashboardId dashboardId) { UUID id = dashboardId.getId(); stored.getStarred().removeIf(filterById(id)); stored.getLast().stream().filter(d -> id.equals(d.getId())).findFirst().ifPresent(d -> d.setStarred(false)); } private void addToStarred(UserDashboardsInfo stored, DashboardId dashboardId) { UUID id = dashboardId.getId(); long ts = System.currentTimeMillis(); var opt = stored.getStarred().stream().filter(filterById(id)).findFirst(); if (opt.isPresent()) { opt.get().setStarredAt(ts); } else { var newInfo = new StarredDashboardInfo(); newInfo.setId(id); newInfo.setStarredAt(System.currentTimeMillis()); stored.getStarred().add(newInfo); } stored.getStarred().sort(Comparator.comparing(StarredDashboardInfo::getStarredAt).reversed()); if (stored.getStarred().size() > MAX_DASHBOARD_INFO_LIST_SIZE) { stored.setStarred(stored.getStarred().stream().limit(MAX_DASHBOARD_INFO_LIST_SIZE).collect(Collectors.toList())); } Set<UUID> starredMap = stored.getStarred().stream().map(AbstractUserDashboardInfo::getId).collect(Collectors.toSet()); stored.getLast().forEach(d -> d.setStarred(starredMap.contains(d.getId()))); } private Predicate<AbstractUserDashboardInfo> filterById(UUID id) { return d -> id.equals(d.getId()); }
private UserDashboardsInfo refreshDashboardTitles(TenantId tenantId, UserDashboardsInfo stored) { if (stored == null) { return UserDashboardsInfo.EMPTY; } stored.getLast().forEach(i -> i.setTitle(null)); stored.getStarred().forEach(i -> i.setTitle(null)); Set<UUID> uniqueIds = new HashSet<>(); stored.getLast().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add); stored.getStarred().stream().map(AbstractUserDashboardInfo::getId).forEach(uniqueIds::add); Map<UUID, String> dashboardTitles = new HashMap<>(); uniqueIds.forEach(id -> { var title = dashboardService.findDashboardTitleById(tenantId, new DashboardId(id)); if (StringUtils.isNotEmpty(title)) { dashboardTitles.put(id, title); } } ); stored.getLast().forEach(i -> i.setTitle(dashboardTitles.get(i.getId()))); stored.getLast().removeIf(EMPTY_TITLE); stored.getStarred().forEach(i -> i.setTitle(dashboardTitles.get(i.getId()))); stored.getStarred().removeIf(EMPTY_TITLE); return stored; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\user\DefaultTbUserSettingsService.java
2
请完成以下Java代码
public int getFullVersion() { return majorVersion * 1000000 + minorVersion * 1000 + fixVersion; } public int getMajorVersion() { return majorVersion; } public SentinelVersion setMajorVersion(int majorVersion) { this.majorVersion = majorVersion; return this; } public int getMinorVersion() { return minorVersion; } public SentinelVersion setMinorVersion(int minorVersion) { this.minorVersion = minorVersion; return this; } public int getFixVersion() { return fixVersion; } public SentinelVersion setFixVersion(int fixVersion) { this.fixVersion = fixVersion; return this; } public String getPostfix() { return postfix; } public SentinelVersion setPostfix(String postfix) { this.postfix = postfix; return this; } public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); } public boolean greaterOrEqual(SentinelVersion version) { if (version == null) {
return true; } return getFullVersion() >= version.getFullVersion(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } SentinelVersion that = (SentinelVersion)o; if (getFullVersion() != that.getFullVersion()) { return false; } return postfix != null ? postfix.equals(that.postfix) : that.postfix == null; } @Override public int hashCode() { int result = majorVersion; result = 31 * result + minorVersion; result = 31 * result + fixVersion; result = 31 * result + (postfix != null ? postfix.hashCode() : 0); return result; } @Override public String toString() { return "SentinelVersion{" + "majorVersion=" + majorVersion + ", minorVersion=" + minorVersion + ", fixVersion=" + fixVersion + ", postfix='" + postfix + '\'' + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\SentinelVersion.java
1
请完成以下Java代码
public void clear() { queuesMap.clear(); } public FrontendPrinterData toFrontendPrinterData() { return queuesMap.values() .stream() .map(PrinterQueue::toFrontendPrinterData) .collect(GuavaCollectors.collectUsingListAccumulator(FrontendPrinterData::of)); } } @RequiredArgsConstructor private static class PrinterQueue { @NonNull private final HardwarePrinter printer; @NonNull private final ArrayList<PrintingDataAndSegment> segments = new ArrayList<>(); public void add( @NonNull PrintingData printingData, @NonNull PrintingSegment segment) { Check.assumeEquals(this.printer, segment.getPrinter(), "Expected segment printer to match: {}, expected={}", segment, printer); segments.add(PrintingDataAndSegment.of(printingData, segment)); } public FrontendPrinterDataItem toFrontendPrinterData() { return FrontendPrinterDataItem.builder() .printer(printer) .filename(suggestFilename()) .data(toByteArray()) .build(); } private byte[] toByteArray() { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final PrintingDataToPDFWriter pdfWriter = new PrintingDataToPDFWriter(baos)) { for (PrintingDataAndSegment printingDataAndSegment : segments)
{ pdfWriter.addArchivePartToPDF(printingDataAndSegment.getPrintingData(), printingDataAndSegment.getSegment()); } } return baos.toByteArray(); } private String suggestFilename() { final ImmutableSet<String> filenames = segments.stream() .map(PrintingDataAndSegment::getDocumentFileName) .collect(ImmutableSet.toImmutableSet()); return filenames.size() == 1 ? filenames.iterator().next() : "report.pdf"; } } @Value(staticConstructor = "of") private static class PrintingDataAndSegment { @NonNull PrintingData printingData; @NonNull PrintingSegment segment; public String getDocumentFileName() { return printingData.getDocumentFileName(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\frontend\FrontendPrinter.java
1
请完成以下Java代码
private void collectHUTransactionCandidate(final IHUTransactionCandidate huTransaction) { final I_M_HU hu = huTransaction.getM_HU(); if (hu == null) { return; } final Quantity quantity = huTransaction.getQuantity(); if (quantity.isZero()) { return; } final I_M_HU topLevelHU = handlingUnitsBL.getTopLevelParent(hu); final LocatorId effectiveLocatorId = CoalesceUtil.coalesceSuppliers( () -> locatorId, huTransaction::getLocatorId, () -> IHandlingUnitsBL.extractLocatorIdOrNull(topLevelHU)); if (effectiveLocatorId == null) { throw new AdempiereException("Cannot figure out on which locator to receive.") .setParameter("providedLocatorId", locatorId) .setParameter("huTransaction", huTransaction) .setParameter("topLevelHU", topLevelHU) .appendParametersToMessage(); } final AggregationKey key = AggregationKey.builder() .locatorId(effectiveLocatorId) .topLevelHUId(HuId.ofRepoId(topLevelHU.getM_HU_ID())) .productId(huTransaction.getProductId()) .build(); requests.computeIfAbsent(key, this::createReceiptCandidateRequestBuilder) .addQtyToReceive(quantity); } private CreateReceiptCandidateRequestBuilder createReceiptCandidateRequestBuilder(final AggregationKey key) { return CreateReceiptCandidateRequest.builder() .orderId(orderId) .orderBOMLineId(coByProductOrderBOMLineId) .orgId(orgId) .date(date) .locatorId(key.getLocatorId()) .topLevelHUId(key.getTopLevelHUId()) .productId(key.getProductId()) .pickingCandidateId(pickingCandidateId); } @Builder @Value private static class AggregationKey { @NonNull LocatorId locatorId; @NonNull HuId topLevelHUId; @NonNull ProductId productId; } } //
// // // // private interface LUTUSpec { } @Value private static class HUPIItemProductLUTUSpec implements LUTUSpec { public static final HUPIItemProductLUTUSpec VIRTUAL = new HUPIItemProductLUTUSpec(HUPIItemProductId.VIRTUAL_HU, null); @NonNull HUPIItemProductId tuPIItemProductId; @Nullable HuPackingInstructionsItemId luPIItemId; public static HUPIItemProductLUTUSpec topLevelTU(@NonNull HUPIItemProductId tuPIItemProductId) { return tuPIItemProductId.isVirtualHU() ? VIRTUAL : new HUPIItemProductLUTUSpec(tuPIItemProductId, null); } public static HUPIItemProductLUTUSpec lu(@NonNull HUPIItemProductId tuPIItemProductId, @NonNull HuPackingInstructionsItemId luPIItemId) { return new HUPIItemProductLUTUSpec(tuPIItemProductId, luPIItemId); } public boolean isTopLevelVHU() { return tuPIItemProductId.isVirtualHU() && luPIItemId == null; } } @Value(staticConstructor = "of") private static class PreciseTUSpec implements LUTUSpec { @NonNull HuPackingInstructionsId tuPackingInstructionsId; @NonNull Quantity qtyCUsPerTU; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\AbstractPPOrderReceiptHUProducer.java
1
请完成以下Java代码
protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if(!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { husToReturn = streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList()); if (husToReturn.isEmpty()) { throw new AdempiereException("@NoSelection@"); }
final Timestamp movementDate = Env.getDate(getCtx()); returnsServiceFacade.createVendorReturnInOutForHUs(husToReturn, movementDate); return MSG_OK; } @Override protected void postProcess(final boolean success) { if (husToReturn != null && !husToReturn.isEmpty()) { getView().removeHUsAndInvalidate(husToReturn); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnToVendor.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Increment. @param IncrementNo The number to increment the last document number by */ public void setIncrementNo (int IncrementNo) { set_Value (COLUMNNAME_IncrementNo, Integer.valueOf(IncrementNo)); } /** Get Increment. @return The number to increment the last document number by */ public int getIncrementNo () { Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo); if (ii == null) return 0; return ii.intValue(); } /** Set Lot Control. @param M_LotCtl_ID Product Lot Control */ public void setM_LotCtl_ID (int M_LotCtl_ID) { if (M_LotCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_LotCtl_ID, Integer.valueOf(M_LotCtl_ID)); } /** Get Lot Control. @return Product Lot Control */ public int getM_LotCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix. @param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); }
/** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java
1
请完成以下Java代码
public List<I_C_BPartner_Product> getBPartnerProductRecords(final Set<ProductId> productIds) { return partnerProductsRepo.retrieveForProductIds(productIds); } public List<I_M_HU_PI_Item_Product> getMHUPIItemProductRecords(final Set<ProductId> productIds) { return huPIItemProductDAO.retrieveAllForProducts(productIds); } public List<UOMConversionsMap> getProductUOMConversions(final Set<ProductId> productIds) { if (productIds.isEmpty()) { return ImmutableList.of(); } return productIds.stream().map(uomConversionDAO::getProductConversions).collect(ImmutableList.toImmutableList()); } public Stream<I_M_Product_Category> streamAllProductCategories() { return productsRepo.streamAllProductCategories(); }
public List<I_C_BPartner> getPartnerRecords(@NonNull final ImmutableSet<BPartnerId> manufacturerIds) { return queryBL.createQueryBuilder(I_C_BPartner.class) .addInArrayFilter(I_C_BPartner.COLUMN_C_BPartner_ID, manufacturerIds) .create() .list(); } @NonNull public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(@NonNull final I_M_Product_Category record) { final ZoneId orgZoneId = orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID())); return JsonCreatedUpdatedInfo.builder() .created(TimeUtil.asZonedDateTime(record.getCreated(), orgZoneId)) .createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM)) .updated(TimeUtil.asZonedDateTime(record.getUpdated(), orgZoneId)) .updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductsServicesFacade.java
1
请完成以下Java代码
public class CashAccount16 { @XmlElement(name = "Id", required = true) protected AccountIdentification4Choice id; @XmlElement(name = "Tp") protected CashAccountType2 tp; @XmlElement(name = "Ccy") protected String ccy; @XmlElement(name = "Nm") protected String nm; /** * Gets the value of the id property. * * @return * possible object is * {@link AccountIdentification4Choice } * */ public AccountIdentification4Choice getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link AccountIdentification4Choice } * */ public void setId(AccountIdentification4Choice value) { this.id = value; } /** * Gets the value of the tp property. * * @return * possible object is * {@link CashAccountType2 } * */ public CashAccountType2 getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link CashAccountType2 } * */ public void setTp(CashAccountType2 value) { this.tp = value;
} /** * Gets the value of the ccy property. * * @return * possible object is * {@link String } * */ public String getCcy() { return ccy; } /** * Sets the value of the ccy property. * * @param value * allowed object is * {@link String } * */ public void setCcy(String value) { this.ccy = value; } /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashAccount16.java
1
请完成以下Java代码
public static void updateOperations() { UpdateOptions options = new UpdateOptions().upsert(true); UpdateResult updateResult = collection.updateOne(Filters.eq("modelName", "X5"), Updates.combine(Updates.set("companyName", "Hero Honda")), options); System.out.println("updateResult:- " + updateResult); } public static void updateSetOnInsertOperations() { UpdateOptions options = new UpdateOptions().upsert(true); UpdateResult updateSetOnInsertResult = collection.updateOne(Filters.eq("modelName", "GTPR"), Updates.combine(Updates.set("companyName", "Hero Honda"), Updates.setOnInsert("launchYear", 2022), Updates.setOnInsert("type", "Bike"), Updates.setOnInsert("registeredNo", "EPS 5562")), options); System.out.println("updateSetOnInsertResult:- " + updateSetOnInsertResult); } public static void findOneAndUpdateOperations() { FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions(); upsertOptions.returnDocument(ReturnDocument.AFTER); upsertOptions.upsert(true); Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda"), upsertOptions); System.out.println("resultDocument:- " + resultDocument); } public static void replaceOneOperations() { UpdateOptions options = new UpdateOptions().upsert(true); Document replaceDocument = new Document(); replaceDocument.append("modelName", "GTPP") .append("companyName", "Hero Honda") .append("launchYear", 2022) .append("type", "Bike") .append("registeredNo", "EPS 5562"); UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options); System.out.println("updateReplaceResult:- " + updateReplaceResult); }
public static void main(String args[]) { // // Connect to cluster (default is localhost:27017) // setUp(); // // Update with upsert operation // updateOperations(); // // Update with upsert operation using setOnInsert // updateSetOnInsertOperations(); // // Update with upsert operation using findOneAndUpdate // findOneAndUpdateOperations(); // // Update with upsert operation using replaceOneOperations // replaceOneOperations(); } }
repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java
1
请完成以下Java代码
public List<HistoricIdentityLink> getHistoricIdentityLinksForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(null, processInstanceId)); } @Override public List<HistoricIdentityLink> getHistoricIdentityLinksForTask(String taskId) { return commandExecutor.execute(new GetHistoricIdentityLinksForTaskCmd(taskId, null)); } @Override public List<HistoricEntityLink> getHistoricEntityLinkChildrenForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricEntityLinkChildrenForProcessInstanceCmd(processInstanceId)); } @Override public List<HistoricEntityLink> getHistoricEntityLinkChildrenWithSameRootAsProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricEntityLinkChildrenWithSameRootAsProcessInstanceCmd(processInstanceId)); } @Override public List<HistoricEntityLink> getHistoricEntityLinkChildrenForTask(String taskId) { return commandExecutor.execute(new GetHistoricEntityLinkChildrenForTaskCmd(taskId)); } @Override public List<HistoricEntityLink> getHistoricEntityLinkParentsForProcessInstance(String processInstanceId) { return commandExecutor.execute(new GetHistoricEntityLinkParentsForProcessInstanceCmd(processInstanceId)); } @Override public List<HistoricEntityLink> getHistoricEntityLinkParentsForTask(String taskId) { return commandExecutor.execute(new GetHistoricEntityLinkParentsForTaskCmd(taskId)); } @Override public ProcessInstanceHistoryLogQuery createProcessInstanceHistoryLogQuery(String processInstanceId) { return new ProcessInstanceHistoryLogQueryImpl(commandExecutor, processInstanceId, configuration); } @Override public void deleteHistoricTaskLogEntry(long logNumber) {
commandExecutor.execute(new DeleteHistoricTaskLogEntryByLogNumberCmd(logNumber)); } @Override public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder(TaskInfo task) { return new HistoricTaskLogEntryBuilderImpl(commandExecutor, task, configuration.getTaskServiceConfiguration()); } @Override public HistoricTaskLogEntryBuilder createHistoricTaskLogEntryBuilder() { return new HistoricTaskLogEntryBuilderImpl(commandExecutor, configuration.getTaskServiceConfiguration()); } @Override public HistoricTaskLogEntryQuery createHistoricTaskLogEntryQuery() { return new HistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration()); } @Override public NativeHistoricTaskLogEntryQuery createNativeHistoricTaskLogEntryQuery() { return new NativeHistoricTaskLogEntryQueryImpl(commandExecutor, configuration.getTaskServiceConfiguration()); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\HistoryServiceImpl.java
1
请完成以下Java代码
public org.activiti.engine.task.Comment getRawObject() { return activit5Comment; } @Override public void setUserId(String userId) { ((CommentEntity) activit5Comment).setUserId(userId); } @Override public void setTime(Date time) { ((CommentEntity) activit5Comment).setTime(time); } @Override public void setTaskId(String taskId) { ((CommentEntity) activit5Comment).setTaskId(taskId); }
@Override public void setProcessInstanceId(String processInstanceId) { ((CommentEntity) activit5Comment).setProcessInstanceId(processInstanceId); } @Override public void setType(String type) { ((CommentEntity) activit5Comment).setType(type); } @Override public void setFullMessage(String fullMessage) { ((CommentEntity) activit5Comment).setFullMessage(fullMessage); } }
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5CommentWrapper.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public AddressEntity getAddress() { return address; } public void setAddress(AddressEntity address) { this.address = address; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Boolean getEnabled() { return enabled; } public void setEnabled(Boolean enabled) {
this.enabled = enabled; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UserEntity that = (UserEntity) o; return Objects.equals(id, that.id); } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "UserEntity{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", email='" + email + '\'' + ", enabled=" + enabled + '}'; } }
repos\spring-examples-java-17\spring-data\src\main\java\itx\examples\springdata\entity\UserEntity.java
1
请完成以下Java代码
private void storePDFAndFireEvent( @NonNull final IPrintingQueueSource source, @NonNull final I_C_Printing_Queue item, @NonNull final PrintingData printingDataToStore) { printingDataToPDFFileStorer.storeInFileSystem(printingDataToStore); // // Notify archiveEventManager.firePrintOut( item.getAD_Archive(), source.getProcessingInfo().getAD_User_PrintJob_ID(), printingDataToStore.getPrinterNames(), IArchiveEventManager.COPIES_ONE, ArchivePrintOutStatus.Success); source.markPrinted(item); } private void enqueueToFrontendPrinterAndFireEvent( @NonNull final FrontendPrinter frontendPrinter, @NonNull final IPrintingQueueSource source, @NonNull final I_C_Printing_Queue item,
@NonNull final PrintingData printingData) { frontendPrinter.add(printingData); // // Notify archiveEventManager.firePrintOut( item.getAD_Archive(), source.getProcessingInfo().getAD_User_PrintJob_ID(), printingData.getPrinterNames(), IArchiveEventManager.COPIES_ONE, ArchivePrintOutStatus.Success); source.markPrinted(item); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\PrintOutputFacade.java
1
请完成以下Java代码
protected QueryVariableValue createQueryVariableValue(String name, Object value, QueryOperator operator, boolean processInstanceScope) { validateVariable(name, value, operator); boolean shouldMatchVariableValuesIgnoreCase = Boolean.TRUE.equals(variableValuesIgnoreCase) && value != null && String.class.isAssignableFrom(value.getClass()); boolean shouldMatchVariableNamesIgnoreCase = Boolean.TRUE.equals(variableNamesIgnoreCase); return new QueryVariableValue(name, value, operator, processInstanceScope, shouldMatchVariableNamesIgnoreCase, shouldMatchVariableValuesIgnoreCase); } protected void validateVariable(String name, Object value, QueryOperator operator) { ensureNotNull(NotValidException.class, "name", name); if(value == null || isBoolean(value)) { // Null-values and booleans can only be used in EQUALS and NOT_EQUALS switch(operator) { case GREATER_THAN: throw new NotValidException("Booleans and null cannot be used in 'greater than' condition"); case LESS_THAN: throw new NotValidException("Booleans and null cannot be used in 'less than' condition"); case GREATER_THAN_OR_EQUAL: throw new NotValidException("Booleans and null cannot be used in 'greater than or equal' condition"); case LESS_THAN_OR_EQUAL: throw new NotValidException("Booleans and null cannot be used in 'less than or equal' condition"); case LIKE: throw new NotValidException("Booleans and null cannot be used in 'like' condition"); case NOT_LIKE: throw new NotValidException("Booleans and null cannot be used in 'not like' condition"); default: break; } } } private boolean isBoolean(Object value) { if (value == null) { return false; } return Boolean.class.isAssignableFrom(value.getClass()) || boolean.class.isAssignableFrom(value.getClass()); } protected void ensureVariablesInitialized() {
if (!getQueryVariableValues().isEmpty()) { ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration(); VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers(); String dbType = processEngineConfiguration.getDatabaseType(); for(QueryVariableValue queryVariableValue : getQueryVariableValues()) { queryVariableValue.initialize(variableSerializers, dbType); } } } public List<QueryVariableValue> getQueryVariableValues() { return queryVariableValues; } public Boolean isVariableNamesIgnoreCase() { return variableNamesIgnoreCase; } public Boolean isVariableValuesIgnoreCase() { return variableValuesIgnoreCase; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\AbstractVariableQueryImpl.java
1
请完成以下Java代码
public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setGLN (final @Nullable java.lang.String GLN) { set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() { return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setLookup_Label (final @Nullable java.lang.String Lookup_Label) { set_ValueNoCheck (COLUMNNAME_Lookup_Label, Lookup_Label); } @Override
public java.lang.String getLookup_Label() { return get_ValueAsString(COLUMNNAME_Lookup_Label); } @Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_Value (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Lookup_BPL_GLN_v.java
1
请完成以下Java代码
private List<ServiceModWithSelector> createServiceModsWithSelectors( @NonNull final InvoiceToExport invoice, @NonNull final List<XmlService> xServices) { final ImmutableList.Builder<ServiceModWithSelector> serviceMods = ImmutableList.builder(); final ImmutableMap<Integer, XmlService> // recordId2xService = Maps.uniqueIndex(xServices, XmlService::getRecordId); for (final InvoiceLine invoiceLine : invoice.getInvoiceLines()) { final int recordId = ExternalIdsUtil.extractSingleRecordId(invoiceLine.getExternalIds()); final XmlService xServiceForInvoiceLine = recordId2xService.get(recordId); final BigDecimal xServiceAmount = xServiceForInvoiceLine.getAmount(); final Money invoiceLineMoney = invoiceLine.getLineAmount(); final BigDecimal invoiceLineAmount = invoiceLineMoney.getAmount(); final ServiceModWithSelectorBuilder serviceMod = ServiceModWithSelector .builder() .recordId(recordId); if (invoiceLineAmount.compareTo(xServiceAmount) == 0) { serviceMods.add(serviceMod.build()); // nothing to change continue; } // note that we don't modify the external factor serviceMod.amount(invoiceLineAmount);
serviceMods.add(serviceMod.build()); } return serviceMods.build(); } /** attach 2ndary attachments to our XML */ private List<XmlDocument> createDocuments(@NonNull final List<InvoiceAttachment> invoiceAttachments) { final ImmutableList.Builder<XmlDocument> xmldocuments = ImmutableList.builder(); for (final InvoiceAttachment invoiceAttachment : invoiceAttachments) { final boolean primaryAttachment = invoiceAttachment.getTags().get(InvoiceExportClientFactory.ATTACHMENT_TAGNAME_BELONGS_TO_EXTERNAL_REFERENCE) == null; if (primaryAttachment) { logger.debug("invoiceAttachment with filename={} is noth the 2ndary (i.e. exported) attachment; -> not exporting it", invoiceAttachment.getFileName()); continue; } logger.debug("Adding invoiceAttachment with filename={} to be exported", invoiceAttachment.getFileName()); final byte[] base64Data = Base64.getEncoder().encode(invoiceAttachment.getData()); final XmlDocument xmlDocument = XmlDocument.builder() .base64(base64Data) .filename(invoiceAttachment.getFileName()) .mimeType(invoiceAttachment.getMimeType()) .build(); xmldocuments.add(xmlDocument); } return xmldocuments.build(); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\invoice\InvoiceExportClientImpl.java
1
请完成以下Java代码
public void insertByteArray(ByteArrayEntity arr) { arr.setCreateTime(ClockUtil.getCurrentTime()); getDbEntityManager().insert(arr); } public DbOperation addRemovalTimeToByteArraysByRootProcessInstanceId(String rootProcessInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("rootProcessInstanceId", rootProcessInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); return getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateByteArraysByRootProcessInstanceId", parameters); } public List<DbOperation> addRemovalTimeToByteArraysByProcessInstanceId(String processInstanceId, Date removalTime, Integer batchSize) { Map<String, Object> parameters = new HashMap<>(); parameters.put("processInstanceId", processInstanceId); parameters.put("removalTime", removalTime); parameters.put("maxResults", batchSize); // Make individual statements for each entity type that references byte arrays. // This can lead to query plans that involve less aggressive locking by databases (e.g. DB2). // See CAM-10360 for reference. List<DbOperation> operations = new ArrayList<>(); operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateVariableByteArraysByProcessInstanceId", parameters));
operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateDecisionInputsByteArraysByProcessInstanceId", parameters)); operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateDecisionOutputsByteArraysByProcessInstanceId", parameters)); operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateJobLogByteArraysByProcessInstanceId", parameters)); operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateExternalTaskLogByteArraysByProcessInstanceId", parameters)); operations.add(getDbEntityManager() .updatePreserveOrder(ByteArrayEntity.class, "updateAttachmentByteArraysByProcessInstanceId", parameters)); return operations; } public DbOperation deleteByteArraysByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) { Map<String, Object> parameters = new HashMap<String, Object>(); parameters.put("removalTime", removalTime); if (minuteTo - minuteFrom + 1 < 60) { parameters.put("minuteFrom", minuteFrom); parameters.put("minuteTo", minuteTo); } parameters.put("batchSize", batchSize); return getDbEntityManager() .deletePreserveOrder(ByteArrayEntity.class, "deleteByteArraysByRemovalTime", new ListQueryParameterObject(parameters, 0, batchSize)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayManager.java
1
请完成以下Java代码
private WEBUI_M_HU_Pick_ParametersFiller createNewDefaultParametersFiller() { final HURow row = getSingleHURow(); return WEBUI_M_HU_Pick_ParametersFiller.defaultFillerBuilder() .huId(row.getHuId()) .salesOrderLineId(getSalesOrderLineId()) .build(); } @ProcessParamLookupValuesProvider(// parameterName = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_PickingSlot_ID, // dependsOn = WEBUI_M_HU_Pick_ParametersFiller.PARAM_M_ShipmentSchedule_ID, // numericKey = true, // lookupSource = LookupSource.lookup) private LookupValuesList getPickingSlotValues(final LookupDataSourceContext context) { final WEBUI_M_HU_Pick_ParametersFiller filler = WEBUI_M_HU_Pick_ParametersFiller .pickingSlotFillerBuilder() .shipmentScheduleId(shipmentScheduleId) .build(); return filler.getPickingSlotValues(context); } @Nullable private OrderLineId getSalesOrderLineId() { final IView view = getView(); if (view instanceof PPOrderLinesView) { final PPOrderLinesView ppOrderLinesView = PPOrderLinesView.cast(view); return ppOrderLinesView.getSalesOrderLineId(); } else { return null; } } @Override protected String doIt() { final HURow row = getSingleHURow(); pickHU(row); // invalidate view in order to be refreshed getView().invalidateAll(); return MSG_OK; } private void pickHU(@NonNull final HURow row) { final HuId huId = row.getHuId(); final PickRequest pickRequest = PickRequest.builder() .shipmentScheduleId(shipmentScheduleId) .pickFrom(PickFrom.ofHuId(huId))
.pickingSlotId(pickingSlotId) .build(); final ProcessPickingRequest.ProcessPickingRequestBuilder pickingRequestBuilder = ProcessPickingRequest.builder() .huIds(ImmutableSet.of(huId)) .shipmentScheduleId(shipmentScheduleId) .isTakeWholeHU(isTakeWholeHU); final IView view = getView(); if (view instanceof PPOrderLinesView) { final PPOrderLinesView ppOrderView = PPOrderLinesView.cast(view); pickingRequestBuilder.ppOrderId(ppOrderView.getPpOrderId()); } WEBUI_PP_Order_ProcessHelper.pickAndProcessSingleHU(pickRequest, pickingRequestBuilder.build()); } @Override protected void postProcess(final boolean success) { if (!success) { return; } invalidateView(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick.java
1
请完成以下Java代码
public ClientSetup setC_Bank_ID(final int bankId) { if (bankId > 0) { orgBankAccount.setC_Bank_ID(bankId); } return this; } public final int getC_Bank_ID() { return orgBankAccount.getC_Bank_ID(); } public ClientSetup setPhone(final String phone) { if (!Check.isEmpty(phone, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setPhone(phone.trim()); } return this; } public final String getPhone() { return orgContact.getPhone(); } public ClientSetup setFax(final String fax) { if (!Check.isEmpty(fax, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setFax(fax.trim()); } return this; } public final String getFax() { return orgContact.getFax(); } public ClientSetup setEMail(final String email) {
if (!Check.isEmpty(email, true)) { // NOTE: we are not setting the Phone, Fax, EMail on C_BPartner_Location because those fields are hidden in BPartner window orgContact.setEMail(email.trim()); } return this; } public final String getEMail() { return orgContact.getEMail(); } public ClientSetup setBPartnerDescription(final String bpartnerDescription) { if (Check.isEmpty(bpartnerDescription, true)) { return this; } orgBPartner.setDescription(bpartnerDescription.trim()); return this; } public String getBPartnerDescription() { return orgBPartner.getDescription(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\de\metas\fresh\setup\process\ClientSetup.java
1
请完成以下Java代码
public Title getTitle() { return title; } public void setTitle(Title title) { this.title = title; } public Tooltip getTooltip() { return tooltip; } public void setTooltip(Tooltip tooltip) { this.tooltip = tooltip; } public Legend getLegend() { return legend; } public void setLegend(Legend legend) { this.legend = legend; } public Grid getGrid() { return grid; } public void setGrid(Grid grid) { this.grid = grid; } public Toolbox getToolbox() { return toolbox; } public void setToolbox(Toolbox toolbox) { this.toolbox = toolbox; }
public XAxis getxAxis() { return xAxis; } public void setxAxis(XAxis xAxis) { this.xAxis = xAxis; } public YAxis getyAxis() { return yAxis; } public void setyAxis(YAxis yAxis) { this.yAxis = yAxis; } public List<Serie> getSeries() { return series; } public void setSeries(List<Serie> series) { this.series = series; } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\echarts\api\model\jmh\Option.java
1
请在Spring Boot框架中完成以下Java代码
public class RelatedDocumentsType { @XmlElement(name = "RelatedDocumentReference") protected List<String> relatedDocumentReference; /** * Gets the value of the relatedDocumentReference property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the relatedDocumentReference property. * * <p> * For example, to add a new item, do as follows: * <pre> * getRelatedDocumentReference().add(newItem); * </pre>
* * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getRelatedDocumentReference() { if (relatedDocumentReference == null) { relatedDocumentReference = new ArrayList<String>(); } return this.relatedDocumentReference; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RelatedDocumentsType.java
2
请完成以下Java代码
public boolean isComponent() { return this == Component; } public boolean isPacking() { return this == Packing; } public boolean isComponentOrPacking() { return isComponent() || isPacking(); } public boolean isCoProduct() { return this == CoProduct; } public boolean isByProduct() { return this == ByProduct; } public boolean isByOrCoProduct() { return isByProduct() || isCoProduct(); } public boolean isVariant() { return this == Variant; }
public boolean isPhantom() { return this == Phantom; } public boolean isTools() { return this == Tools; } // public boolean isReceipt() { return isByOrCoProduct(); } public boolean isIssue() { return !isReceipt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\BOMComponentType.java
1
请完成以下Java代码
static JsonDocument insertExample(Bucket bucket) { JsonObject content = JsonObject.empty().put("name", "John Doe").put("type", "Person").put("email", "john.doe@mydomain.com").put("homeTown", "Chicago"); String id = UUID.randomUUID().toString(); JsonDocument document = JsonDocument.create(id, content); JsonDocument inserted = bucket.insert(document); return inserted; } static JsonDocument retrieveAndUpsertExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Kansas City"); JsonDocument upserted = bucket.upsert(document); return upserted; } static JsonDocument replaceExample(Bucket bucket, String id) { JsonDocument document = bucket.get(id); JsonObject content = document.content(); content.put("homeTown", "Milwaukee"); JsonDocument replaced = bucket.replace(document); return replaced; } static JsonDocument removeExample(Bucket bucket, String id) { JsonDocument removed = bucket.remove(id); return removed; } static JsonDocument getFirstFromReplicaExample(Bucket bucket, String id) { try {
return bucket.get(id); } catch (CouchbaseException e) { List<JsonDocument> list = bucket.getFromReplica(id, ReplicaMode.FIRST); if (!list.isEmpty()) { return list.get(0); } } return null; } static JsonDocument getLatestReplicaVersion(Bucket bucket, String id) { long maxCasValue = -1; JsonDocument latest = null; for (JsonDocument replica : bucket.getFromReplica(id, ReplicaMode.ALL)) { if (replica.cas() > maxCasValue) { latest = replica; maxCasValue = replica.cas(); } } return latest; } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\intro\CodeSnippets.java
1
请完成以下Java代码
public static Map<String, Object> convertParametersMapToJson(@Nullable final Map<?, Object> map, @NonNull final String adLanguage) { if (map == null || map.isEmpty()) { return ImmutableMap.of(); } return map .entrySet() .stream() .map(e -> GuavaCollectors.entry( convertParameterToStringJson(e.getKey(), adLanguage), convertParameterToJson(e.getValue(), adLanguage))) .collect(GuavaCollectors.toImmutableMap()); } @NonNull private static Object convertParameterToJson(@Nullable final Object value, @NonNull final String adLanguage) { if (value == null || Null.isNull(value)) { return "<null>"; } else if (value instanceof ITranslatableString) { return ((ITranslatableString)value).translate(adLanguage); } else if (value instanceof RepoIdAware) { return String.valueOf(((RepoIdAware)value).getRepoId()); } else if (value instanceof ReferenceListAwareEnum) { return ((ReferenceListAwareEnum)value).getCode(); } else if (value instanceof Collection) { //noinspection unchecked final Collection<Object> collection = (Collection<Object>)value; return collection.stream() .map(item -> convertParameterToJson(item, adLanguage)) .collect(Collectors.toList()); } else if (value instanceof Map) { //noinspection unchecked final Map<Object, Object> map = (Map<Object, Object>)value; return convertParametersMapToJson(map, adLanguage); } else { return value.toString(); // return JsonObjectMapperHolder.toJsonOrToString(value); } }
@NonNull private static String convertParameterToStringJson(@Nullable final Object value, @NonNull final String adLanguage) { if (value == null || Null.isNull(value)) { return "<null>"; } else if (value instanceof ITranslatableString) { return ((ITranslatableString)value).translate(adLanguage); } else if (value instanceof RepoIdAware) { return String.valueOf(((RepoIdAware)value).getRepoId()); } else if (value instanceof ReferenceListAwareEnum) { return ((ReferenceListAwareEnum)value).getCode(); } else { return value.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\v2\JsonErrors.java
1
请在Spring Boot框架中完成以下Java代码
public class GolferService { private final GemfireTemplate golfersTemplate; private final GolferRepository golferRepository; public GolferService(@Qualifier("golfersTemplate") GemfireTemplate golfersTemplate, GolferRepository golferRepository) { Assert.notNull(golfersTemplate, "GolfersTemplate must not be null"); Assert.notNull(golferRepository, "GolferRepository must not be null"); this.golfersTemplate = golfersTemplate; this.golferRepository = golferRepository; } // tag::cache-put[] @CachePut(cacheNames = "Golfers", key = "#golfer.name") public Golfer update(Golfer golfer) { return golfer; }
// end::cache-put[] public List<Golfer> getAllGolfersFromCache() { Map<String, Golfer> golferMap = CollectionUtils.nullSafeMap(this.golfersTemplate.getAll(resolveKeys(this.golfersTemplate.getRegion()))); return CollectionUtils.sort(new ArrayList<>(golferMap.values())); } public List<Golfer> getAllGolfersFromDatabase() { return CollectionUtils.sort(this.golferRepository.findAll()); } private Set<String> resolveKeys(Region<String, ?> region) { return RegionUtils.isClient(region) ? region.keySetOnServer() : region.keySet(); } } // end::class[]
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\service\GolferService.java
2
请完成以下Java代码
public void setName(String name) { this.name = name; } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } @GET @Path("{studentId}") public Student getStudent(@PathParam("studentId") int studentId) { return findById(studentId); } @POST public Response createStudent(Student student) { for (Student element : students) { if (element.getId() == student.getId()) { return Response.status(Response.Status.CONFLICT).build(); } } students.add(student); return Response.ok(student).build(); } @DELETE @Path("{studentId}") public Response deleteStudent(@PathParam("studentId") int studentId) { Student student = findById(studentId); if (student == null) { return Response.status(Response.Status.NOT_FOUND).build(); }
students.remove(student); return Response.ok().build(); } private Student findById(int id) { for (Student student : students) { if (student.getId() == id) { return student; } } return null; } @Override public int hashCode() { return id + name.hashCode(); } @Override public boolean equals(Object obj) { return (obj instanceof Course) && (id == ((Course) obj).getId()) && (name.equals(((Course) obj).getName())); } }
repos\tutorials-master\apache-cxf-modules\cxf-jaxrs-implementation\src\main\java\com\baeldung\cxf\jaxrs\implementation\Course.java
1
请在Spring Boot框架中完成以下Java代码
public class RabbitMqConfig { /** * 订单消息实际消费队列所绑定的交换机 */ @Bean DirectExchange orderDirect() { return ExchangeBuilder .directExchange(QueueEnum.QUEUE_ORDER_CANCEL.getExchange()) .durable(true) .build(); } /** * 订单延迟队列所绑定的交换机 */ @Bean DirectExchange orderTtlDirect() { return ExchangeBuilder .directExchange(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getExchange()) .durable(true) .build(); } /** * 订单实际消费队列 */ @Bean public Queue orderQueue() { return new Queue(QueueEnum.QUEUE_ORDER_CANCEL.getName()); } /** * 订单延迟队列(死信队列) */ @Bean public Queue orderTtlQueue() { return QueueBuilder .durable(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getName()) .withArgument("x-dead-letter-exchange", QueueEnum.QUEUE_ORDER_CANCEL.getExchange())//到期后转发的交换机 .withArgument("x-dead-letter-routing-key", QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey())//到期后转发的路由键 .build(); }
/** * 将订单队列绑定到交换机 */ @Bean Binding orderBinding(DirectExchange orderDirect,Queue orderQueue){ return BindingBuilder .bind(orderQueue) .to(orderDirect) .with(QueueEnum.QUEUE_ORDER_CANCEL.getRouteKey()); } /** * 将订单延迟队列绑定到交换机 */ @Bean Binding orderTtlBinding(DirectExchange orderTtlDirect,Queue orderTtlQueue){ return BindingBuilder .bind(orderTtlQueue) .to(orderTtlDirect) .with(QueueEnum.QUEUE_TTL_ORDER_CANCEL.getRouteKey()); } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\config\RabbitMqConfig.java
2
请在Spring Boot框架中完成以下Java代码
public JSONObject addUser(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "username, password, nickname, roleIds"); return userService.addUser(requestJson); } @RequiresPermissions("user:update") @PostMapping("/updateUser") public JSONObject updateUser(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, " nickname, roleIds, deleteStatus, userId"); return userService.updateUser(requestJson); } @RequiresPermissions(value = {"user:add", "user:update"}, logical = Logical.OR) @GetMapping("/getAllRoles") public JSONObject getAllRoles() { return userService.getAllRoles(); } /** * 角色列表 */ @RequiresPermissions("role:list") @GetMapping("/listRole") public JSONObject listRole() { return userService.listRole(); } /** * 查询所有权限, 给角色分配权限时调用 */ @RequiresPermissions("role:list") @GetMapping("/listAllPermission") public JSONObject listAllPermission() { return userService.listAllPermission(); } /** * 新增角色 */ @RequiresPermissions("role:add") @PostMapping("/addRole")
public JSONObject addRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleName,permissions"); return userService.addRole(requestJson); } /** * 修改角色 */ @RequiresPermissions("role:update") @PostMapping("/updateRole") public JSONObject updateRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId,roleName,permissions"); return userService.updateRole(requestJson); } /** * 删除角色 */ @RequiresPermissions("role:delete") @PostMapping("/deleteRole") public JSONObject deleteRole(@RequestBody JSONObject requestJson) { CommonUtil.hasAllRequired(requestJson, "roleId"); return userService.deleteRole(requestJson); } }
repos\SpringBoot-Shiro-Vue-master\back\src\main\java\com\heeexy\example\controller\UserController.java
2
请完成以下Java代码
public Optional<Car> findByModel(String model) { return stream().where(c -> c.getModel() .equals(model)) .findFirst(); } @Override public List<Car> findByModelAndDescription(String model, String desc) { return stream().where(c -> c.getModel() .equals(model) && c.getDescription() .contains(desc)) .toList(); } @Override public List<Tuple3<String, Integer, String>> findWithModelYearAndEngine() { return stream().select(c -> new Tuple3<>(c.getModel(), c.getYear(), c.getEngine())) .toList(); } @Override public Optional<Manufacturer> findManufacturerByModel(String model) { return stream().where(c -> c.getModel() .equals(model)) .select(c -> c.getManufacturer()) .findFirst(); } @Override public List<Pair<Manufacturer, Car>> findCarsPerManufacturer() { return streamOf(Manufacturer.class).join(m -> JinqStream.from(m.getCars())) .toList(); } @Override public long countCarsByModel(String model) {
return stream().where(c -> c.getModel() .equals(model)) .count(); } @Override public List<Car> findAll(int skip, int limit) { return stream().skip(skip) .limit(limit) .toList(); } @Override protected Class<Car> entityType() { return Car.class; } }
repos\tutorials-master\spring-jinq\src\main\java\com\baeldung\spring\jinq\repositories\CarRepositoryImpl.java
1
请完成以下Java代码
public String getFieldName() { return fieldName; } public void setFieldName(String fieldName) { this.fieldName = fieldName; } public String getStringValue() { return stringValue; } public void setStringValue(String stringValue) { this.stringValue = stringValue; } public String getExpression() { return expression;
} public void setExpression(String expression) { this.expression = expression; } public FieldExtension clone() { FieldExtension clone = new FieldExtension(); clone.setValues(this); return clone; } public void setValues(FieldExtension otherExtension) { setFieldName(otherExtension.getFieldName()); setStringValue(otherExtension.getStringValue()); setExpression(otherExtension.getExpression()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\FieldExtension.java
1
请完成以下Java代码
public class Person { private String name; private FullName fullName; private int age; private Date birthday; private List<String> hobbies; private Map<String, String> clothes; private List<Person> friends; public String getName() { return name; } public void setName(String name) { this.name = name; } public FullName getFullName() { return fullName; } public void setFullName(FullName fullName) { this.fullName = fullName; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies;
} public Map<String, String> getClothes() { return clothes; } public void setClothes(Map<String, String> clothes) { this.clothes = clothes; } public List<Person> getFriends() { return friends; } public void setFriends(List<Person> friends) { this.friends = friends; } @Override public String toString() { StringBuilder str = new StringBuilder("Person [name=" + name + ", fullName=" + fullName + ", age=" + age + ", birthday=" + birthday + ", hobbies=" + hobbies + ", clothes=" + clothes + "]\n"); if (friends != null) { str.append("Friends:\n"); for (Person f : friends) { str.append("\t").append(f); } } return str.toString(); } }
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\model\Person.java
1
请在Spring Boot框架中完成以下Java代码
public String xxlJobAdd() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("jobGroup", 2); jobInfo.put("jobCron", "0 0/1 * * * ? *"); jobInfo.put("jobDesc", "手动添加的任务"); jobInfo.put("author", "admin"); jobInfo.put("executorRouteStrategy", "ROUND"); jobInfo.put("executorHandler", "demoTask"); jobInfo.put("executorParam", "手动添加的任务的参数"); jobInfo.put("executorBlockStrategy", ExecutorBlockStrategyEnum.SERIAL_EXECUTION); jobInfo.put("glueType", GlueTypeEnum.BEAN); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/add").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } /** * 测试手动触发一次任务 */ @GetMapping("/trigger") public String xxlJobTrigger() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); jobInfo.put("executorParam", JSONUtil.toJsonStr(jobInfo)); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/trigger").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } /** * 测试手动删除任务 */ @GetMapping("/remove") public String xxlJobRemove() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4);
HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/remove").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } /** * 测试手动停止任务 */ @GetMapping("/stop") public String xxlJobStop() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/stop").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } /** * 测试手动启动任务 */ @GetMapping("/start") public String xxlJobStart() { Map<String, Object> jobInfo = Maps.newHashMap(); jobInfo.put("id", 4); HttpResponse execute = HttpUtil.createGet(baseUri + JOB_INFO_URI + "/start").form(jobInfo).execute(); log.info("【execute】= {}", execute); return execute.body(); } }
repos\spring-boot-demo-master\demo-task-xxl-job\src\main\java\com\xkcoding\task\xxl\job\controller\ManualOperateController.java
2
请完成以下Java代码
public void setProjectCategory (final @Nullable java.lang.String ProjectCategory) { set_ValueNoCheck (COLUMNNAME_ProjectCategory, ProjectCategory); } @Override public java.lang.String getProjectCategory() { return get_ValueAsString(COLUMNNAME_ProjectCategory); } @Override public void setProjectName (final java.lang.String ProjectName) { set_ValueNoCheck (COLUMNNAME_ProjectName, ProjectName); } @Override public java.lang.String getProjectName() { return get_ValueAsString(COLUMNNAME_ProjectName); } @Override public void setProjectPhaseName (final @Nullable java.lang.String ProjectPhaseName) { set_ValueNoCheck (COLUMNNAME_ProjectPhaseName, ProjectPhaseName); } @Override public java.lang.String getProjectPhaseName() { return get_ValueAsString(COLUMNNAME_ProjectPhaseName); } @Override public void setProjectTypeName (final @Nullable java.lang.String ProjectTypeName) { set_ValueNoCheck (COLUMNNAME_ProjectTypeName, ProjectTypeName); } @Override public java.lang.String getProjectTypeName() { return get_ValueAsString(COLUMNNAME_ProjectTypeName); } @Override public void setReferenceNo (final @Nullable java.lang.String ReferenceNo) { set_ValueNoCheck (COLUMNNAME_ReferenceNo, ReferenceNo); } @Override public java.lang.String getReferenceNo() { return get_ValueAsString(COLUMNNAME_ReferenceNo); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null); else set_ValueNoCheck (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setSalesRep_Name (final @Nullable java.lang.String SalesRep_Name) { set_ValueNoCheck (COLUMNNAME_SalesRep_Name, SalesRep_Name);
} @Override public java.lang.String getSalesRep_Name() { return get_ValueAsString(COLUMNNAME_SalesRep_Name); } @Override public void setTaxID (final java.lang.String TaxID) { set_ValueNoCheck (COLUMNNAME_TaxID, TaxID); } @Override public java.lang.String getTaxID() { return get_ValueAsString(COLUMNNAME_TaxID); } @Override public void setTitle (final @Nullable java.lang.String Title) { set_ValueNoCheck (COLUMNNAME_Title, Title); } @Override public java.lang.String getTitle() { return get_ValueAsString(COLUMNNAME_Title); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Header_v.java
1
请完成以下Java代码
public String getExpressionString() { return "@CustomSequenceNo@"; } @Override public Set<CtxName> getParameters() { return PARAMETERS; } @Override public String evaluate(final Evaluatee ctx, final IExpressionEvaluator.OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException { final ClientId adClientId = Optional.ofNullable(ctx.get_ValueAsInt(PARAMETER_AD_Client_ID, null)) .map(ClientId::ofRepoId) .orElseGet(() -> ClientId.ofRepoId(Env.getAD_Client_ID(Env.getCtx()))); final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class);
final String sequenceNo = documentNoFactory.forSequenceId(sequenceId) .setFailOnError(onVariableNotFound.equals(IExpressionEvaluator.OnVariableNotFound.Fail)) .setClientId(adClientId) .build(); if (sequenceNo == null && onVariableNotFound == IExpressionEvaluator.OnVariableNotFound.Fail) { throw new AdempiereException("Failed to compute sequence!") .appendParametersToMessage() .setParameter("sequenceId", sequenceId); } return sequenceNo; } @NonNull public static DocSequenceAwareFieldStringExpression of(@NonNull final DocSequenceId sequenceId) { return new DocSequenceAwareFieldStringExpression(sequenceId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocSequenceAwareFieldStringExpression.java
1