instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class ImportJsonService { private Logger log = LogManager.getLogger(this.getClass()); @Autowired private MongoTemplate mongo; public String importTo(Class<?> type, List<String> jsonLines) { List<Document> mongoDocs = generateMongoDocs(jsonLines, type); String collection = type.getAnnotation(org.springframework.data.mongodb.core.mapping.Document.class) .value(); int inserts = insertInto(collection, mongoDocs); return inserts + "/" + jsonLines.size(); } public String importTo(String collection, List<String> jsonLines) { List<Document> mongoDocs = generateMongoDocs(jsonLines); int inserts = insertInto(collection, mongoDocs); return inserts + "/" + jsonLines.size(); } private int insertInto(String collection, List<Document> mongoDocs) { try { Collection<Document> inserts = mongo.insert(mongoDocs, collection); return inserts.size(); } catch (DataIntegrityViolationException e) { log.error("importing docs", e); if (e.getCause() instanceof MongoBulkWriteException) { return ((MongoBulkWriteException) e.getCause()).getWriteResult() .getInsertedCount(); } return 0; } } private List<Document> generateMongoDocs(List<String> lines) { return generateMongoDocs(lines, null); } private <T> List<Document> generateMongoDocs(List<String> lines, Class<T> type) {
ObjectMapper mapper = new ObjectMapper(); List<Document> docs = new ArrayList<>(); for (String json : lines) { try { if (type != null) { T v = mapper.readValue(json, type); json = mapper.writeValueAsString(v); } docs.add(Document.parse(json)); } catch (Throwable e) { log.error("parsing: " + json, e); } } return docs; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\json\convertfile\service\ImportJsonService.java
2
请完成以下Java代码
public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author;
} public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } @Override public String toString() { return "Book{" + "isbn='" + isbn + '\'' + ", name='" + name + '\'' + ", author='" + author + '\'' + ", pages=" + pages + '}'; } }
repos\tutorials-master\persistence-modules\jnosql\jnosql-diana\src\main\java\com\baeldung\jnosql\diana\key\Book.java
1
请在Spring Boot框架中完成以下Java代码
private String getLadderPromotionMessage(PmsProductLadder ladder) { StringBuilder sb = new StringBuilder(); sb.append("打折优惠:"); sb.append("满"); sb.append(ladder.getCount()); sb.append("件,"); sb.append("打"); sb.append(ladder.getDiscount().multiply(new BigDecimal(10))); sb.append("折"); return sb.toString(); } /** * 根据购买商品数量获取满足条件的打折优惠策略 */ private PmsProductLadder getProductLadder(int count, List<PmsProductLadder> productLadderList) { //按数量从大到小排序 productLadderList.sort(new Comparator<PmsProductLadder>() { @Override public int compare(PmsProductLadder o1, PmsProductLadder o2) { return o2.getCount() - o1.getCount(); } }); for (PmsProductLadder productLadder : productLadderList) { if (count >= productLadder.getCount()) { return productLadder; } } return null; } /** * 获取购物车中指定商品的数量 */ private int getCartItemCount(List<OmsCartItem> itemList) { int count = 0; for (OmsCartItem item : itemList) { count += item.getQuantity(); } return count; } /** * 获取购物车中指定商品的总价 */ private BigDecimal getCartItemAmount(List<OmsCartItem> itemList, List<PromotionProduct> promotionProductList) { BigDecimal amount = new BigDecimal(0); for (OmsCartItem item : itemList) {
//计算出商品原价 PromotionProduct promotionProduct = getPromotionProductById(item.getProductId(), promotionProductList); PmsSkuStock skuStock = getOriginalPrice(promotionProduct,item.getProductSkuId()); amount = amount.add(skuStock.getPrice().multiply(new BigDecimal(item.getQuantity()))); } return amount; } /** * 获取商品的原价 */ private PmsSkuStock getOriginalPrice(PromotionProduct promotionProduct, Long productSkuId) { for (PmsSkuStock skuStock : promotionProduct.getSkuStockList()) { if (productSkuId.equals(skuStock.getId())) { return skuStock; } } return null; } /** * 根据商品id获取商品的促销信息 */ private PromotionProduct getPromotionProductById(Long productId, List<PromotionProduct> promotionProductList) { for (PromotionProduct promotionProduct : promotionProductList) { if (productId.equals(promotionProduct.getId())) { return promotionProduct; } } return null; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsPromotionServiceImpl.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Desktop[") .append(get_ID()).append("]"); return sb.toString(); } /** Set System Color. @param AD_Color_ID Color for backgrounds or indicators */ public void setAD_Color_ID (int AD_Color_ID) { if (AD_Color_ID < 1) set_Value (COLUMNNAME_AD_Color_ID, null); else set_Value (COLUMNNAME_AD_Color_ID, Integer.valueOf(AD_Color_ID)); } /** Get System Color. @return Color for backgrounds or indicators */ public int getAD_Color_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Color_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Desktop. @param AD_Desktop_ID Collection of Workbenches */ public void setAD_Desktop_ID (int AD_Desktop_ID) { if (AD_Desktop_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Desktop_ID, Integer.valueOf(AD_Desktop_ID)); } /** Get Desktop. @return Collection of Workbenches */ public int getAD_Desktop_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Desktop_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Image. @param AD_Image_ID Image or Icon */ public void setAD_Image_ID (int AD_Image_ID) { if (AD_Image_ID < 1) set_Value (COLUMNNAME_AD_Image_ID, null); else set_Value (COLUMNNAME_AD_Image_ID, Integer.valueOf(AD_Image_ID)); } /** Get Image. @return Image or Icon */ public int getAD_Image_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Image_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description.
@param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Desktop.java
1
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ 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; } /** Set Quantity. @param Qty Quantity */ public void setQty (int Qty) { set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty)); } /** Get Quantity. @return Quantity */ public int getQty () { Integer ii = (Integer)get_Value(COLUMNNAME_Qty); if (ii == null)
return 0; return ii.intValue(); } /** Set Start Date. @param StartDate First effective day (inclusive) */ public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Year.java
1
请完成以下Java代码
public String postUser(@ModelAttribute User user) { // 处理"/users/"的POST请求,用来创建User // 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数 users.put(user.getId(), user); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { // 处理"/users/{id}"的GET请求,用来获取url中id值的User信息 // url中的id可通过@PathVariable绑定到函数的参数中 return users.get(id); } @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息 User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 处理"/users/{id}"的DELETE请求,用来删除User users.remove(id); return "success"; } }
repos\SpringBoot-Learning-master\1.x\Chapter3-1-1\src\main\java\com\didispace\web\UserController.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_SubAcct[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_ElementValue getC_ElementValue() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getC_ElementValue_ID(), get_TrxName()); } /** Set Account Element. @param C_ElementValue_ID Account Element */ public void setC_ElementValue_ID (int C_ElementValue_ID) { if (C_ElementValue_ID < 1) set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, null); else set_ValueNoCheck (COLUMNNAME_C_ElementValue_ID, Integer.valueOf(C_ElementValue_ID)); } /** Get Account Element. @return Account Element */ public int getC_ElementValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_ElementValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sub Account. @param C_SubAcct_ID Sub account for Element Value */ public void setC_SubAcct_ID (int C_SubAcct_ID) { if (C_SubAcct_ID < 1) set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, null); else set_ValueNoCheck (COLUMNNAME_C_SubAcct_ID, Integer.valueOf(C_SubAcct_ID)); } /** Get Sub Account. @return Sub account for Element Value */ public int getC_SubAcct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_SubAcct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp ()
{ return (String)get_Value(COLUMNNAME_Help); } /** 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 Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SubAcct.java
1
请完成以下Java代码
public class ESRTransaction { /** * Might be null in case the loader wasn't able to extract the date. In this case, there is an error message in the list. */ private final Date accountingDate; /** * Might be null in case the loader wasn't able to extract the date. In this case, there is an error message in the list. */ private final Date paymentDate; /** * The monetary amount. Currency is the one from the respective header.<br> * Might be null in case the loader wasn't able to extract the date. In this case, there is an error message in the list. */ private final BigDecimal amount; private final String esrParticipantNo; /** * This if the <b>full</b> ESR number. A substring of it is also included in the invoice we did sent to the BPartner and can include all sorts of metasfresh-custom info, such as the org. */ private final String esrReferenceNumber; /** * Used to decide if a given transaction from a file was already imported or no. */ @NonNull private final String transactionKey; @NonNull
private final String trxType; @NonNull private final ESRType type; @Singular private final List<String> errorMsgs; public BigDecimal getAmountNotNull() { if (amount == null) { return BigDecimal.ZERO; } return amount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRTransaction.java
1
请在Spring Boot框架中完成以下Java代码
public class Contact { @Id @GeneratedValue private Long id; @Size(min = 2) private String name; @Email private String email; private String phone; public Contact() { } public Contact(String name, String email, String phone) { this.name = name; this.email = email; this.phone = phone; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public @Size(min = 2) String getName() { return name; }
public void setName(@Size(min = 2) String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
repos\tutorials-master\web-modules\hilla\src\main\java\com\example\demo\Contact.java
2
请完成以下Java代码
public void decode() throws IOException { int[] bread = { 0 }; BERSequence seq = (BERSequence) BERElement.getElement(new SpecificTagDecoder(), new ByteArrayInputStream(PasswordPolicyResponseControl.this.encodedValue), bread); int size = seq.size(); if (logger.isDebugEnabled()) { logger.debug(LogMessage.format("Received PasswordPolicyResponse whose ASN.1 sequence has %d elements", size)); } for (int i = 0; i < seq.size(); i++) { BERTag elt = (BERTag) seq.elementAt(i); int tag = elt.getTag() & 0x1F; if (tag == 0) { BERChoice warning = (BERChoice) elt.getValue(); BERTag content = (BERTag) warning.getValue(); int value = ((BERInteger) content.getValue()).getValue(); if ((content.getTag() & 0x1F) == 0) { PasswordPolicyResponseControl.this.timeBeforeExpiration = value; } else { PasswordPolicyResponseControl.this.graceLoginsRemaining = value; } } else if (tag == 1) { BERIntegral error = (BERIntegral) elt.getValue(); PasswordPolicyResponseControl.this.errorStatus = PasswordPolicyErrorStatus.values()[error .getValue()]; } } } static class SpecificTagDecoder extends BERTagDecoder { /** Allows us to remember which of the two options we're decoding */ private Boolean inChoice = null; @Override public BERElement getElement(BERTagDecoder decoder, int tag, InputStream stream, int[] bytesRead, boolean[] implicit) throws IOException { tag &= 0x1F; implicit[0] = false; if (tag == 0) { // Either the choice or the time before expiry within it if (this.inChoice == null) { setInChoice(true); // Read the choice length from the stream (ignored) BERElement.readLengthOctets(stream, bytesRead); int[] componentLength = new int[1]; BERElement choice = new BERChoice(decoder, stream, componentLength); bytesRead[0] += componentLength[0]; // inChoice = null; return choice; } else { // Must be time before expiry
return new BERInteger(stream, bytesRead); } } else if (tag == 1) { // Either the graceLogins or the error enumeration. if (this.inChoice == null) { // The enumeration setInChoice(false); return new BEREnumerated(stream, bytesRead); } else { if (this.inChoice) { // graceLogins return new BERInteger(stream, bytesRead); } } } throw new DataRetrievalFailureException("Unexpected tag " + tag); } private void setInChoice(boolean inChoice) { this.inChoice = inChoice; } } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\ppolicy\PasswordPolicyResponseControl.java
1
请完成以下Java代码
public static final Number div(TypeConverter converter, Object o1, Object o2) { if (o1 == null && o2 == null) { return LONG_ZERO; } if (isBigDecimalOrBigInteger(o1) || isBigDecimalOrBigInteger(o2)) { return converter .convert(o1, BigDecimal.class) .divide(converter.convert(o2, BigDecimal.class), BigDecimal.ROUND_HALF_UP); } return (converter.convert(o1, Double.class) / converter.convert(o2, Double.class)); } public static final Number mod(TypeConverter converter, Object o1, Object o2) { if (o1 == null && o2 == null) { return LONG_ZERO; } if (isBigDecimalOrFloatOrDoubleOrDotEe(o1) || isBigDecimalOrFloatOrDoubleOrDotEe(o2)) { return (converter.convert(o1, Double.class) % converter.convert(o2, Double.class)); } if (o1 instanceof BigInteger || o2 instanceof BigInteger) { return converter.convert(o1, BigInteger.class).remainder(converter.convert(o2, BigInteger.class)); } return (converter.convert(o1, Long.class) % converter.convert(o2, Long.class)); } public static final Number neg(TypeConverter converter, Object value) { if (value == null) { return LONG_ZERO; } if (value instanceof BigDecimal) { return ((BigDecimal) value).negate(); }
if (value instanceof BigInteger) { return ((BigInteger) value).negate(); } if (value instanceof Double) { return Double.valueOf(-((Double) value).doubleValue()); } if (value instanceof Float) { return Float.valueOf(-((Float) value).floatValue()); } if (value instanceof String) { if (isDotEe((String) value)) { return Double.valueOf(-converter.convert(value, Double.class).doubleValue()); } return Long.valueOf(-converter.convert(value, Long.class).longValue()); } if (value instanceof Long) { return Long.valueOf(-((Long) value).longValue()); } if (value instanceof Integer) { return Integer.valueOf(-((Integer) value).intValue()); } if (value instanceof Short) { return Short.valueOf((short) -((Short) value).shortValue()); } if (value instanceof Byte) { return Byte.valueOf((byte) -((Byte) value).byteValue()); } throw new ELException(LocalMessages.get("error.negate", value.getClass())); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\NumberOperations.java
1
请完成以下Java代码
public Class<?> getType(ELContext context, Object base, Object property) { return resolve(context, base, property) ? Object.class : null; } @Override public Object getValue(ELContext context, Object base, Object property) { if (resolve(context, base, property)) { if (!isProperty((String) property)) { throw new PropertyNotFoundException("Cannot find property " + property); } return getProperty((String) property); } return null; } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return resolve(context, base, property) ? readOnly : false; } @Override public void setValue(ELContext context, Object base, Object property, Object value) throws PropertyNotWritableException { if (resolve(context, base, property)) { if (readOnly) { throw new PropertyNotWritableException("Resolver is read only!"); } setProperty((String) property, value); } } @Override public Object invoke(ELContext context, Object base, Object method, Class<?>[] paramTypes, Object[] params) { if (resolve(context, base, method)) { throw new NullPointerException("Cannot invoke method " + method + " on null"); } return null; } /** * Get property value * * @param property * property name * @return value associated with the given property */ public Object getProperty(String property) {
return map.get(property); } /** * Set property value * * @param property * property name * @param value * property value */ public void setProperty(String property, Object value) { map.put(property, value); } /** * Test property * * @param property * property name * @return <code>true</code> if the given property is associated with a value */ public boolean isProperty(String property) { return map.containsKey(property); } /** * Get properties * * @return all property names (in no particular order) */ public Iterable<String> properties() { return map.keySet(); } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\util\RootPropertyResolver.java
1
请在Spring Boot框架中完成以下Java代码
public class SAPGLJournalCurrencyConverter { private final ICurrencyBL currencyBL = Services.get(ICurrencyBL.class); public Money convertToAcctCurrency( @NonNull final Money amount, @NonNull final SAPGLJournalCurrencyConversionCtx ctx) { if (!CurrencyId.equals(amount.getCurrencyId(), ctx.getCurrencyId())) { throw new AdempiereException("Amount `" + amount + "` has unexpected currency. Expected was the context currency: " + ctx); } return convertToAcctCurrency(amount.toBigDecimal(), ctx); } public Money convertToAcctCurrency( @NonNull final BigDecimal amountBD, @NonNull final SAPGLJournalCurrencyConversionCtx ctx) { final CurrencyConversionResult result = currencyBL.convert(toCurrencyConversionContext(ctx), amountBD, ctx.getCurrencyId(), ctx.getAcctCurrencyId()); return result.getAmountAsMoney();
} public CurrencyConversionContext toCurrencyConversionContext(@NonNull final SAPGLJournalCurrencyConversionCtx ctx) { CurrencyConversionContext currencyConversionContext = currencyBL.createCurrencyConversionContext( ctx.getDate(), ctx.getConversionTypeId(), ctx.getClientAndOrgId().getClientId(), ctx.getClientAndOrgId().getOrgId()); if (ctx.getFixedConversionRate() != null) { currencyConversionContext = currencyConversionContext.withFixedConversionRate(ctx.getFixedConversionRate()); } return currencyConversionContext; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalCurrencyConverter.java
2
请完成以下Java代码
public class ES_FTS_Filter_Test extends JavaProcess { private final FTSConfigService ftsConfigService = SpringContextHolder.instance.getBean(FTSConfigService.class); private final FTSSearchService ftsSearchService = SpringContextHolder.instance.getBean(FTSSearchService.class); @Param(parameterName = "TestSearchText") private String p_TestSearchText; @Override protected String doIt() throws Exception { final FTSFilterDescriptorId filterId = FTSFilterDescriptorId.ofRepoId(getRecord_ID()); final FTSFilterDescriptor filter = ftsConfigService.getFilterById(filterId); final FTSConfig ftsConfig = ftsConfigService.getConfigById(filter.getFtsConfigId()); final FTSSearchRequest request = FTSSearchRequest.builder() .searchId("test-search-" + UUID.randomUUID()) .searchText(p_TestSearchText) .esIndexName(ftsConfig.getEsIndexName()) .filterDescriptor(filter)
.build(); addLog("Request: {}", request); final Stopwatch stopwatch = Stopwatch.createStarted(); final FTSSearchResult result = ftsSearchService.search(request); stopwatch.stop(); addLog("Got {} items. Took {}", result.getItems().size(), stopwatch); for (final FTSSearchResultItem item : result.getItems()) { addLog("Result item: {}", item); } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\query\process\ES_FTS_Filter_Test.java
1
请完成以下Java代码
public void destroy() { log.info("destroy"); m_serverMgr = null; } // destroy /** * Log error/warning * * @param message message * @param e exception */ @Override public void log(final String message, final Throwable e) { if (e == null) { log.warn(message); } log.error(message, e); } // log /**
* Log debug * * @param message message */ @Override public void log(String message) { log.debug(message); } // log @Override public String getServletName() { return NAME; } @Override public String getServletInfo() { return "Server Monitor"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java
1
请完成以下Java代码
public class OAuth2UserRequest { private final ClientRegistration clientRegistration; private final OAuth2AccessToken accessToken; private final Map<String, Object> additionalParameters; /** * Constructs an {@code OAuth2UserRequest} using the provided parameters. * @param clientRegistration the client registration * @param accessToken the access token */ public OAuth2UserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken) { this(clientRegistration, accessToken, Collections.emptyMap()); } /** * Constructs an {@code OAuth2UserRequest} using the provided parameters. * @param clientRegistration the client registration * @param accessToken the access token * @param additionalParameters the additional parameters, may be empty * @since 5.1 */ public OAuth2UserRequest(ClientRegistration clientRegistration, OAuth2AccessToken accessToken, Map<String, Object> additionalParameters) { Assert.notNull(clientRegistration, "clientRegistration cannot be null"); Assert.notNull(accessToken, "accessToken cannot be null"); this.clientRegistration = clientRegistration; this.accessToken = accessToken; this.additionalParameters = Collections.unmodifiableMap(CollectionUtils.isEmpty(additionalParameters) ? Collections.emptyMap() : new LinkedHashMap<>(additionalParameters)); } /** * Returns the {@link ClientRegistration client registration}. * @return the {@link ClientRegistration} */
public ClientRegistration getClientRegistration() { return this.clientRegistration; } /** * Returns the {@link OAuth2AccessToken access token}. * @return the {@link OAuth2AccessToken} */ public OAuth2AccessToken getAccessToken() { return this.accessToken; } /** * Returns the additional parameters that may be used in the request. * @return a {@code Map} of the additional parameters, may be empty. * @since 5.1 */ public Map<String, Object> getAdditionalParameters() { return this.additionalParameters; } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\userinfo\OAuth2UserRequest.java
1
请在Spring Boot框架中完成以下Java代码
public Region getRegion(String albertaApiKey, String _id) throws ApiException { ApiResponse<Region> resp = getRegionWithHttpInfo(albertaApiKey, _id); return resp.getData(); } /** * Daten einer einzelnen Region abrufen * Szenario - das WaWi fragt bei Alberta nach, wie die Daten der Region mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id der Region (required) * @return ApiResponse&lt;Region&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<Region> getRegionWithHttpInfo(String albertaApiKey, String _id) throws ApiException { com.squareup.okhttp.Call call = getRegionValidateBeforeCall(albertaApiKey, _id, null, null); Type localVarReturnType = new TypeToken<Region>(){}.getType(); return apiClient.execute(call, localVarReturnType); } /** * Daten einer einzelnen Region abrufen (asynchronously) * Szenario - das WaWi fragt bei Alberta nach, wie die Daten der Region mit der angegebenen Id sind * @param albertaApiKey (required) * @param _id eindeutige id der Region (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call getRegionAsync(String albertaApiKey, String _id, final ApiCallback<Region> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null; ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() {
@Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = getRegionValidateBeforeCall(albertaApiKey, _id, progressListener, progressRequestListener); Type localVarReturnType = new TypeToken<Region>(){}.getType(); apiClient.executeAsync(call, localVarReturnType, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\api\RegionApi.java
2
请完成以下Java代码
public void convertCorpus(String pkuPath, String tsvPath) throws IOException { final BufferedWriter bw = IOUtil.newBufferedWriter(tsvPath); IOUtility.loadInstance(pkuPath, new InstanceHandler() { @Override public boolean process(Sentence sentence) { Utility.normalize(sentence); try { convertCorpus(sentence, bw); bw.newLine(); } catch (IOException e) { throw new RuntimeException(e); } return false; } }); bw.close(); } /** * 导出特征模板 * * @param templatePath * @throws IOException */ public void dumpTemplate(String templatePath) throws IOException {
BufferedWriter bw = IOUtil.newBufferedWriter(templatePath); String template = getTemplate(); bw.write(template); bw.close(); } /** * 获取特征模板 * * @return */ public String getTemplate() { String template = getDefaultFeatureTemplate(); if (model != null && model.getFeatureTemplateArray() != null) { StringBuilder sbTemplate = new StringBuilder(); for (FeatureTemplate featureTemplate : model.getFeatureTemplateArray()) { sbTemplate.append(featureTemplate.getTemplate()).append('\n'); } } return template; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFTagger.java
1
请在Spring Boot框架中完成以下Java代码
public class ConfigureDataSource { @Bean(name = "dataSource") public HikariDataSource dataSource() { HikariDataSource hds = new HikariDataSource(); hds.setJdbcUrl("jdbc:postgresql://localhost:5432/postgres"); hds.setUsername("postgres"); hds.setPassword("postgres"); hds.setConnectionTimeout(50000); hds.setIdleTimeout(300000); hds.setMaxLifetime(900000); hds.setMaximumPoolSize(8); hds.setMinimumIdle(8); hds.setPoolName("MyPool"); hds.setConnectionTestQuery("select 1");
hds.setAutoCommit(false); return hds; } @FlywayDataSource @Bean(initMethod = "migrate") public Flyway flyway(@Qualifier("dataSource") HikariDataSource dataSource) { return Flyway.configure() .dataSource(dataSource) .locations("classpath:db/migration") // this path is default .load(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayPostgreSQLProg\src\main\java\com\bookstore\dsconfig\ConfigureDataSource.java
2
请完成以下Java代码
public class DependencyRangesInfoContributor implements InfoContributor { private final InitializrMetadataProvider metadataProvider; public DependencyRangesInfoContributor(InitializrMetadataProvider metadataProvider) { this.metadataProvider = metadataProvider; } @Override public void contribute(Info.Builder builder) { Map<String, Object> details = new LinkedHashMap<>(); this.metadataProvider.get().getDependencies().getAll().forEach((dependency) -> { if (dependency.getBom() == null) { contribute(details, dependency); } }); if (!details.isEmpty()) { builder.withDetail("dependency-ranges", details); } } private void contribute(Map<String, Object> details, Dependency dependency) { if (!ObjectUtils.isEmpty(dependency.getMappings())) { Map<String, VersionRange> dep = new LinkedHashMap<>(); dependency.getMappings().forEach((it) -> { if (it.getRange() != null && it.getVersion() != null) { dep.put(it.getVersion(), it.getRange()); } }); if (!dep.isEmpty()) { if (dependency.getRange() == null) { boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null); if (!openRange) { Version higher = getHigher(dep);
dep.put("managed", new VersionRange(higher)); } } Map<String, Object> depInfo = new LinkedHashMap<>(); dep.forEach((k, r) -> depInfo.put(k, "Spring Boot " + r)); details.put(dependency.getId(), depInfo); } } else if (dependency.getVersion() != null && dependency.getRange() != null) { Map<String, Object> dep = new LinkedHashMap<>(); String requirement = "Spring Boot " + dependency.getRange(); dep.put(dependency.getVersion(), requirement); details.put(dependency.getId(), dep); } } private Version getHigher(Map<String, VersionRange> dep) { Version higher = null; for (VersionRange versionRange : dep.values()) { Version candidate = versionRange.getHigherVersion(); if (higher == null) { higher = candidate; } else if (candidate.compareTo(higher) > 0) { higher = candidate; } } return higher; } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\info\DependencyRangesInfoContributor.java
1
请完成以下Java代码
public class BasicConnectionPool implements ConnectionPool { private final String url; private final String user; private final String password; private final List<Connection> connectionPool; private final List<Connection> usedConnections = new ArrayList<>(); private static final int INITIAL_POOL_SIZE = 10; private static final int MAX_POOL_SIZE = 20; private static final int MAX_TIMEOUT = 5; public static BasicConnectionPool create(String url, String user, String password) throws SQLException { List<Connection> pool = new ArrayList<>(INITIAL_POOL_SIZE); for (int i = 0; i < INITIAL_POOL_SIZE; i++) { pool.add(createConnection(url, user, password)); } return new BasicConnectionPool(url, user, password, pool); } private BasicConnectionPool(String url, String user, String password, List<Connection> connectionPool) { this.url = url; this.user = user; this.password = password; this.connectionPool = connectionPool; } @Override public Connection getConnection() throws SQLException { if (connectionPool.isEmpty()) { if (usedConnections.size() < MAX_POOL_SIZE) { connectionPool.add(createConnection(url, user, password)); } else { throw new RuntimeException("Maximum pool size reached, no available connections!"); } } Connection connection = connectionPool.remove(connectionPool.size() - 1); if(!connection.isValid(MAX_TIMEOUT)){ connection = createConnection(url, user, password); } usedConnections.add(connection); return connection; } @Override public boolean releaseConnection(Connection connection) { connectionPool.add(connection);
return usedConnections.remove(connection); } private static Connection createConnection(String url, String user, String password) throws SQLException { return DriverManager.getConnection(url, user, password); } @Override public int getSize() { return connectionPool.size() + usedConnections.size(); } @Override public List<Connection> getConnectionPool() { return connectionPool; } @Override public String getUrl() { return url; } @Override public String getUser() { return user; } @Override public String getPassword() { return password; } @Override public void shutdown() throws SQLException { usedConnections.forEach(this::releaseConnection); for (Connection c : connectionPool) { c.close(); } connectionPool.clear(); } }
repos\tutorials-master\persistence-modules\core-java-persistence\src\main\java\com\baeldung\connectionpool\BasicConnectionPool.java
1
请完成以下Java代码
public class ConditionEvaluationBuilderImpl implements ConditionEvaluationBuilder { protected CommandExecutor commandExecutor; protected String businessKey; protected String processDefinitionId; protected VariableMap variables = new VariableMapImpl(); protected String tenantId = null; protected boolean isTenantIdSet = false; public ConditionEvaluationBuilderImpl(CommandExecutor commandExecutor) { ensureNotNull("commandExecutor", commandExecutor); this.commandExecutor = commandExecutor; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public String getBusinessKey() { return businessKey; } public String getProcessDefinitionId() { return processDefinitionId; } public VariableMap getVariables() { return variables; } public String getTenantId() { return tenantId; } public boolean isTenantIdSet() { return isTenantIdSet; } protected <T> T execute(Command<T> command) { return commandExecutor.execute(command); } @Override public ConditionEvaluationBuilder processInstanceBusinessKey(String businessKey) { ensureNotNull("businessKey", businessKey); this.businessKey = businessKey; return this; } @Override public ConditionEvaluationBuilder processDefinitionId(String processDefinitionId) { ensureNotNull("processDefinitionId", processDefinitionId); this.processDefinitionId = processDefinitionId; return this; } @Override public ConditionEvaluationBuilder setVariable(String variableName, Object variableValue) { ensureNotNull("variableName", variableName);
this.variables.put(variableName, variableValue); return this; } @Override public ConditionEvaluationBuilder setVariables(Map<String, Object> variables) { ensureNotNull("variables", variables); if (variables != null) { this.variables.putAll(variables); } return this; } @Override public ConditionEvaluationBuilder tenantId(String tenantId) { ensureNotNull( "The tenant-id cannot be null. Use 'withoutTenantId()' if you want to evaluate conditional start event with a process definition which has no tenant-id.", "tenantId", tenantId); isTenantIdSet = true; this.tenantId = tenantId; return this; } @Override public ConditionEvaluationBuilder withoutTenantId() { isTenantIdSet = true; tenantId = null; return this; } @Override public List<ProcessInstance> evaluateStartConditions() { return execute(new EvaluateStartConditionCmd(this)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ConditionEvaluationBuilderImpl.java
1
请在Spring Boot框架中完成以下Java代码
private static String getConfig(String name) { // env String val = System.getenv(name); if (StringUtils.isNotEmpty(val)) { return val; } // properties val = System.getProperty(name); if (StringUtils.isNotEmpty(val)) { return val; } return ""; } protected static String getConfigStr(String name) { if (cacheMap.containsKey(name)) { return (String) cacheMap.get(name); } String val = getConfig(name); if (StringUtils.isBlank(val)) { return null; } cacheMap.put(name, val); return val; } protected static int getConfigInt(String name, int defaultVal, int minVal) { if (cacheMap.containsKey(name)) { return (int)cacheMap.get(name); } int val = NumberUtils.toInt(getConfig(name)); if (val == 0) { val = defaultVal; } else if (val < minVal) { val = minVal; } cacheMap.put(name, val); return val;
} public static String getAuthUsername() { return getConfigStr(CONFIG_AUTH_USERNAME); } public static String getAuthPassword() { return getConfigStr(CONFIG_AUTH_PASSWORD); } public static int getHideAppNoMachineMillis() { return getConfigInt(CONFIG_HIDE_APP_NO_MACHINE_MILLIS, 0, 60000); } public static int getRemoveAppNoMachineMillis() { return getConfigInt(CONFIG_REMOVE_APP_NO_MACHINE_MILLIS, 0, 120000); } public static int getAutoRemoveMachineMillis() { return getConfigInt(CONFIG_AUTO_REMOVE_MACHINE_MILLIS, 0, 300000); } public static int getUnhealthyMachineMillis() { return getConfigInt(CONFIG_UNHEALTHY_MACHINE_MILLIS, DEFAULT_MACHINE_HEALTHY_TIMEOUT_MS, 30000); } public static void clearCache() { cacheMap.clear(); } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\config\DashboardConfig.java
2
请在Spring Boot框架中完成以下Java代码
public ConnectionKeepAliveStrategy connectionKeepAliveStrategy() { return new ConnectionKeepAliveStrategy() { @Override public long getKeepAliveDuration(HttpResponse response, HttpContext httpContext) { HeaderElementIterator it = new BasicHeaderElementIterator (response.headerIterator(HTTP.CONN_KEEP_ALIVE)); while (it.hasNext()) { HeaderElement he = it.nextElement(); String param = he.getName(); String value = he.getValue(); if (value != null && param.equalsIgnoreCase("timeout")) { return Long.parseLong(value) * 1000; } } return p.getDefaultKeepAliveTimeMillis(); } }; } @Bean public CloseableHttpClient httpClient() { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(p.getRequestTimeout()) .setConnectTimeout(p.getConnectTimeout()) .setSocketTimeout(p.getSocketTimeout()).build(); return HttpClients.custom() .setDefaultRequestConfig(requestConfig) .setConnectionManager(poolingConnectionManager()) .setKeepAliveStrategy(connectionKeepAliveStrategy()) .setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)) // 重试次数 .build(); }
@Bean public Runnable idleConnectionMonitor(final PoolingHttpClientConnectionManager connectionManager) { return new Runnable() { @Override @Scheduled(fixedDelay = 10000) public void run() { try { if (connectionManager != null) { LOGGER.trace("run IdleConnectionMonitor - Closing expired and idle connections..."); connectionManager.closeExpiredConnections(); connectionManager.closeIdleConnections(p.getCloseIdleConnectionWaitTimeSecs(), TimeUnit.SECONDS); } else { LOGGER.trace("run IdleConnectionMonitor - Http Client Connection manager is not initialised"); } } catch (Exception e) { LOGGER.error("run IdleConnectionMonitor - Exception occurred. msg={}, e={}", e.getMessage(), e); } } }; } @Bean public TaskScheduler taskScheduler() { ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler(); scheduler.setThreadNamePrefix("poolScheduler"); scheduler.setPoolSize(50); return scheduler; } }
repos\SpringBootBucket-master\springboot-resttemplate\src\main\java\com\xncoding\pos\config\HttpClientConfig.java
2
请完成以下Java代码
public void addTablesToIgnoreList(@NonNull final String... tableNames) { addTablesToIgnoreList(ImmutableSet.copyOf(tableNames)); } public synchronized void addTablesToIgnoreList(@NonNull final Collection<String> tableNames) { if (tableNames.isEmpty()) { return; } this._tablesIgnoreSystemUC = addTableNamesUC(this._tablesIgnoreSystemUC, tableNames); this._tablesIgnoreClientUC = addTableNamesUC(this._tablesIgnoreClientUC, tableNames); logger.info("Skip migration scripts logging for: {}", tableNames); } public ImmutableSet<String> getTablesToIgnoreUC(final ClientId clientId) { return clientId.isSystem() ? _tablesIgnoreSystemUC : _tablesIgnoreClientUC; } private static ImmutableSet<String> addTableNamesUC( @NonNull final ImmutableSet<String> targetListUC, @NonNull final Collection<String> tableNamesToAdd) {
if (tableNamesToAdd.isEmpty()) { return targetListUC; } final ImmutableSet.Builder<String> builder = ImmutableSet.builder(); builder.addAll(targetListUC); tableNamesToAdd.stream().map(String::toUpperCase).forEach(builder::add); final ImmutableSet<String> result = builder.build(); if (targetListUC.size() == result.size()) { return targetListUC; // no change } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\TableNamesSkipList.java
1
请完成以下Java代码
public class SysFormFile { /**id*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "id") private String id; /**表名*/ @Excel(name = "表名", width = 15) @Schema(description = "表名") private String tableName; /**数据id*/ @Excel(name = "数据id", width = 15) @Schema(description = "数据id") private String tableDataId; /**关联文件id*/ @Excel(name = "关联文件id", width = 15)
@Schema(description = "关联文件id") private String fileId; /**文档类型(folder:文件夹 excel:excel doc:word pp:ppt image:图片 archive:其他文档 video:视频)*/ @Excel(name = "文档类型(folder:文件夹 excel:excel doc:word pp:ppt image:图片 archive:其他文档 video:视频)", width = 15) @Schema(description = "文档类型(folder:文件夹 excel:excel doc:word pp:ppt image:图片 archive:其他文档 video:视频)") private String fileType; /**创建人登录名称*/ @Excel(name = "创建人登录名称", width = 15) @Schema(description = "创建人登录名称") private String createBy; /**创建日期*/ @Excel(name = "创建日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") @Schema(description = "创建日期") private Date createTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysFormFile.java
1
请完成以下Java代码
public class CollectionsConcurrencyIssues { private void putIfAbsentList_NonAtomicOperation_ProneToConcurrencyIssues() { List<String> list = Collections.synchronizedList(new ArrayList<>()); if (!list.contains("foo")) { list.add("foo"); } } private void putIfAbsentList_AtomicOperation_ThreadSafe() { List<String> list = Collections.synchronizedList(new ArrayList<>()); synchronized (list) { if (!list.contains("foo")) { list.add("foo"); } } } private void putIfAbsentMap_NonAtomicOperation_ProneToConcurrencyIssues() { Map<String, String> map = new ConcurrentHashMap<>(); if (!map.containsKey("foo")) { map.put("foo", "bar"); } }
private void putIfAbsentMap_AtomicOperation_BetterApproach() { Map<String, String> map = new ConcurrentHashMap<>(); synchronized (map) { if (!map.containsKey("foo")) { map.put("foo", "bar"); } } } private void putIfAbsentMap_AtomicOperation_BestApproach() { Map<String, String> map = new ConcurrentHashMap<>(); map.putIfAbsent("foo", "bar"); } private void computeIfAbsentMap_AtomicOperation() { Map<String, String> map = new ConcurrentHashMap<>(); map.computeIfAbsent("foo", key -> key + "bar"); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\commonissues\CollectionsConcurrencyIssues.java
1
请完成以下Java代码
private static double chord(int stops, int i, double r) { return 2.0 * r * abs(sin(PI * i / stops)); } private static double dist(final int[] path) { return IntStream.range(0, STOPS) .mapToDouble(i -> ADJACENCE[path[i]][path[(i + 1) % STOPS]]) .sum(); } public static void main(String[] args) { final Engine<EnumGene<Integer>, Double> engine = Engine.builder(TravelingSalesman::dist, codecs.ofPermutation(STOPS)) .optimize(Optimize.MINIMUM) .maximalPhenotypeAge(11) .populationSize(500)
.alterers(new SwapMutator<>(0.2), new PartiallyMatchedCrossover<>(0.35)) .build(); final EvolutionStatistics<Double, ?> statistics = EvolutionStatistics.ofNumber(); final Phenotype<EnumGene<Integer>, Double> best = engine.stream() .limit(bySteadyFitness(15)) .limit(250) .peek(statistics) .collect(toBestPhenotype()); System.out.println(statistics); System.out.println(best); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\TravelingSalesman.java
1
请完成以下Java代码
public static List<List<Term>> seg2sentence(String text) { List<List<Term>> sentenceList = SEGMENT.seg2sentence(text); for (List<Term> sentence : sentenceList) { ListIterator<Term> listIterator = sentence.listIterator(); while (listIterator.hasNext()) { if (!CoreStopWordDictionary.shouldInclude(listIterator.next())) { listIterator.remove(); } } } return sentenceList; } /** * 分词断句 输出句子形式 * * @param text 待分词句子 * @param shortest 是否断句为最细的子句(将逗号也视作分隔符) * @return 句子列表,每个句子由一个单词列表组成 */ public static List<List<Term>> seg2sentence(String text, boolean shortest) { return SEGMENT.seg2sentence(text, shortest); } /**
* 切分为句子形式 * * @param text * @param filterArrayChain 自定义过滤器链 * @return */ public static List<List<Term>> seg2sentence(String text, Filter... filterArrayChain) { List<List<Term>> sentenceList = SEGMENT.seg2sentence(text); for (List<Term> sentence : sentenceList) { ListIterator<Term> listIterator = sentence.listIterator(); while (listIterator.hasNext()) { if (filterArrayChain != null) { Term term = listIterator.next(); for (Filter filter : filterArrayChain) { if (!filter.shouldInclude(term)) { listIterator.remove(); break; } } } } } return sentenceList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\NotionalTokenizer.java
1
请完成以下Java代码
public class ProductRow { @DataField(pos = 1) private String bpartnerIdentifier; @DataField(pos = 2) private String productIdentifier; @DataField(pos = 3) private String value; @DataField(pos = 4) private String name; @DataField(pos = 5) private String description; @DataField(pos = 6) private String ean; @DataField(pos = 7) private String taxRate; @DataField(pos = 9)
private String qty; @DataField(pos = 10) private String uomCode; @Nullable public BigDecimal getTaxRate() { return CamelProcessorUtil.parseGermanNumberString(taxRate); } @Nullable public BigDecimal getQty() { return CamelProcessorUtil.parseGermanNumberString(qty); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-pcm-file-import\src\main\java\de\metas\camel\externalsystems\pcm\product\model\ProductRow.java
1
请完成以下Java代码
public static final boolean ge(TypeConverter converter, Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return !lt0(converter, o1, o2); } public static final boolean le(TypeConverter converter, Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } return !gt0(converter, o1, o2); } public static final boolean eq(TypeConverter converter, Object o1, Object o2) { if (o1 == o2) { return true; } if (o1 == null || o2 == null) { return false; } Class<?> t1 = o1.getClass(); Class<?> t2 = o2.getClass(); if (BigDecimal.class.isAssignableFrom(t1) || BigDecimal.class.isAssignableFrom(t2)) { return (converter.convert(o1, BigDecimal.class).compareTo(converter.convert(o2, BigDecimal.class)) == 0); } if (SIMPLE_FLOAT_TYPES.contains(t1) || SIMPLE_FLOAT_TYPES.contains(t2)) { return converter.convert(o1, Double.class).equals(converter.convert(o2, Double.class)); } if (BigInteger.class.isAssignableFrom(t1) || BigInteger.class.isAssignableFrom(t2)) { return (converter.convert(o1, BigInteger.class).compareTo(converter.convert(o2, BigInteger.class)) == 0); } if (SIMPLE_INTEGER_TYPES.contains(t1) || SIMPLE_INTEGER_TYPES.contains(t2)) { return converter.convert(o1, Long.class).equals(converter.convert(o2, Long.class)); } if (t1 == Boolean.class || t2 == Boolean.class) { return converter.convert(o1, Boolean.class).equals(converter.convert(o2, Boolean.class)); } if (o1 instanceof Enum<?>) { return o1 == converter.convert(o2, o1.getClass()); }
if (o2 instanceof Enum<?>) { return converter.convert(o1, o2.getClass()) == o2; } if (t1 == String.class || t2 == String.class) { return converter.convert(o1, String.class).equals(converter.convert(o2, String.class)); } return o1.equals(o2); } public static final boolean ne(TypeConverter converter, Object o1, Object o2) { return !eq(converter, o1, o2); } public static final boolean empty(TypeConverter converter, Object o) { if (o == null || "".equals(o)) { return true; } if (o instanceof Object[]) { return ((Object[]) o).length == 0; } if (o instanceof Map<?, ?>) { return ((Map<?, ?>) o).isEmpty(); } if (o instanceof Collection<?>) { return ((Collection<?>) o).isEmpty(); } return false; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\misc\BooleanOperations.java
1
请完成以下Java代码
private class SessionValues extends AbstractCollection<Object> { @Override public Iterator<Object> iterator() { return new Iterator<Object>() { private Iterator<Entry<String, Object>> i = entrySet().iterator(); @Override public boolean hasNext() { return this.i.hasNext(); } @Override public Object next() { return this.i.next().getValue(); } @Override public void remove() { this.i.remove(); } }; }
@Override public int size() { return SpringSessionMap.this.size(); } @Override public boolean isEmpty() { return SpringSessionMap.this.isEmpty(); } @Override public void clear() { SpringSessionMap.this.clear(); } @Override public boolean contains(Object v) { return SpringSessionMap.this.containsValue(v); } } } }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\server\session\SpringSessionWebSessionStore.java
1
请完成以下Java代码
protected void doRelease(UUID scriptId) throws Exception { doRelease(scriptId, scriptInfoMap.remove(scriptId)); } @Override public String validate(TenantId tenantId, String scriptBody) { String errorMessage = super.validate(tenantId, scriptBody); if (errorMessage == null) { return JsValidator.validate(scriptBody); } return errorMessage; } protected abstract ListenableFuture<UUID> doEval(UUID scriptId, JsScriptInfo jsInfo, String scriptBody); protected abstract ListenableFuture<Object> doInvokeFunction(UUID scriptId, JsScriptInfo jsInfo, Object[] args); protected abstract void doRelease(UUID scriptId, JsScriptInfo scriptInfo) throws Exception; private String generateJsScript(ScriptType scriptType, String functionName, String scriptBody, String... argNames) { if (scriptType == ScriptType.RULE_NODE_SCRIPT) { return RuleNodeScriptFactory.generateRuleNodeScript(functionName, scriptBody, argNames); } throw new RuntimeException("No script factory implemented for scriptType: " + scriptType); }
protected String constructFunctionName(UUID scriptId, String scriptHash) { return "invokeInternal_" + scriptId.toString().replace('-', '_'); } protected String hash(TenantId tenantId, String scriptBody) { return Hashing.murmur3_128().newHasher() .putLong(tenantId.getId().getMostSignificantBits()) .putLong(tenantId.getId().getLeastSignificantBits()) .putUnencodedChars(scriptBody) .hash().toString(); } @Override protected StatsType getStatsType() { return StatsType.JS_INVOKE; } }
repos\thingsboard-master\common\script\script-api\src\main\java\org\thingsboard\script\api\js\AbstractJsInvokeService.java
1
请完成以下Java代码
public class InvoicedSumProvider implements IInvoicedSumProvider { /** * @return the sum of <code>C_Invoice.TotalLines</code> of all invoices that * <ul> * <li>are either completed or closed and * <li>that reference the given <code>materialtracking</code> and * <li>have a "quality inspection" docType * </ul> */ @Override public BigDecimal getAlreadyInvoicedNetSum(final I_M_Material_Tracking materialTracking) { final IMaterialTrackingDAO materialTrackingDAO = Services.get(IMaterialTrackingDAO.class); final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final List<I_C_Invoice> invoices = materialTrackingDAO.retrieveReferences(materialTracking, I_C_Invoice.class); BigDecimal result = BigDecimal.ZERO; for (final I_C_Invoice invoice : invoices) { final DocStatus invoiceDocStatus = DocStatus.ofCode(invoice.getDocStatus()); if(!invoiceDocStatus.isCompletedOrClosed()) { continue; }
// note: completed/closed implies that a C_DocType is set. final I_C_DocType docType = docTypeDAO.getById(invoice.getC_DocType_ID()); final String docSubType = docType.getDocSubType(); if (!IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_DownPayment.equals(docSubType) && !IMaterialTrackingBL.C_DocType_INVOICE_DOCSUBTYPE_QI_FinalSettlement.equals(docSubType)) { continue; } result = result.add(invoice.getTotalLines()); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\InvoicedSumProvider.java
1
请完成以下Java代码
public MaterialEvent toMaterialEvent(@NonNull final Event metasfreshEvent) { final Object materialEventObj = metasfreshEvent.getProperty(PROPERTY_MATERIAL_EVENT); if (materialEventObj instanceof MaterialEvent) { return (MaterialEvent)materialEventObj; } if (materialEventObj instanceof String) { // in case the Event has not been deserialized, then the material event is still a string return jsonObjectMapper.readValue(materialEventObj.toString()); }
throw new IllegalArgumentException("Cannot convert " + materialEventObj + " to MaterialEvent"); } /** * Note: the returned metasfresh event shall be logged. */ public Event fromMaterialEvent(@NonNull final MaterialEvent materialEvent) { return Event.builder() .putProperty(PROPERTY_MATERIAL_EVENT, materialEvent) .setEventName(materialEvent.getEventName()) .setSourceRecordReference(materialEvent.getSourceTableReference()) .shallBeLogged() .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\eventbus\MaterialEventConverter.java
1
请完成以下Java代码
public void setIsTaxIncluded (final boolean IsTaxIncluded) { set_Value (COLUMNNAME_IsTaxIncluded, IsTaxIncluded); } @Override public boolean isTaxIncluded() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIncluded); } @Override public void setIsWholeTax (final boolean IsWholeTax) { set_Value (COLUMNNAME_IsWholeTax, IsWholeTax); } @Override public boolean isWholeTax() { return get_ValueAsBoolean(COLUMNNAME_IsWholeTax); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt);
} @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); 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_InvoiceTax.java
1
请完成以下Java代码
public final class AuthorizeReturnObjectCoreHintsRegistrar implements SecurityHintsRegistrar { private final AuthorizationProxyFactory proxyFactory; private final SecurityAnnotationScanner<AuthorizeReturnObject> scanner = SecurityAnnotationScanners .requireUnique(AuthorizeReturnObject.class); private final Set<Class<?>> visitedClasses = new HashSet<>(); public AuthorizeReturnObjectCoreHintsRegistrar(AuthorizationProxyFactory proxyFactory) { Assert.notNull(proxyFactory, "proxyFactory cannot be null"); this.proxyFactory = proxyFactory; } /** * {@inheritDoc} */ @Override public void registerHints(RuntimeHints hints, ConfigurableListableBeanFactory beanFactory) { List<Class<?>> toProxy = new ArrayList<>(); for (String name : beanFactory.getBeanDefinitionNames()) {
Class<?> clazz = beanFactory.getType(name, false); if (clazz == null) { continue; } for (Method method : clazz.getDeclaredMethods()) { AuthorizeReturnObject annotation = this.scanner.scan(method, clazz); if (annotation == null) { continue; } toProxy.add(method.getReturnType()); } } new AuthorizeReturnObjectHintsRegistrar(this.proxyFactory, toProxy).registerHints(hints, beanFactory); } }
repos\spring-security-main\core\src\main\java\org\springframework\security\aot\hint\AuthorizeReturnObjectCoreHintsRegistrar.java
1
请完成以下Java代码
public void setName(String name) { this.name = name; } public void setFields(Set<String> fields) { this.fields = fields; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public boolean isAll() { return all; } public void setAll(boolean all) { this.all = all; } /** * 判断是否有相同字段 * * @param fieldString * @return */ public boolean existSameField(String fieldString) { String[] controlFields = fieldString.split(","); for (String sqlField : fields) { for (String controlField : controlFields) { if (sqlField.equals(controlField)) { // 非常明确的列直接比较 log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true; } else { // 使用表达式的列 只能判读字符串包含了 String aliasColumn = controlField; if (StringUtils.isNotBlank(alias)) { aliasColumn = alias + "." + controlField; } if (sqlField.indexOf(aliasColumn) != -1) { log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询"); return true; } } } } return false; } @Override public String toString() { return "QueryTable{" + "name='" + name + '\'' + ", alias='" + alias + '\'' + ", fields=" + fields + ", all=" + all + '}'; } } public String getError(){ // TODO return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\AbstractQueryBlackListHandler.java
1
请完成以下Java代码
Class<? extends Exception>[] getRetryableExceptions() { return this.retryableExceptions; } } /** * Configure customizers for components instantiated by the retry topics feature. */ public static class CustomizersConfigurer { @Nullable private Consumer<DefaultErrorHandler> errorHandlerCustomizer; @Nullable private Consumer<ConcurrentMessageListenerContainer<?, ?>> listenerContainerCustomizer; @Nullable private Consumer<DeadLetterPublishingRecoverer> deadLetterPublishingRecovererCustomizer; /** * Customize the {@link CommonErrorHandler} instances that will be used for the * feature. * @param errorHandlerCustomizer the customizer. * @return the configurer. * @see DefaultErrorHandler */ @SuppressWarnings("unused") public CustomizersConfigurer customizeErrorHandler(Consumer<DefaultErrorHandler> errorHandlerCustomizer) { this.errorHandlerCustomizer = errorHandlerCustomizer; return this; } /** * Customize the {@link ConcurrentMessageListenerContainer} instances created * for the retry and DLT consumers. * @param listenerContainerCustomizer the customizer. * @return the configurer. */ public CustomizersConfigurer customizeListenerContainer(Consumer<ConcurrentMessageListenerContainer<?, ?>> listenerContainerCustomizer) { this.listenerContainerCustomizer = listenerContainerCustomizer;
return this; } /** * Customize the {@link DeadLetterPublishingRecoverer} that will be used to * forward the records to the retry topics and DLT. * @param dlprCustomizer the customizer. * @return the configurer. */ public CustomizersConfigurer customizeDeadLetterPublishingRecoverer(Consumer<DeadLetterPublishingRecoverer> dlprCustomizer) { this.deadLetterPublishingRecovererCustomizer = dlprCustomizer; return this; } @Nullable Consumer<DefaultErrorHandler> getErrorHandlerCustomizer() { return this.errorHandlerCustomizer; } @Nullable Consumer<ConcurrentMessageListenerContainer<?, ?>> getListenerContainerCustomizer() { return this.listenerContainerCustomizer; } @Nullable Consumer<DeadLetterPublishingRecoverer> getDeadLetterPublishingRecovererCustomizer() { return this.deadLetterPublishingRecovererCustomizer; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfigurationSupport.java
1
请完成以下Java代码
public QueueElement deQueue() { if (pHead == null) return null; QueueElement pRet = pHead; pHead = pHead.next; return pRet; } /** * 读取第一个元素,但不执行DeQueue操作 * @return */ public QueueElement GetFirst() { pLastAccess = pHead; return pLastAccess; } /** * 读取上次读取后的下一个元素,不执行DeQueue操作 * @return */ public QueueElement GetNext() { if (pLastAccess != null) pLastAccess = pLastAccess.next; return pLastAccess; } /** * 是否仍然有下一个元素可供读取
* @return */ public boolean CanGetNext() { return (pLastAccess.next != null); } /** * 清除所有元素 */ public void clear() { pHead = null; pLastAccess = null; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\NShort\Path\CQueue.java
1
请完成以下Java代码
public String getLastPropertyKeyWithValue() throws IOException { List<String> fileLines = getFileLines(); return fileLines.get(fileLines.size() - 1); } public void addPropertyKeyWithValue(String keyAndValue) throws IOException { File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName)); List<String> fileContent = getFileLines(propertiesFile); fileContent.add(keyAndValue); Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8); } public int updateProperty(String oldKeyValuePair, String newKeyValuePair) throws IOException { File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName)); List<String> fileContent = getFileLines(propertiesFile); int updatedIndex = -1; for (int i = 0; i < fileContent.size(); i++) { if (fileContent.get(i) .replaceAll("\\s+", "") .equals(oldKeyValuePair)) { fileContent.set(i, newKeyValuePair); updatedIndex = i; break; } } Files.write(propertiesFile.toPath(), fileContent, StandardCharsets.UTF_8);
// depending on the system, sometimes the first line will be a comment with a timestamp of the file read // the next line will make this method compatible with all systems if (fileContent.get(0).startsWith("#")) { updatedIndex--; } return updatedIndex; } private List<String> getFileLines() throws IOException { File propertiesFile = new File(propertyLoader.getFilePathFromResources(propertyFileName)); return getFileLines(propertiesFile); } private List<String> getFileLines(File propertiesFile) throws IOException { return new ArrayList<>(Files.readAllLines(propertiesFile.toPath(), StandardCharsets.UTF_8)); } }
repos\tutorials-master\core-java-modules\core-java-properties\src\main\java\com\baeldung\core\java\properties\FileAPIPropertyMutator.java
1
请完成以下Java代码
public boolean isEmpty() { try { return reportData.contentLength() <= 0; } catch (final IOException e) { return true; // reportdata couldn't be resolved, so we say it's empty } } public File writeToTemporaryFile(@NonNull final String filenamePrefix) { final File file = createTemporaryFile(filenamePrefix); try { FileUtils.copyInputStreamToFile(reportData.getInputStream(), file); return file; } catch (final IOException ex) { throw new AdempiereException("Failed writing " + file.getAbsolutePath(), ex);
} } @NonNull private File createTemporaryFile(@NonNull final String filenamePrefix) { try { final String ext = MimeType.getExtensionByType(reportContentType); final String suffix = Check.isNotBlank(ext) ? "." + ext : ""; return File.createTempFile(filenamePrefix, suffix); } catch (final IOException ex) { throw new AdempiereException("Failed creating temporary file with `" + filenamePrefix + "` prefix", ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\ReportResultData.java
1
请完成以下Java代码
public Dimension minimumLayoutSize(Container parent) { return preferredLayoutSize(parent); } // minimumLayoutSize /************************************************************************** * Lays out the specified container. * @param parent the container to be laid out * @see java.awt.LayoutManager#layoutContainer(Container) */ public void layoutContainer (Container parent) { Insets insets = parent.getInsets(); // int width = insets.left; int height = insets.top; // We need to layout if (needLayout(parent)) { int x = 5; int y = 5; // Go through all components for (int i = 0; i < parent.getComponentCount(); i++) { Component comp = parent.getComponent(i); if (comp.isVisible() && comp instanceof WFNodeComponent) { Dimension ps = comp.getPreferredSize(); comp.setLocation(x, y); comp.setBounds(x, y, ps.width, ps.height); // width = x + ps.width; height = y + ps.height; // next pos if (x == 5) x = 230; else { x = 5; y += 100; } // x += ps.width-20; // y += ps.height+20; } } } else // we have an Layout { // Go through all components for (int i = 0; i < parent.getComponentCount(); i++) { Component comp = parent.getComponent(i); if (comp.isVisible() && comp instanceof WFNodeComponent) { Dimension ps = comp.getPreferredSize(); Point loc = comp.getLocation(); int maxWidth = comp.getX() + ps.width; int maxHeight = comp.getY() + ps.height; if (width < maxWidth) width = maxWidth; if (height < maxHeight) height = maxHeight; comp.setBounds(loc.x, loc.y, ps.width, ps.height); } } // for all components } // have layout // Create Lines WFContentPanel panel = (WFContentPanel)parent; panel.createLines(); // Calculate size width += insets.right;
height += insets.bottom; // return size m_size = new Dimension(width, height); log.trace("Size=" + m_size); } // layoutContainer /** * Need Layout * @param parent parent * @return true if we need to layout */ private boolean needLayout (Container parent) { Point p00 = new Point(0,0); // Go through all components for (int i = 0; i < parent.getComponentCount(); i++) { Component comp = parent.getComponent(i); if (comp instanceof WFNodeComponent && comp.getLocation().equals(p00)) { log.debug("{}", comp); return true; } } return false; } // needLayout /** * Invalidates the layout, indicating that if the layout manager * has cached information it should be discarded. */ private void invalidateLayout() { m_size = null; } // invalidateLayout } // WFLayoutManager
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFLayoutManager.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_AD_Attribute_Value[") .append(get_ID()).append("]"); return sb.toString(); } /** Set System Attribute. @param AD_Attribute_ID System Attribute */ public void setAD_Attribute_ID (int AD_Attribute_ID) { if (AD_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Attribute_ID, Integer.valueOf(AD_Attribute_ID)); } /** Get System Attribute. @return System Attribute */ public int getAD_Attribute_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Attribute_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Record ID. @param Record_ID Direct internal record ID */ public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Record ID. @return Direct internal record ID */ public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** Set V_Date. @param V_Date V_Date */ public void setV_Date (Timestamp V_Date) { set_Value (COLUMNNAME_V_Date, V_Date); }
/** Get V_Date. @return V_Date */ public Timestamp getV_Date () { return (Timestamp)get_Value(COLUMNNAME_V_Date); } /** Set V_Number. @param V_Number V_Number */ public void setV_Number (String V_Number) { set_Value (COLUMNNAME_V_Number, V_Number); } /** Get V_Number. @return V_Number */ public String getV_Number () { return (String)get_Value(COLUMNNAME_V_Number); } /** Set V_String. @param V_String V_String */ public void setV_String (String V_String) { set_Value (COLUMNNAME_V_String, V_String); } /** Get V_String. @return V_String */ public String getV_String () { return (String)get_Value(COLUMNNAME_V_String); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute_Value.java
1
请完成以下Java代码
public class Sendungsnummern { @XmlElement(name = "Seitengroesse", required = true) protected String seitengroesse; @XmlElement(name = "SendungsnummerAX4", type = Integer.class) protected List<Integer> sendungsnummerAX4; /** * Gets the value of the seitengroesse property. * * @return * possible object is * {@link String } * */ public String getSeitengroesse() { return seitengroesse; } /** * Sets the value of the seitengroesse property. * * @param value * allowed object is * {@link String } * */ public void setSeitengroesse(String value) { this.seitengroesse = value; } /** * Gets the value of the sendungsnummerAX4 property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the sendungsnummerAX4 property. *
* <p> * For example, to add a new item, do as follows: * <pre> * getSendungsnummerAX4().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Integer } * * */ public List<Integer> getSendungsnummerAX4() { if (sendungsnummerAX4 == null) { sendungsnummerAX4 = new ArrayList<Integer>(); } return this.sendungsnummerAX4; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\Sendungsnummern.java
1
请在Spring Boot框架中完成以下Java代码
public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } @ApiModelProperty(example = "newOrderMessage") public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "tenant1") public String getTenantId() { return tenantId; } @ApiModelProperty(example = "overrideTenant1") public String getOverrideDefinitionTenantId() { return overrideDefinitionTenantId; } public void setOverrideDefinitionTenantId(String overrideDefinitionTenantId) { this.overrideDefinitionTenantId = overrideDefinitionTenantId; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getTransientVariables() { return transientVariables; }
public void setTransientVariables(List<RestVariable> transientVariables) { this.transientVariables = transientVariables; } @JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class) public List<RestVariable> getStartFormVariables() { return startFormVariables; } public void setStartFormVariables(List<RestVariable> startFormVariables) { this.startFormVariables = startFormVariables; } public String getOutcome() { return outcome; } public void setOutcome(String outcome) { this.outcome = outcome; } @JsonIgnore public boolean isTenantSet() { return tenantId != null && !StringUtils.isEmpty(tenantId); } // Added by Ryan Johnston public boolean getReturnVariables() { return returnVariables; } // Added by Ryan Johnston public void setReturnVariables(boolean returnVariables) { this.returnVariables = returnVariables; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ProcessInstanceCreateRequest.java
2
请完成以下Java代码
public void onInvoiceCandidateChanged(final I_C_Invoice_Candidate invoiceCandidate) { // Skip if not a group line if (!InvoiceCandidateCompensationGroupUtils.isInGroup(invoiceCandidate)) { return; } // Don't touch processed lines if (invoiceCandidate.isProcessed()) { return; } final boolean groupCompensationLine = invoiceCandidate.isGroupCompensationLine(); final String amtType = invoiceCandidate.getGroupCompensationAmtType(); if (!groupCompensationLine) { onRegularGroupLineChanged(invoiceCandidate); } else if (X_C_OrderLine.GROUPCOMPENSATIONAMTTYPE_Percent.equals(amtType))
{ onPercentageCompensationLineChanged(invoiceCandidate); } } private void onRegularGroupLineChanged(final I_C_Invoice_Candidate regularLine) { final GroupId groupId = groupsRepo.extractGroupId(regularLine); groupsRepo.invalidateCompensationInvoiceCandidatesOfGroup(groupId); } private void onPercentageCompensationLineChanged(final I_C_Invoice_Candidate compensationLine) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateGroupCompensationChangesHandler.java
1
请完成以下Java代码
public int getC_UOM_To_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_UOM_To_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Divisor. @param DivideRate Der Divisor ist der Kehrwert des Umrechnungsfaktors. */ @Override public void setDivideRate (java.math.BigDecimal DivideRate) { set_Value (COLUMNNAME_DivideRate, DivideRate); } /** Get Divisor. @return Der Divisor ist der Kehrwert des Umrechnungsfaktors. */ @Override public java.math.BigDecimal getDivideRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DivideRate); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Ziel ist Catch-Maßeinheit. @param IsCatchUOMForProduct Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public void setIsCatchUOMForProduct (boolean IsCatchUOMForProduct) { set_Value (COLUMNNAME_IsCatchUOMForProduct, Boolean.valueOf(IsCatchUOMForProduct)); } /** Get Ziel ist Catch-Maßeinheit. @return Legt fest ob die Ziel-Maßeinheit die Parallel-Maßeinheit des Produktes ist, auf die bei einer Catch-Weight-Abrechnung zurückgegriffen wird */ @Override public boolean isCatchUOMForProduct () { Object oo = get_Value(COLUMNNAME_IsCatchUOMForProduct); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Faktor. @param MultiplyRate Rate to multiple the source by to calculate the target. */ @Override public void setMultiplyRate (java.math.BigDecimal MultiplyRate) { set_Value (COLUMNNAME_MultiplyRate, MultiplyRate); } /** Get Faktor. @return Rate to multiple the source by to calculate the target. */ @Override public java.math.BigDecimal getMultiplyRate () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MultiplyRate); 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_UOM_Conversion.java
1
请在Spring Boot框架中完成以下Java代码
public List listByParent(Long parentId) { return super.getSessionTemplate().selectList(getStatement("listByParent"), parentId); } /** * 根据菜单ID查找菜单(可用于判断菜单下是否还有子菜单). * * @param parentId * . * @return menuList. */ @Override public List<PmsMenu> listByParentId(Long parentId) { return super.getSessionTemplate().selectList(getStatement("listByParentId"), parentId); }
/*** * 根据名称和是否叶子节点查询数据 * * @param isLeaf * 是否是叶子节点 * @param name * 节点名称 * @return */ public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) { return super.getSessionTemplate().selectList(getStatement("listBy"), map); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsMenuDaoImpl.java
2
请在Spring Boot框架中完成以下Java代码
public void setPricePromisedUserEntered(@NonNull final BigDecimal pricePromisedUserEntered) { this.pricePromisedUserEntered = pricePromisedUserEntered; } public BigDecimal getQtyPromisedUserEntered() { return quantities.stream() .map(RfqQty::getQtyPromisedUserEntered) .reduce(BigDecimal.ZERO, BigDecimal::add); } public void setQtyPromised(@NonNull final LocalDate date, @NonNull final BigDecimal qtyPromised) { final RfqQty rfqQty = getOrCreateQty(date); rfqQty.setQtyPromisedUserEntered(qtyPromised); updateConfirmedByUser(); } private RfqQty getOrCreateQty(@NonNull final LocalDate date) { final RfqQty existingRfqQty = getRfqQtyByDate(date); if (existingRfqQty != null) { return existingRfqQty; } else { final RfqQty rfqQty = RfqQty.builder() .rfq(this) .datePromised(date) .build(); addRfqQty(rfqQty); return rfqQty; } } private void addRfqQty(final RfqQty rfqQty) { rfqQty.setRfq(this); quantities.add(rfqQty); } @Nullable public RfqQty getRfqQtyByDate(@NonNull final LocalDate date) { for (final RfqQty rfqQty : quantities) { if (date.equals(rfqQty.getDatePromised())) {
return rfqQty; } } return null; } private void updateConfirmedByUser() { this.confirmedByUser = computeConfirmedByUser(); } private boolean computeConfirmedByUser() { if (pricePromised.compareTo(pricePromisedUserEntered) != 0) { return false; } for (final RfqQty rfqQty : quantities) { if (!rfqQty.isConfirmedByUser()) { return false; } } return true; } public void closeIt() { this.closed = true; } public void confirmByUser() { this.pricePromised = getPricePromisedUserEntered(); quantities.forEach(RfqQty::confirmByUser); updateConfirmedByUser(); } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\Rfq.java
2
请在Spring Boot框架中完成以下Java代码
public class ExcludeWeekendBusinessDayMatcher implements IBusinessDayMatcher { private static final ImmutableSet<DayOfWeek> DEFAULT_WEEKEND_DAYS = ImmutableSet.of(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY); /** Matcher with Saturday and Sunday as non working days */ public static final ExcludeWeekendBusinessDayMatcher DEFAULT = ExcludeWeekendBusinessDayMatcher.builder().build(); private final ImmutableSet<DayOfWeek> weekendDays; @Builder private ExcludeWeekendBusinessDayMatcher(final Set<DayOfWeek> excludeWeekendDays) { weekendDays = buildWeekendDays(excludeWeekendDays); } private static ImmutableSet<DayOfWeek> buildWeekendDays(final Set<DayOfWeek> excludeWeekendDays)
{ if (excludeWeekendDays == null || excludeWeekendDays.isEmpty()) { return DEFAULT_WEEKEND_DAYS; } final Set<DayOfWeek> weekendDays = new HashSet<>(DEFAULT_WEEKEND_DAYS); weekendDays.removeAll(excludeWeekendDays); return ImmutableSet.copyOf(weekendDays); } @Override public boolean isBusinessDay(@NonNull final LocalDate date) { return !weekendDays.contains(date.getDayOfWeek()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\calendar\ExcludeWeekendBusinessDayMatcher.java
2
请完成以下Java代码
public void setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; } public RequestOptions getRequest() { return request; } public void setRequest(RequestOptions request) { this.request = request; } @Override public String toString() { return "LocalResponseCacheProperties{" + "size=" + size + ", timeToLive=" + timeToLive + ", request=" + request + '}'; } public static class RequestOptions { private NoCacheStrategy noCacheStrategy = NoCacheStrategy.SKIP_UPDATE_CACHE_ENTRY; public NoCacheStrategy getNoCacheStrategy() { return noCacheStrategy; } public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) { this.noCacheStrategy = noCacheStrategy; } @Override
public String toString() { return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}'; } } /** * When client sends "no-cache" directive in "Cache-Control" header, the response * should be re-validated from upstream. There are several strategies that indicates * what to do with the new fresh response. */ public enum NoCacheStrategy { /** * Update the cache entry by the fresh response coming from upstream with a new * time to live. */ UPDATE_CACHE_ENTRY, /** * Skip the update. The client will receive the fresh response, other clients will * receive the old entry in cache. */ SKIP_UPDATE_CACHE_ENTRY } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java
1
请完成以下Java代码
public void setState(String state) { this.state = state; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; }
public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } @Override protected Object clone() throws CloneNotSupportedException { super.clone(); Address address = new Address(); address.setCity(this.city); address.setCountry(this.country); address.setState(this.state); address.setStreet(this.street); address.setZipcode(this.zipcode); return address; } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced\src\main\java\com\baeldung\arraycopy\model\Address.java
1
请完成以下Java代码
default @Nullable Entry resolve(ZipEntry entry) { return resolve(entry.getName()); } /** * Resolve the entry with the specified name, return {@code null} if the entry should * not be handled. * @param name the name of the entry to handle * @return the resolved {@link Entry} */ @Nullable Entry resolve(String name); /** * Create the {@link Manifest} for the launcher jar, applying the specified operator * on each classpath entry. * @param libraryTransformer the operator to apply on each classpath entry * @return the manifest to use for the launcher jar */ Manifest createLauncherManifest(UnaryOperator<String> libraryTransformer); /** * Return the location of the application classes. * @return the location of the application classes */ String getClassesLocation();
/** * An entry to handle in the exploded structure. * * @param originalLocation the original location * @param location the relative location * @param type of the entry */ record Entry(String originalLocation, String location, Type type) { enum Type { LIBRARY, APPLICATION_CLASS_OR_RESOURCE, LOADER, META_INF } } }
repos\spring-boot-4.0.1\loader\spring-boot-jarmode-tools\src\main\java\org\springframework\boot\jarmode\tools\JarStructure.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getAddresses() {
return addresses; } public void setAddresses(List<String> addresses) { this.addresses = addresses; } public List<String> getBooks() { return books; } public void setBooks(List<String> books) { this.books = books; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\listrepositories\entity\Library.java
1
请完成以下Java代码
public User register(Username username, Password password) { Assert.notNull(username, "Username must not be null!"); Assert.notNull(password, "Password must not be null!"); repository.findByUsername(username).ifPresent(user -> { throw new IllegalArgumentException("User with that name already exists!"); }); var encryptedPassword = Password.encrypted(encoder.encode(password)); return repository.save(new User(username, encryptedPassword)); } /** * Returns a {@link Page} of {@link User} for the given {@link Pageable}. * * @param pageable must not be {@literal null}. * @return */ public Page<User> findAll(Pageable pageable) { Assert.notNull(pageable, "Pageable must not be null!"); return repository.findAll(pageable); } /** * Returns the {@link User} with the given {@link Username}. * * @param username must not be {@literal null}. * @return */
public Optional<User> findByUsername(Username username) { Assert.notNull(username, "Username must not be null!"); return repository.findByUsername(username); } /** * Creates a few sample users. */ @PostConstruct public void init() { IntStream.range(0, 41).forEach(index -> { register(new Username("user" + index), Password.raw("foobar")); }); } }
repos\spring-data-examples-main\web\example\src\main\java\example\users\UserManagement.java
1
请完成以下Java代码
public void setNameLike(String groupNameLike) { this.nameLike = groupNameLike; } @CamundaQueryParam("type") public void setType(String groupType) { this.type = groupType; } @CamundaQueryParam("member") public void setMember(String member) { this.member = member; } @CamundaQueryParam("memberOfTenant") public void setMemberOfTenant(String tenantId) { this.tenantId = tenantId; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected GroupQuery createNewQuery(ProcessEngine engine) { return engine.getIdentityService().createGroupQuery(); } @Override protected void applyFilters(GroupQuery query) { if (id != null) { query.groupId(id); } if (ids != null) {
query.groupIdIn(ids); } if (name != null) { query.groupName(name); } if (nameLike != null) { query.groupNameLike(nameLike); } if (type != null) { query.groupType(type); } if (member != null) { query.groupMember(member); } if (tenantId != null) { query.memberOfTenant(tenantId); } } @Override protected void applySortBy(GroupQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_GROUP_ID_VALUE)) { query.orderByGroupId(); } else if (sortBy.equals(SORT_BY_GROUP_NAME_VALUE)) { query.orderByGroupName(); } else if (sortBy.equals(SORT_BY_GROUP_TYPE_VALUE)) { query.orderByGroupType(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupQueryDto.java
1
请完成以下Java代码
@Override public void enterId(LabeledExprParser.IdContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitId(LabeledExprParser.IdContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitInt(LabeledExprParser.IntContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p>
*/ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\LabeledExprBaseListener.java
1
请完成以下Java代码
protected void makeEventDefinitionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) { for (EventDefinitionEntity eventDefinition : parsedDeployment.getAllEventDefinitions()) { EventDefinitionEntity persistedEventDefinition = eventDeploymentHelper.getPersistedInstanceOfEventDefinition(eventDefinition); if (persistedEventDefinition != null) { eventDefinition.setId(persistedEventDefinition.getId()); eventDefinition.setVersion(persistedEventDefinition.getVersion()); } } } /** * Loads the persisted version of each channel definition and set values on the in-memory version to be consistent. */ protected void makeChannelDefinitionsConsistentWithPersistedVersions(ParsedDeployment parsedDeployment) { for (ChannelDefinitionEntity channelDefinition : parsedDeployment.getAllChannelDefinitions()) { ChannelDefinitionEntity persistedChannelDefinition = channelDeploymentHelper.getPersistedInstanceOfChannelDefinition(channelDefinition); if (persistedChannelDefinition != null) { channelDefinition.setId(persistedChannelDefinition.getId()); channelDefinition.setVersion(persistedChannelDefinition.getVersion()); } } } public IdGenerator getIdGenerator() { return idGenerator; } public void setIdGenerator(IdGenerator idGenerator) { this.idGenerator = idGenerator; } public ParsedDeploymentBuilderFactory getExParsedDeploymentBuilderFactory() { return parsedDeploymentBuilderFactory; } public void setParsedDeploymentBuilderFactory(ParsedDeploymentBuilderFactory parsedDeploymentBuilderFactory) { this.parsedDeploymentBuilderFactory = parsedDeploymentBuilderFactory; } public EventDefinitionDeploymentHelper getEventDeploymentHelper() { return eventDeploymentHelper; } public void setEventDeploymentHelper(EventDefinitionDeploymentHelper eventDeploymentHelper) { this.eventDeploymentHelper = eventDeploymentHelper; }
public ChannelDefinitionDeploymentHelper getChannelDeploymentHelper() { return channelDeploymentHelper; } public void setChannelDeploymentHelper(ChannelDefinitionDeploymentHelper channelDeploymentHelper) { this.channelDeploymentHelper = channelDeploymentHelper; } public CachingAndArtifactsManager getCachingAndArtifcatsManager() { return cachingAndArtifactsManager; } public void setCachingAndArtifactsManager(CachingAndArtifactsManager manager) { this.cachingAndArtifactsManager = manager; } public boolean isUsePrefixId() { return usePrefixId; } public void setUsePrefixId(boolean usePrefixId) { this.usePrefixId = usePrefixId; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\deployer\EventDefinitionDeployer.java
1
请完成以下Java代码
public MessageCorrelationAsyncBuilder createMessageCorrelationAsync(String messageName) { return new MessageCorrelationAsyncBuilderImpl(commandExecutor, messageName); } @Override public ProcessInstanceModificationBuilder createProcessInstanceModification(String processInstanceId) { return new ProcessInstanceModificationBuilderImpl(commandExecutor, processInstanceId); } @Override public ProcessInstantiationBuilder createProcessInstanceById(String processDefinitionId) { return ProcessInstantiationBuilderImpl.createProcessInstanceById(commandExecutor, processDefinitionId); } @Override public ProcessInstantiationBuilder createProcessInstanceByKey(String processDefinitionKey) { return ProcessInstantiationBuilderImpl.createProcessInstanceByKey(commandExecutor, processDefinitionKey); } @Override public MigrationPlanBuilder createMigrationPlan(String sourceProcessDefinitionId, String targetProcessDefinitionId) { return new MigrationPlanBuilderImpl(commandExecutor, sourceProcessDefinitionId, targetProcessDefinitionId); } @Override public MigrationPlanExecutionBuilder newMigration(MigrationPlan migrationPlan) { return new MigrationPlanExecutionBuilderImpl(commandExecutor, migrationPlan); } @Override public ModificationBuilder createModification(String processDefinitionId) { return new ModificationBuilderImpl(commandExecutor, processDefinitionId); } @Override
public RestartProcessInstanceBuilder restartProcessInstances(String processDefinitionId) { return new RestartProcessInstanceBuilderImpl(commandExecutor, processDefinitionId); } @Override public Incident createIncident(String incidentType, String executionId, String configuration) { return createIncident(incidentType, executionId, configuration, null); } @Override public Incident createIncident(String incidentType, String executionId, String configuration, String message) { return commandExecutor.execute(new CreateIncidentCmd(incidentType, executionId, configuration, message)); } @Override public void resolveIncident(String incidentId) { commandExecutor.execute(new ResolveIncidentCmd(incidentId)); } @Override public void setAnnotationForIncidentById(String incidentId, String annotation) { commandExecutor.execute(new SetAnnotationForIncidentCmd(incidentId, annotation)); } @Override public void clearAnnotationForIncidentById(String incidentId) { commandExecutor.execute(new SetAnnotationForIncidentCmd(incidentId, null)); } @Override public ConditionEvaluationBuilder createConditionEvaluation() { return new ConditionEvaluationBuilderImpl(commandExecutor); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RuntimeServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<I_C_Invoice> retrieveBySalesrepPartnerId(@NonNull final BPartnerId salesRepBPartnerId, @NonNull final InstantInterval invoicedDateInterval) { final Timestamp from = TimeUtil.asTimestamp(invoicedDateInterval.getFrom()); final Timestamp to = TimeUtil.asTimestamp(invoicedDateInterval.getTo()); return queryBL.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_C_BPartner_SalesRep_ID, salesRepBPartnerId.getRepoId()) .addBetweenFilter(I_C_Invoice.COLUMNNAME_DateInvoiced, from, to) .create() .list(); } @Override public List<I_C_Invoice> retrieveSalesInvoiceByPartnerId(@NonNull final BPartnerId bpartnerId, @NonNull final InstantInterval invoicedDateInterval) { final Timestamp from = TimeUtil.asTimestamp(invoicedDateInterval.getFrom()); final Timestamp to = TimeUtil.asTimestamp(invoicedDateInterval.getTo()); return queryBL.createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_Invoice.COLUMNNAME_IsSOTrx, true) .addEqualsFilter(I_C_Invoice.COLUMNNAME_C_BPartner_ID, bpartnerId.getRepoId()) .addBetweenFilter(I_C_Invoice.COLUMNNAME_DateInvoiced, from, to) .create() .list(); } @Override public Collection<InvoiceAndLineId> getInvoiceLineIds(final InvoiceId id) { return queryBL.createQueryBuilder(I_C_InvoiceLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_InvoiceLine.COLUMNNAME_C_Invoice_ID, id) .create() .idsAsSet(lineId -> InvoiceAndLineId.ofRepoId(id, lineId)); }
private boolean matchesDocType(@NonNull final I_C_Invoice serviceFeeInvoiceCandidate, @Nullable final DocBaseAndSubType targetDocType) { if (targetDocType == null) { return true; } final DocTypeId docTypeId = CoalesceUtil.coalesceNotNull( DocTypeId.ofRepoIdOrNull(serviceFeeInvoiceCandidate.getC_DocType_ID()), DocTypeId.ofRepoId(serviceFeeInvoiceCandidate.getC_DocTypeTarget_ID())); final I_C_DocType docTypeRecord = docTypeDAO.getById(docTypeId); final DocBaseAndSubType docBaseAndSubType = DocBaseAndSubType.of(docTypeRecord.getDocBaseType(), docTypeRecord.getDocSubType()); return docBaseAndSubType.equals(targetDocType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\AbstractInvoiceDAO.java
2
请在Spring Boot框架中完成以下Java代码
public void start() { this.scheduler = this.createScheduler(); this.subscription = Flux.from(this.publisher) .subscribeOn(this.scheduler) .log(this.log.getName(), Level.FINEST) .doOnSubscribe((s) -> this.log.debug("Subscribed to {} events", this.eventType)) .ofType(this.eventType) .cast(this.eventType) .transform(this::handle) .onErrorContinue((throwable, o) -> this.log.warn("Unexpected error", throwable)) .subscribe(); } protected abstract Publisher<Void> handle(Flux<T> publisher);
protected Scheduler createScheduler() { return Schedulers.newSingle(this.getClass().getSimpleName()); } public void stop() { if (this.subscription != null) { this.subscription.dispose(); this.subscription = null; } if (this.scheduler != null) { this.scheduler.dispose(); this.scheduler = null; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\AbstractEventHandler.java
2
请完成以下Java代码
public void insert(SuspendedJobEntity jobEntity) { insert(jobEntity, true); } @Override public void delete(SuspendedJobEntity jobEntity) { super.delete(jobEntity); deleteExceptionByteArrayRef(jobEntity); if (jobEntity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( jobEntity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setSuspendedJobCount(executionEntity.getSuspendedJobCount() - 1); } } // Send event if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this) ); } } /** * Deletes a the byte array used to store the exception information. Subclasses may override * to provide custom implementations. */ protected void deleteExceptionByteArrayRef(SuspendedJobEntity jobEntity) { ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef(); if (exceptionByteArrayRef != null) { exceptionByteArrayRef.delete(); } } protected SuspendedJobEntity createSuspendedJob(AbstractJobEntity job) {
SuspendedJobEntity newSuspendedJobEntity = create(); newSuspendedJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration()); newSuspendedJobEntity.setJobHandlerType(job.getJobHandlerType()); newSuspendedJobEntity.setExclusive(job.isExclusive()); newSuspendedJobEntity.setRepeat(job.getRepeat()); newSuspendedJobEntity.setRetries(job.getRetries()); newSuspendedJobEntity.setEndDate(job.getEndDate()); newSuspendedJobEntity.setExecutionId(job.getExecutionId()); newSuspendedJobEntity.setProcessInstanceId(job.getProcessInstanceId()); newSuspendedJobEntity.setProcessDefinitionId(job.getProcessDefinitionId()); // Inherit tenant newSuspendedJobEntity.setTenantId(job.getTenantId()); newSuspendedJobEntity.setJobType(job.getJobType()); return newSuspendedJobEntity; } protected SuspendedJobDataManager getDataManager() { return jobDataManager; } public void setJobDataManager(SuspendedJobDataManager jobDataManager) { this.jobDataManager = jobDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\SuspendedJobEntityManagerImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<QueryVariable> getProcessVariables() { return processVariables; } public void setProcessVariables(List<QueryVariable> processVariables) { this.processVariables = processVariables; } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public Boolean getWithoutScopeId() { return withoutScopeId; } public void setWithoutScopeId(Boolean withoutScopeId) { this.withoutScopeId = withoutScopeId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantIdLike() { return tenantIdLike; } public void setTenantIdLike(String tenantIdLike) { this.tenantIdLike = tenantIdLike; } public Boolean getWithoutTenantId() { return withoutTenantId; } public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId;
} public Boolean getWithoutDeleteReason() { return withoutDeleteReason; } public void setWithoutDeleteReason(Boolean withoutDeleteReason) { this.withoutDeleteReason = withoutDeleteReason; } public String getTaskCandidateGroup() { return taskCandidateGroup; } public void setTaskCandidateGroup(String taskCandidateGroup) { this.taskCandidateGroup = taskCandidateGroup; } public boolean isIgnoreTaskAssignee() { return ignoreTaskAssignee; } public void setIgnoreTaskAssignee(boolean ignoreTaskAssignee) { this.ignoreTaskAssignee = ignoreTaskAssignee; } public String getRootScopeId() { return rootScopeId; } public void setRootScopeId(String rootScopeId) { this.rootScopeId = rootScopeId; } public String getParentScopeId() { return parentScopeId; } public void setParentScopeId(String parentScopeId) { this.parentScopeId = parentScopeId; } public Set<String> getScopeIds() { return scopeIds; } public void setScopeIds(Set<String> scopeIds) { this.scopeIds = scopeIds; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceQueryRequest.java
2
请在Spring Boot框架中完成以下Java代码
public void createIndex(String index) { createIndexRequest(index); } @Override public void deleteIndex(String index) { deleteIndexRequest(index); } @Override public void insert(String index, List<Person> list) { try { list.forEach(person -> { IndexRequest request = buildIndexRequest(index, String.valueOf(person.getId()), person); try { client.index(request, COMMON_OPTIONS); } catch (IOException e) { e.printStackTrace(); } }); } finally { try { client.close(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void update(String index, List<Person> list) { list.forEach(person -> { updateRequest(index, String.valueOf(person.getId()), person); }); } @Override public void delete(String index, Person person) {
if (ObjectUtils.isEmpty(person)) { // 如果person 对象为空,则删除全量 searchList(index).forEach(p -> { deleteRequest(index, String.valueOf(p.getId())); }); } deleteRequest(index, String.valueOf(person.getId())); } @Override public List<Person> searchList(String index) { SearchResponse searchResponse = search(index); SearchHit[] hits = searchResponse.getHits().getHits(); List<Person> personList = new ArrayList<>(); Arrays.stream(hits).forEach(hit -> { Map<String, Object> sourceAsMap = hit.getSourceAsMap(); Person person = BeanUtil.mapToBean(sourceAsMap, Person.class, true); personList.add(person); }); return personList; } }
repos\spring-boot-demo-master\demo-elasticsearch-rest-high-level-client\src\main\java\com\xkcoding\elasticsearch\service\impl\PersonServiceImpl.java
2
请完成以下Spring Boot application配置
spring: application: name: demo-consumer # Spring 应用名 cloud: nacos: # Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类 discovery: server-addr: 127.0.0.1:8848 # Nacos 服务器地址 service: ${spring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。 server: port: 28080 # 服务器端口。默认为 8080 management: endpoints: web: exposure: include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。 en
dpoint: # Health 端点配置项,对应 HealthProperties 配置类 health: enabled: true # 是否开启。默认为 true 开启。 show-details: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。
repos\SpringBoot-Labs-master\labx-01-spring-cloud-alibaba-nacos-discovery\labx-01-sca-nacos-discovery-demo03-consumer\src\main\resources\application.yaml
2
请完成以下Java代码
public ExternalTaskQueryDto getExternalTaskQuery() { return externalTaskQuery; } public void setExternalTaskQuery(ExternalTaskQueryDto externalTaskQuery) { this.externalTaskQuery = externalTaskQuery; } public ProcessInstanceQueryDto getProcessInstanceQuery() { return processInstanceQuery; } public void setProcessInstanceQuery(ProcessInstanceQueryDto processInstanceQueryDto) { this.processInstanceQuery = processInstanceQueryDto; }
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() { return historicProcessInstanceQuery; } public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQueryDto) { this.historicProcessInstanceQuery = historicProcessInstanceQueryDto; } public Integer getRetries() { return retries; } public void setRetries(Integer retries) { this.retries = retries; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\externaltask\SetRetriesForExternalTasksDto.java
1
请完成以下Java代码
public GridTab getGridTab() { return panel.getCurrentTab(); } public int getTableId() { GridTab gridTab = getGridTab(); return gridTab == null ? -1 : gridTab.getAD_Table_ID(); } public int getRecordId() { GridTab gridTab = getGridTab(); return gridTab == null ? -1 : gridTab.getRecord_ID(); } @Override public boolean canImport(TransferHandler.TransferSupport support) { final GridTab gridTab = getGridTab(); if (gridTab == null) return false; // if (!support.isDataFlavorSupported(DataFlavor.javaFileListFlavor) // && !support.isDataFlavorSupported(DataFlavor.getTextPlainUnicodeFlavor())) { // return false; // } return true; } @Override public boolean importData(TransferHandler.TransferSupport support) { final GridTab gridTab = getGridTab(); if (gridTab == null) { return false; } if (!canImport(support)) { return false; } Transferable t = support.getTransferable(); DataFlavor[] flavors = t.getTransferDataFlavors(); final TableRecordReference tableRecordReference =TableRecordReference.of(getTableId(), getRecordId()); final AttachmentEntryService attachmentEntryService = Adempiere.getBean(AttachmentEntryService.class); for (int i = 0; i < flavors.length; i++) { DataFlavor flavor = flavors[i];
try { if (flavor.equals(DataFlavor.javaFileListFlavor)) { @SuppressWarnings("unchecked") List<File> files = (List<File>)t.getTransferData(DataFlavor.javaFileListFlavor); attachmentEntryService.createNewAttachments(tableRecordReference, AttachmentEntryCreateRequest.fromFiles(files)); } else if (flavor.getMimeType().startsWith("text")) { final Object data = t.getTransferData(DataFlavor.stringFlavor); if (data == null) continue; final String text = data.toString(); final DateFormat df = DisplayType.getDateFormat(DisplayType.DateTime); final String name = "Text " + df.format(new Timestamp(System.currentTimeMillis())); attachmentEntryService.createNewAttachment(tableRecordReference, name, text.getBytes(StandardCharsets.UTF_8)); } } catch (Exception ex) { log.error(ex.getLocalizedMessage(), ex); ADialog.error(gridTab.getWindowNo(), null, "Error", ex.getLocalizedMessage()); return false; } } // inform APanel/.. -> dataStatus with row updated gridTab.loadAttachments(); final DataStatusEvent dataStatusEvent = DataStatusEvent.builder() .source(gridTab) .totalRows(gridTab.getRowCount()) .changed(false) .autoSave(true) .inserting(false) .build(); dataStatusEvent.setCurrentRow(gridTab.getCurrentRow()); final String status = dataStatusEvent.getAD_Message(); if (status == null || status.length() == 0) dataStatusEvent.setInfo("NavigateOrUpdate", null, false, false); gridTab.fireDataStatusChanged(dataStatusEvent); return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\de\schaeffer\compiere\tools\AttachmentDnDTransferHandler.java
1
请完成以下Java代码
static class WebApplicationTypeRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { for (String servletIndicatorClass : SERVLET_INDICATOR_CLASSES) { registerTypeIfPresent(servletIndicatorClass, classLoader, hints); } } private void registerTypeIfPresent(String typeName, @Nullable ClassLoader classLoader, RuntimeHints hints) { if (ClassUtils.isPresent(typeName, classLoader)) { hints.reflection().registerType(TypeReference.of(typeName)); } } } /** * Strategy that may be implemented by a module that can deduce the
* {@link WebApplicationType}. * * @since 4.0.1 */ @FunctionalInterface public interface Deducer { /** * Deduce the web application type. * @return the deduced web application type or {@code null} */ @Nullable WebApplicationType deduceWebApplicationType(); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\WebApplicationType.java
1
请完成以下Java代码
public void setDeleted(DbEntity dbEntity) { CachedDbEntity cachedEntity = getCachedEntity(dbEntity); if(cachedEntity != null) { if(cachedEntity.getEntityState() == TRANSIENT) { cachedEntity.setEntityState(DELETED_TRANSIENT); } else if(cachedEntity.getEntityState() == PERSISTENT){ cachedEntity.setEntityState(DELETED_PERSISTENT); } else if(cachedEntity.getEntityState() == MERGED){ cachedEntity.setEntityState(DELETED_MERGED); } } else { // put a deleted merged into the cache CachedDbEntity cachedDbEntity = new CachedDbEntity(); cachedDbEntity.setEntity(dbEntity); cachedDbEntity.setEntityState(DELETED_MERGED);
putInternal(cachedDbEntity); } } public void undoDelete(DbEntity dbEntity) { CachedDbEntity cachedEntity = getCachedEntity(dbEntity); if (cachedEntity.getEntityState() == DbEntityState.DELETED_TRANSIENT) { cachedEntity.setEntityState(DbEntityState.TRANSIENT); } else { cachedEntity.setEntityState(DbEntityState.MERGED); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\cache\DbEntityCache.java
1
请完成以下Java代码
public void setK_Entry_ID (int K_Entry_ID) { if (K_Entry_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Entry_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Entry_ID, Integer.valueOf(K_Entry_ID)); } /** Get Entry. @return Knowledge Entry */ public int getK_Entry_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Entry_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Related Entry. @param K_EntryRelated_ID Related Entry for this Enntry */ public void setK_EntryRelated_ID (int K_EntryRelated_ID) { if (K_EntryRelated_ID < 1) set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, null); else set_ValueNoCheck (COLUMNNAME_K_EntryRelated_ID, Integer.valueOf(K_EntryRelated_ID)); } /** Get Related Entry. @return Related Entry for this Enntry */ public int getK_EntryRelated_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair
*/ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getK_EntryRelated_ID())); } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_EntryRelated.java
1
请完成以下Java代码
protected HUEditorView getView() { return getView(HUEditorView.class); } protected List<I_M_ReceiptSchedule> getM_ReceiptSchedules() { return getView() .getReferencingDocumentPaths().stream() .map(referencingDocumentPath -> getReceiptSchedule(referencingDocumentPath)) .collect(GuavaCollectors.toImmutableList()); } private I_M_ReceiptSchedule getReceiptSchedule(@NonNull final DocumentPath referencingDocumentPath) { return documentsCollection .getTableRecordReference(referencingDocumentPath) .getModel(this, I_M_ReceiptSchedule.class); } protected Set<HuId> retrieveHUsToReceive() { // https://github.com/metasfresh/metasfresh/issues/1863 // if the queryFilter is empty, then *do not* return everything to avoid an OOME
final IQueryFilter<I_M_HU> processInfoFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); final IQuery<I_M_HU> query = Services.get(IQueryBL.class) .createQueryBuilder(I_M_HU.class, this) .filter(processInfoFilter) .addOnlyActiveRecordsFilter() .create(); final Set<HuId> huIds = query .listIds() .stream() .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); if (huIds.isEmpty()) { throw new AdempiereException("@NoSelection@ @M_HU_ID@") .appendParametersToMessage() .setParameter("query", query); } return huIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_Base.java
1
请在Spring Boot框架中完成以下Java代码
public class ISysClientFallback implements ISysClient { @Override public Dept getDept(Long id) { return null; } @Override public String getDeptName(Long id) { return null; } @Override public String getDeptIds(String tenantId, String deptNames) { return null; } @Override public List<String> getDeptNames(String deptIds) { return null; } @Override public String getPostIds(String tenantId, String postNames) { return null; } @Override public List<String> getPostNames(String postIds) { return null; } @Override public Role getRole(Long id) { return null;
} @Override public String getRoleIds(String tenantId, String roleNames) { return null; } @Override public String getRoleName(Long id) { return null; } @Override public List<String> getRoleNames(String roleIds) { return null; } @Override public String getRoleAlias(Long id) { return null; } @Override public R<Tenant> getTenant(Long id) { return null; } @Override public R<Tenant> getTenant(String tenantId) { return null; } }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\feign\ISysClientFallback.java
2
请在Spring Boot框架中完成以下Java代码
public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> attributeMap = importMetadata .getAnnotationAttributes(EnableRedisWebSession.class.getName()); AnnotationAttributes attributes = AnnotationAttributes.fromMap(attributeMap); if (attributes == null) { return; } this.maxInactiveInterval = Duration.ofSeconds(attributes.<Integer>getNumber("maxInactiveIntervalInSeconds")); String redisNamespaceValue = attributes.getString("redisNamespace"); if (StringUtils.hasText(redisNamespaceValue)) { this.redisNamespace = this.embeddedValueResolver.resolveStringValue(redisNamespaceValue); } this.saveMode = attributes.getEnum("saveMode"); } private ReactiveRedisTemplate<String, Object> createReactiveRedisTemplate() { RedisSerializer<String> keySerializer = RedisSerializer.string(); RedisSerializer<Object> defaultSerializer = (this.defaultRedisSerializer != null) ? this.defaultRedisSerializer
: new JdkSerializationRedisSerializer(this.classLoader); RedisSerializationContext<String, Object> serializationContext = RedisSerializationContext .<String, Object>newSerializationContext(defaultSerializer) .key(keySerializer) .hashKey(keySerializer) .build(); return new ReactiveRedisTemplate<>(this.redisConnectionFactory, serializationContext); } @Autowired(required = false) public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\server\RedisWebSessionConfiguration.java
2
请完成以下Java代码
public comment addElement(Element element) { addElementToRegistry(element); return (this); } /** * * Adds an Element to the element. * * @param element Adds an Element to the element. * */ public comment addElement(String element) { addElementToRegistry(element); return (this); } /** * * Removes an Element from the element. * * @param hashcode the name of the element to be removed. * */ public comment removeElement(String hashcode) { removeElementFromRegistry(hashcode); return (this); } protected String createStartTag() { setEndTagChar(' '); StringBuffer out = new StringBuffer(); out.append(getStartTagChar()); if (getBeginStartModifierDefined()) { out.append(getBeginStartModifier()); } out.append(getElementType()); if (getBeginEndModifierDefined()) { out.append(getBeginEndModifier()); } out.append(getEndTagChar()); setEndTagChar('>'); // put back the end tag character. return (out.toString()); } protected String createEndTag() {
StringBuffer out = new StringBuffer(); setStartTagChar(' '); setEndStartModifier(' '); out.append(getStartTagChar()); if (getEndStartModifierDefined()) { out.append(getEndStartModifier()); } out.append(getElementType()); if (getEndEndModifierDefined()) { out.append(getEndEndModifier()); } out.append(getEndTagChar()); setStartTagChar('<'); // put back the tag start character return (out.toString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\comment.java
1
请在Spring Boot框架中完成以下Java代码
public class User { // ------------------------ // PRIVATE FIELDS // ------------------------ // An autogenerated id (unique for each user in the db) @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; // The user's email @NotNull private String email; // The user's name @NotNull private String name; // ------------------------ // PUBLIC METHODS // ------------------------ public User() { } public User(long id) { this.id = id; } public User(String email, String name) { this.email = email; this.name = name; } // Getter and setter methods
public long getId() { return id; } public void setId(long value) { this.id = value; } public String getEmail() { return email; } public void setEmail(String value) { this.email = value; } public String getName() { return name; } public void setName(String value) { this.name = value; } } // class User
repos\spring-boot-samples-master\spring-boot-mysql-springdatajpa-hibernate\src\main\java\netgloo\models\User.java
2
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** * EntityType AD_Reference_ID=389 * Reference name: _EntityTypeNew */ public static final int ENTITYTYPE_AD_Reference_ID=389; /** Set Entitäts-Art. @param EntityType Dictionary Entity Type; Determines ownership and synchronization */ @Override public void setEntityType (java.lang.String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitäts-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ @Override public java.lang.String getEntityType () { return (java.lang.String)get_Value(COLUMNNAME_EntityType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name)
{ set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override 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\adempiere\pricing\model\X_C_PricingRule.java
1
请完成以下Java代码
public class ConnectionGroupVO { private String namespace; private List<ConnectionDescriptorVO> connectionSet; private Integer connectedCount; public String getNamespace() { return namespace; } public ConnectionGroupVO setNamespace(String namespace) { this.namespace = namespace; return this; } public List<ConnectionDescriptorVO> getConnectionSet() { return connectionSet; } public ConnectionGroupVO setConnectionSet( List<ConnectionDescriptorVO> connectionSet) { this.connectionSet = connectionSet; return this; } public Integer getConnectedCount() { return connectedCount; }
public ConnectionGroupVO setConnectedCount(Integer connectedCount) { this.connectedCount = connectedCount; return this; } @Override public String toString() { return "ConnectionGroupVO{" + "namespace='" + namespace + '\'' + ", connectionSet=" + connectionSet + ", connectedCount=" + connectedCount + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\ConnectionGroupVO.java
1
请完成以下Java代码
public void sendEvent(OutboundEvent<Object> event) { try { Object rawEvent = event.getBody(); Map<String, Object> headerMap = event.getHeaders(); List<Header> headers = new ArrayList<>(); for (String headerKey : headerMap.keySet()) { Object headerValue = headerMap.get(headerKey); if (headerValue != null) { headers.add(new RecordHeader(headerKey, headerValue.toString().getBytes(StandardCharsets.UTF_8))); } } Integer partition = partitionProvider == null ? null : partitionProvider.determinePartition(event); Object key = messageKeyProvider == null ? null : messageKeyProvider.determineMessageKey(event); ProducerRecord<Object, Object> producerRecord = new ProducerRecord<>(topic, partition, key, rawEvent, headers); kafkaOperations.send(producerRecord).get();
} catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new FlowableException("Sending the event was interrupted", e); } catch (ExecutionException e) { if (e.getCause() instanceof RuntimeException) { throw (RuntimeException) e.getCause(); } else { throw new FlowableException("failed to send event", e.getCause()); } } } @Override public void sendEvent(Object rawEvent, Map<String, Object> headerMap) { throw new UnsupportedOperationException("Outbound processor should never call this"); } }
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\kafka\KafkaOperationsOutboundEventChannelAdapter.java
1
请完成以下Java代码
public class DeferredLogs implements DeferredLogFactory { private final Lines lines = new Lines(); private final List<DeferredLog> loggers = new ArrayList<>(); /** * Create a new {@link DeferredLog} for the given destination. * @param destination the ultimate log destination * @return a deferred log instance that will switch to the destination when * appropriate. */ @Override public Log getLog(Class<?> destination) { return getLog(() -> LogFactory.getLog(destination)); } /** * Create a new {@link DeferredLog} for the given destination. * @param destination the ultimate log destination * @return a deferred log instance that will switch to the destination when * appropriate. */ @Override public Log getLog(Log destination) { return getLog(() -> destination); } /** * Create a new {@link DeferredLog} for the given destination. * @param destination the ultimate log destination * @return a deferred log instance that will switch to the destination when
* appropriate. */ @Override public Log getLog(Supplier<Log> destination) { synchronized (this.lines) { DeferredLog logger = new DeferredLog(destination, this.lines); this.loggers.add(logger); return logger; } } /** * Switch over all deferred logs to their supplied destination. */ public void switchOverAll() { synchronized (this.lines) { for (Line line : this.lines) { line.getLevel().log(line.getDestination(), line.getMessage(), line.getThrowable()); } for (DeferredLog logger : this.loggers) { logger.switchOver(); } this.lines.clear(); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\DeferredLogs.java
1
请在Spring Boot框架中完成以下Java代码
public at.erpel.schemas._1p0.documents.extensions.edifact.SupplierExtensionType getSupplierExtension() { return supplierExtension; } /** * Sets the value of the supplierExtension property. * * @param value * allowed object is * {@link at.erpel.schemas._1p0.documents.extensions.edifact.SupplierExtensionType } * */ public void setSupplierExtension(at.erpel.schemas._1p0.documents.extensions.edifact.SupplierExtensionType value) { this.supplierExtension = value; } /** * Gets the value of the erpelSupplierExtension property. * * @return * possible object is
* {@link CustomType } * */ public CustomType getErpelSupplierExtension() { return erpelSupplierExtension; } /** * Sets the value of the erpelSupplierExtension property. * * @param value * allowed object is * {@link CustomType } * */ public void setErpelSupplierExtension(CustomType value) { this.erpelSupplierExtension = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ext\SupplierExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
public static class ODataServiceRootLocator extends ODataRootLocator { private OdataJpaServiceFactory serviceFactory; @Inject public ODataServiceRootLocator (OdataJpaServiceFactory serviceFactory) { this.serviceFactory = serviceFactory; } @Override public ODataServiceFactory getServiceFactory() { return this.serviceFactory; } } @Provider public static class EntityManagerFilter implements ContainerRequestFilter, ContainerResponseFilter { public static final String EM_REQUEST_ATTRIBUTE = EntityManagerFilter.class.getName() + "_ENTITY_MANAGER"; private final EntityManagerFactory entityManagerFactory; @Context private HttpServletRequest httpRequest; public EntityManagerFilter(EntityManagerFactory entityManagerFactory) { this.entityManagerFactory = entityManagerFactory; } @Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException { EntityManager entityManager = this.entityManagerFactory.createEntityManager(); httpRequest.setAttribute(EM_REQUEST_ATTRIBUTE, entityManager); if (!"GET".equalsIgnoreCase(containerRequestContext.getMethod())) { entityManager.getTransaction().begin(); } } @Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { EntityManager entityManager = (EntityManager) httpRequest.getAttribute(EM_REQUEST_ATTRIBUTE); if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { EntityTransaction entityTransaction = entityManager.getTransaction(); //we do not commit because it's just a READ if (entityTransaction.isActive() && !entityTransaction.getRollbackOnly()) { entityTransaction.commit(); } } entityManager.close(); } } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\config\JerseyConfig.java
2
请完成以下Java代码
private String getTableName() { Table tableAnnotation = clazz.getAnnotation(Table.class); if (ObjectUtil.isNotNull(tableAnnotation)) { return StrUtil.format("`{}`", tableAnnotation.name()); } else { return StrUtil.format("`{}`", clazz.getName().toLowerCase()); } } /** * 获取列 * * @param fieldList 字段列表 * @return 列信息列表 */ private List<String> getColumns(List<Field> fieldList) { // 构造列 List<String> columnList = CollUtil.newArrayList(); for (Field field : fieldList) { Column columnAnnotation = field.getAnnotation(Column.class); String columnName; if (ObjectUtil.isNotNull(columnAnnotation)) { columnName = columnAnnotation.name(); } else { columnName = field.getName(); } columnList.add(StrUtil.format("`{}`", columnName)); } return columnList;
} /** * 获取字段列表 {@code 过滤数据库中不存在的字段,以及自增列} * * @param t 对象 * @param ignoreNull 是否忽略空值 * @return 字段列表 */ private List<Field> getField(T t, Boolean ignoreNull) { // 获取所有字段,包含父类中的字段 Field[] fields = ReflectUtil.getFields(t.getClass()); // 过滤数据库中不存在的字段,以及自增列 List<Field> filterField; Stream<Field> fieldStream = CollUtil.toList(fields).stream().filter(field -> ObjectUtil.isNull(field.getAnnotation(Ignore.class)) || ObjectUtil.isNull(field.getAnnotation(Pk.class))); // 是否过滤字段值为null的字段 if (ignoreNull) { filterField = fieldStream.filter(field -> ObjectUtil.isNotNull(ReflectUtil.getFieldValue(t, field))).collect(Collectors.toList()); } else { filterField = fieldStream.collect(Collectors.toList()); } return filterField; } }
repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\dao\base\BaseDao.java
1
请完成以下Java代码
public void setC_BPartner_From_ID (final int C_BPartner_From_ID) { if (C_BPartner_From_ID < 1) set_Value (COLUMNNAME_C_BPartner_From_ID, null); else set_Value (COLUMNNAME_C_BPartner_From_ID, C_BPartner_From_ID); } @Override public int getC_BPartner_From_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_From_ID); } @Override public void setC_BPartner_To_ID (final int C_BPartner_To_ID) { if (C_BPartner_To_ID < 1) set_Value (COLUMNNAME_C_BPartner_To_ID, null); else set_Value (COLUMNNAME_C_BPartner_To_ID, C_BPartner_To_ID); } @Override public int getC_BPartner_To_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_To_ID); } @Override public void setDate_OrgChange (final java.sql.Timestamp Date_OrgChange) { set_Value (COLUMNNAME_Date_OrgChange, Date_OrgChange); }
@Override public java.sql.Timestamp getDate_OrgChange() { return get_ValueAsTimestamp(COLUMNNAME_Date_OrgChange); } @Override public void setIsCloseInvoiceCandidate (final boolean IsCloseInvoiceCandidate) { set_Value (COLUMNNAME_IsCloseInvoiceCandidate, IsCloseInvoiceCandidate); } @Override public boolean isCloseInvoiceCandidate() { return get_ValueAsBoolean(COLUMNNAME_IsCloseInvoiceCandidate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_OrgChange_History.java
1
请完成以下Java代码
public static GregorianCalendar asGregorianCalendar() { final GregorianCalendar cal = new GregorianCalendar(); cal.setTimeInMillis(millis()); return cal; } public static Date asDate() { return new Date(millis()); } public static Timestamp asTimestamp() { return new Timestamp(millis()); } /** * Same as {@link #asTimestamp()} but the returned date will be truncated to DAY. */ public static Timestamp asDayTimestamp() { final GregorianCalendar cal = asGregorianCalendar(); cal.set(Calendar.HOUR_OF_DAY, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); return new Timestamp(cal.getTimeInMillis()); } public static Instant asInstant() { return Instant.ofEpochMilli(millis()); } public static LocalDateTime asLocalDateTime() { return asZonedDateTime().toLocalDateTime(); } @NonNull public static LocalDate asLocalDate() {
return asLocalDate(zoneId()); } @NonNull public static LocalDate asLocalDate(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId).toLocalDate(); } public static ZonedDateTime asZonedDateTime() { return asZonedDateTime(zoneId()); } public static ZonedDateTime asZonedDateTimeAtStartOfDay() { return asZonedDateTime(zoneId()).truncatedTo(ChronoUnit.DAYS); } public static ZonedDateTime asZonedDateTimeAtEndOfDay(@NonNull final ZoneId zoneId) { return asZonedDateTime(zoneId) .toLocalDate() .atTime(LocalTime.MAX) .atZone(zoneId); } public static ZonedDateTime asZonedDateTime(@NonNull final ZoneId zoneId) { return asInstant().atZone(zoneId); } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\time\SystemTime.java
1
请完成以下Java代码
public int getM_AttributeSetInstance_ID() { return shipmentSchedule.getM_AttributeSetInstance_ID(); } @Override public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { shipmentSchedule.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID); } @Override public int getC_UOM_ID() { return shipmentSchedule.getC_UOM_ID(); } @Override public void setC_UOM_ID(final int uomId) { // we assume inoutLine's UOM is correct if (uomId > 0) { shipmentSchedule.setC_UOM_ID(uomId); } } @Override public void setQty(final BigDecimal qty) { shipmentSchedule.setQtyOrdered_Override(qty); } @Override public BigDecimal getQty() { // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule); return qtyOrdered; } @Override public int getM_HU_PI_Item_Product_ID() { return shipmentSchedule.getM_HU_PI_Item_Product_ID(); } @Override public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId) { values.setM_HU_PI_Item_Product_ID(huPiItemProductId); }
@Override public BigDecimal getQtyTU() { return shipmentSchedule.getQtyOrdered_TU(); } @Override public void setQtyTU(final BigDecimal qtyPacks) { shipmentSchedule.setQtyOrdered_TU(qtyPacks); } @Override public void setC_BPartner_ID(final int partnerId) { values.setC_BPartner_ID(partnerId); } @Override public int getC_BPartner_ID() { return values.getC_BPartner_ID(); } @Override public boolean isInDispute() { return values.isInDispute(); } @Override public void setInDispute(final boolean inDispute) { values.setInDispute(inDispute); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ShipmentScheduleHUPackingAware.java
1
请完成以下Java代码
private DocumentToRepost extractDocumentToRepostFromTableAndRecordIdRow(final IViewRow row) { final int adTableId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Table_ID, -1); final int recordId = row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_Record_ID, -1); final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } private DocumentToRepost extractDocumentToRepostFromRegularRow(final IViewRow row) { final int adTableId = adTablesRepo.retrieveTableId(getTableName()); final int recordId = row.getId().toInt();
final ClientId adClientId = ClientId.ofRepoId(row.getFieldValueAsInt(I_Fact_Acct.COLUMNNAME_AD_Client_ID, -1)); return DocumentToRepost.builder() .adTableId(adTableId) .recordId(recordId) .clientId(adClientId) .build(); } @Override protected void postProcess(final boolean success) { getView().invalidateSelection(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\accounting\process\WEBUI_Fact_Acct_Repost_ViewRows.java
1
请在Spring Boot框架中完成以下Java代码
public class Comment { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String text; public Comment(String text) { this.text = text; } public Comment() { } @ManyToOne private Post post; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) {
this.text = text; } public Post getPost() { return post; } public void setPost(Post post) { this.post = post; } @Override public String toString() { return "Comment{" + "id=" + id + ", name='" + text + '\'' + ", post=" + post + '}'; } }
repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\detachedentity\entity\Comment.java
2
请完成以下Java代码
public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; } @Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height;
} @Override public void setHeight(int height) { this.height = height; } @Override public boolean isAsync() { return isAsync; } public void setAsync(boolean isAsync) { this.isAsync = isAsync; } @Override public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
1
请完成以下Java代码
public void stop() { this.lock.lock(); try { if (this.running) { if (this.ownContainer) { this.container.stop(); } this.running = false; this.stopInvoked = true; } } finally { this.lock.unlock(); } } @Override public boolean isRunning() { this.lock.lock(); try { return this.running; } finally { this.lock.unlock(); } } @Override public int getPhase() { return this.phase; } public void setPhase(int phase) { this.phase = phase; } @Override public boolean isAutoStartup() { return this.autoStartup; } public void setAutoStartup(boolean autoStartup) { this.autoStartup = autoStartup; } @Override public void onMessage(Message message) {
if (this.applicationEventPublisher != null) { this.applicationEventPublisher.publishEvent(new BrokerEvent(this, message.getMessageProperties())); } else { if (logger.isWarnEnabled()) { logger.warn("No event publisher available for " + message + "; if the BrokerEventListener " + "is not defined as a bean, you must provide an ApplicationEventPublisher"); } } } @Override public void onCreate(@Nullable Connection connection) { this.bindingsFailedException = null; TopicExchange exchange = new TopicExchange("amq.rabbitmq.event"); try { this.admin.declareQueue(this.eventQueue); Arrays.stream(this.eventKeys).forEach(k -> { Binding binding = BindingBuilder.bind(this.eventQueue).to(exchange).with(k); this.admin.declareBinding(binding); }); } catch (Exception e) { logger.error("failed to declare event queue/bindings - is the plugin enabled?", e); this.bindingsFailedException = e; } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BrokerEventListener.java
1
请在Spring Boot框架中完成以下Java代码
public DataSize getMaxFileSize() { return this.maxFileSize; } public void setMaxFileSize(DataSize maxFileSize) { this.maxFileSize = maxFileSize; } public DataSize getMaxRequestSize() { return this.maxRequestSize; } public void setMaxRequestSize(DataSize maxRequestSize) { this.maxRequestSize = maxRequestSize; } public DataSize getFileSizeThreshold() { return this.fileSizeThreshold; } public void setFileSizeThreshold(DataSize fileSizeThreshold) { this.fileSizeThreshold = fileSizeThreshold; } public boolean isResolveLazily() { return this.resolveLazily; } public void setResolveLazily(boolean resolveLazily) { this.resolveLazily = resolveLazily; } public boolean isStrictServletCompliance() { return this.strictServletCompliance; } public void setStrictServletCompliance(boolean strictServletCompliance) { this.strictServletCompliance = strictServletCompliance;
} /** * Create a new {@link MultipartConfigElement} using the properties. * @return a new {@link MultipartConfigElement} configured using there properties */ public MultipartConfigElement createMultipartConfig() { MultipartConfigFactory factory = new MultipartConfigFactory(); PropertyMapper map = PropertyMapper.get(); map.from(this.fileSizeThreshold).to(factory::setFileSizeThreshold); map.from(this.location).whenHasText().to(factory::setLocation); map.from(this.maxRequestSize).to(factory::setMaxRequestSize); map.from(this.maxFileSize).to(factory::setMaxFileSize); return factory.createMultipartConfig(); } }
repos\spring-boot-4.0.1\module\spring-boot-servlet\src\main\java\org\springframework\boot\servlet\autoconfigure\MultipartProperties.java
2
请完成以下Java代码
public @NonNull Set<T> toSet() { assertNotAny(); return onlyValues; // we can return it as is because it's already readonly } @SafeVarargs public final InSetPredicate<T> intersectWith(@NonNull final T... onlyValues) { return intersectWith(only(onlyValues)); } public InSetPredicate<T> intersectWith(@NonNull final Set<T> onlyValues) { return intersectWith(only(onlyValues)); } public InSetPredicate<T> intersectWith(@NonNull final InSetPredicate<T> other) { if (isNone() || other.isNone()) { return none(); } if (isAny()) { return other; } else if (other.isAny()) { return this; } return only(Sets.intersection(this.toSet(), other.toSet())); }
public interface CaseConsumer<T> { void anyValue(); void noValue(); void onlyValues(Set<T> onlyValues); } public void apply(@NonNull final CaseConsumer<T> caseConsumer) { switch (mode) { case ANY: caseConsumer.anyValue(); break; case NONE: caseConsumer.noValue(); break; case ONLY: caseConsumer.onlyValues(onlyValues); break; default: throw new IllegalStateException("Unknown mode: " + mode); // shall not happen } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\InSetPredicate.java
1
请完成以下Java代码
public void setAD_PInstance_ID (final int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, AD_PInstance_ID); } @Override public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } /** * Data_Export_Action AD_Reference_ID=541389 * Reference name: Data_Export_Actions */ public static final int DATA_EXPORT_ACTION_AD_Reference_ID=541389; /** Exported-Standalone = Exported-Standalone */ public static final String DATA_EXPORT_ACTION_Exported_Standalone = "Exported-Standalone"; /** Exported-AlongWithParent = Exported-AlongWithParent */ public static final String DATA_EXPORT_ACTION_Exported_AlongWithParent = "Exported-AlongWithParent"; /** AssignedToParent = AssignedToParent */ public static final String DATA_EXPORT_ACTION_AssignedToParent = "AssignedToParent"; /** Deleted = Deleted */ public static final String DATA_EXPORT_ACTION_Deleted = "Deleted"; @Override public void setData_Export_Action (final java.lang.String Data_Export_Action) { set_Value (COLUMNNAME_Data_Export_Action, Data_Export_Action); } @Override public java.lang.String getData_Export_Action() { return get_ValueAsString(COLUMNNAME_Data_Export_Action); } @Override public org.compiere.model.I_Data_Export_Audit getData_Export_Audit() { return get_ValueAsPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class); } @Override public void setData_Export_Audit(final org.compiere.model.I_Data_Export_Audit Data_Export_Audit) {
set_ValueFromPO(COLUMNNAME_Data_Export_Audit_ID, org.compiere.model.I_Data_Export_Audit.class, Data_Export_Audit); } @Override public void setData_Export_Audit_ID (final int Data_Export_Audit_ID) { if (Data_Export_Audit_ID < 1) set_Value (COLUMNNAME_Data_Export_Audit_ID, null); else set_Value (COLUMNNAME_Data_Export_Audit_ID, Data_Export_Audit_ID); } @Override public int getData_Export_Audit_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_ID); } @Override public void setData_Export_Audit_Log_ID (final int Data_Export_Audit_Log_ID) { if (Data_Export_Audit_Log_ID < 1) set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, null); else set_ValueNoCheck (COLUMNNAME_Data_Export_Audit_Log_ID, Data_Export_Audit_Log_ID); } @Override public int getData_Export_Audit_Log_ID() { return get_ValueAsInt(COLUMNNAME_Data_Export_Audit_Log_ID); } @Override public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID) { if (ExternalSystem_Config_ID < 1) set_Value (COLUMNNAME_ExternalSystem_Config_ID, null); else set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID); } @Override public int getExternalSystem_Config_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Data_Export_Audit_Log.java
1
请完成以下Java代码
public String getExecutionId() { return executionId; } public String getActivityInstanceId() { return activityInstanceId; } public String getCaseDefinitionKey() { return caseDefinitionKey; } public String getCaseDefinitionId() { return caseDefinitionId; } public String getCaseInstanceId() { return caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public String getTaskId() { return taskId; } public String getErrorMessage() { return errorMessage; } public String getTenantId() { return tenantId; } public String getState() { return state; } public Date getCreateTime() { return createTime; } public Date getRemovalTime() { return removalTime; }
public String getRootProcessInstanceId() { return rootProcessInstanceId; } public static HistoricVariableInstanceDto fromHistoricVariableInstance(HistoricVariableInstance historicVariableInstance) { HistoricVariableInstanceDto dto = new HistoricVariableInstanceDto(); dto.id = historicVariableInstance.getId(); dto.name = historicVariableInstance.getName(); dto.processDefinitionKey = historicVariableInstance.getProcessDefinitionKey(); dto.processDefinitionId = historicVariableInstance.getProcessDefinitionId(); dto.processInstanceId = historicVariableInstance.getProcessInstanceId(); dto.executionId = historicVariableInstance.getExecutionId(); dto.activityInstanceId = historicVariableInstance.getActivityInstanceId(); dto.caseDefinitionKey = historicVariableInstance.getCaseDefinitionKey(); dto.caseDefinitionId = historicVariableInstance.getCaseDefinitionId(); dto.caseInstanceId = historicVariableInstance.getCaseInstanceId(); dto.caseExecutionId = historicVariableInstance.getCaseExecutionId(); dto.taskId = historicVariableInstance.getTaskId(); dto.tenantId = historicVariableInstance.getTenantId(); dto.state = historicVariableInstance.getState(); dto.createTime = historicVariableInstance.getCreateTime(); dto.removalTime = historicVariableInstance.getRemovalTime(); dto.rootProcessInstanceId = historicVariableInstance.getRootProcessInstanceId(); if(historicVariableInstance.getErrorMessage() == null) { VariableValueDto.fromTypedValue(dto, historicVariableInstance.getTypedValue()); } else { dto.errorMessage = historicVariableInstance.getErrorMessage(); dto.type = VariableValueDto.toRestApiTypeName(historicVariableInstance.getTypeName()); } return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricVariableInstanceDto.java
1
请完成以下Java代码
private void dbUpdateErrorMessages(@NonNull final ImportRecordsSelection selection) { StringBuilder sql; int no; sql = new StringBuilder("UPDATE I_DiscountSchema ") .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No BPartner, ' ") .append("WHERE C_BPartner_ID IS NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No BPartner = {}", no); } sql = new StringBuilder("UPDATE I_DiscountSchema ") .append("SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'ERR=No Product, ' ") .append("WHERE M_Product_ID IS NULL ") .append("AND I_IsImported<>'Y' ") .append(selection.toSqlWhereClause()); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("No Product = {}", no); } //
sql = new StringBuilder("UPDATE I_DiscountSchema i " + "SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid C_PaymentTerm, ' " + "WHERE C_PaymentTerm_ID IS NULL AND PaymentTermValue IS NOT NULL AND PaymentTermValue <> '0' " + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("Invalid C_PaymentTerm={}", no); } sql = new StringBuilder("UPDATE I_DiscountSchema i " + "SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid Base_PricingSystem, ' " + "WHERE Base_PricingSystem_ID IS NULL AND Base_PricingSystem_Value IS NOT NULL" + " AND " + COLUMNNAME_I_IsImported + "<>'Y'") .append(selection.toSqlWhereClause("i")); no = DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited); if (no != 0) { logger.warn("Invalid Base_PricingSystem_ID={}", no); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\impexp\MDiscountSchemaImportTableSqlUpdater.java
1
请完成以下Java代码
protected Map<String, Object> invokeCustomPropertiesResolver( DelegateExecution execution, CustomPropertiesResolver customPropertiesResolver ) { Map<String, Object> customPropertiesMapToUse = null; if (customPropertiesResolver != null) { customPropertiesMapToUse = customPropertiesResolver.getCustomPropertiesMap(execution); } return customPropertiesMapToUse; } protected void addTransactionListener(ActivitiListener activitiListener, TransactionListener transactionListener) { TransactionContext transactionContext = Context.getTransactionContext(); if ( TransactionDependentExecutionListener.ON_TRANSACTION_BEFORE_COMMIT.equals(
activitiListener.getOnTransaction() ) ) { transactionContext.addTransactionListener(TransactionState.COMMITTING, transactionListener); } else if ( TransactionDependentExecutionListener.ON_TRANSACTION_COMMITTED.equals(activitiListener.getOnTransaction()) ) { transactionContext.addTransactionListener(TransactionState.COMMITTED, transactionListener); } else if ( TransactionDependentExecutionListener.ON_TRANSACTION_ROLLED_BACK.equals(activitiListener.getOnTransaction()) ) { transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, transactionListener); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ListenerNotificationHelper.java
1
请完成以下Java代码
public static HuId ofHUValue(@NonNull final String huValue) { try { return ofRepoId(Integer.parseInt(huValue)); } catch (final Exception ex) { final AdempiereException metasfreshException = new AdempiereException("Invalid HUValue `" + huValue + "`. It cannot be converted to M_HU_ID."); metasfreshException.addSuppressed(ex); throw metasfreshException; } } public static HuId ofHUValueOrNull(@Nullable final String huValue) { final String huValueNorm = StringUtils.trimBlankToNull(huValue); if (huValueNorm == null) {return null;} try { return ofRepoIdOrNull(NumberUtils.asIntOrZero(huValueNorm)); } catch (final Exception ex) { return null; } } public String toHUValue() {return String.valueOf(repoId);} int repoId; private HuId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "M_HU_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final HuId o1, @Nullable final HuId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\handlingunits\HuId.java
1
请在Spring Boot框架中完成以下Java代码
public class DailyCollectAccountHistoryVo implements Serializable { /** * */ private static final long serialVersionUID = -2451289258390618916L; /** * 账户编号 */ private String accountNo; /** * 汇总日期 */ private Date collectDate; /** * 总金额 */ private BigDecimal totalAmount = BigDecimal.ZERO; /** * 总笔数 */ private Integer totalNum = 0; /** * 最后ID */ private Long lastId = 0L; /** * 风险预存期 */ private Integer riskDay; /** * 账户编号 */ public String getAccountNo() { return accountNo; } /** * 账户编号 */ public void setAccountNo(String accountNo) { this.accountNo = accountNo; } /** * 汇总日期 */ public Date getCollectDate() { return collectDate; } /** * 汇总日期 */ public void setCollectDate(Date collectDate) { this.collectDate = collectDate; } /** * 总金额 */ public BigDecimal getTotalAmount() { return totalAmount; } /** * 总金额 */ public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount;
} /** * 总笔数 */ public Integer getTotalNum() { return totalNum; } /** * 总笔数 */ public void setTotalNum(Integer totalNum) { this.totalNum = totalNum; } /** * 最后ID * * @return */ public Long getLastId() { return lastId; } /** * 最后ID * * @return */ public void setLastId(Long lastId) { this.lastId = lastId; } /** * 风险预存期 */ public Integer getRiskDay() { return riskDay; } /** * 风险预存期 */ public void setRiskDay(Integer riskDay) { this.riskDay = riskDay; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\vo\DailyCollectAccountHistoryVo.java
2
请完成以下Java代码
public class MAttributeSet extends X_M_AttributeSet { @SuppressWarnings("unused") public MAttributeSet(Properties ctx, int M_AttributeSet_ID, String trxName) { super(ctx, M_AttributeSet_ID, trxName); if (is_new()) { // setName (null); setIsInstanceAttribute(false); setMandatoryType(MANDATORYTYPE_NotMandatary); } } // MAttributeSet @SuppressWarnings("unused") public MAttributeSet(Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MAttributeSet @Override protected boolean beforeSave(boolean newRecord) { if (!isInstanceAttribute()) setIsInstanceAttribute(true); return true; } // beforeSave @Override protected boolean afterSave(boolean newRecord, boolean success) { // Set Instance Attribute if (!isInstanceAttribute()) { String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='Y' " + "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID() + " AND IsInstanceAttribute='N'" + " AND (EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')" + ")"; int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); if (no != 0) { log.warn("Set Instance Attribute"); setIsInstanceAttribute(true);
} } // Reset Instance Attribute if (isInstanceAttribute()) { String sql = "UPDATE M_AttributeSet mas" + " SET IsInstanceAttribute='N' " + "WHERE M_AttributeSet_ID=" + getM_AttributeSet_ID() + " AND IsInstanceAttribute='Y'" + " AND NOT EXISTS (SELECT * FROM M_AttributeUse mau" + " INNER JOIN M_Attribute ma ON (mau.M_Attribute_ID=ma.M_Attribute_ID) " + "WHERE mau.M_AttributeSet_ID=mas.M_AttributeSet_ID" + " AND mau.IsActive='Y' AND ma.IsActive='Y'" + " AND ma.IsInstanceAttribute='Y')"; int no = DB.executeUpdateAndThrowExceptionOnFail(sql, get_TrxName()); if (no != 0) { log.warn("Reset Instance Attribute"); setIsInstanceAttribute(false); } } return success; } // afterSave } // MAttributeSet
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MAttributeSet.java
1
请完成以下Java代码
public final class EAN13 { @NonNull private final String barcode; @Getter @NonNull private final EAN13Prefix prefix; @Getter @NonNull private final EAN13ProductCode productNo; @Nullable private final BigDecimal weightInKg; @Getter private final int checksum; public static ExplainedOptional<EAN13> ofString(@NonNull final String barcode) { return EAN13Parser.parse(barcode); } @JsonCreator @Nullable public static EAN13 ofNullableString(@Nullable final String barcode) { final String barcodeNorm = StringUtils.trimBlankToNull(barcode); return barcodeNorm != null ? EAN13Parser.parse(barcodeNorm).orElseThrow() : null; } @Override @Deprecated 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