instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class F2FPayResultVo { /** * 交易状态 */ private String status; /** * 交易流水号流水号 */ private String trxNo; /** * 商户订单号 */ private String orderNo; /** * 支付KEY */ private String payKey; /** 产品名称 **/ private String productName; /** 支付备注 **/ private String remark; /** 下单Ip **/ private String orderIp; /** 备注字段1 **/ private String field1; /** 备注字段2 **/ private String field2; /** 备注字段3 **/ private String field3; /** 备注字段4 **/ private String field4; /** 备注字段5 **/ private String field5; /** * 签名数据 */ private String sign; public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public String getTrxNo() { return trxNo; } public void setTrxNo(String trxNo) { this.trxNo = trxNo; } public String getOrderNo() { return orderNo; } public void setOrderNo(String orderNo) { this.orderNo = orderNo; } public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getOrderIp() { return orderIp; } public void setOrderIp(String orderIp) { this.orderIp = orderIp;
} public String getField1() { return field1; } public void setField1(String field1) { this.field1 = field1; } public String getField2() { return field2; } public void setField2(String field2) { this.field2 = field2; } public String getField3() { return field3; } public void setField3(String field3) { this.field3 = field3; } public String getField4() { return field4; } public void setField4(String field4) { this.field4 = field4; } public String getField5() { return field5; } public void setField5(String field5) { this.field5 = field5; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\F2FPayResultVo.java
2
请完成以下Java代码
public void setDynamicSubProcessId(String dynamicSubProcessId) { this.dynamicSubProcessId = dynamicSubProcessId; } public String nextSubProcessId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicSubProcess", flowElementMap); } public String nextTaskId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicTask", flowElementMap); } public String nextFlowId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicFlow", flowElementMap); } public String nextForkGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicForkGateway", flowElementMap); } public String nextJoinGatewayId(Map<String, FlowElement> flowElementMap) { return nextId("dynamicJoinGateway", flowElementMap); }
public String nextStartEventId(Map<String, FlowElement> flowElementMap) { return nextId("startEvent", flowElementMap); } public String nextEndEventId(Map<String, FlowElement> flowElementMap) { return nextId("endEvent", flowElementMap); } protected String nextId(String prefix, Map<String, FlowElement> flowElementMap) { String nextId = null; boolean nextIdNotFound = true; while (nextIdNotFound) { if (!flowElementMap.containsKey(prefix + counter)) { nextId = prefix + counter; nextIdNotFound = false; } counter++; } return nextId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\DynamicEmbeddedSubProcessBuilder.java
1
请完成以下Java代码
public String toString() { return "-"; } }; private final Operator operator; private final AstNode left, right; public AstBinary(AstNode left, AstNode right, Operator operator) { this.left = left; this.right = right; this.operator = operator; } public Operator getOperator() { return operator; } @Override public Object eval(Bindings bindings, ELContext context) { return operator.eval(bindings, context, left, right); } @Override
public String toString() { return "'" + operator.toString() + "'"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { left.appendStructure(b, bindings); b.append(' '); b.append(operator); b.append(' '); right.appendStructure(b, bindings); } public int getCardinality() { return 2; } public AstNode getChild(int i) { return i == 0 ? left : i == 1 ? right : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBinary.java
1
请完成以下Java代码
private ITranslatableString extractWarehouseFrom(final @NotNull DDOrderReference ddOrderReference) { return TranslatableStrings.anyLanguage(warehouseService.getWarehouseName(ddOrderReference.getFromWarehouseId())); } private ITranslatableString extractWarehouseTo(final @NotNull DDOrderReference ddOrderReference) { return TranslatableStrings.anyLanguage(warehouseService.getWarehouseName(ddOrderReference.getToWarehouseId())); } private ITranslatableString extractPickDate(final @NotNull DDOrderReference ddOrderReference) { return TranslatableStrings.dateAndTime(ddOrderReference.getDisplayDate()); } private ITranslatableString extractPlant(final @NotNull DDOrderReference ddOrderReference) { final ResourceId plantId = ddOrderReference.getPlantId(); return plantId != null ? TranslatableStrings.anyLanguage(sourceDocService.getPlantName(plantId)) : TranslatableStrings.empty(); } private static ITranslatableString extractQty(final @NotNull DDOrderReference ddOrderReference) { final Quantity qty = ddOrderReference.getQty(); return qty != null ? TranslatableStrings.builder().appendQty(qty.toBigDecimal(), qty.getUOMSymbol()).build() : TranslatableStrings.empty(); } private ITranslatableString extractProductValueAndName(final @NotNull DDOrderReference ddOrderReference) { final ProductId productId = ddOrderReference.getProductId(); return productId != null ? TranslatableStrings.anyLanguage(productService.getProductValueAndName(productId)) : TranslatableStrings.empty(); } private @NotNull ITranslatableString extractGTIN(final @NotNull DDOrderReference ddOrderReference) {
return Optional.ofNullable(ddOrderReference.getProductId()) .flatMap(productService::getGTIN) .map(GTIN::getAsString) .map(TranslatableStrings::anyLanguage) .orElse(TranslatableStrings.empty()); } @NonNull private ITranslatableString extractSourceDoc(@NonNull final DDOrderReference ddOrderReference) { ImmutablePair<ITranslatableString, String> documentTypeAndNo; if (ddOrderReference.getSalesOrderId() != null) { documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getSalesOrderId()); } else if (ddOrderReference.getPpOrderId() != null) { documentTypeAndNo = sourceDocService.getDocumentTypeAndName(ddOrderReference.getPpOrderId()); } else { return TranslatableStrings.empty(); } return TranslatableStrings.builder() .append(documentTypeAndNo.getLeft()) .append(" ") .append(documentTypeAndNo.getRight()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\DistributionLauncherCaptionProvider.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** 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); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */
public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation.java
1
请在Spring Boot框架中完成以下Java代码
public ResourceBundleThemeSource themeSource() { ResourceBundleThemeSource themeSource = new ResourceBundleThemeSource(); themeSource.setDefaultEncoding("UTF-8"); themeSource.setBasenamePrefix("themes."); return themeSource; } @Bean public CookieThemeResolver themeResolver() { CookieThemeResolver resolver = new CookieThemeResolver(); resolver.setDefaultThemeName("default"); resolver.setCookieName("example-theme-cookie"); return resolver; } @Bean public ThemeChangeInterceptor themeChangeInterceptor() { ThemeChangeInterceptor interceptor = new ThemeChangeInterceptor(); interceptor.setParamName("theme"); return interceptor;
} @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(themeChangeInterceptor()); } @Bean public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() { return factory -> factory.setRegisterDefaultServlet(true); } @Bean public ObjectMapper objectMapper() { return new ObjectMapper(); } }
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\web\config\WebConfig.java
2
请完成以下Java代码
public static UserAuthQRCode fromGlobalQRCodeJsonString(final String qrCodeString) { return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString)); } public static UserAuthQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode) { if (!isTypeMatching(globalQRCode)) { throw new AdempiereException("Invalid QR Code") .setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long } final GlobalQRCodeVersion version = globalQRCode.getVersion(); if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{ return JsonConverterV1.fromGlobalQRCode(globalQRCode); } else { throw new AdempiereException("Invalid QR Code version: " + version); } } public static boolean isTypeMatching(final @NonNull GlobalQRCode globalQRCode) { return GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\qr\UserAuthQRCodeJsonConverter.java
1
请在Spring Boot框架中完成以下Java代码
public Result<Map<String, String>> getDepPostIdByDepId(@RequestParam(name = "depIds") String depIds) { String departIds = sysDepartService.getDepPostIdByDepId(depIds); return Result.OK(departIds); } /** * 更新改变后的部门数据 * * @param changeDepartVo * @return */ @PutMapping("/updateChangeDepart") @RequiresPermissions("system:depart:updateChange") @RequiresRoles({"admin"}) public Result<String> updateChangeDepart(@RequestBody SysChangeDepartVo changeDepartVo) { sysDepartService.updateChangeDepart(changeDepartVo); return Result.ok("调整部门位置成功!"); }
/** * 获取部门负责人 * * @param departId * @return */ @GetMapping("/getDepartmentHead") public Result<IPage<SysUser>> getDepartmentHead(@RequestParam(name = "departId") String departId, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize){ Page<SysUser> page = new Page<>(pageNo, pageSize); IPage<SysUser> pageList = sysDepartService.getDepartmentHead(departId,page); return Result.OK(pageList); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDepartController.java
2
请完成以下Spring Boot application配置
initializr: env: kotlin: default-version: "1.9.22" group-id: value: org.acme dependencies: - name: Web content: - name: Web id: web description: Servlet web application with Spring MVC and Tomcat languages: - name: Java id: java default: true - name: Kotlin id: kotlin default: false - name: Groovy id: groovy default: false javaVersions: - id: 17 default: true - id: 11 default: false - id: 1.8 name: 8 default: false packagings: - name: Jar id: jar default: true - name: War id: war default: false types: - name: Maven Project id: maven-project description: Generate a Maven based project archive tags: build: maven format: project default: true acti
on: /starter.zip - name: Gradle Project id: gradle-project description: Generate a Gradle based project archive tags: build: gradle format: project default: false action: /starter.zip configuration-file-formats: - name: Properties id: properties default: true - name: YAML id: yaml default: false
repos\initializr-main\initializr-service-sample\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public static class AdditionalCost { @XmlElement(name = "AdditionalCostType", required = true) protected String additionalCostType; @XmlElement(name = "AdditionalCostAmount", required = true) protected BigDecimal additionalCostAmount; @XmlElement(name = "VATRate") protected BigDecimal vatRate; /** * Gets the value of the additionalCostType property. * * @return * possible object is * {@link String } * */ public String getAdditionalCostType() { return additionalCostType; } /** * Sets the value of the additionalCostType property. * * @param value * allowed object is * {@link String } * */ public void setAdditionalCostType(String value) { this.additionalCostType = value; } /** * Gets the value of the additionalCostAmount property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getAdditionalCostAmount() { return additionalCostAmount; } /** * Sets the value of the additionalCostAmount property. * * @param value * allowed object is * {@link BigDecimal } *
*/ public void setAdditionalCostAmount(BigDecimal value) { this.additionalCostAmount = value; } /** * Gets the value of the vatRate property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getVATRate() { return vatRate; } /** * Sets the value of the vatRate property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setVATRate(BigDecimal value) { this.vatRate = value; } } }
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\AdditionalCostsType.java
2
请完成以下Java代码
public class WordCounterActor extends AbstractActor { private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this); public static final class CountWords { String line; public CountWords(String line) { this.line = line; } } @Override public void preStart() { log.info("Starting WordCounterActor {}", this); } @Override public Receive createReceive() { return receiveBuilder() .match(CountWords.class, r -> { try { log.info("Received CountWords message from " + getSender()); int numberOfWords = countWordsFromLine(r.line); getSender().tell(numberOfWords, getSelf()); } catch (Exception ex) { getSender().tell(new akka.actor.Status.Failure(ex), getSelf()); throw ex; } }) .build(); }
private int countWordsFromLine(String line) throws Exception { if (line == null) { throw new IllegalArgumentException("The text to process can't be null!"); } int numberOfWords = 0; String[] words = line.split(" "); for (String possibleWord : words) { if (possibleWord.trim().length() > 0) { numberOfWords++; } } return numberOfWords; } }
repos\tutorials-master\akka-modules\akka-actors\src\main\java\com\baeldung\akkaactors\WordCounterActor.java
1
请在Spring Boot框架中完成以下Java代码
public AuthorView fetchNextPage(long id, int limit) { List<Author> authors = authorRepository.fetchAll(id, limit + 1); if (authors.size() == (limit + 1)) { authors.remove(authors.size() - 1); return new AuthorView(authors, false); } return new AuthorView(authors, true); } public AuthorViewDto fetchNextPageDto(long id, int limit) { List<AuthorDto> authors = authorRepository.fetchAllDto(id, limit + 1); if (authors.size() == (limit + 1)) { authors.remove(authors.size() - 1); return new AuthorViewDto(authors, false); }
return new AuthorViewDto(authors, true); } // Or, like this (rely on Author.toString() method): /* public Map<List<Author>, Boolean> fetchNextPage(long id, int limit) { List<Author> authors = authorRepository.fetchAll(id, limit + 1); if (authors.size() == (limit + 1)) { authors.remove(authors.size() - 1); return Collections.singletonMap(authors, true); } return Collections.singletonMap(authors, false); } */ }
repos\Hibernate-SpringBoot-master\HibernateSpringBootKeysetPaginationNextPage\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public void setTrxType (final java.lang.String TrxType) { set_Value (COLUMNNAME_TrxType, TrxType); } @Override public java.lang.String getTrxType() { return get_ValueAsString(COLUMNNAME_TrxType); } @Override public org.compiere.model.I_C_ElementValue getUser1() { return get_ValueAsPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class); } @Override public void setUser1(final org.compiere.model.I_C_ElementValue User1) { set_ValueFromPO(COLUMNNAME_User1_ID, org.compiere.model.I_C_ElementValue.class, User1); } @Override public void setUser1_ID (final int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, User1_ID); } @Override public int getUser1_ID() { return get_ValueAsInt(COLUMNNAME_User1_ID); } @Override public org.compiere.model.I_C_ElementValue getUser2() { return get_ValueAsPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class); } @Override
public void setUser2(final org.compiere.model.I_C_ElementValue User2) { set_ValueFromPO(COLUMNNAME_User2_ID, org.compiere.model.I_C_ElementValue.class, User2); } @Override public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } @Override public void setVoiceAuthCode (final @Nullable java.lang.String VoiceAuthCode) { set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode); } @Override public java.lang.String getVoiceAuthCode() { return get_ValueAsString(COLUMNNAME_VoiceAuthCode); } @Override public void setWriteOffAmt (final @Nullable BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } @Override public BigDecimal getWriteOffAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WriteOffAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment.java
1
请完成以下Java代码
private DocumentIdsSelection getSelectedRootDocumentIds() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isAll()) { return selectedRowIds; } else if (selectedRowIds.isEmpty()) { return selectedRowIds; } else { return selectedRowIds.stream().filter(DocumentId::isInt).collect(DocumentIdsSelection.toDocumentIdsSelection()); } } private Optional<ProductBarcodeFilterData> getProductBarcodeFilterData() {
return PackageableFilterDescriptorProvider.extractProductBarcodeFilterData(getView()); } private List<ShipmentScheduleId> getShipmentScheduleIds() { final DocumentIdsSelection selectedRowIds = getSelectedRootDocumentIds(); return getView().streamByIds(selectedRowIds) .flatMap(selectedRow -> selectedRow.getIncludedRows().stream()) .map(IViewRow::getId) .distinct() .map(DocumentId::removeDocumentPrefixAndConvertToInt) .map(ShipmentScheduleId::ofRepoIdOrNull) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\process\WEBUI_Picking_Launcher.java
1
请完成以下Java代码
public class Html2PdfUsingFlyingSaucer { private static final String HTML_INPUT = "src/main/resources/htmlforopenpdf.html"; private static final String PDF_OUTPUT = "src/main/resources/html2pdf.pdf"; public static void main(String[] args) { try { Html2PdfUsingFlyingSaucer htmlToPdf = new Html2PdfUsingFlyingSaucer(); htmlToPdf.generateHtmlToPdf(); } catch (Exception e) { e.printStackTrace(); } } private void generateHtmlToPdf() throws Exception { File inputHTML = new File(HTML_INPUT); Document inputHtml = createWellFormedHtml(inputHTML); File outputPdf = new File(PDF_OUTPUT); xhtmlToPdf(inputHtml, outputPdf); }
private Document createWellFormedHtml(File inputHTML) throws IOException { Document document = Jsoup.parse(inputHTML, "UTF-8"); document.outputSettings() .syntax(Document.OutputSettings.Syntax.xml); return document; } private void xhtmlToPdf(Document xhtml, File outputPdf) throws Exception { try (OutputStream outputStream = new FileOutputStream(outputPdf)) { ITextRenderer renderer = new ITextRenderer(); SharedContext sharedContext = renderer.getSharedContext(); sharedContext.setPrint(true); sharedContext.setInteractive(false); sharedContext.setReplacedElementFactory(new CustomElementFactoryImpl()); renderer.setDocumentFromString(xhtml.html()); renderer.layout(); renderer.createPDF(outputStream); } } }
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\openpdf\Html2PdfUsingFlyingSaucer.java
1
请完成以下Java代码
public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_Occupation_Specialization_ID (final int AD_User_Occupation_Specialization_ID) { if (AD_User_Occupation_Specialization_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Specialization_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_Occupation_Specialization_ID, AD_User_Occupation_Specialization_ID); } @Override public int getAD_User_Occupation_Specialization_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_Occupation_Specialization_ID); }
@Override public org.compiere.model.I_CRM_Occupation getCRM_Occupation() { return get_ValueAsPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class); } @Override public void setCRM_Occupation(final org.compiere.model.I_CRM_Occupation CRM_Occupation) { set_ValueFromPO(COLUMNNAME_CRM_Occupation_ID, org.compiere.model.I_CRM_Occupation.class, CRM_Occupation); } @Override public void setCRM_Occupation_ID (final int CRM_Occupation_ID) { if (CRM_Occupation_ID < 1) set_Value (COLUMNNAME_CRM_Occupation_ID, null); else set_Value (COLUMNNAME_CRM_Occupation_ID, CRM_Occupation_ID); } @Override public int getCRM_Occupation_ID() { return get_ValueAsInt(COLUMNNAME_CRM_Occupation_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Occupation_Specialization.java
1
请在Spring Boot框架中完成以下Java代码
public class PersistenceProductConfiguration { private final Environment env; public PersistenceProductConfiguration(Environment env) { this.env = env; } @Bean public LocalContainerEntityManagerFactoryBean productEntityManager() { final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean(); em.setDataSource(productDataSource()); em.setPackagesToScan("com.baeldung.jpa.paginationsorting"); final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); em.setJpaVendorAdapter(vendorAdapter); final HashMap<String, Object> properties = new HashMap<String, Object>(); properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto")); properties.put("hibernate.dialect", env.getProperty("hibernate.dialect")); em.setJpaPropertyMap(properties); return em; } @Bean
public DataSource productDataSource() { final DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(Preconditions.checkNotNull(env.getProperty("jdbc.driverClassName"))); dataSource.setUrl(Preconditions.checkNotNull(env.getProperty("product.jdbc.url"))); dataSource.setUsername(Preconditions.checkNotNull(env.getProperty("jdbc.user"))); dataSource.setPassword(Preconditions.checkNotNull(env.getProperty("jdbc.pass"))); return dataSource; } @Bean public PlatformTransactionManager productTransactionManager() { final JpaTransactionManager transactionManager = new JpaTransactionManager(); transactionManager.setEntityManagerFactory(productEntityManager().getObject()); return transactionManager; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\paginationsorting\config\PersistenceProductConfiguration.java
2
请完成以下Java代码
public class Info_Column extends ColumnInfo { @Getter @Setter private int seqNo; public Info_Column(String colHeader, @NonNull String columnName, Class<?> colClass) { super(colHeader, columnName, colClass); setColumnName(columnName); } public Info_Column(@NonNull String columnName, String colHeader, String colSQL, Class<?> colClass, String IDcolSQL) { super(colHeader, colSQL, colClass, true, false, IDcolSQL); setColumnName(columnName); } public void setIDcolSQL(String IDcolSQL) { super.setKeyPairColSQL(IDcolSQL); }
public String getIDcolSQL() { return super.getKeyPairColSQL(); } public boolean isIDcol() { return super.isKeyPairCol(); } @Override public String toString() { return super.toString(); } } // infoColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\search\Info_Column.java
1
请完成以下Java代码
public org.compiere.model.I_M_CostElement getM_CostElement() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class); } @Override public void setM_CostElement(org.compiere.model.I_M_CostElement M_CostElement) { set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement); } /** Set Kostenart. @param M_CostElement_ID Produkt-Kostenart */ @Override public void setM_CostElement_ID (int M_CostElement_ID) { if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null); else set_Value (COLUMNNAME_M_CostElement_ID, Integer.valueOf(M_CostElement_ID)); } /** Get Kostenart. @return Produkt-Kostenart */ @Override public int getM_CostElement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostElement_ID); 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_AcctSchema_CostElement.java
1
请完成以下Java代码
public boolean isVirtualColumn(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.isVirtualColumn(); } @Override public boolean isKeyColumnName(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.isKey(); } @Override public boolean isCalculated(final String columnName) { final GridField field = getGridField(columnName); return field != null && field.getVO().isCalculated(); } @Override public boolean hasColumnName(final String columnName) { return gridTabWrapper.hasColumnName(columnName); } @Override public Object getValue(final String columnName, final int columnIndex, final Class<?> returnType) { return gridTabWrapper.getValue(columnName, returnType); } @Override public Object getValue(final String columnName, final Class<?> returnType) { return gridTabWrapper.getValue(columnName, returnType); } @Override public boolean setValue(final String columnName, final Object value) { gridTabWrapper.setValue(columnName, value); return true; } @Override public boolean setValueNoCheck(final String columnName, final Object value) { gridTabWrapper.setValue(columnName, value); return true; } @Override public Object getReferencedObject(final String columnName, final Method interfaceMethod) throws Exception
{ // TODO: implement throw new UnsupportedOperationException(); } @Override public void setValueFromPO(final String idColumnName, final Class<?> parameterType, final Object value) { // TODO: implement throw new UnsupportedOperationException(); } @Override public boolean invokeEquals(final Object[] methodArgs) { // TODO: implement throw new UnsupportedOperationException(); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { // TODO: implement throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\GridTabModelInternalAccessor.java
1
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNSequenceFlowImpl that = (BPMNSequenceFlowImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(sourceActivityElementId, that.getSourceActivityElementId()) && Objects.equals(sourceActivityType, that.getSourceActivityType()) && Objects.equals(sourceActivityName, that.getSourceActivityName()) && Objects.equals(targetActivityElementId, that.getTargetActivityElementId()) && Objects.equals(targetActivityType, that.getTargetActivityType()) && Objects.equals(targetActivityName, that.getTargetActivityName()) ); } @Override public int hashCode() { return Objects.hash(getElementId(), sourceActivityElementId, targetActivityElementId); } @Override
public String toString() { return ( "SequenceFlowImpl{" + "sourceActivityElementId='" + sourceActivityElementId + '\'' + ", sourceActivityName='" + sourceActivityName + '\'' + ", sourceActivityType='" + sourceActivityType + '\'' + ", targetActivityElementId='" + targetActivityElementId + '\'' + ", targetActivityName='" + targetActivityName + '\'' + ", targetActivityType='" + targetActivityType + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNSequenceFlowImpl.java
1
请完成以下Spring Boot application配置
spring: application: name: listener-demo # RabbitMQ 相关配置项 rabbitmq: host: localhost port: 5672 username: guest password: guest server: port: 18080 # 随机端口,方便启动多个消费者 management: endpoints: # Actuator HTTP 配置项,对应 WebEndpointPr
operties 配置类 web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
repos\SpringBoot-Labs-master\labx-18\labx-18-sc-bus-rabbitmq-demo-listener-actuator\src\main\resources\application.yml
2
请在Spring Boot框架中完成以下Java代码
public class DocTypeInvoicingPoolId implements RepoIdAware { @JsonCreator public static DocTypeInvoicingPoolId ofRepoId(final int repoId) { return new DocTypeInvoicingPoolId(repoId); } @Nullable public static DocTypeInvoicingPoolId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } @NonNull public static Optional<DocTypeInvoicingPoolId> optionalOfRepoId(@Nullable final Integer repoId) { return repoId != null ? Optional.ofNullable(ofRepoIdOrNull(repoId)) : Optional.empty(); }
int repoId; private DocTypeInvoicingPoolId(final int docTypeInvoicingPoolRepoId) { this.repoId = Check.assumeGreaterThanZero(docTypeInvoicingPoolRepoId, I_C_DocType_Invoicing_Pool.COLUMNNAME_C_DocType_Invoicing_Pool_ID); } @Override @JsonValue public int getRepoId() { return repoId; } public static int toRepoId(@Nullable final DocTypeInvoicingPoolId docTypeInvoicingPoolId) { return docTypeInvoicingPoolId != null ? docTypeInvoicingPoolId.getRepoId() : -1; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\invoicingpool\DocTypeInvoicingPoolId.java
2
请完成以下Java代码
public String toString() {return getAsString();} @JsonValue public String getAsString() {return barcode;} /** * @return true if standard/fixed code (i.e. not starting with prefix 28 nor 29) */ public boolean isFixed() {return prefix.isFixed();} public boolean isVariable() {return prefix.isFixed();} /** * @return true if variable weight EAN13 (i.e. starts with prefix 28) */ public boolean isVariableWeight() {return prefix.isVariableWeight();} /** * @return true if internal or variable measure EAN13 (i.e. starts with prefix 29) */
public boolean isInternalUseOrVariableMeasure() {return prefix.isInternalUseOrVariableMeasure();} public Optional<BigDecimal> getWeightInKg() {return Optional.ofNullable(weightInKg);} public GTIN toGTIN() {return GTIN.ofEAN13(this);} public boolean isMatching(@NonNull final EAN13ProductCode expectedProductNo) { return EAN13ProductCode.equals(this.productNo, expectedProductNo); } public boolean productCodeEndsWith(final @NonNull EAN13ProductCode expectedProductCode) { return this.productNo.endsWith(expectedProductCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\gs1\ean13\EAN13.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getDisplayOrder() { return displayOrder; } public void setDisplayOrder(Integer displayOrder) { this.displayOrder = displayOrder;
} public String getIncludeInStageOverview() { return includeInStageOverview; } public void setIncludeInStageOverview(String includeInStageOverview) { this.includeInStageOverview = includeInStageOverview; } public PlanItemDefinition getPlanItemDefinition() { return planItemDefinition; } public void setPlanItemDefinition(PlanItemDefinition planItemDefinition) { this.planItemDefinition = planItemDefinition; } } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetHistoricStageOverviewCmd.java
1
请完成以下Java代码
public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public void setCity(String city) { this.city = city; } public void setCountry(String country) { this.country = country; } public void setZipCode(int zipCode) { this.zipCode = zipCode; }
@Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; return zipCode == address.zipCode && Objects.equals(addressLine1, address.addressLine1) && Objects.equals(addressLine2, address.addressLine2) && Objects.equals(city, address.city) && Objects.equals(country, address.country); } @Override public int hashCode() { return Objects.hash(addressLine1, addressLine2, city, country, zipCode); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\Address.java
1
请完成以下Java代码
public Amount getUserEnteredPrice() { return Amount.of(getUserEnteredPriceValue(), getCurrencyCode()); } public ProductProposalPrice withUserEnteredPriceValue(@NonNull final BigDecimal userEnteredPriceValue) { if (this.userEnteredPriceValue.equals(userEnteredPriceValue)) { return this; } return toBuilder().userEnteredPriceValue(userEnteredPriceValue).build(); }
public ProductProposalPrice withPriceListPriceValue(@NonNull final BigDecimal priceListPriceValue) { return withPriceListPrice(Amount.of(priceListPriceValue, getCurrencyCode())); } public ProductProposalPrice withPriceListPrice(@NonNull final Amount priceListPrice) { if (this.priceListPrice.equals(priceListPrice)) { return this; } return toBuilder().priceListPrice(priceListPrice).build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductProposalPrice.java
1
请完成以下Java代码
public IWorkPackageBuilder setUserInChargeId(@Nullable final UserId userInChargeId) { assertNotBuilt(); this.userInChargeId = userInChargeId; return this; } @Override public WorkPackageBuilder setAsyncBatchId(@Nullable final AsyncBatchId asyncBatchId) { if (asyncBatchId == null) { return this; } assertNotBuilt(); this.asyncBatchId = asyncBatchId; this.asyncBatchSet = true; return this; } @Override public IWorkPackageBuilder setAD_PInstance_ID(final PInstanceId adPInstanceId) { this.adPInstanceId = adPInstanceId; return this; } @NonNull private I_C_Queue_WorkPackage enqueue(@NonNull final I_C_Queue_WorkPackage workPackage, @Nullable final ILockCommand elementsLocker) { final IWorkPackageQueue workPackageQueue = getWorkpackageQueue(); final IWorkpackagePrioStrategy workPackagePriority = getPriority(); final String originalWorkPackageTrxName = getTrxName(workPackage); try (final IAutoCloseable ignored = () -> setTrxName(workPackage, originalWorkPackageTrxName)) { // Fact: the workpackage trxName is used when creating the workpackage and its elements. // Therefore, we temporarily set it to be our _trxName. // Otherwise, if the current trx fails, the workpackage will have been created, but not have been flagged as "ReadyForProcessing" (which sucks). setTrxName(workPackage, _trxName);
// Set the Async batch if provided if (asyncBatchSet) { workPackage.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId)); } if (userInChargeId != null) { workPackage.setAD_User_InCharge_ID(userInChargeId.getRepoId()); } @SuppressWarnings("deprecation") // Suppressing the warning, because *this class* is the workpackage builder to be used final I_C_Queue_WorkPackage enqueuedWorkpackage = workPackageQueue.enqueueWorkPackage( workPackage, workPackagePriority); try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(enqueuedWorkpackage)) { // Create workpackage parameters if (_parametersBuilder != null) { _parametersBuilder.setC_Queue_WorkPackage(enqueuedWorkpackage); _parametersBuilder.build(); } createWorkpackageElements(workPackageQueue, enqueuedWorkpackage); // // Lock enqueued workpackage elements if (elementsLocker != null) { final ILock lock = elementsLocker.acquire(); lock.unlockAllAfterTrxRollback(); } // // Actually mark the workpackage as ready for processing // NOTE: method also accepts null transaction and in that case it will immediately mark as ready for processing workPackageQueue.markReadyForProcessingAfterTrxCommit(enqueuedWorkpackage, _trxName); } return enqueuedWorkpackage; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageBuilder.java
1
请完成以下Java代码
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException { // 排除指定条件 if ("id".equals(field.getName()) // 排除 id 字段,因为作为查询主键 || field.getAnnotation(Transient.class) != null // 排除 @Transient 注解的字段,因为非存储字段 || Modifier.isStatic(field.getModifiers())) { // 排除静态字段 return; } // 设置字段可反射 if (!field.isAccessible()) { field.setAccessible(true); } // 排除字段为空的情况 if (field.get(entity) == null) { return; } // 设置更新条件 update.set(field.getName(), field.get(entity)); } }); // 防御,避免有业务传递空的 Update 对象 if (update.getUpdateObject().isEmpty()) { return; } // 执行更新 mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(entity.getId())), update, UserDO.class); } public void deleteById(Integer id) {
mongoTemplate.remove(new Query(Criteria.where("_id").is(id)), UserDO.class); } public UserDO findById(Integer id) { return mongoTemplate.findOne(new Query(Criteria.where("_id").is(id)), UserDO.class); } public UserDO findByUsername(String username) { return mongoTemplate.findOne(new Query(Criteria.where("username").is(username)), UserDO.class); } public List<UserDO> findAllById(List<Integer> ids) { return mongoTemplate.find(new Query(Criteria.where("_id").in(ids)), UserDO.class); } }
repos\SpringBoot-Labs-master\lab-16-spring-data-mongo\lab-16-spring-data-mongodb\src\main\java\cn\iocoder\springboot\lab16\springdatamongodb\dao\UserDao.java
1
请完成以下Java代码
public boolean isFunctionRow(final int row) { return false; } @Override public boolean isPageBreak(final int row, final int col) { return false; } @Override protected List<CellValue> getNextRow() { return CellValues.toCellValues(getNextRawDataRow()); } private List<Object> getNextRawDataRow() { try { final List<Object> row = new ArrayList<>(); for (int col = 1; col <= getColumnCount(); col++) { final Object o = m_resultSet.getObject(col); row.add(o); } noDataAddedYet = false;
return row; } catch (final SQLException e) { throw DBException.wrapIfNeeded(e); } } @Override protected boolean hasNextRow() { try { return m_resultSet.next(); } catch (SQLException e) { throw DBException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\JdbcExcelExporter.java
1
请完成以下Java代码
public static MLandedCostAllocation[] getOfInvoiceLine (Properties ctx, int C_InvoiceLine_ID, String trxName) { ArrayList<MLandedCostAllocation> list = new ArrayList<MLandedCostAllocation>(); String sql = "SELECT * FROM C_LandedCostAllocation WHERE C_InvoiceLine_ID=?"; PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, trxName); pstmt.setInt (1, C_InvoiceLine_ID); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MLandedCostAllocation (ctx, rs, trxName)); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { s_log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } MLandedCostAllocation[] retValue = new MLandedCostAllocation[list.size ()]; list.toArray (retValue); return retValue; } // getOfInvliceLine /** Logger */ private static Logger s_log = LogManager.getLogger(MLandedCostAllocation.class); /*************************************************************************** * Standard Constructor * @param ctx context * @param C_LandedCostAllocation_ID id * @param trxName trx */ public MLandedCostAllocation (Properties ctx, int C_LandedCostAllocation_ID, String trxName) { super (ctx, C_LandedCostAllocation_ID, trxName); if (C_LandedCostAllocation_ID == 0) { // setM_CostElement_ID(0); setAmt (Env.ZERO); setQty (Env.ZERO); setBase (Env.ZERO); } } // MLandedCostAllocation /**
* Load Constructor * @param ctx context * @param rs result name * @param trxName trx */ public MLandedCostAllocation (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // MLandedCostAllocation /** * Parent Constructor * @param parent parent * @param M_CostElement_ID cost element */ public MLandedCostAllocation (MInvoiceLine parent, int M_CostElement_ID) { this (parent.getCtx(), 0, parent.get_TrxName()); setClientOrg(parent); setC_InvoiceLine_ID(parent.getC_InvoiceLine_ID()); setM_CostElement_ID(M_CostElement_ID); } // MLandedCostAllocation /** * Set Amt * @param Amt amount * @param precision precision */ public void setAmt (double Amt, CurrencyPrecision precision) { BigDecimal bd = precision.roundIfNeeded(new BigDecimal(Amt)); super.setAmt(bd); } // setAmt } // MLandedCostAllocation
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MLandedCostAllocation.java
1
请完成以下Java代码
default List<String> getAudience() { return this.getClaimAsStringList(IdTokenClaimNames.AUD); } /** * Returns the Expiration time {@code (exp)} on or after which the ID Token MUST NOT * be accepted. * @return the Expiration time on or after which the ID Token MUST NOT be accepted */ default Instant getExpiresAt() { return this.getClaimAsInstant(IdTokenClaimNames.EXP); } /** * Returns the time at which the ID Token was issued {@code (iat)}. * @return the time at which the ID Token was issued */ default Instant getIssuedAt() { return this.getClaimAsInstant(IdTokenClaimNames.IAT); } /** * Returns the time when the End-User authentication occurred {@code (auth_time)}. * @return the time when the End-User authentication occurred */ default Instant getAuthenticatedAt() { return this.getClaimAsInstant(IdTokenClaimNames.AUTH_TIME); } /** * Returns a {@code String} value {@code (nonce)} used to associate a Client session * with an ID Token, and to mitigate replay attacks. * @return the nonce used to associate a Client session with an ID Token */ default String getNonce() { return this.getClaimAsString(IdTokenClaimNames.NONCE); } /** * Returns the Authentication Context Class Reference {@code (acr)}. * @return the Authentication Context Class Reference */ default String getAuthenticationContextClass() { return this.getClaimAsString(IdTokenClaimNames.ACR); } /** * Returns the Authentication Methods References {@code (amr)}. * @return the Authentication Methods References */ default List<String> getAuthenticationMethods() { return this.getClaimAsStringList(IdTokenClaimNames.AMR); }
/** * Returns the Authorized party {@code (azp)} to which the ID Token was issued. * @return the Authorized party to which the ID Token was issued */ default String getAuthorizedParty() { return this.getClaimAsString(IdTokenClaimNames.AZP); } /** * Returns the Access Token hash value {@code (at_hash)}. * @return the Access Token hash value */ default String getAccessTokenHash() { return this.getClaimAsString(IdTokenClaimNames.AT_HASH); } /** * Returns the Authorization Code hash value {@code (c_hash)}. * @return the Authorization Code hash value */ default String getAuthorizationCodeHash() { return this.getClaimAsString(IdTokenClaimNames.C_HASH); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\IdTokenClaimAccessor.java
1
请完成以下Java代码
public void setTabLevel (int level) { if (level == 0) putClientProperty(AdempiereLookAndFeel.TABLEVEL, null); else putClientProperty(AdempiereLookAndFeel.TABLEVEL, new Integer(level)); } // setTabLevel /** * Get Tab Hierarchy Level * @return Tab Level */ public int getTabLevel() { try { Integer ll = (Integer)getClientProperty(AdempiereLookAndFeel.TABLEVEL); if (ll != null) return ll.intValue(); } catch (Exception e) { System.err.println("ClientProperty: " + e.getMessage()); } return 0; } // getTabLevel
/************************************************************************** * String representation * @return String representation */ @Override public String toString() { final StringBuilder sb = new StringBuilder("CPanel ["); sb.append(super.toString()); MFColor bg = getBackgroundColor(); if (bg != null) sb.append(bg.toString()); sb.append("]"); return sb.toString(); } // toString } // CPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CPanel.java
1
请完成以下Java代码
private void assertColumnNameValid(@NonNull final String columnName, final int displayType) { if (DisplayType.isID(displayType) && displayType != DisplayType.Account) { if (!columnName.endsWith("_ID") && !columnName.equals("CreatedBy") && !columnName.equals("UpdatedBy") && !columnName.equals("AD_Language") && !columnName.equals("EntityType")) { throw new AdempiereException("Lookup or ID columns shall have the name ending with `_ID`"); } if (displayType == DisplayType.Locator && !columnName.contains("Locator")) { throw new AdempiereException("A Locator column name must contain the term `Locator`."); } } else if (displayType == DisplayType.Account) { if (!columnName.endsWith("_Acct")) { throw new AdempiereException("Account columns shall have the name ending with `_Acct`"); }
} else { if (columnName.endsWith("_ID") && displayType != DisplayType.Button) { throw new AdempiereException("Ending a non lookup column with `_ID` might be misleading"); } if (columnName.endsWith("_Acct")) { throw new AdempiereException("Ending a non Account column with `_Acct` might be misleading"); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\model\interceptor\AD_Column.java
1
请完成以下Java代码
public class LoginRequest implements Serializable { private static final long serialVersionUID = -8864218635418155189L; private String username; private String password; private String hostKey = null; @Override public String toString() { return "LoginRequest [username=" + username + ", password=*********" + ", hostKey=" + hostKey + "]"; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() {
return password; } public void setPassword(String password) { this.password = password; } public String getHostKey() { return hostKey; } public void setHostKey(String hostKey) { this.hostKey = hostKey; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.common\de.metas.printing.api\src\main\java\de\metas\printing\esb\api\LoginRequest.java
1
请完成以下Java代码
public Map<AttributeCode, String> getAttributesAsMap() { if (attributes == null || attributes.isEmpty()) { return ImmutableMap.of(); } final HashMap<AttributeCode, String> result = new HashMap<>(); for (final Attribute attribute : attributes) { result.put(attribute.getCode(), attribute.getValue()); } return result; }
// // // // // @Value @Builder @Jacksonized public static class Attribute { @NonNull AttributeCode code; @Nullable String value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\json\JsonCountRequest.java
1
请完成以下Java代码
public void setIsManual (boolean IsManual) { set_ValueNoCheck (COLUMNNAME_IsManual, Boolean.valueOf(IsManual)); } /** Get Manuell. @return This is a manual process */ @Override public boolean isManual () { Object oo = get_Value(COLUMNNAME_IsManual); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Over/Under Payment. @param OverUnderAmt Over-Payment (unallocated) or Under-Payment (partial payment) Amount */ @Override public void setOverUnderAmt (java.math.BigDecimal OverUnderAmt) { set_Value (COLUMNNAME_OverUnderAmt, OverUnderAmt); } /** Get Over/Under Payment. @return Over-Payment (unallocated) or Under-Payment (partial payment) Amount */ @Override public java.math.BigDecimal getOverUnderAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OverUnderAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Abschreibung Betrag. @param PaymentWriteOffAmt Abschreibung Betrag */ @Override public void setPaymentWriteOffAmt (java.math.BigDecimal PaymentWriteOffAmt) { set_Value (COLUMNNAME_PaymentWriteOffAmt, PaymentWriteOffAmt); } /** Get Abschreibung Betrag. @return Abschreibung Betrag */ @Override public java.math.BigDecimal getPaymentWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PaymentWriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } @Override public org.compiere.model.I_C_AllocationLine getReversalLine() { return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class); } @Override public void setReversalLine(org.compiere.model.I_C_AllocationLine ReversalLine) { set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_C_AllocationLine.class, ReversalLine);
} /** Set Storno-Zeile. @param ReversalLine_ID Storno-Zeile */ @Override public void setReversalLine_ID (int ReversalLine_ID) { if (ReversalLine_ID < 1) set_Value (COLUMNNAME_ReversalLine_ID, null); else set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID)); } /** Get Storno-Zeile. @return Storno-Zeile */ @Override public int getReversalLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Abschreiben. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_ValueNoCheck (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Abschreiben. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AllocationLine.java
1
请完成以下Java代码
public static AttributeValueType ofCode(@NonNull final String code) { return index.ofCode(code); } public boolean isList() {return LIST.equals(this);} public interface CaseMapper<T> { T string(); T number(); T date(); T list(); } public <T> T map(@NonNull final CaseMapper<T> mapper) { switch (this) { case STRING: { return mapper.string(); } case NUMBER: { return mapper.number(); } case DATE: { return mapper.date(); } case LIST: { return mapper.list(); } default: { throw new AdempiereException("Unsupported value type: " + this); } } }
public interface CaseConsumer { void string(); void number(); void date(); void list(); } public void apply(@NonNull final CaseConsumer consumer) { switch (this) { case STRING: { consumer.string(); break; } case NUMBER: { consumer.number(); break; } case DATE: { consumer.date(); break; } case LIST: { consumer.list(); break; } default: { throw new AdempiereException("Unsupported value type: " + this); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\mm\attributes\AttributeValueType.java
1
请完成以下Java代码
public void setBillTo(final Boolean billTo) { this.billTo = billTo; this.billToSet = true; } public void setBillToDefault(final Boolean billToDefault) { this.billToDefault = billToDefault; this.billToDefaultSet = true; } public void setEphemeral(final Boolean ephemeral) { this.ephemeral = ephemeral; this.ephemeralSet = true; } public void setEmail(@Nullable final String email) { this.email = email; this.emailSet = true; } public void setPhone(final String phone) { this.phone = phone; this.phoneSet = true; } public void setVisitorsAddress(final Boolean visitorsAddress)
{ this.visitorsAddress = visitorsAddress; this.visitorsAddressSet = true; } public void setVisitorsAddressDefault(final Boolean visitorsAddressDefault) { this.visitorsAddressDefault = visitorsAddressDefault; this.visitorsAddressDefaultSet = true; } public void setVatId(final String vatId) { this.vatId = vatId; this.vatIdSet = true; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\request\JsonRequestLocation.java
1
请完成以下Java代码
public void output(PrintWriter out) { if (doctype != null) { doctype.output(out); try { out.write('\n'); } catch ( Exception e) {} } // XhtmlDocument is just a convient wrapper for html call html.output html.output(out); } /** Override the toString() method so that it prints something meaningful. */ public final String toString() { StringBuffer sb = new StringBuffer(); if ( getCodeset() != null ) { if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return (sb.toString()); } else { if (doctype != null) sb.append (doctype.toString()); sb.append (html.toString()); return(sb.toString()); } }
/** Override the toString() method so that it prints something meaningful. */ public final String toString(String codeset) { StringBuffer sb = new StringBuffer(); if (doctype != null) sb.append (doctype.toString(getCodeset())); sb.append (html.toString(getCodeset())); return(sb.toString()); } /** Allows the document to be cloned. Doesn't return an instance of document returns instance of html. NOTE: If you have a doctype set, then it will be lost. Feel free to submit a patch to fix this. It isn't trivial. */ public Object clone() { return(html.clone()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\XhtmlDocument.java
1
请完成以下Java代码
public void setFavouriteLanguage(final List<String> favouriteLanguage) { this.favouriteLanguage = favouriteLanguage; } public String getNotes() { return notes; } public void setNotes(final String notes) { this.notes = notes; } public List<String> getFruit() { return fruit; } public void setFruit(final List<String> fruit) { this.fruit = fruit; }
public String getBook() { return book; } public void setBook(final String book) { this.book = book; } public MultipartFile getFile() { return file; } public void setFile(final MultipartFile file) { this.file = file; } }
repos\tutorials-master\spring-web-modules\spring-mvc-xml-2\src\main\java\com\baeldung\spring\taglibrary\Person.java
1
请完成以下Java代码
public int getPickFrom_HU_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID); } @Override public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID) { if (PickFrom_Locator_ID < 1) set_Value (COLUMNNAME_PickFrom_Locator_ID, null); else set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID); } @Override public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyPicked (final BigDecimal QtyPicked) { set_Value (COLUMNNAME_QtyPicked, QtyPicked); } @Override public BigDecimal getQtyPicked() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyToPick (final BigDecimal QtyToPick) { set_ValueNoCheck (COLUMNNAME_QtyToPick, QtyToPick); } @Override public BigDecimal getQtyToPick() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyToPick); return bd != null ? bd : BigDecimal.ZERO; } /** * RejectReason AD_Reference_ID=541422 * Reference name: QtyNotPicked RejectReason */ public static final int REJECTREASON_AD_Reference_ID=541422; /** NotFound = N */ public static final String REJECTREASON_NotFound = "N"; /** Damaged = D */ public static final String REJECTREASON_Damaged = "D"; @Override public void setRejectReason (final @Nullable java.lang.String RejectReason)
{ set_Value (COLUMNNAME_RejectReason, RejectReason); } @Override public java.lang.String getRejectReason() { return get_ValueAsString(COLUMNNAME_RejectReason); } /** * Status AD_Reference_ID=541435 * Reference name: DD_OrderLine_Schedule_Status */ public static final int STATUS_AD_Reference_ID=541435; /** NotStarted = NS */ public static final String STATUS_NotStarted = "NS"; /** InProgress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_DD_Order_MoveSchedule.java
1
请完成以下Java代码
public String getUserId() { if (user != null) { return user.getId(); } else { return null; } } public String getGroupId() { if (group != null) { return group.getId(); } else { return null; } }
public TenantEntity getTenant() { return tenant; } public void setTenant(TenantEntity tenant) { this.tenant = tenant; } @Override public String toString() { return "TenantMembershipEntity [id=" + id + ", tenant=" + tenant + ", user=" + user + ", group=" + group + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TenantMembershipEntity.java
1
请完成以下Java代码
public void setRequiredDecisionResults(Collection<DmnDecisionLogicEvaluationEvent> requiredDecisionResults) { this.requiredDecisionResults = requiredDecisionResults; } @Override public long getExecutedDecisionInstances() { return executedDecisionInstances; } public void setExecutedDecisionInstances(long executedDecisionInstances) { this.executedDecisionInstances = executedDecisionInstances; } @Override public long getExecutedDecisionElements() { return executedDecisionElements; } public void setExecutedDecisionElements(long executedDecisionElements) {
this.executedDecisionElements = executedDecisionElements; } @Override public String toString() { DmnDecision dmnDecision = decisionResult.getDecision(); return "DmnDecisionEvaluationEventImpl{" + " key="+ dmnDecision.getKey() + ", name="+ dmnDecision.getName() + ", decisionLogic=" + dmnDecision.getDecisionLogic() + ", requiredDecisionResults=" + requiredDecisionResults + ", executedDecisionInstances=" + executedDecisionInstances + ", executedDecisionElements=" + executedDecisionElements + '}'; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnDecisionEvaluationEventImpl.java
1
请完成以下Java代码
public MStatus[] getStatus(boolean reload) { if (m_status != null && !reload) return m_status; String sql = "SELECT * FROM R_Status " + "WHERE R_StatusCategory_ID=? " + "ORDER BY SeqNo"; ArrayList<MStatus> list = new ArrayList<MStatus>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getR_StatusCategory_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MStatus (getCtx(), rs, null)); rs.close (); pstmt.close (); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } // m_status = new MStatus[list.size ()]; list.toArray (m_status); return m_status; } // getStatus /** * Get Default R_Status_ID * @return id or 0
*/ public int getDefaultR_Status_ID() { if (m_status == null) getStatus(false); for (int i = 0; i < m_status.length; i++) { if (m_status[i].isDefault() && m_status[i].isActive()) return m_status[i].getR_Status_ID(); } if (m_status.length > 0 && m_status[0].isActive()) return m_status[0].getR_Status_ID(); return 0; } // getDefaultR_Status_ID /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("RStatusCategory["); sb.append (get_ID()).append ("-").append(getName()).append ("]"); return sb.toString (); } // toString } // RStatusCategory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MStatusCategory.java
1
请完成以下Java代码
public static String md5(String source) { // 验证传入的字符串 if (StringUtils.isEmpty(source)) { return ""; } try { MessageDigest md = MessageDigest.getInstance(MD5); byte[] bytes = md.digest(source.getBytes("utf-8")); return byteArrayToHexString(bytes); } catch (Exception e) { logger.error("字符串使用Md5加密失败" + source + "' to MD5!", e); return null; } } /** * 转换字节数组为十六进制字符串 * * @param bytes * 字节数组
* @return 十六进制字符串 */ private static String byteArrayToHexString(byte[] bytes) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < bytes.length; i++) { sb.append(Integer.toHexString((bytes[i] & 0xFF) | 0x100).toUpperCase().substring(1, 3)); } return sb.toString(); } /** * 测试方法 * * @param args */ public static void main(String[] args) throws Exception { String key = "123"; System.out.println(sha(key)); System.out.println(md5(key)); } }
repos\spring-boot-student-master\spring-boot-student-encode\src\main\java\com\xiaolyuh\utils\EncodeUtil.java
1
请完成以下Java代码
public static PickOnTheFlyQRCode fromScannedCodeOrNullIfNotHandled(@NonNull final ScannedCode scannedCode) { return fromStringOrNullIfNotHandled(scannedCode.getAsString()); } @Nullable public static PickOnTheFlyQRCode fromStringOrNullIfNotHandled(@NonNull final String string) { final String stringNorm = StringUtils.trimBlankToNull(string); if (STRING_VALUE.equals(stringNorm)) { return instance; } else { return null; } }
@Override @Deprecated public String toString() {return getAsString();} @JsonValue public String getAsString() {return STRING_VALUE;} @Override public Optional<BigDecimal> getWeightInKg() {return Optional.empty();} @Override public Optional<LocalDate> getBestBeforeDate() {return Optional.empty();} @Override public Optional<String> getLotNumber() {return Optional.empty();} }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\special\PickOnTheFlyQRCode.java
1
请完成以下Java代码
public SignalPayload getSignalPayload() { return signalPayload; } public void setSignalPayload(SignalPayload signalPayload) { this.signalPayload = signalPayload; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } BPMNSignalImpl that = (BPMNSignalImpl) o; return ( Objects.equals(getElementId(), that.getElementId()) && Objects.equals(signalPayload, that.getSignalPayload()) ); } @Override
public int hashCode() { return Objects.hash( getElementId(), signalPayload != null ? signalPayload.getId() : null, signalPayload != null ? signalPayload.getName() : null ); } @Override public String toString() { return ( "BPMNActivityImpl{" + ", elementId='" + getElementId() + '\'' + ", signalPayload='" + (signalPayload != null ? signalPayload.toString() : null) + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNSignalImpl.java
1
请完成以下Java代码
private static void updateRecordFrom( @NonNull final I_M_CostRevaluation_Detail record, @NonNull final CostSegmentAndElement from) { record.setCostingLevel(from.getCostingLevel().getCode()); record.setC_AcctSchema_ID(from.getAcctSchemaId().getRepoId()); record.setM_CostType_ID(from.getCostTypeId().getRepoId()); Check.assumeEquals(record.getAD_Client_ID(), from.getClientId().getRepoId(), "Record {} shall match {}", record, from.getClientId()); record.setAD_Org_ID(from.getOrgId().getRepoId()); record.setM_Product_ID(from.getProductId().getRepoId()); record.setM_AttributeSetInstance_ID(from.getAttributeSetInstanceId().getRepoId()); record.setM_CostElement_ID(from.getCostElementId().getRepoId()); } public void deleteLinesByRevaluationId(@NonNull final CostRevaluationId costRevaluationId) { queryBL.createQueryBuilder(I_M_CostRevaluationLine.class) .addEqualsFilter(I_M_CostRevaluationLine.COLUMNNAME_M_CostRevaluation_ID, costRevaluationId) .create() .delete(); } public void deleteDetailsByRevaluationId(@NonNull final CostRevaluationId costRevaluationId) { queryBL.createQueryBuilder(I_M_CostRevaluation_Detail.class) .addEqualsFilter(I_M_CostRevaluation_Detail.COLUMNNAME_M_CostRevaluation_ID, costRevaluationId) .create() .delete();
} public void deleteDetailsByLineId(@NonNull final CostRevaluationLineId lineId) { deleteDetailsByLineIds(ImmutableSet.of(lineId)); } public void deleteDetailsByLineIds(@NonNull final Collection<CostRevaluationLineId> lineIds) { if (lineIds.isEmpty()) { return; } queryBL.createQueryBuilder(I_M_CostRevaluation_Detail.class) .addInArrayFilter(I_M_CostRevaluation_Detail.COLUMNNAME_M_CostRevaluationLine_ID, lineIds) .create() .delete(); } public void save(@NonNull final CostRevaluationLine line) { final I_M_CostRevaluationLine record = InterfaceWrapperHelper.load(line.getId(), I_M_CostRevaluationLine.class); record.setIsRevaluated(line.isRevaluated()); record.setDeltaAmt(line.getDeltaAmountToBook().toBigDecimal()); InterfaceWrapperHelper.save(record); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\CostRevaluationRepository.java
1
请在Spring Boot框架中完成以下Java代码
public Duration getTimeInNano() { return timeInNano; } public void setTimeInNano(Duration timeInNano) { this.timeInNano = timeInNano; } public Duration getTimeInDays() { return timeInDays; } public void setTimeInDays(Duration timeInDays) { this.timeInDays = timeInDays; } public DataSize getSizeInDefaultUnit() { return sizeInDefaultUnit; } public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { this.sizeInDefaultUnit = sizeInDefaultUnit; } public DataSize getSizeInGB() { return sizeInGB; } public void setSizeInGB(DataSize sizeInGB) { this.sizeInGB = sizeInGB; }
public DataSize getSizeInTB() { return sizeInTB; } public void setSizeInTB(DataSize sizeInTB) { this.sizeInTB = sizeInTB; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } }
repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\PropertyConversion.java
2
请完成以下Java代码
protected void createScopeStartEvent(BpmnParse bpmnParse, ActivityImpl startEventActivity, StartEvent startEvent) { ScopeImpl scope = bpmnParse.getCurrentScope(); Object triggeredByEvent = scope.getProperty("triggeredByEvent"); boolean isTriggeredByEvent = triggeredByEvent != null && ((Boolean) triggeredByEvent); if (isTriggeredByEvent) { // event subprocess // all start events of an event subprocess share common behavior EventSubProcessStartEventActivityBehavior activityBehavior = bpmnParse.getActivityBehaviorFactory().createEventSubProcessStartEventActivityBehavior(startEvent, startEventActivity.getId()); startEventActivity.setActivityBehavior(activityBehavior); if (!startEvent.getEventDefinitions().isEmpty()) { EventDefinition eventDefinition = startEvent.getEventDefinitions().get(0); if (eventDefinition instanceof org.flowable.bpmn.model.ErrorEventDefinition || eventDefinition instanceof MessageEventDefinition || eventDefinition instanceof SignalEventDefinition) { bpmnParse.getBpmnParserHandlers().parseElement(bpmnParse, eventDefinition); } else { LOGGER.warn("start event of event subprocess must be of type 'error', 'message' or 'signal' for start event {}", startEvent.getId()); } }
} else { // "regular" subprocess if (!startEvent.getEventDefinitions().isEmpty()) { LOGGER.warn("event definitions only allowed on start event if subprocess is an event subprocess {}", bpmnParse.getCurrentSubProcess().getId()); } if (scope.getProperty(PROPERTYNAME_INITIAL) == null) { scope.setProperty(PROPERTYNAME_INITIAL, startEventActivity); startEventActivity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createNoneStartEventActivityBehavior(startEvent)); } else { LOGGER.warn("multiple start events not supported for subprocess {}", bpmnParse.getCurrentSubProcess().getId()); } } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\StartEventParseHandler.java
1
请完成以下Java代码
protected void paintComponent (Graphics g) { Graphics2D g2D = (Graphics2D)g; // center icon m_icon.paintIcon(this, g2D, s_size.width/2 - m_icon.getIconWidth()/2, 5); // Paint Text Color color = getForeground(); g2D.setPaint(color); Font font = getFont(); // AttributedString aString = new AttributedString(m_name); aString.addAttribute(TextAttribute.FONT, font); aString.addAttribute(TextAttribute.FOREGROUND, color); AttributedCharacterIterator iter = aString.getIterator(); // LineBreakMeasurer measurer = new LineBreakMeasurer(iter, g2D.getFontRenderContext()); float width = s_size.width - m_icon.getIconWidth() - 2;
TextLayout layout = measurer.nextLayout(width); // center text float xPos = (float)(s_size.width/2 - layout.getBounds().getWidth()/2); float yPos = m_icon.getIconHeight() + 20; // layout.draw(g2D, xPos, yPos); width = s_size.width - 4; // 2 pt while (measurer.getPosition() < iter.getEndIndex()) { layout = measurer.nextLayout(width); yPos += layout.getAscent() + layout.getDescent() + layout.getLeading(); layout.draw(g2D, xPos, yPos); } } // paintComponent } // WFNode
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFNodeComponent.java
1
请在Spring Boot框架中完成以下Java代码
class DataSourceJmxConfiguration { private static final Log logger = LogFactory.getLog(DataSourceJmxConfiguration.class); @Configuration(proxyBeanMethods = false) @ConditionalOnClass(HikariDataSource.class) @ConditionalOnSingleCandidate(DataSource.class) static class Hikari { private final DataSource dataSource; private final ObjectProvider<MBeanExporter> mBeanExporter; Hikari(DataSource dataSource, ObjectProvider<MBeanExporter> mBeanExporter) { this.dataSource = dataSource; this.mBeanExporter = mBeanExporter; validateMBeans(); } private void validateMBeans() { HikariDataSource hikariDataSource = DataSourceUnwrapper.unwrap(this.dataSource, HikariConfigMXBean.class, HikariDataSource.class); if (hikariDataSource != null && hikariDataSource.isRegisterMbeans()) { this.mBeanExporter.ifUnique((exporter) -> exporter.addExcludedBean("dataSource")); } } } @Configuration(proxyBeanMethods = false) @ConditionalOnBooleanProperty("spring.datasource.tomcat.jmx-enabled") @ConditionalOnClass(DataSourceProxy.class) @ConditionalOnSingleCandidate(DataSource.class) static class TomcatDataSourceJmxConfiguration { @Bean @ConditionalOnMissingBean(name = "dataSourceMBean")
@Nullable Object dataSourceMBean(DataSource dataSource) { DataSourceProxy dataSourceProxy = DataSourceUnwrapper.unwrap(dataSource, PoolConfiguration.class, DataSourceProxy.class); if (dataSourceProxy != null) { try { return dataSourceProxy.createPool().getJmxPool(); } catch (SQLException ex) { logger.warn("Cannot expose DataSource to JMX (could not connect)"); } } return null; } } }
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceJmxConfiguration.java
2
请完成以下Java代码
public int getStartOffset() { return m_view.getStartOffset(); } /** * Returns the ending offset into the model for this view. * * @return the ending offset */ public int getEndOffset() { return m_view.getEndOffset(); } /** * Gets the element that this view is mapped to. * * @return the view */ public Element getElement() { return m_view.getElement(); } /** * Sets the view size. *
* @param width the width * @param height the height */ public void setSize(float width, float height) { this.m_width = (int) width; m_view.setSize(width, height); } /** * Fetches the factory to be used for building the * various view fragments that make up the view that * represents the model. This is what determines * how the model will be represented. This is implemented * to fetch the factory provided by the associated * EditorKit. * * @return the factory */ public ViewFactory getViewFactory() { return m_factory; } } // HTMLRenderer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HTMLRenderer.java
1
请完成以下Java代码
public boolean isReversed() { return this == Reversed; } public boolean isReversedOrVoided() { return this == Reversed || this == Voided; } public boolean isClosedReversedOrVoided() { return this == Closed || this == Reversed || this == Voided; } public boolean isCompleted() { return this == Completed; } public boolean isClosed() { return this == Closed; } public boolean isCompletedOrClosed() { return COMPLETED_OR_CLOSED_STATUSES.contains(this); } public static Set<DocStatus> completedOrClosedStatuses() { return COMPLETED_OR_CLOSED_STATUSES; } public boolean isCompletedOrClosedOrReversed() { return this == Completed || this == Closed || this == Reversed; } public boolean isCompletedOrClosedReversedOrVoided() { return this == Completed || this == Closed || this == Reversed || this == Voided; } public boolean isWaitingForPayment() { return this == WaitingPayment; } public boolean isInProgress() {
return this == InProgress; } public boolean isInProgressCompletedOrClosed() { return this == InProgress || this == Completed || this == Closed; } public boolean isDraftedInProgressOrInvalid() { return this == Drafted || this == InProgress || this == Invalid; } @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean isDraftedInProgressOrCompleted() { return this == Drafted || this == InProgress || this == Completed; } public boolean isNotProcessed() { return isDraftedInProgressOrInvalid() || this == Approved || this == NotApproved; } public boolean isVoided() {return this == Voided;} public boolean isAccountable() { return this == Completed || this == Reversed || this == Voided; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java
1
请完成以下Java代码
public static Object valueToJsonObject( @Nullable final Object value, @NonNull final JSONOptions jsonOpts, @NonNull final UnaryOperator<Object> fallbackMapper) { if (JSONNullValue.isNull(value)) { return JSONNullValue.instance; } else if (value instanceof java.util.Date) { final Instant valueDate = ((Date)value).toInstant(); return DateTimeConverters.toJson(valueDate, jsonOpts.getZoneId()); } else if (value instanceof LocalDate) { return localDateToJson((LocalDate)value); } else if (value instanceof LocalTime) { return DateTimeConverters.toJson((LocalTime)value); } else if (value instanceof ZonedDateTime) { return DateTimeConverters.toJson((ZonedDateTime)value, jsonOpts.getZoneId()); } else if (value instanceof Instant) { return DateTimeConverters.toJson((Instant)value, jsonOpts.getZoneId()); } else if (value instanceof DateRangeValue) { final DateRangeValue dateRange = (DateRangeValue)value; return JSONRange.of(dateRange); } else if (value instanceof LookupValue) { final LookupValue lookupValue = (LookupValue)value; return JSONLookupValue.ofLookupValue(lookupValue, jsonOpts.getAdLanguage()); } else if (value instanceof LookupValuesList) { final LookupValuesList lookupValues = (LookupValuesList)value; return JSONLookupValuesList.ofLookupValuesList(lookupValues, jsonOpts.getAdLanguage()); } else if (value instanceof NamePair) { final NamePair lookupValue = (NamePair)value; return JSONLookupValue.ofNamePair(lookupValue); } else if (value instanceof BigDecimal)
{ return bigDecimalToJson((BigDecimal)value); } else if (value instanceof Quantity) { return bigDecimalToJson(((Quantity)value).toBigDecimal()); } else if (value instanceof Money) { return bigDecimalToJson(((Money)value).toBigDecimal()); } else if (value instanceof Amount) { return bigDecimalToJson(((Amount)value).getAsBigDecimal()); } else if (value instanceof DocumentId) { return ((DocumentId)value).toJson(); } else if (value instanceof Collection) { final Collection<?> valuesList = (Collection<?>)value; return valuesList.stream() .map(v -> valueToJsonObject(v, jsonOpts, fallbackMapper)) .collect(Collectors.toCollection(ArrayList::new)); // don't use ImmutableList because we might get null values } else { return fallbackMapper.apply(value); } } public static String localDateToJson(final LocalDate value) { return DateTimeConverters.toJson(value); } private static String bigDecimalToJson(final BigDecimal value) { // NOTE: because javascript cannot distinguish between "1.00" and "1.0" as number, // we need to provide the BigDecimals as Strings. return value.toPlainString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\Values.java
1
请完成以下Java代码
public boolean lock() { // 请求锁超时时间,纳秒 long timeout = timeOut * 1000000; // 系统当前时间,纳秒 long nowTime = System.nanoTime(); while ((System.nanoTime() - nowTime) < timeout) { // 分布式服务器有时差,这里给1秒的误差值 expires = System.currentTimeMillis() + expireTime * 1000 + 1 * 1000; String expiresStr = String.valueOf(expires); //锁到期时间 if (redisTemplate.opsForValue().setIfAbsent(lockKey, expiresStr)) { locked = true; // 设置锁的有效期,也是锁的自动释放时间,也是一个客户端在其他客户端能抢占锁之前可以执行任务的时间 // 可以防止因异常情况无法释放锁而造成死锁情况的发生 redisTemplate.expire(lockKey, expireTime, TimeUnit.SECONDS); // 上锁成功结束请求 return true; } String currentValueStr = redisTemplate.opsForValue().get(lockKey); //redis里的时间 if (currentValueStr != null && Long.parseLong(currentValueStr) < System.currentTimeMillis()) { //判断是否为空,不为空的情况下,如果被其他线程设置了值,则第二个条件判断是过不去的 // lock is expired String oldValueStr = redisTemplate.opsForValue().getAndSet(lockKey, expiresStr); //获取上一个锁到期时间,并设置现在的锁到期时间, //只有一个线程才能获取上一个线上的设置时间,因为jedis.getSet是同步的 if (oldValueStr != null && oldValueStr.equals(currentValueStr)) { //防止误删(覆盖,因为key是相同的)了他人的锁——这里达不到效果,这里值会被覆盖,但是因为什么相差了很少的时间,所以可以接受 //[分布式的情况下]:如过这个时候,多个线程恰好都到了这里,但是只有一个线程的设置值和当前值相同,他才有权利获取锁 // lock acquired
locked = true; return true; } } /* 延迟10 毫秒, 这里使用随机时间可能会好一点,可以防止饥饿进程的出现,即,当同时到达多个进程, 只会有一个进程获得锁,其他的都用同样的频率进行尝试,后面有来了一些进行,也以同样的频率申请锁,这将可能导致前面来的锁得不到满足. 使用随机的等待时间可以一定程度上保证公平性 */ try { Thread.sleep(10, random.nextInt(50000)); } catch (InterruptedException e) { logger.error("获取分布式锁休眠被中断:", e); } } return locked; } /** * 解锁 */ public void unlock() { // 只有加锁成功并且锁还有效才去释放锁 if (locked && expires > System.currentTimeMillis()) { redisTemplate.delete(lockKey); locked = false; } } }
repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\redis\lock\RedisLock2.java
1
请完成以下Java代码
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); } /** * Type AD_Reference_ID=540047 * Reference name: AD_BoilerPlate_VarType */ public static final int TYPE_AD_Reference_ID=540047; /** SQL = S */ public static final String TYPE_SQL = "S"; /** Rule Engine = R */ public static final String TYPE_RuleEngine = "R"; /** Set Type. @param Type Type of Validation (SQL, Java Script, Java Language) */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Type. @return Type of Validation (SQL, Java Script, Java Language) */
@Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate_Var.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } public String getOperationType() { return operationType; } public void setOperationType(String operationType) { this.operationType = operationType; } public String getEntityType() { return entityType; } public void setEntityType(String entityType) { this.entityType = entityType; } public List<PropertyChange> getPropertyChanges() { return propertyChanges; } public void setPropertyChanges(List<PropertyChange> propertyChanges) { this.propertyChanges = propertyChanges; } public String getProcessDefinitionKey() { return processDefinitionKey; } public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey; } public String getJobDefinitionId() { return jobDefinitionId; } public void setJobDefinitionId(String jobDefinitionId) { this.jobDefinitionId = jobDefinitionId; } public String getJobId() { return jobId; } public void setJobId(String jobId) { this.jobId = jobId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; } public void setExternalTaskId(String externalTaskId) { this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntry.java
1
请完成以下Java代码
public ResponseEntity<ErrorResponse> handle(ConstraintViolationException e) { ErrorResponse errors = new ErrorResponse(); for (ConstraintViolation violation : e.getConstraintViolations()) { ErrorItem error = new ErrorItem(); error.setCode(violation.getMessageTemplate()); error.setMessage(violation.getMessage()); errors.addError(error); } return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST); } @SuppressWarnings("rawtypes") @ExceptionHandler(ResourceNotFoundException.class) public ResponseEntity<ErrorItem> handle(ResourceNotFoundException e) { ErrorItem error = new ErrorItem(); error.setMessage(e.getMessage()); return new ResponseEntity<>(error, HttpStatus.NOT_FOUND); } public static class ErrorItem { @JsonInclude(JsonInclude.Include.NON_NULL) private String code; private String message; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; }
} public static class ErrorResponse { private List<ErrorItem> errors = new ArrayList<>(); public List<ErrorItem> getErrors() { return errors; } public void setErrors(List<ErrorItem> errors) { this.errors = errors; } public void addError(ErrorItem error) { this.errors.add(error); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-angular\src\main\java\com\baeldung\ecommerce\exception\ApiExceptionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public Cookie getCookie() { return this.cookie; } } } /** * Strategies for supporting forward headers. */ public enum ForwardHeadersStrategy { /** * Use the underlying container's native support for forwarded headers. */ NATIVE, /** * Use Spring's support for handling forwarded headers. */ FRAMEWORK, /** * Ignore X-Forwarded-* headers. */
NONE } public static class Encoding { /** * Mapping of locale to charset for response encoding. */ private @Nullable Map<Locale, Charset> mapping; public @Nullable Map<Locale, Charset> getMapping() { return this.mapping; } public void setMapping(@Nullable Map<Locale, Charset> mapping) { this.mapping = mapping; } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\autoconfigure\ServerProperties.java
2
请完成以下Java代码
public String getParamName () { return (String)get_Value(COLUMNNAME_ParamName); } /** Set Parameterwert. @param ParamValue Parameterwert */ public void setParamValue (String ParamValue) { set_Value (COLUMNNAME_ParamValue, ParamValue); } /** Get Parameterwert. @return Parameterwert */ public String getParamValue () { return (String)get_Value(COLUMNNAME_ParamValue); } /** Set Reihenfolge. @param SeqNo
Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_Impex_ConnectorParam.java
1
请完成以下Java代码
public ArrayKeyBuilder append(final Object obj) { keyParts.add(obj); return this; } public ArrayKeyBuilder appendAll(@NonNull final Collection<Object> objs) { keyParts.addAll(objs); return this; } public ArrayKeyBuilder append(final String name, final Object obj) { keyParts.add(name); keyParts.add(obj); return this; } /** * Appends given ID. If ID is less or equal with ZERO then -1 will be appended. * * @param id ID to append * @return this
*/ public ArrayKeyBuilder appendId(final int id) { keyParts.add(id <= 0 ? -1 : id); return this; } public ArrayKeyBuilder appendModelId(final Object model) { final int modelId; if (model == null) { modelId = -1; } else { modelId = InterfaceWrapperHelper.getId(model); } keyParts.add(modelId); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\util\ArrayKeyBuilder.java
1
请完成以下Java代码
public List<String> getParameterTypes() { return parameterTypes; } public void setParameterTypes(List<String> parameterTypes) { this.parameterTypes = parameterTypes; } /** * 必须重写equals和hashCode方法,否则放到set集合里没法去重 * * @param o * @return */ @Override public boolean equals(Object o) { if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; } CachedMethodInvocation that = (CachedMethodInvocation) o; return key.equals(that.key); } @Override public int hashCode() { return key.hashCode(); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CachedMethodInvocation.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_TreeNode[") .append(get_ID()).append("]"); return sb.toString(); } public I_AD_Tree getAD_Tree() throws RuntimeException { return (I_AD_Tree)MTable.get(getCtx(), I_AD_Tree.Table_Name) .getPO(getAD_Tree_ID(), get_TrxName()); } /** Set Tree. @param AD_Tree_ID Identifies a Tree */ public void setAD_Tree_ID (int AD_Tree_ID) { if (AD_Tree_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Tree_ID, Integer.valueOf(AD_Tree_ID)); } /** Get Tree. @return Identifies a Tree */ public int getAD_Tree_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Tree_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Node_ID. @param Node_ID Node_ID */ public void setNode_ID (int Node_ID) { if (Node_ID < 0) set_ValueNoCheck (COLUMNNAME_Node_ID, null); else set_ValueNoCheck (COLUMNNAME_Node_ID, Integer.valueOf(Node_ID)); } /** Get Node_ID. @return Node_ID */ public int getNode_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Node_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Parent. @param Parent_ID Parent of Entity */ public void setParent_ID (int Parent_ID) { if (Parent_ID < 1)
set_Value (COLUMNNAME_Parent_ID, null); else set_Value (COLUMNNAME_Parent_ID, Integer.valueOf(Parent_ID)); } /** Get Parent. @return Parent of Entity */ public int getParent_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_ID); if (ii == null) return 0; return ii.intValue(); } /** 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_AD_TreeNode.java
1
请完成以下Java代码
public class SingleSelectCapability extends ServiceCapability<List<DefaultMetadataElement>> implements Defaultable<DefaultMetadataElement> { private final List<DefaultMetadataElement> content = new ArrayList<>(); private final ReadWriteLock contentLock = new ReentrantReadWriteLock(); @JsonCreator SingleSelectCapability(@JsonProperty("id") String id) { this(id, null, null); } public SingleSelectCapability(String id, String title, String description) { super(id, ServiceCapabilityType.SINGLE_SELECT, title, description); } @Override public List<DefaultMetadataElement> getContent() { return Collections.unmodifiableList(withReadableContent(ArrayList::new)); } public void addContent(DefaultMetadataElement element) { withWritableContent((content) -> content.add(element)); } public void setContent(List<DefaultMetadataElement> newContent) { withWritableContent((content) -> { content.clear(); content.addAll(newContent); }); } /** * Return the default element of this capability. */ @Override public DefaultMetadataElement getDefault() { return withReadableContent( (content) -> content.stream().filter(DefaultMetadataElement::isDefault).findFirst().orElse(null)); } /** * Return the element with the specified id or {@code null} if no such element exists. * @param id the ID of the element to find * @return the element or {@code null} */ public DefaultMetadataElement get(String id) { return withReadableContent(
(content) -> content.stream().filter((it) -> id.equals(it.getId())).findFirst().orElse(null)); } @Override public void merge(List<DefaultMetadataElement> otherContent) { withWritableContent((content) -> otherContent.forEach((it) -> { if (get(it.getId()) == null) { this.content.add(it); } })); } private <T> T withReadableContent(Function<List<DefaultMetadataElement>, T> consumer) { this.contentLock.readLock().lock(); try { return consumer.apply(this.content); } finally { this.contentLock.readLock().unlock(); } } private void withWritableContent(Consumer<List<DefaultMetadataElement>> consumer) { this.contentLock.writeLock().lock(); try { consumer.accept(this.content); } finally { this.contentLock.writeLock().unlock(); } } }
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\SingleSelectCapability.java
1
请完成以下Java代码
public ImmutableList<I_M_Package> createM_Packages(@NonNull final List<CreatePackagesRequest> packagesRequestList) { return packagesRequestList.stream().map(this::createM_Package).collect(ImmutableList.toImmutableList()); } private I_M_Package createM_Package(@NonNull final CreatePackagesRequest createPackageRequest) { final I_M_InOut inOut = inOutDAO.getById(createPackageRequest.getInOutId()); final I_M_Package mPackage = newInstance(I_M_Package.class); mPackage.setM_Shipper_ID(createPackageRequest.getShipperId().getRepoId()); mPackage.setAD_Org_ID(inOut.getAD_Org_ID()); mPackage.setProcessed(createPackageRequest.isProcessed()); mPackage.setShipDate(null); mPackage.setC_BPartner_ID(inOut.getC_BPartner_ID()); mPackage.setC_BPartner_Location_ID(inOut.getC_BPartner_Location_ID());
mPackage.setM_InOut_ID(inOut.getM_InOut_ID()); mPackage.setPOReference(inOut.getPOReference()); mPackage.setTrackingInfo(createPackageRequest.getTrackingCode()); mPackage.setPackageWeight(createPackageRequest.getWeightInKg()); mPackage.setTrackingURL(createPackageRequest.getTrackingURL()); final PackageDimensions packageDimensions = createPackageRequest.getPackageDimensions(); mPackage.setLengthInCm(packageDimensions.getLengthInCM()); mPackage.setHeightInCm(packageDimensions.getHeightInCM()); mPackage.setWidthInCm(packageDimensions.getWidthInCM()); InterfaceWrapperHelper.save(mPackage); return mPackage; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\InOutPackageRepository.java
1
请完成以下Java代码
public void setTitle(final String title) { if (link != null) { link.setText(title); } } /** * * @return collapsible pane */ public JXCollapsiblePane getCollapsiblePane() { return collapsible; } public JComponent getContentPane() { return (JComponent)getCollapsiblePane().getContentPane(); } public void setContentPane(JComponent contentPanel) { getCollapsiblePane().setContentPane(contentPanel); } /** * The border between the stack components. It separates each component with a fine line border. */ class SeparatorBorder implements Border { boolean isFirst(final Component c) { return c.getParent() == null || c.getParent().getComponent(0) == c; } @Override public Insets getBorderInsets(final Component c) { // if the collapsible is collapsed, we do not want its border to be // painted. if (c instanceof JXCollapsiblePane) { if (((JXCollapsiblePane)c).isCollapsed()) { return new Insets(0, 0, 0, 0); } } return new Insets(4, 0, 1, 0); } @Override public boolean isBorderOpaque() { return true; }
@Override public void paintBorder(final Component c, final Graphics g, final int x, final int y, final int width, final int height) { // if the collapsible is collapsed, we do not want its border to be painted. if (c instanceof JXCollapsiblePane) { if (((JXCollapsiblePane)c).isCollapsed()) { return; } } g.setColor(getSeparatorColor()); if (isFirst(c)) { g.drawLine(x, y + 2, x + width, y + 2); } g.drawLine(x, y + height - 1, x + width, y + height - 1); } } @Override public final Component add(final Component comp) { return collapsible.add(comp); } public final void setCollapsed(final boolean collapsed) { collapsible.setCollapsed(collapsed); } public final void setCollapsible(final boolean collapsible) { this.toggleAction.setEnabled(collapsible); if (!collapsible) { this.collapsible.setCollapsed(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CollapsiblePanel.java
1
请完成以下Java代码
public class EventConsumerInfo { protected String eventSubscriptionId; protected String subScopeId; protected String scopeDefinitionId; protected String scopeType; protected boolean hasExistingInstancesForUniqueCorrelation; public EventConsumerInfo() {} public EventConsumerInfo(String eventSubscriptionId, String subScopeId, String scopeDefinitionId, String scopeType) { this.eventSubscriptionId = eventSubscriptionId; this.subScopeId = subScopeId; this.scopeDefinitionId = scopeDefinitionId; this.scopeType = scopeType; } public String getEventSubscriptionId() { return eventSubscriptionId; } public void setEventSubscriptionId(String eventSubscriptionId) { this.eventSubscriptionId = eventSubscriptionId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeType() { return scopeType; }
public void setScopeType(String scopeType) { this.scopeType = scopeType; } public boolean isHasExistingInstancesForUniqueCorrelation() { return hasExistingInstancesForUniqueCorrelation; } public void setHasExistingInstancesForUniqueCorrelation(boolean hasExistingInstancesForUniqueCorrelation) { this.hasExistingInstancesForUniqueCorrelation = hasExistingInstancesForUniqueCorrelation; } @Override public String toString() { return new StringJoiner(", ", getClass().getSimpleName() + "[", "]") .add("eventSubscriptionId='" + eventSubscriptionId + "'") .add("subScopeId='" + subScopeId + "'") .add("scopeType='" + scopeType + "'") .add("scopeDefinitionId='" + scopeDefinitionId + "'") .add("hasExistingInstancesForUniqueCorrelation=" + hasExistingInstancesForUniqueCorrelation) .toString(); } }
repos\flowable-engine-main\modules\flowable-event-registry-api\src\main\java\org\flowable\eventregistry\api\EventConsumerInfo.java
1
请完成以下Java代码
public void setUserCache(UserCache userCache) { this.userCache = userCache; } @Override public boolean supports(Class<?> authentication) { return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication)); } protected UserDetailsChecker getPreAuthenticationChecks() { return this.preAuthenticationChecks; } /** * Sets the policy will be used to verify the status of the loaded * <tt>UserDetails</tt> <em>before</em> validation of the credentials takes place. * @param preAuthenticationChecks strategy to be invoked prior to authentication. */ public void setPreAuthenticationChecks(UserDetailsChecker preAuthenticationChecks) { this.preAuthenticationChecks = preAuthenticationChecks; } protected UserDetailsChecker getPostAuthenticationChecks() { return this.postAuthenticationChecks; } public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) { this.postAuthenticationChecks = postAuthenticationChecks; } public void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) { this.authoritiesMapper = authoritiesMapper; } private class DefaultPreAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isAccountNonLocked()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is locked");
throw new LockedException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.locked", "User account is locked")); } if (!user.isEnabled()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account is disabled"); throw new DisabledException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.disabled", "User is disabled")); } if (!user.isAccountNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account has expired"); throw new AccountExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.expired", "User account has expired")); } } } private class DefaultPostAuthenticationChecks implements UserDetailsChecker { @Override public void check(UserDetails user) { if (!user.isCredentialsNonExpired()) { AbstractUserDetailsAuthenticationProvider.this.logger .debug("Failed to authenticate since user account credentials have expired"); throw new CredentialsExpiredException(AbstractUserDetailsAuthenticationProvider.this.messages .getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpired", "User credentials have expired")); } } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\dao\AbstractUserDetailsAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
public void setResourceLocation(String resourceLocation) { this.resourceLocation = resourceLocation; } /** * Sets a Resource that is a Properties file in the format defined in * {@link UserDetailsResourceFactoryBean}. * @param resource the Resource to use */ public void setResource(Resource resource) { this.resource = resource; } private Resource getPropertiesResource() { Resource result = this.resource; if (result == null && this.resourceLocation != null) { result = this.resourceLoader.getResource(this.resourceLocation); } Assert.notNull(result, "resource cannot be null if resourceLocation is null"); return result; } /** * Create a UserDetailsResourceFactoryBean with the location of a Resource that is a * Properties file in the format defined in {@link UserDetailsResourceFactoryBean}. * @param resourceLocation the location of the properties file that contains the users * (i.e. "classpath:users.properties") * @return the UserDetailsResourceFactoryBean */ public static UserDetailsResourceFactoryBean fromResourceLocation(String resourceLocation) { UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean(); result.setResourceLocation(resourceLocation); return result; } /** * Create a UserDetailsResourceFactoryBean with a Resource that is a Properties file * in the format defined in {@link UserDetailsResourceFactoryBean}. * @param propertiesResource the Resource that is a properties file that contains the
* users * @return the UserDetailsResourceFactoryBean */ public static UserDetailsResourceFactoryBean fromResource(Resource propertiesResource) { UserDetailsResourceFactoryBean result = new UserDetailsResourceFactoryBean(); result.setResource(propertiesResource); return result; } /** * Creates a UserDetailsResourceFactoryBean with a resource from the provided String * @param users the string representing the users * @return the UserDetailsResourceFactoryBean */ public static UserDetailsResourceFactoryBean fromString(String users) { InMemoryResource resource = new InMemoryResource(users); return fromResource(resource); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\UserDetailsResourceFactoryBean.java
2
请在Spring Boot框架中完成以下Java代码
public Job zappJob(JobBuilderFactory jobBuilderFactory, @Qualifier("zappStep1") Step s1) { return jobBuilderFactory.get("zappJob") .incrementer(new RunIdIncrementer()) .flow(s1)//为Job指定Step .end() .listener(new MyJobListener())//绑定监听器csvJobListener .build(); } /** * step步骤,包含ItemReader,ItemProcessor和ItemWriter * * @param stepBuilderFactory * @param reader * @param writer * @param processor * @return */ @Bean(name = "zappStep1") public Step zappStep1(StepBuilderFactory stepBuilderFactory, @Qualifier("appReader") ItemReader<App> reader, @Qualifier("appWriter") ItemWriter<App> writer, @Qualifier("appProcessor") ItemProcessor<App, App> processor) { return stepBuilderFactory .get("zappStep1") .<App, App>chunk(5000)//批处理每次提交5000条数据 .reader(reader)//给step绑定reader .processor(processor)//给step绑定processor .writer(writer)//给step绑定writer .faultTolerant() .retry(Exception.class) // 重试 .noRetry(ParseException.class) .retryLimit(1) //每条记录重试一次
.skip(Exception.class) .skipLimit(200) //一共允许跳过200次异常 // .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好 // .throttleLimit(10) //并发任务数为 10,默认为4 .build(); } @Bean public Validator<App> csvBeanValidator() { return new MyBeanValidator<>(); } }
repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\zapp\AppConfig.java
2
请完成以下Java代码
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 Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Buyer.java
1
请完成以下Java代码
public String toString() {return getValue();} @JsonValue public String toJson() {return getValue();} public boolean isAlberta() {return Alberta.equals(this);} public boolean isRabbitMQ() {return RabbitMQ.equals(this);} public boolean isWOO() {return WOO.equals(this);} public boolean isGRSSignum() {return GRSSignum.equals(this);} public boolean isLeichUndMehl() {return LeichUndMehl.equals(this);}
public boolean isPrintClient() {return PrintClient.equals(this);} public boolean isProCareManagement() {return ProCareManagement.equals(this);} public boolean isShopware6() {return Shopware6.equals(this);} public boolean isOther() {return Other.equals(this);} public boolean isGithub() {return Github.equals(this);} public boolean isEverhour() {return Everhour.equals(this);} public boolean isScriptedExportConversion() {return ScriptedExportConversion.equals(this);} public boolean isScriptedImportConversion() {return ScriptedImportConversion.equals(this);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemType.java
1
请完成以下Java代码
public void mouseExited(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) */ @Override public void mousePressed(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) */ @Override public void mouseReleased(MouseEvent e) { } /* (non-Javadoc) * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent) */ @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == mRefresh) { if (m_goals != null) { for (MGoal m_goal : m_goals) { m_goal.updateGoal(true); } } htmlUpdate(lastUrl); Container parent = getParent(); if (parent != null) { parent.invalidate(); } invalidate(); if (parent != null) { parent.repaint(); } else { repaint(); } } } class PageLoader implements Runnable { private JEditorPane html; private URL url; private Cursor cursor; PageLoader( JEditorPane html, URL url, Cursor cursor ) { this.html = html; this.url = url; this.cursor = cursor;
} @Override public void run() { if( url == null ) { // restore the original cursor html.setCursor( cursor ); // PENDING(prinz) remove this hack when // automatic validation is activated. Container parent = html.getParent(); parent.repaint(); } else { Document doc = html.getDocument(); try { html.setPage( url ); } catch( IOException ioe ) { html.setDocument( doc ); } finally { // schedule the cursor to revert after // the paint has happended. url = null; SwingUtilities.invokeLater( this ); } } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\apps\graph\HtmlDashboard.java
1
请完成以下Java代码
private void invoiceDone() { // Close Old if (m_invoice != null) { if (m_linecount == 0) m_invoice.delete(false); else { m_invoice.processIt(MInvoice.ACTION_Prepare); m_invoice.save(); addLog(0, null, m_invoice.getGrandTotal(), m_invoice.getDocumentNo()); } } m_invoice = null; } // invoiceDone /** * New Invoice * @param request request */ private void invoiceNew (MRequest request) { m_invoice = new MInvoice (getCtx(), 0, get_TrxName()); m_invoice.setIsSOTrx(true); I_C_BPartner partner = Services.get(IBPartnerDAO.class).getById(request.getC_BPartner_ID()); m_invoice.setBPartner(partner); m_invoice.save(); m_linecount = 0; } // invoiceNew /** * Invoice Line * @param request request
*/ private void invoiceLine (MRequest request) { MRequestUpdate[] updates = request.getUpdates(null); for (int i = 0; i < updates.length; i++) { BigDecimal qty = updates[i].getQtyInvoiced(); if (qty == null || qty.signum() == 0) continue; // if (updates[i].getC_InvoiceLine_ID() > 0) // continue; MInvoiceLine il = new MInvoiceLine(m_invoice); m_linecount++; il.setLine(m_linecount*10); // il.setQty(qty); // Product int M_Product_ID = updates[i].getM_ProductSpent_ID(); if (M_Product_ID == 0) M_Product_ID = p_M_Product_ID; il.setM_Product_ID(M_Product_ID); // il.setPrice(); il.save(); // updates[i].setC_InvoiceLine_ID(il.getC_InvoiceLine_ID()); // updates[i].save(); } } // invoiceLine } // RequestInvoice
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\RequestInvoice.java
1
请在Spring Boot框架中完成以下Java代码
public String getConnectionString() { String connectionString = this.properties.getConnectionString(); Assert.state(connectionString != null, "'connectionString' must not be null"); return connectionString; } @Override public @Nullable String getUsername() { return this.properties.getUsername(); } @Override public @Nullable String getPassword() { return this.properties.getPassword(); } @Override
public @Nullable SslBundle getSslBundle() { Ssl ssl = this.properties.getEnv().getSsl(); if (!ssl.getEnabled()) { return null; } if (StringUtils.hasLength(ssl.getBundle())) { Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context"); return this.sslBundles.getBundle(ssl.getBundle()); } return SslBundle.systemDefault(); } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java
2
请完成以下Java代码
public String toString() { String status; if (httpStatus.getHttpStatus() != null) { status = String.valueOf(httpStatus.getHttpStatus().value()); } else { status = httpStatus.getStatus().toString(); } return filterToStringCreator(RedirectToGatewayFilterFactory.this).append(status, uri) .append(INCLUDE_REQUEST_PARAMS_KEY, includeRequestParams) .toString(); } }; } public static class Config { private @Nullable String status; private @Nullable String url; boolean includeRequestParams; public @Nullable String getStatus() { return status; } public void setStatus(String status) { this.status = status; }
public @Nullable String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public boolean isIncludeRequestParams() { return includeRequestParams; } public void setIncludeRequestParams(boolean includeRequestParams) { this.includeRequestParams = includeRequestParams; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RedirectToGatewayFilterFactory.java
1
请完成以下Java代码
public class JmsChannelMessageListenerAdapter extends AbstractAdaptableMessageListener { protected EventRegistry eventRegistry; protected InboundChannelModel inboundChannelModel; public JmsChannelMessageListenerAdapter(EventRegistry eventRegistry, InboundChannelModel inboundChannelModel) { this.eventRegistry = eventRegistry; this.inboundChannelModel = inboundChannelModel; } @Override public void onMessage(Message message, Session session) throws JMSException { eventRegistry.eventReceived(inboundChannelModel, new JmsMessageInboundEvent(message)); } public EventRegistry getEventRegistry() {
return eventRegistry; } public void setEventRegistry(EventRegistry eventRegistry) { this.eventRegistry = eventRegistry; } public InboundChannelModel getInboundChannelModel() { return inboundChannelModel; } public void setInboundChannelModel(InboundChannelModel inboundChannelModel) { this.inboundChannelModel = inboundChannelModel; } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsChannelMessageListenerAdapter.java
1
请完成以下Java代码
public class BranchData2 { @XmlElement(name = "Id") protected String id; @XmlElement(name = "Nm") protected String nm; @XmlElement(name = "PstlAdr") protected PostalAddress6 pstlAdr; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = 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; }
/** * Gets the value of the pstlAdr property. * * @return * possible object is * {@link PostalAddress6 } * */ public PostalAddress6 getPstlAdr() { return pstlAdr; } /** * Sets the value of the pstlAdr property. * * @param value * allowed object is * {@link PostalAddress6 } * */ public void setPstlAdr(PostalAddress6 value) { this.pstlAdr = 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\BranchData2.java
1
请完成以下Java代码
public static String getMoneyIntoWords(final double money) { long dollar = (long) money; long cents = Math.round((money - dollar) * 100); if (money == 0D) { return ""; } if (money < 0) { return INVALID_INPUT_GIVEN; } String dollarPart = ""; if (dollar > 0) { dollarPart = convert(dollar) + " dollar" + (dollar == 1 ? "" : "s"); } String centsPart = ""; if (cents > 0) { if (dollarPart.length() > 0) { centsPart = " and "; } centsPart += convert(cents) + " cent" + (cents == 1 ? "" : "s"); } return dollarPart + centsPart; }
private static String convert(final long n) { if (n < 0) { return INVALID_INPUT_GIVEN; } if (n < 20) { return ones[(int) n]; } if (n < 100) { return tens[(int) n / 10] + ((n % 10 != 0) ? " " : "") + ones[(int) n % 10]; } if (n < 1000) { return ones[(int) n / 100] + " hundred" + ((n % 100 != 0) ? " " : "") + convert(n % 100); } if (n < 1_000_000) { return convert(n / 1000) + " thousand" + ((n % 1000 != 0) ? " " : "") + convert(n % 1000); } if (n < 1_000_000_000) { return convert(n / 1_000_000) + " million" + ((n % 1_000_000 != 0) ? " " : "") + convert(n % 1_000_000); } return convert(n / 1_000_000_000) + " billion" + ((n % 1_000_000_000 != 0) ? " " : "") + convert(n % 1_000_000_000); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\numberwordconverter\NumberWordConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class SecurityConfig extends AbstractHttpConfigurer<SecurityConfig, HttpSecurity> { @Override public void configure(HttpSecurity http) throws Exception { AuthenticationManager authenticationManager = http.getSharedObject(AuthenticationManager.class); http.addFilterBefore(authenticationFilter(authenticationManager), UsernamePasswordAuthenticationFilter.class); } public static SecurityConfig securityConfig() { return new SecurityConfig(); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.csrf(AbstractHttpConfigurer::disable) .authorizeRequests() .requestMatchers("/css/**", "/index") .permitAll() .requestMatchers("/user/**") .authenticated() .and()
.formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login").permitAll()) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutUrl("/logout").permitAll()) .with(securityConfig(), Customizer.withDefaults()); return http.getOrBuild(); } public SimpleAuthenticationFilter authenticationFilter(AuthenticationManager authenticationManager) throws Exception { SimpleAuthenticationFilter filter = new SimpleAuthenticationFilter(); filter.setAuthenticationManager(authenticationManager); filter.setAuthenticationFailureHandler(failureHandler()); filter.setAuthenticationSuccessHandler(new SavedRequestAwareAuthenticationSuccessHandler()); filter.setSecurityContextRepository(new HttpSessionSecurityContextRepository()); return filter; } public SimpleUrlAuthenticationFailureHandler failureHandler() { return new SimpleUrlAuthenticationFailureHandler("/login?error=true"); } }
repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldssimple\SecurityConfig.java
2
请完成以下Java代码
static Observer<Integer> getFirstObserver() { return new Observer<Integer>() { @Override public void onNext(Integer value) { subscriber1 += value; System.out.println("Subscriber1: " + value); } @Override public void onError(Throwable e) { System.out.println("error"); } @Override public void onCompleted() { System.out.println("Subscriber1 completed"); } }; } static Observer<Integer> getSecondObserver() { return new Observer<Integer>() { @Override public void onNext(Integer value) { subscriber2 += value; System.out.println("Subscriber2: " + value);
} @Override public void onError(Throwable e) { System.out.println("error"); } @Override public void onCompleted() { System.out.println("Subscriber2 completed"); } }; } public static void main(String[] args) throws InterruptedException { System.out.println(subjectMethod()); } }
repos\tutorials-master\rxjava-modules\rxjava-core\src\main\java\com\baeldung\rxjava\SubjectImpl.java
1
请完成以下Java代码
public class DocLine_Payroll extends DocLine<Doc_HRProcess> { /** * Constructor * @param line Payroll line * @param doc header */ public DocLine_Payroll (MHRMovement line, Doc_HRProcess doc) { super (line, doc); int C_BPartner_ID = line.getC_BPartner_ID(); I_C_BPartner bpartner = Services.get(IBPartnerDAO.class).getById(C_BPartner_ID); MHRConcept concept = MHRConcept.get(Env.getCtx(), line.getHR_Concept_ID()); // m_HR_Concept_ID = concept.getHR_Concept_ID(); m_HR_Process_ID = line.getHR_Process_ID(); m_C_BPartner_ID = BPartnerId.ofRepoId(C_BPartner_ID); m_HR_Department_ID = line.getHR_Department_ID(); m_C_BP_Group_ID = bpartner.getC_BP_Group_ID(); m_AccountSign = concept.getAccountSign(); m_Amount = line.getAmount(); setAmount(line.getAmount()); } // DocLine_Payroll // References private int m_HR_Process_ID = 0; private int m_HR_Concept_ID = 0; private BPartnerId m_C_BPartner_ID; private ActivityId m_C_Activity_ID; private String m_AccountSign = ""; private BigDecimal m_Amount = BigDecimal.ZERO; private int m_HR_Department_ID = 0; private int m_C_BP_Group_ID = 0; public int getHR_Process_ID(){ return m_HR_Process_ID; } public int getHR_Concept_ID(){
return m_HR_Concept_ID; } public String getAccountSign(){ return m_AccountSign; } @Override public BPartnerId getBPartnerId(){ return m_C_BPartner_ID; } @Override public ActivityId getActivityId() { return m_C_Activity_ID; } public BigDecimal getAmount() { return m_Amount; } public int getHR_Department_ID() { return m_HR_Department_ID; } public int getC_BP_Group_ID() { return m_C_BP_Group_ID; } } // DocLine_Payroll
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\compiere\acct\DocLine_Payroll.java
1
请完成以下Java代码
public DepartIdModel convertByUserDepart(SysDepart sysDepart) { this.key = sysDepart.getId(); this.value = sysDepart.getId(); this.code = sysDepart.getOrgCode(); this.title = sysDepart.getDepartName(); return this; } public List<DepartIdModel> getChildren() { return children; } public void setChildren(List<DepartIdModel> children) { this.children = children; } public static long getSerialVersionUID() { return serialVersionUID; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getValue() { return value; }
public void setValue(String value) { this.value = value; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\DepartIdModel.java
1
请完成以下Java代码
public void setM_Shipment_Declaration_ID (int M_Shipment_Declaration_ID) { if (M_Shipment_Declaration_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_ID, Integer.valueOf(M_Shipment_Declaration_ID)); } /** Get Abgabemeldung. @return Abgabemeldung */ @Override public int getM_Shipment_Declaration_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_ValueNoCheck (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false;
} /** Set Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration.java
1
请完成以下Java代码
public static void main(String[] args) { /* Static text */ Logger.info("Hello World!"); /* Placeholders */ Logger.info("Hello {}!", "Alice"); Logger.info("π = {0.00}", Math.PI); /* Lazy Logging */ Logger.debug("Expensive computation: {}", () -> compute()); // Visible in log files but not on the console /* Exceptions */ int a = 42; int b = 0;
try { int i = a / b; } catch (Exception ex) { Logger.error(ex, "Cannot divide {} by {}", a, b); } try { int i = a / b; } catch (Exception ex) { Logger.error(ex); } } private static int compute() { return 42; // In real applications, we would perform an expensive computation here } }
repos\tutorials-master\logging-modules\tinylog2\src\main\java\com\baeldung\tinylog\TinylogExamples.java
1
请完成以下Java代码
public JsonResponseLocation getJsonBPartnerLocationById(@Nullable final String orgCode, @NonNull final BPartnerLocationId bpartnerLocationId) { final ResponseEntity<JsonResponseLocation> location = bpartnerRestController.retrieveBPartnerLocation( orgCode, Integer.toString(bpartnerLocationId.getBpartnerId().getRepoId()), Integer.toString(bpartnerLocationId.getRepoId())); return Optional.ofNullable(location.getBody()) .orElseThrow(() -> new AdempiereException("No BPartnerLocation found for the given bPartnerIdentifier,BPartnerLocationIdentifier!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", bpartnerLocationId.getBpartnerId().getRepoId()) .setParameter("BPartnerLocationIdentifier", bpartnerLocationId.getRepoId())); } @NonNull public JsonResponseContact getJsonBPartnerContactById(@Nullable final String orgCode, @NonNull final BPartnerContactId bpartnerContactId) { final ResponseEntity<JsonResponseContact> contact = bpartnerRestController.retrieveBPartnerContact( orgCode, Integer.toString(bpartnerContactId.getBpartnerId().getRepoId()), Integer.toString(bpartnerContactId.getRepoId())); return Optional.ofNullable(contact.getBody()) .orElseThrow(() -> new AdempiereException("No BPartnerContact found for the given bPartnerIdentifier,BPartnerContactId!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", bpartnerContactId.getBpartnerId().getRepoId())
.setParameter("bpartnerContactIdentifier", bpartnerContactId.getRepoId())); } @NonNull public JsonResponseBPartner getJsonBPartnerByExternalIdentifier(@Nullable final String orgCode, @NonNull final String externalIdentifier) { final ResponseEntity<JsonResponseComposite> bpartner = bpartnerRestController.retrieveBPartner(orgCode, externalIdentifier); return Optional.ofNullable(bpartner.getBody()) .map(JsonResponseComposite::getBpartner) .orElseThrow(() -> new AdempiereException("No BPartner found for the given external identifier!") .appendParametersToMessage() .setParameter("BPartnerIdentifier", externalIdentifier)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\ordercandidates\impl\BPartnerEndpointAdapter.java
1
请完成以下Java代码
public long getCreatedTime() { return super.getCreatedTime(); } @Schema(description = "JSON object with Tenant Id. Use 'assignDeviceToTenant' to change the Tenant Id.", accessMode = Schema.AccessMode.READ_ONLY) @Override public TenantId getTenantId() { return this.tenantId; } @Schema(description = "JSON object with Customer Id. Use 'assignEdgeToCustomer' to change the Customer Id.", accessMode = Schema.AccessMode.READ_ONLY) @Override public CustomerId getCustomerId() { return this.customerId; } @Schema(description = "JSON object with Root Rule Chain Id. Use 'setEdgeRootRuleChain' to change the Root Rule Chain Id.", accessMode = Schema.AccessMode.READ_ONLY) public RuleChainId getRootRuleChainId() { return this.rootRuleChainId; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Unique Edge Name in scope of Tenant", example = "Silo_A_Edge") @Override public String getName() { return this.name; }
@Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge type", example = "Silos") public String getType() { return this.type; } @Schema(description = "Label that may be used in widgets", example = "Silo Edge on far field") public String getLabel() { return this.label; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge routing key ('username') to authorize on cloud") public String getRoutingKey() { return this.routingKey; } @Schema(requiredMode = Schema.RequiredMode.REQUIRED, description = "Edge secret ('password') to authorize on cloud") public String getSecret() { return this.secret; } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\edge\Edge.java
1
请完成以下Java代码
public Date getClaimTime() { return null; } @Override public String getClaimedBy() { return null; } @Override public Date getSuspendedTime() { return null; } @Override
public String getSuspendedBy() { return null; } @Override public Date getInProgressStartDueDate() { return null; } @Override public void setInProgressStartDueDate(Date inProgressStartDueDate) { // nothing } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntity.java
1
请完成以下Java代码
public class JakartaEjbProcessApplicationReference implements ProcessApplicationReference { private static ProcessApplicationLogger LOG = ProcessEngineLogger.PROCESS_APPLICATION_LOGGER; /** this is an EjbProxy and can be cached */ protected ProcessApplicationInterface selfReference; /** the name of the process application */ protected String processApplicationName; public JakartaEjbProcessApplicationReference(ProcessApplicationInterface selfReference, String name) { this.selfReference = selfReference; this.processApplicationName = name; } @Override public String getName() { return processApplicationName; } @Override
public ProcessApplicationInterface getProcessApplication() throws ProcessApplicationUnavailableException { try { // check whether process application is still deployed selfReference.getName(); } catch (EJBException e) { throw LOG.processApplicationUnavailableException(processApplicationName, e); } return selfReference; } public void processEngineStopping(ProcessEngine processEngine) throws ProcessApplicationUnavailableException { // do nothing. } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\JakartaEjbProcessApplicationReference.java
1
请完成以下Java代码
public class SecretKey { private static final SecureRandom random = new SecureRandom(); private final String string; private SecretKey(@NonNull final String string) { this.string = string; } public static SecretKey random() { final byte[] bytes = new byte[20]; random.nextBytes(bytes); return new SecretKey(BaseEncoding.base32().encode(bytes)); } public static SecretKey ofString(@NonNull String string) { return new SecretKey(string); } public static Optional<SecretKey> optionalOfString(@Nullable String string) { return StringUtils.trimBlankToOptional(string).map(SecretKey::new); } @Deprecated
@Override public String toString() {return getAsString();} public String getAsString() {return string;} public boolean isValid(@NonNull final OTP otp) { return TOTPUtils.validate(this, otp); } public String toHexString() { final byte[] bytes = BaseEncoding.base32().decode(string); //return java.util.HexFormat.of().formatHex(bytes); return Hex.encodeHexString(bytes); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\user_2fa\totp\SecretKey.java
1
请在Spring Boot框架中完成以下Java代码
private void storeFailed( @NonNull final TimeRecord timeRecord, @NonNull final String errorMsg, @NonNull OrgId orgId) { final StringBuilder errorMessage = new StringBuilder(errorMsg); String jsonValue = null; try { jsonValue = objectMapper.writeValueAsString(timeRecord); } catch (final JsonProcessingException e) { Loggables.withLogger(log, Level.ERROR) .addLog(IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX + e.getMessage()); errorMessage.append("\n Error while trying to write TimeRecord as JSON: ").append(e.getMessage()); } final FailedTimeBooking failedTimeBooking = FailedTimeBooking.builder() .jsonValue(jsonValue) .orgId(orgId) .externalId(timeRecord.getId()) .externalSystem(externalSystemRepository.getByType(ExternalSystemType.Everhour)) .errorMsg(errorMessage.toString()) .build(); failedTimeBookingRepository.save(failedTimeBooking); } private void importFailedTimeBookings() { Loggables.withLogger(log, Level.DEBUG).addLog(" {} start importing failed time bookings", IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX); final Stopwatch stopWatch = Stopwatch.createStarted(); final ImmutableList<FailedTimeBooking> failedTimeBookings = failedTimeBookingRepository.listBySystem(externalSystemRepository.getByType(ExternalSystemType.Everhour)); for (FailedTimeBooking failedTimeBooking : failedTimeBookings) { if (Check.isBlank(failedTimeBooking.getJsonValue())) { continue; } importTimeBooking(getTimeRecordFromFailed(failedTimeBooking), failedTimeBooking.getOrgId()); } Loggables.withLogger(log, Level.DEBUG).addLog(" {} finished importing failed time bookings! elapsed time: {}",
IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX, stopWatch); } private TimeRecord getTimeRecordFromFailed(@NonNull final FailedTimeBooking failedTimeBooking) { try { return objectMapper.readValue(failedTimeBooking.getJsonValue(), TimeRecord.class); } catch (final Exception e) { throw new AdempiereException("Failed to read value from failed time booking!") .appendParametersToMessage() .setParameter("failedTimeBooking.getJsonValue()", failedTimeBooking.getJsonValue()); } } private void acquireLock() { final boolean lockAcquired = lock.tryLock(); if (!lockAcquired) { throw new AdempiereException("The import is already running!"); } log.debug(" {} EverhourImporterService: lock acquired, starting the import!", IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX); } private void releaseLock() { lock.unlock(); log.debug(" {} EverhourImporterService: lock released!", IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\everhour\EverhourImporterService.java
2
请完成以下Java代码
public BankStatementLineAmounts addDifferenceToTrxAmt() { if (differenceAmt.signum() == 0) { return this; } return toBuilder() .trxAmt(this.trxAmt.add(differenceAmt)) .build(); } public BankStatementLineAmounts withTrxAmt(@NonNull final BigDecimal trxAmt) { return !this.trxAmt.equals(trxAmt) ? toBuilder().trxAmt(trxAmt).build() : this; } public BankStatementLineAmounts addDifferenceToBankFeeAmt() { if (differenceAmt.signum() == 0)
{ return this; } return toBuilder() .bankFeeAmt(this.bankFeeAmt.subtract(differenceAmt)) .build(); } public BankStatementLineAmounts withBankFeeAmt(@NonNull final BigDecimal bankFeeAmt) { return !this.bankFeeAmt.equals(bankFeeAmt) ? toBuilder().bankFeeAmt(bankFeeAmt).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\model\BankStatementLineAmounts.java
1
请完成以下Java代码
public void setPageURL (String PageURL) { set_Value (COLUMNNAME_PageURL, PageURL); } /** Get Page URL. @return Page URL */ public String getPageURL () { return (String)get_Value(COLUMNNAME_PageURL); } /** Set Counter Count. @param W_CounterCount_ID Web Counter Count Management */ public void setW_CounterCount_ID (int W_CounterCount_ID) { if (W_CounterCount_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, null); else set_ValueNoCheck (COLUMNNAME_W_CounterCount_ID, Integer.valueOf(W_CounterCount_ID)); } /** Get Counter Count. @return Web Counter Count Management */ public int getW_CounterCount_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_CounterCount_ID); 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_W_CounterCount.java
1
请在Spring Boot框架中完成以下Java代码
public ResponseEntity<?> updateOrder(@CurrentUser UserPrincipal userPrincipal, @RequestBody OrderResponse orderResponse) { return orderService.statusDelivered(userPrincipal, orderResponse); } @PostMapping("/order/repeatOrderRequest") public ResponseEntity<?> repeatOrder(@CurrentUser UserPrincipal currentUser, @RequestBody List<GoodOrderDetailsResponse> detailsResponseList) { boolean isGoodExists = true; User user = userRepository.findById(currentUser.getId()).orElse(null); if(user != null) { Orders bucket = orderRepository.findFirstByStatusAndUser(OrderStatus.NEW, user).orElse(null); if(bucket == null) { bucket = new Orders(); bucket.setUser(user); bucket.setStatus(OrderStatus.NEW); orderRepository.save(bucket); } //TODO: если уже есть товары в корзине, то спрашивать перед тем как чистить корзину List<OrderDetails> bucketGoods = orderDetailsRepository.findAllByOrder(bucket); for(OrderDetails orderDetails : bucketGoods) { orderDetailsRepository.delete(orderDetails); } for(GoodOrderDetailsResponse goodOrderDetailsResponse : detailsResponseList) {
List<Good> goodList = goodsRepository.findAllByInternalCodeAndIsOutdated(goodOrderDetailsResponse.getInternalCode(), false); if(!goodList.isEmpty()) { Good good = goodsRepository.findAllByInternalCodeAndIsOutdated(goodOrderDetailsResponse.getInternalCode(), false).get(0); OrderDetails orderDetails = new OrderDetails(); orderDetails.setOrder(bucket); orderDetails.setGood(good); orderDetails.setQuantity(goodOrderDetailsResponse.getQuantity()); orderDetailsRepository.save(orderDetails); } else isGoodExists = false; } } if(!isGoodExists) return new ResponseEntity(new ApiResponse(false, "Извините, некоторых товаров уже нет в магазине!"), HttpStatus.INTERNAL_SERVER_ERROR); else return new ResponseEntity(new ApiResponse(true, "Запрос на повторное создание заказа успешно создан!"), HttpStatus.OK); } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\controller\OrderController.java
2
请在Spring Boot框架中完成以下Java代码
private ITemplateResolver htmlTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/views/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.HTML); return resolver; } private ITemplateResolver javascriptTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/js/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.JAVASCRIPT); return resolver; } private ITemplateResolver plainTemplateResolver() { SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver(); resolver.setApplicationContext(applicationContext); resolver.setPrefix("/WEB-INF/txt/"); resolver.setCacheable(false); resolver.setTemplateMode(TemplateMode.TEXT); return resolver; } @Bean @Description("Spring Message Resolver") public ResourceBundleMessageSource messageSource() { ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource(); messageSource.setBasename("messages"); return messageSource; } @Bean public LocaleResolver localeResolver() { SessionLocaleResolver localeResolver = new SessionLocaleResolver(); localeResolver.setDefaultLocale(new Locale("en")); return localeResolver; } @Bean public LocaleChangeInterceptor localeChangeInterceptor() { LocaleChangeInterceptor localeChangeInterceptor = new LocaleChangeInterceptor(); localeChangeInterceptor.setParamName("lang");
return localeChangeInterceptor; } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(localeChangeInterceptor()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**", "/css/**") .addResourceLocations("/WEB-INF/resources/", "/WEB-INF/css/"); } @Override @Description("Custom Conversion Service") public void addFormatters(FormatterRegistry registry) { registry.addFormatter(new NameFormatter()); } }
repos\tutorials-master\spring-web-modules\spring-thymeleaf\src\main\java\com\baeldung\thymeleaf\config\WebMVCConfig.java
2
请在Spring Boot框架中完成以下Java代码
public void addComment(CommentResource comment) { if (this.taskComments == null) { this.taskComments = new ArrayList<>(); } this.taskComments.add(comment); } /** * @return the taskComments */ public List<CommentResource> getTaskComments() { return taskComments; } /** * @param taskComments * the taskComments to set */ public void setTaskComments(List<CommentResource> taskComments) { this.taskComments = taskComments; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((taskComments == null) ? 0 : taskComments.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CommentCollectionResource other = (CommentCollectionResource) obj; if (taskComments == null) { if (other.taskComments != null) return false; } else if (!taskComments.equals(other.taskComments)) return false; return true; }
/* * (non-Javadoc) * * @see java.lang.Object#toString() */ @Override public String toString() { return "CommentCollectionResource [taskComments=" + taskComments + "]"; } } /** * Inner class to perform the de-serialization of the comments array * * @author anilallewar * */ class CommentsCollectionDeserializer extends JsonDeserializer<CommentCollectionResource> { @Override public CommentCollectionResource deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException { CommentCollectionResource commentArrayResource = new CommentCollectionResource(); CommentResource commentResource = null; JsonNode jsonNode = jp.readValueAsTree(); for (JsonNode childNode : jsonNode) { if (childNode.has(CommentResource.JP_TASKID)) { commentResource = new CommentResource(); commentResource.setTaskId(childNode.get(CommentResource.JP_TASKID).asText()); commentResource.setComment(childNode.get(CommentResource.JP_COMMENT).asText()); commentResource.setPosted(new Date(childNode.get(CommentResource.JP_POSTED).asLong())); commentArrayResource.addComment(commentResource); } } return commentArrayResource; } }
repos\spring-boot-microservices-master\task-webservice\src\main\java\com\rohitghatol\microservices\task\model\CommentCollectionResource.java
2
请完成以下Java代码
public final class Password { @JsonCreator public static Password ofNullableString(final String password) { return password != null ? new Password(password) : null; } public static Password cast(final Object value) { return (Password)value; } public static final String OBFUSCATE_STRING = "********"; private final String password; private Password(@NonNull final String password) { this.password = password; }
@Override public String toString() { return MoreObjects.toStringHelper(this) .add("password", "********") .toString(); } @JsonValue public String toJson() { return OBFUSCATE_STRING; } public String getAsString() { return password; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\Password.java
1
请完成以下Java代码
public void creatingInitialAdminUser(User adminUser) { logDebug("010", "Creating initial Admin User: {}", adminUser); } public void skipAdminUserCreation(User existingUser) { logDebug("011", "Skip creating initial Admin User, user does exist: {}", existingUser); } public void createInitialFilter(Filter filter) { logInfo("015", "Create initial filter: id={} name={}", filter.getId(), filter.getName()); } public void skipCreateInitialFilter(String filterName) { logInfo("016", "Skip initial filter creation, the filter with this name already exists: {}", filterName); } public void skipAutoDeployment() { logInfo("020", "ProcessApplication enabled: autoDeployment via springConfiguration#deploymentResourcePattern is disabled"); } public void autoDeployResources(Set<Resource> resources) { // Only log the description of `Resource` objects since log libraries that serialize them and // therefore consume the input stream make the deployment fail since the input stream has // already been consumed. Set<String> resourceDescriptions = resources.stream() .filter(Objects::nonNull) .map(Resource::getDescription) .filter(Objects::nonNull) .collect(Collectors.toSet());
logInfo("021", "Auto-Deploying resources: {}", resourceDescriptions); } public void enterLicenseKey(String licenseKeySource) { logInfo("030", "Setting up license key: {}", licenseKeySource); } public void enterLicenseKeyFailed(URL licenseKeyFile, Exception e) { logWarn("031", "Failed setting up license key: {}", licenseKeyFile, e); } public void configureJobExecutorPool(Integer corePoolSize, Integer maxPoolSize) { logInfo("040", "Setting up jobExecutor with corePoolSize={}, maxPoolSize:{}", corePoolSize, maxPoolSize); } public SpringBootStarterException exceptionDuringBinding(String message) { return new SpringBootStarterException(exceptionMessage( "050", message)); } public void propertiesApplied(GenericProperties genericProperties) { logDebug("051", "Properties bound to configuration: {}", genericProperties); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\util\SpringBootProcessEngineLogger.java
1