instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class WebExceptionResolver implements HandlerExceptionResolver { private static transient Logger logger = LoggerFactory.getLogger(WebExceptionResolver.class); @Override public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { if (!(ex instanceof XxlJobException)) { logger.error("WebExceptionResolver:{}", ex); } // if json boolean isJson = false; if (handler instanceof HandlerMethod) { HandlerMethod method = (HandlerMethod)handler; ResponseBody responseBody = method.getMethodAnnotation(ResponseBody.class); if (responseBody != null) { isJson = true; } } // error result
ReturnT<String> errorResult = new ReturnT<String>(ReturnT.FAIL_CODE, ex.toString().replaceAll("\n", "<br/>")); // response ModelAndView mv = new ModelAndView(); if (isJson) { try { response.setContentType("application/json;charset=utf-8"); response.getWriter().print(JacksonUtil.writeValueAsString(errorResult)); } catch (IOException e) { logger.error(e.getMessage(), e); } return mv; } else { mv.addObject("exceptionMsg", errorResult.getMsg()); mv.setViewName("/common/common.exception"); return mv; } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\resolver\WebExceptionResolver.java
2
请在Spring Boot框架中完成以下Java代码
protected Duration getMaxInactiveInterval() { return this.maxInactiveInterval; } public void setRedisNamespace(String namespace) { Assert.hasText(namespace, "namespace must not be empty"); this.redisNamespace = namespace; } protected String getRedisNamespace() { return this.redisNamespace; } public void setFlushMode(FlushMode flushMode) { Assert.notNull(flushMode, "flushMode must not be null"); this.flushMode = flushMode; } protected FlushMode getFlushMode() { return this.flushMode; } public void setSaveMode(SaveMode saveMode) { Assert.notNull(saveMode, "saveMode must not be null"); this.saveMode = saveMode; } protected SaveMode getSaveMode() { return this.saveMode; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<RedisConnectionFactory> redisConnectionFactory) { this.redisConnectionFactory = springSessionRedisConnectionFactory .getIfAvailable(redisConnectionFactory::getObject); } protected RedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } protected RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer;
} @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected RedisTemplate<String, Object> createRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); if (getDefaultRedisSerializer() != null) { redisTemplate.setDefaultSerializer(getDefaultRedisSerializer()); } redisTemplate.setConnectionFactory(getRedisConnectionFactory()); redisTemplate.setBeanClassLoader(this.classLoader); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
2
请完成以下Java代码
private final JTable getTable() { final JTable table = tableRef.get(); Check.assumeNotNull(table, "table not null"); return table; } private final List<AnnotatedTableAction> getTableActions() { final List<AnnotatedTableAction> tableActions = new ArrayList<>(); for (final MenuElement me : getSubElements()) { if (!(me instanceof AbstractButton)) { continue; } final AbstractButton button = (AbstractButton)me; final Action action = button.getAction(); if (action instanceof AnnotatedTableAction) {
final AnnotatedTableAction tableAction = (AnnotatedTableAction)action; tableActions.add(tableAction); } } return tableActions; } private final void popupMenuWillBecomeVisible(final PopupMenuEvent e) { for (final AnnotatedTableAction tableAction : getTableActions()) { tableAction.setTable(getTable()); tableAction.updateBeforeDisplaying(); } } private final void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { // nothing atm } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTablePopupMenu.java
1
请完成以下Java代码
public void setC_Project_Label_ID (final int C_Project_Label_ID) { if (C_Project_Label_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_Label_ID, C_Project_Label_ID); } @Override public int getC_Project_Label_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_Label_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override
public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setNote (final @Nullable java.lang.String Note) { set_Value (COLUMNNAME_Note, Note); } @Override public java.lang.String getNote() { return get_ValueAsString(COLUMNNAME_Note); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Label.java
1
请完成以下Java代码
public boolean isUpdateable () { Object oo = get_Value(COLUMNNAME_IsUpdateable); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); }
/** Set Max. Value. @param ValueMax Maximum Value for a field */ public void setValueMax (String ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } /** Get Max. Value. @return Maximum Value for a field */ public String getValueMax () { return (String)get_Value(COLUMNNAME_ValueMax); } /** Set Min. Value. @param ValueMin Minimum Value for a field */ public void setValueMin (String ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } /** Get Min. Value. @return Minimum Value for a field */ public String getValueMin () { return (String)get_Value(COLUMNNAME_ValueMin); } /** Set Value Format. @param VFormat Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public void setVFormat (String VFormat) { set_Value (COLUMNNAME_VFormat, VFormat); } /** Get Value Format. @return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09" */ public String getVFormat () { return (String)get_Value(COLUMNNAME_VFormat); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attribute.java
1
请在Spring Boot框架中完成以下Java代码
public List<HistoryJob> findHistoryJobsByQueryCriteria(HistoryJobQueryImpl jobQuery) { final String query = "selectHistoryJobByQueryCriteria"; return getDbSqlSession().selectList(query, jobQuery); } @Override public long findHistoryJobCountByQueryCriteria(HistoryJobQueryImpl jobQuery) { return (Long) getDbSqlSession().selectOne("selectHistoryJobCountByQueryCriteria", jobQuery); } @Override public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) { HashMap<String, Object> params = new HashMap<>(); params.put("deploymentId", deploymentId); params.put("tenantId", newTenantId); getDbSqlSession().directUpdate("updateHistoryJobTenantIdForDeployment", params); } @Override public void bulkUpdateJobLockWithoutRevisionCheck(List<HistoryJobEntity> historyJobs, String lockOwner, Date lockExpirationTime) { Map<String, Object> params = new HashMap<>(3); params.put("lockOwner", lockOwner); params.put("lockExpirationTime", lockExpirationTime);
bulkUpdateEntities("updateHistoryJobLocks", params, "historyJobs", historyJobs); } @Override public void resetExpiredJob(String jobId) { Map<String, Object> params = new HashMap<>(2); params.put("id", jobId); getDbSqlSession().directUpdate("resetExpiredHistoryJob", params); } @Override protected IdGenerator getIdGenerator() { return jobServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisHistoryJobDataManager.java
2
请完成以下Java代码
public void setPointsBase_Invoiceable (final BigDecimal PointsBase_Invoiceable) { set_Value (COLUMNNAME_PointsBase_Invoiceable, PointsBase_Invoiceable); } @Override public BigDecimal getPointsBase_Invoiceable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiceable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPointsBase_Invoiced (final BigDecimal PointsBase_Invoiced) { set_Value (COLUMNNAME_PointsBase_Invoiced, PointsBase_Invoiced); } @Override public BigDecimal getPointsBase_Invoiced() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PointsBase_Invoiced); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Instance.java
1
请完成以下Java代码
public void destroy() throws Exception { System.out.println("接口-执行InitBeanAndDestroyBeanTest:destroy方法"); } /** * Bean所有属性设置完(初始化完)之后调用 * * @throws Exception Exception */ @Override public void afterPropertiesSet() throws Exception { System.out.println("接口-执行InitBeanAndDestroyBeanTest:afterPropertiesSet方法"); } @PostConstruct public void postConstructstroy() { System.out.println("注解-执行InitBeanAndDestroyBeanTest:preDestroy方法"); } @PreDestroy public void preDestroy() {
System.out.println("注解--执行InitBeanAndDestroyBeanTest:preDestroy方法"); } /** * 真正的Bean初始化方法 */ public void initMethod() { System.out.println("XML配置-执行InitBeanAndDestroyBeanTest:init-method方法"); } /** * 真正的Bean销毁方法 */ public void destroyMethod() { System.out.println("XML配置-执行InitBeanAndDestroyBeanTest:destroy-method方法"); } }
repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\init\destory\InitBeanAndDestroyBean.java
1
请在Spring Boot框架中完成以下Java代码
public StaticResourceRequestMatcher excluding(StaticResourceLocation first, StaticResourceLocation... rest) { return excluding(EnumSet.of(first, rest)); } /** * Return a new {@link StaticResourceRequestMatcher} based on this one but * excluding the specified locations. * @param locations the locations to exclude * @return a new {@link StaticResourceRequestMatcher} */ public StaticResourceRequestMatcher excluding(Set<StaticResourceLocation> locations) { Assert.notNull(locations, "'locations' must not be null"); Set<StaticResourceLocation> subset = new LinkedHashSet<>(this.locations); subset.removeAll(locations); return new StaticResourceRequestMatcher(subset); } @Override protected void initialized(Supplier<DispatcherServletPath> dispatcherServletPath) { this.delegate = new OrRequestMatcher(getDelegateMatchers(dispatcherServletPath.get()).toList()); } private Stream<RequestMatcher> getDelegateMatchers(DispatcherServletPath dispatcherServletPath) { return getPatterns(dispatcherServletPath).map(PathPatternRequestMatcher.withDefaults()::matcher); } private Stream<String> getPatterns(DispatcherServletPath dispatcherServletPath) { return this.locations.stream() .flatMap(StaticResourceLocation::getPatterns) .map(dispatcherServletPath::getRelativePath); }
@Override protected boolean ignoreApplicationContext(WebApplicationContext applicationContext) { return hasServerNamespace(applicationContext, "management"); } @Override protected boolean matches(HttpServletRequest request, Supplier<DispatcherServletPath> context) { RequestMatcher delegate = this.delegate; Assert.state(delegate != null, "'delegate' must not be null"); return delegate.matches(request); } } }
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\StaticResourceRequest.java
2
请完成以下Java代码
public CompanyType getCompany() { return company; } /** * Sets the value of the company property. * * @param value * allowed object is * {@link CompanyType } * */ public void setCompany(CompanyType value) { this.company = value; } /** * Gets the value of the person property. * * @return * possible object is * {@link PersonType } * */ public PersonType getPerson() { return person; } /** * Sets the value of the person property. * * @param value * allowed object is * {@link PersonType } * */ public void setPerson(PersonType value) { this.person = value; } /** * Gets the value of the eanParty property. * * @return * possible object is * {@link String } * */ public String getEanParty() { return eanParty; } /** * Sets the value of the eanParty property. * * @param value * allowed object is * {@link String } * */ public void setEanParty(String value) { this.eanParty = value; } /** * Gets the value of the zsr property. * * @return * possible object is * {@link String } * */ public String getZsr() { return zsr;
} /** * Sets the value of the zsr property. * * @param value * allowed object is * {@link String } * */ public void setZsr(String value) { this.zsr = value; } /** * Gets the value of the specialty property. * * @return * possible object is * {@link String } * */ public String getSpecialty() { return specialty; } /** * Sets the value of the specialty property. * * @param value * allowed object is * {@link String } * */ public void setSpecialty(String value) { this.specialty = value; } /** * Gets the value of the uidNumber property. * * @return * possible object is * {@link String } * */ public String getUidNumber() { return uidNumber; } /** * Sets the value of the uidNumber property. * * @param value * allowed object is * {@link String } * */ public void setUidNumber(String value) { this.uidNumber = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BillerAddressType.java
1
请完成以下Java代码
public void setDataEntry_ListValue_ID (int DataEntry_ListValue_ID) { if (DataEntry_ListValue_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_ListValue_ID, Integer.valueOf(DataEntry_ListValue_ID)); } /** Get Eingabefeldwert. @return Eingabefeldwert */ @Override public int getDataEntry_ListValue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_ListValue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override 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); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @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\de\metas\dataentry\model\X_DataEntry_ListValue.java
1
请完成以下Java代码
public int getAD_Table_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Exclude Attribute Set. @param M_AttributeSetExclude_ID Exclude the ability to enter Attribute Sets */ public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID) { if (M_AttributeSetExclude_ID < 1) set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID)); } /** Get Exclude Attribute Set. @return Exclude the ability to enter Attribute Sets */ public int getM_AttributeSetExclude_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_AttributeSet getM_AttributeSet() throws RuntimeException
{ return (I_M_AttributeSet)MTable.get(getCtx(), I_M_AttributeSet.Table_Name) .getPO(getM_AttributeSet_ID(), get_TrxName()); } /** Set Attribute Set. @param M_AttributeSet_ID Product Attribute Set */ public void setM_AttributeSet_ID (int M_AttributeSet_ID) { if (M_AttributeSet_ID < 0) set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null); else set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, Integer.valueOf(M_AttributeSet_ID)); } /** Get Attribute Set. @return Product Attribute Set */ public int getM_AttributeSet_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSet_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSetExclude.java
1
请在Spring Boot框架中完成以下Java代码
public Integer del() { // redisTemplate. return null; } @Override public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } @Override public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } private static String name_sex = ""; public static int getNum(int start,int end) { return (int)(Math.random()*(end-start+1)+start); } private static String getChineseName() { int index=getNum(0, firstName.length()-1); String first=firstName.substring(index, index+1); int sex=getNum(0,1); String str=boy; int length=boy.length(); if(sex==0){ str=girl;
length=girl.length(); name_sex = "女"; }else { name_sex="男"; } index=getNum(0,length-1); String second=str.substring(index, index+1); int hasThird=getNum(0,1); String third=""; if(hasThird==1){ index=getNum(0,length-1); third=str.substring(index, index+1); } return first+second+third; } }
repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\service\impl\CompanyServiceImpl.java
2
请完成以下Java代码
final InvoiceCandRecomputeTag getRecomputeTag() { Check.assumeNotNull(_recomputeTag, "_recomputeTag not null"); return _recomputeTag; } @Override public InvoiceCandRecomputeTagger setLockedBy(final ILock lockedBy) { this._lockedBy = lockedBy; return this; } /* package */ILock getLockedBy() { return _lockedBy; } @Override public InvoiceCandRecomputeTagger setTaggedWith(@Nullable final InvoiceCandRecomputeTag tag) { _taggedWith = tag; return this; } @Override public InvoiceCandRecomputeTagger setTaggedWithNoTag() { return setTaggedWith(InvoiceCandRecomputeTag.NULL); } @Override public IInvoiceCandRecomputeTagger setTaggedWithAnyTag() { return setTaggedWith(null); } /* package */ @Nullable InvoiceCandRecomputeTag getTaggedWith() {
return _taggedWith; } @Override public InvoiceCandRecomputeTagger setLimit(final int limit) { this._limit = limit; return this; } /* package */int getLimit() { return _limit; } @Override public void setOnlyInvoiceCandidateIds(@NonNull final InvoiceCandidateIdsSelection onlyInvoiceCandidateIds) { this.onlyInvoiceCandidateIds = onlyInvoiceCandidateIds; } @Override @Nullable public final InvoiceCandidateIdsSelection getOnlyInvoiceCandidateIds() { return onlyInvoiceCandidateIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandRecomputeTagger.java
1
请在Spring Boot框架中完成以下Java代码
public class UITraceRepository { @NonNull private static final Logger logger = LogManager.getLogger(UITraceRepository.class); @NonNull private final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); public void create(@NonNull final Collection<UITraceEventCreateRequest> requests) { for (final UITraceEventCreateRequest request : requests) { final I_UI_Trace record = InterfaceWrapperHelper.newInstance(I_UI_Trace.class); updateRecord(record, request); InterfaceWrapperHelper.save(record); } } private void updateRecord(final I_UI_Trace record, final UITraceEventCreateRequest from) { record.setExternalId(from.getId().getAsString()); record.setEventName(from.getEventName()); record.setTimestamp(Timestamp.from(from.getTimestamp())); record.setURL(from.getUrl()); record.setUserName(from.getUsername()); record.setCaption(from.getCaption()); record.setUI_ApplicationId(from.getApplicationId() != null ? from.getApplicationId().getAsString() : null); record.setUI_DeviceId(from.getDeviceId()); record.setUI_TabId(from.getTabId()); record.setUserAgent(from.getUserAgent()); record.setEventData(extractPropertiesAsJsonString(from)); } private String extractPropertiesAsJsonString(final UITraceEventCreateRequest request) { final Map<String, Object> properties = request.getProperties();
if (properties == null) { return ""; } try { return jsonObjectMapper.writeValueAsString(properties); } catch (JsonProcessingException e) { logger.warn("Failed converting request's properties to string: {}", request, e); return properties.toString(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui_trace\UITraceRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class Order { @Id private String orderId; private String productId; @Max(5) private Long amount; public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; }
public String getProductId() { return productId; } public void setProductId(String productId) { this.productId = productId; } public Long getAmount() { return amount; } public void setAmount(Long amount) { this.amount = amount; } }
repos\tutorials-master\persistence-modules\atomikos\src\main\java\com\baeldung\atomikos\spring\jpa\order\Order.java
2
请完成以下Java代码
private PO getParentPO() { final PO parentPO = parentPORef.get(); if (parentPO == null) { // cleanup this.poRef = null; // throw exception throw new AdempiereException("Parent PO reference expired"); } return parentPO; } @Override protected Properties getParentCtx() { return getParentPO().getCtx(); } @Override protected String getParentTrxName() { return getParentPO().get_TrxName(); } @Override
protected int getId() { final PO parentPO = getParentPO(); final String parentColumnName = getParentColumnName(); return parentPO.get_ValueAsInt(parentColumnName); } @Override protected boolean setId(final int id) { final PO parentPO = getParentPO(); final Integer value = id < 0 ? null : id; final String parentColumnName = getParentColumnName(); final boolean ok = parentPO.set_ValueOfColumn(parentColumnName, value); if (!ok) { logger.warn("Cannot set " + parentColumnName + "=" + id + " to " + parentPO); } return ok; } public POCacheLocal copy(@NonNull final PO parentPO) { final POCacheLocal poCacheLocalNew = newInstance(parentPO, getParentColumnName(), getTableName()); poCacheLocalNew.poRef = this.poRef; return poCacheLocalNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\POCacheLocal.java
1
请完成以下Java代码
private void printHULabelsIfNeeded(final List<I_M_HU> createdHUs) { final InventoryDocSubType inventoryDocSubType = InventoryDocSubType.of(inventory.getDocBaseAndSubType()); if (!inventoryDocSubType.isActualPhysicalInventory()) {return;} huLabelService.print( HULabelPrintRequest.builder() .sourceDocType(HULabelSourceDocType.Inventory) .hus(HUToReportWrapper.ofList(createdHUs)) .onlyIfAutoPrint(true) .failOnMissingLabelConfig(false) .build() ); } private I_M_InventoryLine getInventoryLineRecordFor(final @NotNull InventoryLine inventoryLine) { final InventoryAndLineId inventoryAndLineId = InventoryAndLineId.of(inventory.getId(), inventoryLine.getIdNonNull()); final I_M_InventoryLine inventoryLineRecord = inventoryLineRecords.get(inventoryAndLineId); if (inventoryLineRecord == null) { throw new AdempiereException("No inventory line found for " + inventoryAndLineId); } return inventoryLineRecord; } private IAllocationDestination createAllocationDestination(final @NonNull InventoryLine inventoryLine, final @NonNull InventoryLineHU inventoryLineHU) { if (inventoryLineHU.getHuId() == null) { if (inventoryLineHU.getHuQRCode() != null) { return HUProducerDestination.of(inventoryLineHU.getHuQRCode().getPackingInstructionsId()) .setHUStatus(X_M_HU.HUSTATUS_Active) .setLocatorId(inventoryLine.getLocatorId()); } else { final InventoryLinePackingInstructions packingInstructions = inventoryLine.getPackingInstructions(); if (packingInstructions.isVHU()) { return HUProducerDestination.ofVirtualPI() .setHUStatus(X_M_HU.HUSTATUS_Active) .setLocatorId(inventoryLine.getLocatorId()); } else { final LUTUProducerDestination lutuProducer = new LUTUProducerDestination(); lutuProducer.setHUStatus(X_M_HU.HUSTATUS_Active); lutuProducer.setLocatorId(inventoryLine.getLocatorId()); lutuProducer.setTUPI(packingInstructions.getTuPIItemProductId(), inventoryLine.getProductId());
if (packingInstructions.getLuPIId() != null) { lutuProducer.setLUPI(packingInstructions.getLuPIId()); lutuProducer.setMaxLUsInfinite(); } else { lutuProducer.setNoLU(); } return lutuProducer; } } } else { final I_M_HU hu = handlingUnitsBL.getById(inventoryLineHU.getHuId()); return HUListAllocationSourceDestination.of(hu, AllocationStrategyType.UNIFORM); } } private static List<I_M_HU> extractCreatedHUs( @NonNull final IAllocationDestination huDestination) { if (huDestination instanceof IHUProducerAllocationDestination) { return ((IHUProducerAllocationDestination)huDestination).getCreatedHUs(); } else { throw new HUException("No HU was created by " + huDestination); } } private boolean isIgnoreOnInventoryMinusAndNoHU() { return sysConfigBL.getBooleanValue(SYSCONFIG_IgnoreOnInventoryMinusAndNoHU, false); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\impl\SyncInventoryQtyToHUsCommand.java
1
请在Spring Boot框架中完成以下Java代码
ReactiveJwtAuthenticationConverter reactiveJwtAuthenticationConverter() { JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter(); PropertyMapper map = PropertyMapper.get(); map.from(this.properties.getAuthorityPrefix()).to(grantedAuthoritiesConverter::setAuthorityPrefix); map.from(this.properties.getAuthoritiesClaimDelimiter()) .to(grantedAuthoritiesConverter::setAuthoritiesClaimDelimiter); map.from(this.properties.getAuthoritiesClaimName()) .to(grantedAuthoritiesConverter::setAuthoritiesClaimName); ReactiveJwtAuthenticationConverter jwtAuthenticationConverter = new ReactiveJwtAuthenticationConverter(); map.from(this.properties.getPrincipalClaimName()).to(jwtAuthenticationConverter::setPrincipalClaimName); jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter( new ReactiveJwtGrantedAuthoritiesConverterAdapter(grantedAuthoritiesConverter)); return jwtAuthenticationConverter; } } @Configuration(proxyBeanMethods = false) @ConditionalOnMissingBean(SecurityWebFilterChain.class) static class WebSecurityConfiguration { @Bean @ConditionalOnBean(ReactiveJwtDecoder.class) SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http, ReactiveJwtDecoder jwtDecoder) { http.authorizeExchange((exchanges) -> exchanges.anyExchange().authenticated()); http.oauth2ResourceServer((server) -> customDecoder(server, jwtDecoder)); return http.build(); } private void customDecoder(OAuth2ResourceServerSpec server, ReactiveJwtDecoder decoder) { server.jwt((jwt) -> jwt.jwtDecoder(decoder)); } } private static class JwtConverterPropertiesCondition extends AnyNestedCondition {
JwtConverterPropertiesCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authority-prefix") static class OnAuthorityPrefix { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.principal-claim-name") static class OnPrincipalClaimName { } @ConditionalOnProperty("spring.security.oauth2.resourceserver.jwt.authorities-claim-name") static class OnAuthoritiesClaimName { } } }
repos\spring-boot-4.0.1\module\spring-boot-security-oauth2-resource-server\src\main\java\org\springframework\boot\security\oauth2\server\resource\autoconfigure\reactive\ReactiveOAuth2ResourceServerJwkConfiguration.java
2
请完成以下Java代码
private VendorReturnsInOutProducer createVendorReturnInOutProducer(final BPartnerId bpartnerId, final WarehouseId warehouseId, final I_C_Order originOrder) { final IBPartnerDAO bpartnerDAO = Services.get(IBPartnerDAO.class); final Properties ctx = Env.getCtx(); final I_C_BPartner partner = Services.get(IBPartnerDAO.class).getById(bpartnerId); final I_C_BPartner_Location shipFromLocation = bpartnerDAO.retrieveShipToLocation(ctx, bpartnerId.getRepoId(), ITrx.TRXNAME_None); final I_M_Warehouse warehouse = Services.get(IWarehouseDAO.class).getById(warehouseId); final VendorReturnsInOutProducer producer = VendorReturnsInOutProducer.newInstance(); producer.setC_BPartner(partner); producer.setC_BPartner_Location(shipFromLocation); producer.setMovementType(X_M_Transaction.MOVEMENTTYPE_VendorReturns); producer.setM_Warehouse(warehouse); producer.setMovementDate(getMovementDate()); producer.setC_Order(originOrder); return producer; } public MultiVendorHUReturnsInOutProducer setMovementDate(final Timestamp movementDate) { _movementDate = movementDate; return this; }
private Timestamp getMovementDate() { if (_movementDate == null) { _movementDate = Env.getDate(); // use login date by default } return _movementDate; } private final List<I_M_HU> getHUsToReturn() { return _husToReturn; } public MultiVendorHUReturnsInOutProducer addHUsToReturn(final List<I_M_HU> hus) { _husToReturn.addAll(hus); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\vendor\MultiVendorHUReturnsInOutProducer.java
1
请在Spring Boot框架中完成以下Java代码
protected void toString(final MoreObjects.ToStringHelper toStringHelper) { toStringHelper .add("email", email) .add("language", language) // WARNING: never ever output the password ; } public Long getBpartnerId() { return getBpartner().getId(); } public BPartner getBpartner() { return bpartner; } public void setBpartner(final BPartner bpartner) { this.bpartner = bpartner; } public String getEmail() { return email; } public void setEmail(final String email) { this.email = email; } public void setLanguage(final String language) { this.language = language; } public String getLanguage() { return language; } public LanguageKey getLanguageKeyOrDefault() { final LanguageKey languageKey = LanguageKey.ofNullableString(getLanguage()); return languageKey != null ? languageKey : LanguageKey.getDefault(); } public String getPassword() { return password; } public void setPassword(final String password) {
this.password = password; } @Nullable public String getPasswordResetKey() { return passwordResetKey; } public void setPasswordResetKey(@Nullable final String passwordResetKey) { this.passwordResetKey = passwordResetKey; } public void markDeleted() { setDeleted(true); deleted_id = getId(); // FRESH-176: set the delete_id to current ID just to avoid the unique constraint } public void markNotDeleted() { setDeleted(false); deleted_id = null; // FRESH-176: set the delete_id to NULL just to make sure the the unique index is enforced } @Nullable @VisibleForTesting public Long getDeleted_id() { return deleted_id; } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\User.java
2
请完成以下Java代码
public String getType() { return type; } public void setType(String type) { this.type = type; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result;
} @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (id != other.id) return false; return true; } @Override public String toString() { return MessageFormat.format("id:{0}, name:{1}, active:{2}, type:{3}", id, name, active, type); } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicupdate\model\Account.java
1
请完成以下Java代码
public class UserDTO { @NotBlank(message = "{user.name.notblank}") private String name; @Email(message = "{user.email.invalid}") private String email; @Min(value = 18, message = "{user.age.min}") private int age; // Getters and setters public String getName() { return name; } public void setName(String name) { this.name = name; }
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\spring-boot-modules\spring-boot-custom-validation\src\main\java\com\baeldung\validation\custommessage\UserDTO.java
1
请完成以下Java代码
default String getValueAsString(@NonNull final String attributeKey) { return getValueAsString(AttributeCode.ofString(attributeKey)); } @Nullable default String getValueAsString(@NonNull final I_M_Attribute attribute) { return getValueAsString(AttributeCode.ofString(attribute.getValue())); } @Nullable default AttributeValueId getAttributeValueIdOrNull(final AttributeCode attributeCode) { return null; } default boolean isValueSet(final Attribute attribute) { if (!hasAttribute(attribute)) { return false; } final String value = getValueAsStringOrNull(attribute.getAttributeCode()); return value != null && !Check.isBlank(value); } /** * Set attribute's value and propagate to its parent/child attribute sets. * * @throws AttributeNotFoundException if given attribute was not found or is not supported */ void setValue(AttributeCode attributeCode, Object value); default void setValue(@NonNull final String attribute, final Object value) {
setValue(AttributeCode.ofString(attribute), value); } void setValue(AttributeId attributeId, Object value); default void setValue(final @NonNull I_M_Attribute attribute, final Object value) { setValue(attribute.getValue(), value); } /** * @return {@link IAttributeValueCallout} instance; never return null */ IAttributeValueCallout getAttributeValueCallout(final I_M_Attribute attribute); /** * @return true if the given <code>attribute</code>'s value was newly generated */ boolean isNew(final I_M_Attribute attribute); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\IAttributeSet.java
1
请完成以下Java代码
public Void execute(CommandContext context) { checkAuthorization(context); ensureNotNull(BadUserRequestException.class, "decisionDefinitionId", decisionDefinitionId); if (historyTimeToLive != null) { ensureGreaterThanOrEqual(BadUserRequestException.class, "", "historyTimeToLive", historyTimeToLive, 0); } validate(historyTimeToLive, context); DecisionDefinitionEntity decisionDefinitionEntity = context.getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId); logUserOperation(context, decisionDefinitionEntity); decisionDefinitionEntity.setHistoryTimeToLive(historyTimeToLive); return null; } protected void checkAuthorization(CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateDecisionDefinitionById(decisionDefinitionId); } }
protected void logUserOperation(CommandContext commandContext, DecisionDefinitionEntity decisionDefinitionEntity) { List<PropertyChange> propertyChanges = new ArrayList<>(); propertyChanges.add(new PropertyChange("historyTimeToLive", decisionDefinitionEntity.getHistoryTimeToLive(), historyTimeToLive)); propertyChanges.add(new PropertyChange("decisionDefinitionId", null, decisionDefinitionId)); propertyChanges.add(new PropertyChange("decisionDefinitionKey", null, decisionDefinitionEntity.getKey())); commandContext.getOperationLogManager() .logDecisionDefinitionOperation(UserOperationLogEntry.OPERATION_TYPE_UPDATE_HISTORY_TIME_TO_LIVE, decisionDefinitionEntity.getTenantId(), propertyChanges); } protected void validate(Integer historyTimeToLive, CommandContext context) { HistoryTimeToLiveParser parser = HistoryTimeToLiveParser.create(context); parser.validate(historyTimeToLive); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateDecisionDefinitionHistoryTimeToLiveCmd.java
1
请完成以下Java代码
public BranchAndFinancialInstitutionIdentification4 getIssgAgt() { return issgAgt; } /** * Sets the value of the issgAgt property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public void setIssgAgt(BranchAndFinancialInstitutionIdentification4 value) { this.issgAgt = value; } /** * Gets the value of the sttlmPlc property. * * @return * possible object is * {@link BranchAndFinancialInstitutionIdentification4 } * */ public BranchAndFinancialInstitutionIdentification4 getSttlmPlc() { return sttlmPlc; } /** * Sets the value of the sttlmPlc property. * * @param value * allowed object is * {@link BranchAndFinancialInstitutionIdentification4 } * */
public void setSttlmPlc(BranchAndFinancialInstitutionIdentification4 value) { this.sttlmPlc = value; } /** * Gets the value of the prtry 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 prtry property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPrtry().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ProprietaryAgent2 } * * */ public List<ProprietaryAgent2> getPrtry() { if (prtry == null) { prtry = new ArrayList<ProprietaryAgent2>(); } return this.prtry; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TransactionAgents2.java
1
请完成以下Java代码
public static <K, V, K2> Function<Map.Entry<K, V>, ImmutableMapEntry<K2, V>> mapKey(@NonNull final Function<K, K2> keyMapper) { return entry -> entry(keyMapper.apply(entry.getKey()), entry.getValue()); } public static <K, V, V2> Function<Map.Entry<K, V>, ImmutableMapEntry<K, V2>> mapValue(@NonNull final Function<V, V2> valueMapper) { return entry -> entry(entry.getKey(), valueMapper.apply(entry.getValue())); } public static <T, R> Collector<T, ?, R> collectUsingListAccumulator(@NonNull final Function<List<T>, R> finisher) { final Supplier<List<T>> supplier = ArrayList::new; final BiConsumer<List<T>, T> accumulator = List::add; final BinaryOperator<List<T>> combiner = (acc1, acc2) -> { acc1.addAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R> Collector<T, ?, R> collectUsingHashSetAccumulator(@NonNull final Function<HashSet<T>, R> finisher) { final Supplier<HashSet<T>> supplier = HashSet::new; final BiConsumer<HashSet<T>, T> accumulator = HashSet::add; final BinaryOperator<HashSet<T>> combiner = (acc1, acc2) -> { acc1.addAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R, K> Collector<T, ?, R> collectUsingMapAccumulator(@NonNull final Function<T, K> keyMapper, @NonNull final Function<Map<K, T>, R> finisher) { final Supplier<Map<K, T>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, T>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), item); final BinaryOperator<Map<K, T>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; };
return Collector.of(supplier, accumulator, combiner, finisher); } public static <T, R, K, V> Collector<T, ?, R> collectUsingMapAccumulator( @NonNull final Function<T, K> keyMapper, @NonNull final Function<T, V> valueMapper, @NonNull final Function<Map<K, V>, R> finisher) { final Supplier<Map<K, V>> supplier = LinkedHashMap::new; final BiConsumer<Map<K, V>, T> accumulator = (map, item) -> map.put(keyMapper.apply(item), valueMapper.apply(item)); final BinaryOperator<Map<K, V>> combiner = (acc1, acc2) -> { acc1.putAll(acc2); return acc1; }; return Collector.of(supplier, accumulator, combiner, finisher); } public static <R, K, V> Collector<Map.Entry<K, V>, ?, R> collectUsingMapAccumulator(@NonNull final Function<Map<K, V>, R> finisher) { return collectUsingMapAccumulator(Map.Entry::getKey, Map.Entry::getValue, finisher); } public static <T> Collector<T, ?, Optional<ImmutableSet<T>>> toOptionalImmutableSet() { return Collectors.collectingAndThen( ImmutableSet.toImmutableSet(), set -> !set.isEmpty() ? Optional.of(set) : Optional.empty()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GuavaCollectors.java
1
请完成以下Java代码
public abstract class HUIteratorListenerAdapter implements IHUIteratorListener { private Result _defaultResult = Result.CONTINUE; private IHUIterator iterator = null; // we don't allow direct instantiation protected HUIteratorListenerAdapter() { init(); } /** * Method called when this object is constructed * * To be extended by implementors */ protected void init() { // nothing } public void setDefaultResult(@NonNull final Result defaultResult) { _defaultResult = defaultResult; } /** * Gets default result to be returned by all methods which were not implemented by extending class. * * @return default result * @see #setDefaultResult(de.metas.handlingunits.IHUIteratorListener.Result) */ protected Result getDefaultResult() { return _defaultResult; } @Override public void setHUIterator(final IHUIterator iterator) { if (this.iterator != null && iterator != null && this.iterator != iterator) { throw new AdempiereException("Changing the iterator from " + this.iterator + " to " + iterator + " is not allowed for " + this + "." + " You need to explicitelly set it to null first and then set it again."); } this.iterator = iterator; } public final IHUIterator getHUIterator() { return iterator; }
@Override public Result beforeHU(final IMutable<I_M_HU> hu) { return getDefaultResult(); } @Override public Result afterHU(final I_M_HU hu) { return getDefaultResult(); } @Override public Result beforeHUItem(final IMutable<I_M_HU_Item> item) { return getDefaultResult(); } @Override public Result afterHUItem(final I_M_HU_Item item) { return getDefaultResult(); } @Override public Result beforeHUItemStorage(final IMutable<IHUItemStorage> itemStorage) { return getDefaultResult(); } @Override public Result afterHUItemStorage(final IHUItemStorage itemStorage) { return getDefaultResult(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUIteratorListenerAdapter.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) { this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; } public boolean isAllowComments() { return this.allowComments; } public void setAllowComments(boolean allowComments) { this.allowComments = allowComments;
} /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
public String getExternalSystemValue() { return get_ValueAsString(COLUMNNAME_ExternalSystemValue); } @Override public void setIsPluFileExportAuditEnabled (final boolean IsPluFileExportAuditEnabled) { set_Value (COLUMNNAME_IsPluFileExportAuditEnabled, IsPluFileExportAuditEnabled); } @Override public boolean isPluFileExportAuditEnabled() { return get_ValueAsBoolean(COLUMNNAME_IsPluFileExportAuditEnabled); } /** * PluFileDestination AD_Reference_ID=541911 * Reference name: PluFileDestination */ public static final int PLUFILEDESTINATION_AD_Reference_ID=541911; /** Disk = 2DSK */ public static final String PLUFILEDESTINATION_Disk = "2DSK"; /** TCP = 1TCP */ public static final String PLUFILEDESTINATION_TCP = "1TCP"; @Override public void setPluFileDestination (final java.lang.String PluFileDestination) { set_Value (COLUMNNAME_PluFileDestination, PluFileDestination); } @Override public java.lang.String getPluFileDestination() { return get_ValueAsString(COLUMNNAME_PluFileDestination); } @Override public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder) { set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder); } @Override public java.lang.String getPluFileLocalFolder() { return get_ValueAsString(COLUMNNAME_PluFileLocalFolder); } @Override public void setProduct_BaseFolderName (final String Product_BaseFolderName) { set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName); }
@Override public String getProduct_BaseFolderName() { return get_ValueAsString(COLUMNNAME_Product_BaseFolderName); } @Override public void setTCP_Host (final String TCP_Host) { set_Value (COLUMNNAME_TCP_Host, TCP_Host); } @Override public String getTCP_Host() { return get_ValueAsString(COLUMNNAME_TCP_Host); } @Override public void setTCP_PortNumber (final int TCP_PortNumber) { set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber); } @Override public int getTCP_PortNumber() { return get_ValueAsInt(COLUMNNAME_TCP_PortNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java
1
请完成以下Java代码
public I_M_HU_PI getTuPI() { return tuPIItem.getM_HU_PI_Version().getM_HU_PI(); } @Override public I_M_HU_PI_Item getLuPIItem() { return luPIItem; } @Override public I_M_HU_PI getLuPI() { return luPIItem.getM_HU_PI_Version().getM_HU_PI(); } @Override public ProductId getCuProductId() { return cuProductId; } @Override public I_C_UOM getCuUOM() { return cuUOM; } @Override public BigDecimal getCuPerTU() {
return cuPerTU; } @Override public BigDecimal getTuPerLU() { return tuPerLU; } @Override public BigDecimal getMaxLUToAllocate() { return maxLUToAllocate; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\HUSplitDefinition.java
1
请完成以下Spring Boot application配置
ms.db.driverClassName=com.mysql.jdbc.Driver ms.db.url=jdbc:mysql://localhost:3306/cache?prepStmtCacheSize=517&cachePrepStmts=true&autoReconnect=true&useUnicode=true&characterEncoding=utf-8&useSSL=false&allowMultiQueries=true ms.db.username=root ms.db.password=admin ms.db.maxActive=500 #最多缓存 500 条 ,缓存在 30
分钟后失效 #spring.cache.guava.spec= maximumSize=500,expireAfterWrite=30m #redis.hostname=xxxxxx redis.hostname=xxxxxx redis.port=6379
repos\springBoot-master\springboot-Cache\src\main\resources\application.properties
2
请完成以下Java代码
private MailTextBuilder createMailTextBuilder(final I_C_RfQResponse rfqResponse, final RfQReportType rfqReportType) { final I_C_RfQ_Topic rfqTopic = rfqResponse.getC_RfQ().getC_RfQ_Topic(); final MailTextBuilder mailTextBuilder; if (rfqReportType == RfQReportType.Invitation) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Invitation_MailText_ID())); } else if (rfqReportType == RfQReportType.InvitationWithoutQtyRequired) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_InvitationWithoutQty_MailText_ID())); } else if (rfqReportType == RfQReportType.Won) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Win_MailText_ID()));
} else if (rfqReportType == RfQReportType.Lost) { mailTextBuilder = mailService.newMailTextBuilder(MailTemplateId.ofRepoId(rfqTopic.getRfQ_Lost_MailText_ID())); } else { throw new AdempiereException("@Invalid@ @Type@: " + rfqReportType); } mailTextBuilder.bpartner(rfqResponse.getC_BPartner()); mailTextBuilder.bpartnerContact(rfqResponse.getAD_User()); mailTextBuilder.record(rfqResponse); return mailTextBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\MailRfqResponsePublisherInstance.java
1
请完成以下Java代码
public void associateConnection(Object connection) throws ResourceException { if (connection == null) { throw new ResourceException("Null connection handle"); } if (!(connection instanceof JcaExecutorServiceConnectionImpl)) { throw new ResourceException("Wrong connection handle"); } this.connection = (JcaExecutorServiceConnectionImpl) connection; } public void cleanup() throws ResourceException { // no-op } public void destroy() throws ResourceException { // no-op } public void addConnectionEventListener(ConnectionEventListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.add(listener); } public void removeConnectionEventListener(ConnectionEventListener listener) { if (listener == null) { throw new IllegalArgumentException("Listener is null"); } listeners.remove(listener); } void closeHandle(JcaExecutorServiceConnection handle) { ConnectionEvent event = new ConnectionEvent(this, ConnectionEvent.CONNECTION_CLOSED); event.setConnectionHandle(handle); for (ConnectionEventListener cel : listeners) { cel.connectionClosed(event); } } public PrintWriter getLogWriter() throws ResourceException { return logwriter; } public void setLogWriter(PrintWriter out) throws ResourceException { logwriter = out; }
public LocalTransaction getLocalTransaction() throws ResourceException { throw new NotSupportedException("LocalTransaction not supported"); } public XAResource getXAResource() throws ResourceException { throw new NotSupportedException("GetXAResource not supported not supported"); } public ManagedConnectionMetaData getMetaData() throws ResourceException { return null; } // delegate methods ///////////////////////////////////////// public boolean schedule(Runnable runnable, boolean isLongRunning) { return delegate.schedule(runnable, isLongRunning); } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return delegate.getExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnection.java
1
请完成以下Java代码
public String getHostname() { return hostname; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public String getBatchId() { return batchId; } public boolean isCreationLog() { return creationLog; } public boolean isFailureLog() { return failureLog; } public boolean isSuccessLog() { return successLog; } public boolean isDeletionLog() { return deletionLog; } public static HistoricJobLogDto fromHistoricJobLog(HistoricJobLog historicJobLog) { HistoricJobLogDto result = new HistoricJobLogDto(); result.id = historicJobLog.getId(); result.timestamp = historicJobLog.getTimestamp(); result.removalTime = historicJobLog.getRemovalTime(); result.jobId = historicJobLog.getJobId(); result.jobDueDate = historicJobLog.getJobDueDate(); result.jobRetries = historicJobLog.getJobRetries(); result.jobPriority = historicJobLog.getJobPriority(); result.jobExceptionMessage = historicJobLog.getJobExceptionMessage(); result.jobDefinitionId = historicJobLog.getJobDefinitionId(); result.jobDefinitionType = historicJobLog.getJobDefinitionType();
result.jobDefinitionConfiguration = historicJobLog.getJobDefinitionConfiguration(); result.activityId = historicJobLog.getActivityId(); result.failedActivityId = historicJobLog.getFailedActivityId(); result.executionId = historicJobLog.getExecutionId(); result.processInstanceId = historicJobLog.getProcessInstanceId(); result.processDefinitionId = historicJobLog.getProcessDefinitionId(); result.processDefinitionKey = historicJobLog.getProcessDefinitionKey(); result.deploymentId = historicJobLog.getDeploymentId(); result.tenantId = historicJobLog.getTenantId(); result.hostname = historicJobLog.getHostname(); result.rootProcessInstanceId = historicJobLog.getRootProcessInstanceId(); result.batchId = historicJobLog.getBatchId(); result.creationLog = historicJobLog.isCreationLog(); result.failureLog = historicJobLog.isFailureLog(); result.successLog = historicJobLog.isSuccessLog(); result.deletionLog = historicJobLog.isDeletionLog(); return result; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricJobLogDto.java
1
请完成以下Java代码
public class X_M_Product_Category_MaxNetAmount extends org.compiere.model.PO implements I_M_Product_Category_MaxNetAmount, org.compiere.model.I_Persistent { private static final long serialVersionUID = 1209190109L; /** Standard Constructor */ public X_M_Product_Category_MaxNetAmount (final Properties ctx, final int M_Product_Category_MaxNetAmount_ID, @Nullable final String trxName) { super (ctx, M_Product_Category_MaxNetAmount_ID, trxName); } /** Load Constructor */ public X_M_Product_Category_MaxNetAmount (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_Currency_ID (final int C_Currency_ID) { if (C_Currency_ID < 1) set_Value (COLUMNNAME_C_Currency_ID, null); else set_Value (COLUMNNAME_C_Currency_ID, C_Currency_ID); } @Override public int getC_Currency_ID() { return get_ValueAsInt(COLUMNNAME_C_Currency_ID); } @Override public void setMaxNetAmount (final BigDecimal MaxNetAmount) { set_Value (COLUMNNAME_MaxNetAmount, MaxNetAmount); } @Override public BigDecimal getMaxNetAmount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxNetAmount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_Product_Category_ID (final int M_Product_Category_ID) { if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID); } @Override public int getM_Product_Category_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID); } @Override public void setM_Product_Category_MaxNetAmount_ID (final int M_Product_Category_MaxNetAmount_ID) { if (M_Product_Category_MaxNetAmount_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Category_MaxNetAmount_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Category_MaxNetAmount_ID, M_Product_Category_MaxNetAmount_ID); } @Override public int getM_Product_Category_MaxNetAmount_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_Category_MaxNetAmount_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Category_MaxNetAmount.java
1
请完成以下Java代码
public static void set(HttpServletResponse response, String key, String value, boolean ifRemember) { int age = ifRemember?COOKIE_MAX_AGE:-1; set(response, key, value, null, COOKIE_PATH, age, true); } /** * 保存 * * @param response * @param key * @param value * @param maxAge */ private static void set(HttpServletResponse response, String key, String value, String domain, String path, int maxAge, boolean isHttpOnly) { Cookie cookie = new Cookie(key, value); if (domain != null) { cookie.setDomain(domain); } cookie.setPath(path); cookie.setMaxAge(maxAge); cookie.setHttpOnly(isHttpOnly); response.addCookie(cookie); } /** * 查询value * * @param request * @param key * @return */ public static String getValue(HttpServletRequest request, String key) { Cookie cookie = get(request, key); if (cookie != null) { return cookie.getValue(); } return null; } /**
* 查询Cookie * * @param request * @param key */ private static Cookie get(HttpServletRequest request, String key) { Cookie[] arr_cookie = request.getCookies(); if (arr_cookie != null && arr_cookie.length > 0) { for (Cookie cookie : arr_cookie) { if (cookie.getName().equals(key)) { return cookie; } } } return null; } /** * 删除Cookie * * @param request * @param response * @param key */ public static void remove(HttpServletRequest request, HttpServletResponse response, String key) { Cookie cookie = get(request, key); if (cookie != null) { set(response, key, "", null, COOKIE_PATH, 0, true); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\util\CookieUtil.java
1
请完成以下Java代码
public String toString() { return filterToStringCreator(SetStatusGatewayFilterFactory.this).append("status", config.getStatus()) .toString(); } }; } public @Nullable String getOriginalStatusHeaderName() { return originalStatusHeaderName; } public void setOriginalStatusHeaderName(String originalStatusHeaderName) { this.originalStatusHeaderName = originalStatusHeaderName; }
public static class Config { // TODO: relaxed HttpStatus converter private @Nullable String status; public @Nullable String getStatus() { return status; } public void setStatus(String status) { this.status = status; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetStatusGatewayFilterFactory.java
1
请在Spring Boot框架中完成以下Java代码
public void setCategory(String category) { this.category = category; categorySet = true; } public String getCategory() { return category; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; tenantIdSet = true; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; formKeySet = true; } public boolean isOwnerSet() { return ownerSet; } public boolean isAssigneeSet() { return assigneeSet; } public boolean isDelegationStateSet() { return delegationStateSet; } public boolean isNameSet() { return nameSet; } public boolean isDescriptionSet() { return descriptionSet; } public boolean isDuedateSet() {
return duedateSet; } public boolean isPrioritySet() { return prioritySet; } public boolean isParentTaskIdSet() { return parentTaskIdSet; } public boolean isCategorySet() { return categorySet; } public boolean isTenantIdSet() { return tenantIdSet; } public boolean isFormKeySet() { return formKeySet; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
2
请完成以下Java代码
public Stream<ShipmentScheduleAndJobScheduleId> stream() {return ids.stream();} public Set<ShipmentScheduleAndJobScheduleId> toSet() {return ids;} public Set<ShipmentScheduleId> getShipmentScheduleIds() { return streamShipmentScheduleIds().collect(ImmutableSet.toImmutableSet()); } public Stream<ShipmentScheduleId> streamShipmentScheduleIds() { return ids.stream() .map(ShipmentScheduleAndJobScheduleId::getShipmentScheduleId) .distinct(); } public Set<ShipmentScheduleId> getShipmentScheduleIdsWithoutJobSchedules() { return ids.stream() .filter(scheduleId -> !scheduleId.isJobSchedule()) .map(ShipmentScheduleAndJobScheduleId::getShipmentScheduleId) .collect(ImmutableSet.toImmutableSet()); } public Set<PickingJobScheduleId> getJobScheduleIds() { return ids.stream() .map(ShipmentScheduleAndJobScheduleId::getJobScheduleId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } public Set<PickingJobScheduleId> getJobScheduleIds(final @NonNull ShipmentScheduleId shipmentScheduleId) { return ids.stream() .filter(id -> ShipmentScheduleId.equals(id.getShipmentScheduleId(), shipmentScheduleId)) .map(ShipmentScheduleAndJobScheduleId::getJobScheduleId) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); }
public void forEachShipmentScheduleId(@NonNull final BiConsumer<ShipmentScheduleId, Set<PickingJobScheduleId>> consumer) { final LinkedHashMap<ShipmentScheduleId, HashSet<PickingJobScheduleId>> map = new LinkedHashMap<>(); ids.forEach(id -> { final HashSet<PickingJobScheduleId> jobScheduleIds = map.computeIfAbsent(id.getShipmentScheduleId(), key -> new HashSet<>()); final PickingJobScheduleId jobScheduleId = id.getJobScheduleId(); if (jobScheduleId != null) { jobScheduleIds.add(jobScheduleId); } }); map.forEach(consumer); } public ShipmentScheduleAndJobScheduleIdSet retainOnlyShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds) { if (isEmpty()) {return this;} Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds is not empty"); final ImmutableSet<ShipmentScheduleAndJobScheduleId> retainedIds = ids.stream() .filter(id -> shipmentScheduleIds.contains(id.getShipmentScheduleId())) .collect(ImmutableSet.toImmutableSet()); return Objects.equals(this.ids, retainedIds) ? this : ofCollection(retainedIds); } @Nullable public ShipmentScheduleAndJobScheduleId singleOrNull() { return ids.size() == 1 ? ids.iterator().next() : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\ShipmentScheduleAndJobScheduleIdSet.java
1
请完成以下Java代码
public HUMoveToDirectWarehouseService setMovementDate(final Instant movementDate) { _movementDate = movementDate; return this; } private Instant getMovementDate() { return _movementDate; } public HUMoveToDirectWarehouseService setDescription(final String description) { _description = description; return this; } private String getDescription() { return _description; } public HUMoveToDirectWarehouseService setLoggable(@NonNull final ILoggable loggable) { this.loggable = loggable; return this; } public HUMoveToDirectWarehouseService setFailOnFirstError(final boolean failOnFirstError) { _failOnFirstError = failOnFirstError; return this; } private boolean isFailOnFirstError() { return _failOnFirstError; } public HUMoveToDirectWarehouseService setFailIfNoHUs(final boolean failIfNoHUs) { _failIfNoHUs = failIfNoHUs; return this; } private boolean isFailIfNoHUs() { return _failIfNoHUs; } public HUMoveToDirectWarehouseService setDocumentsCollection(final DocumentCollection documentsCollection) { this.documentsCollection = documentsCollection; return this; }
public HUMoveToDirectWarehouseService setHUView(final HUEditorView huView) { this.huView = huView; return this; } private void notifyHUMoved(final I_M_HU hu) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); // // Invalidate all documents which are about this HU. if (documentsCollection != null) { try { documentsCollection.invalidateDocumentByRecordId(I_M_HU.Table_Name, huId.getRepoId()); } catch (final Exception ex) { logger.warn("Failed invalidating documents for M_HU_ID={}. Ignored", huId, ex); } } // // Remove this HU from the view // Don't invalidate. We will do it at the end of all processing. // // NOTE/Later edit: we decided to not remove it anymore // because in some views it might make sense to keep it there. // The right way would be to check if after moving it, the HU is still elgible for view's filters. // // if (huView != null) { huView.removeHUIds(ImmutableSet.of(huId)); } } /** * @return target warehouse where the HUs will be moved to. */ @NonNull private LocatorId getTargetLocatorId() { if (_targetLocatorId == null) { _targetLocatorId = huMovementBL.getDirectMoveLocatorId(); } return _targetLocatorId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\HUMoveToDirectWarehouseService.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(this.factoryFromRetryTopicConfiguration, this.listenerContainerFactoryName); } } static class Cache { private final Map<Key, ConcurrentKafkaListenerContainerFactory<?, ?>> cacheMap; Cache() { this.cacheMap = new HashMap<>(); } ConcurrentKafkaListenerContainerFactory<?, ?> addIfAbsent(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config, ConcurrentKafkaListenerContainerFactory<?, ?> resolvedFactory) { synchronized (this.cacheMap) { Key key = cacheKey(factoryFromKafkaListenerAnnotation, config); this.cacheMap.putIfAbsent(key, resolvedFactory); return resolvedFactory; } } @Nullable ConcurrentKafkaListenerContainerFactory<?, ?> fromCache(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config) { synchronized (this.cacheMap) { return this.cacheMap.get(cacheKey(factoryFromKafkaListenerAnnotation, config)); } } private Key cacheKey(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config) { return new Key(factoryFromKafkaListenerAnnotation, config);
} static class Key { private final @Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation; private final Configuration config; Key(@Nullable KafkaListenerContainerFactory<?> factoryFromKafkaListenerAnnotation, Configuration config) { this.factoryFromKafkaListenerAnnotation = factoryFromKafkaListenerAnnotation; this.config = config; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Key key = (Key) o; return Objects.equals(this.factoryFromKafkaListenerAnnotation, key.factoryFromKafkaListenerAnnotation) && Objects.equals(this.config, key.config); } @Override public int hashCode() { return Objects.hash(this.factoryFromKafkaListenerAnnotation, this.config); } } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\ListenerContainerFactoryResolver.java
1
请完成以下Java代码
private Set<String> determinePropertyImports(KotlinPropertyDeclaration propertyDeclaration) { return (propertyDeclaration.getReturnType() != null) ? Set.of(propertyDeclaration.getReturnType()) : Collections.emptySet(); } private Set<String> determineFunctionImports(KotlinFunctionDeclaration functionDeclaration) { Set<String> imports = new LinkedHashSet<>(); imports.add(functionDeclaration.getReturnType()); imports.addAll(appendImports(functionDeclaration.annotations().values(), Annotation::getImports)); for (Parameter parameter : functionDeclaration.getParameters()) { imports.add(parameter.getType()); imports.addAll(appendImports(parameter.annotations().values(), Annotation::getImports)); } imports.addAll(functionDeclaration.getCode().getImports()); return imports; } private <T> List<String> appendImports(Stream<T> candidates, Function<T, Collection<String>> mapping) { return candidates.map(mapping).flatMap(Collection::stream).collect(Collectors.toList()); } private String getUnqualifiedName(String name) { if (!name.contains(".")) { return name; } return name.substring(name.lastIndexOf(".") + 1); } private boolean isImportCandidate(CompilationUnit<?> compilationUnit, String name) { if (name == null || !name.contains(".")) { return false; } String packageName = name.substring(0, name.lastIndexOf('.')); return !"java.lang".equals(packageName) && !compilationUnit.getPackageName().equals(packageName); } static class KotlinFormattingOptions implements FormattingOptions {
@Override public String statementSeparator() { return ""; } @Override public CodeBlock arrayOf(CodeBlock... values) { return CodeBlock.of("[$L]", CodeBlock.join(Arrays.asList(values), ", ")); } @Override public CodeBlock classReference(ClassName className) { return CodeBlock.of("$T::class", className); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\kotlin\KotlinSourceCodeWriter.java
1
请完成以下Java代码
public Filter removeAttribute(String name) { try { this.remove(name); } catch ( Exception e ) { } return this; } /** Check to see if something is going to be filtered. */ public boolean hasAttribute(String key) { return(this.containsKey(key)); } /** Perform the filtering operation. */ public String process(String to_process) { if ( to_process == null || to_process.length() == 0 ) return ""; StringBuffer bs = new StringBuffer(to_process.length() + 50);
StringCharacterIterator sci = new StringCharacterIterator(to_process); String tmp = null; for (char c = sci.first(); c != CharacterIterator.DONE; c = sci.next()) { tmp = String.valueOf(c); if (hasAttribute(tmp)) tmp = (String) this.get(tmp); int ii = c; if (ii > 255) tmp = "&#" + ii + ";"; bs.append(tmp); } return(bs.toString()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\filter\CharacterFilter.java
1
请完成以下Java代码
public Integer getMaxPriority() { return maxPriority; } public String getAssigneeLike() { return assigneeLike; } public List<String> getAssigneeIds() { return assigneeIds; } public String getInvolvedUser() { return involvedUser; } public String getOwner() { return owner; } public String getOwnerLike() { return ownerLike; } public String getCategory() { return category; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public List<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public String getProcessDefinitionNameLike() { return processDefinitionNameLike; } public List<String> getProcessCategoryInList() { return processCategoryInList; } public List<String> getProcessCategoryNotInList() { return processCategoryNotInList; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public String getProcessInstanceBusinessKeyLike() { return processInstanceBusinessKeyLike; } public Date getDueDate() { return dueDate; } public Date getDueBefore() { return dueBefore; } public Date getDueAfter() { return dueAfter; } public boolean isWithoutDueDate() { return withoutDueDate; } public SuspensionState getSuspensionState() { return suspensionState; } public boolean isIncludeTaskLocalVariables() { return includeTaskLocalVariables;
} public boolean isIncludeProcessVariables() { return includeProcessVariables; } public boolean isBothCandidateAndAssigned() { return bothCandidateAndAssigned; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getDescriptionLikeIgnoreCase() { return descriptionLikeIgnoreCase; } public String getAssigneeLikeIgnoreCase() { return assigneeLikeIgnoreCase; } public String getOwnerLikeIgnoreCase() { return ownerLikeIgnoreCase; } public String getProcessInstanceBusinessKeyLikeIgnoreCase() { return processInstanceBusinessKeyLikeIgnoreCase; } public String getProcessDefinitionKeyLikeIgnoreCase() { return processDefinitionKeyLikeIgnoreCase; } public boolean isOrActive() { return orActive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\TaskQueryImpl.java
1
请完成以下Java代码
public File getSchemaFile() { // final String schemaPackageDir = getSchemaPackageDirectory(); final String schemaDir = p_Target_Directory + "/src/main/xsd"; final File dir = new File(schemaDir); dir.mkdirs(); return new File(dir, "schema.xsd"); } public String getTestModelFileName(final I_EXP_Format format) { return format.getValue() + ".xml"; } public File getTestModelDirectory() { final String schemaPackageDir = getSchemaPackageDirectory(); final String schemaDir = p_Target_Directory + "/src/test/resources/" + schemaPackageDir + "/schema"; final File dir = new File(schemaDir); dir.mkdirs(); return dir; } /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { if (Check.isEmpty(System.getProperty("PropertyFile"), true)) { throw new AdempiereException("Please set the PropertyFile"); } final String outputFolder = System.getProperty("OutputFolder"); if (Check.isEmpty(outputFolder, true)) { throw new AdempiereException("Please set the OutputFolder");
} final String entityType = System.getProperty(PARAM_EntityType); if (Check.isEmpty(entityType, true)) { throw new AdempiereException("Please set the EntityType"); } LogManager.initialize(true); // just to make sure we are using the client side settings AdempiereToolsHelper.getInstance().startupMinimal(); final ProcessInfo pi = ProcessInfo.builder() .setCtx(Env.getCtx()) .setTitle("GenerateCanonicalXSD") .setAD_Process_ID(-1) // N/A .setClassname(GenerateCanonicalXSD.class.getName()) .addParameter(PARAM_Target_Directory, outputFolder) .addParameter(PARAM_EntityType, entityType) .build(); final GenerateCanonicalXSD process = new GenerateCanonicalXSD(); process.p_FilterBy_AD_Client_ID = false; LogManager.setLevel(Level.INFO); process.startProcess(pi, ITrx.TRX_None); // // CanonicalXSDGenerator.validateXML(new File("d:/tmp/C_BPartner.xml"), proc.getSchemaFile()); // CanonicalXSDGenerator.validateXML(new File("d:/tmp/clientPartners.xml"), proc.getSchemaFile()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\esb\process\GenerateCanonicalXSD.java
1
请在Spring Boot框架中完成以下Java代码
public class GlobalActionEvent { @NonNull GlobalActionType type; String payload; private static final String SEPARATOR = "#"; public static GlobalActionEvent parseQRCode(@NonNull final String eventStr) { final int idx = eventStr.indexOf(SEPARATOR); if (idx > 0) { final String typeStr = eventStr.substring(0, idx); final GlobalActionType type = GlobalActionType.forCode(typeStr); final String payload = Strings.emptyToNull(eventStr.substring(idx + SEPARATOR.length())); return builder() .type(type) .payload(payload) .build(); } else { final GlobalActionType type = GlobalActionType.forCode(eventStr); return builder() .type(type) .build(); } } @Override @Deprecated public String toString() { return toQRCodeString(); } public String toQRCodeString()
{ if (payload == null || payload.isEmpty()) { return type.getCode(); } else { return type.getCode() + SEPARATOR + payload; } } public ProcessExecutionResult.DisplayQRCode toDisplayQRCodeProcessResult() { return ProcessExecutionResult.DisplayQRCode.builder() .code(toQRCodeString()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\globalaction\GlobalActionEvent.java
2
请完成以下Java代码
private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException { final List<Object> values = new ArrayList<Object>(); for (final String columnName : sqlFields) { final Object value = rs.getObject(columnName); values.add(value); } return values; } private Integer rowsCount = null; @Override public int size() { if (Check.isEmpty(sqlCount, true)) { throw new IllegalStateException("Counting is not supported"); } if (rowsCount == null) { logger.info("SQL: {}", sqlCount); logger.info("SQL Params: {}", sqlParams); rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams); logger.info("Rows Count: {}" + rowsCount);
} return rowsCount; } public String getSqlSelect() { return sqlSelect; } public List<Object> getSqlParams() { if (sqlParams == null) { return Collections.emptyList(); } return sqlParams; } public String getSqlWhereClause() { return sqlWhereClause; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java
1
请完成以下Java代码
public class AuthorizationEvent extends ApplicationEvent { @Serial private static final long serialVersionUID = -9053927371500241295L; private final Supplier<Authentication> authentication; private final AuthorizationResult result; /** * Construct an {@link AuthorizationEvent} * @param authentication the principal requiring access * @param object the object to which access was requested * @param result whether authorization was granted or denied */ public AuthorizationEvent(Supplier<Authentication> authentication, Object object, AuthorizationDecision result) { super(object); Assert.notNull(authentication, "authentication supplier cannot be null"); this.authentication = authentication; this.result = result; } /** * Construct an {@link AuthorizationEvent} * @param authentication the principal requiring access * @param object the object to which access was requested * @param result whether authorization was granted or denied */ public AuthorizationEvent(Supplier<Authentication> authentication, Object object, AuthorizationResult result) { super(object); Assert.notNull(authentication, "authentication supplier cannot be null"); this.authentication = authentication; this.result = result; } /**
* Get the principal requiring access * @return the principal requiring access */ public Supplier<Authentication> getAuthentication() { return this.authentication; } /** * Get the object to which access was requested * @return the object to which access was requested */ public Object getObject() { return getSource(); } /** * Get the response to the principal's request * @return the response to the principal's request * @since 6.4 */ public AuthorizationResult getAuthorizationResult() { return this.result; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\event\AuthorizationEvent.java
1
请完成以下Java代码
public class C_BankStatement { private final IBankStatementBL bankStatementBL; public C_BankStatement( @NonNull final IBankStatementBL bankStatementBL) { this.bankStatementBL = bankStatementBL; } @CalloutMethod(columnNames = { I_C_BankStatement.COLUMNNAME_BeginningBalance, I_C_BankStatement.COLUMNNAME_StatementDifference }) public void updateEndingBalance(final I_C_BankStatement bankStatement, final ICalloutField unused) { bankStatementBL.updateEndingBalance(bankStatement); } @CalloutMethod(columnNames = I_C_BankStatement.COLUMNNAME_C_DocType_ID) public void onDocTypeChanged(final I_C_BankStatement bankStatement) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(bankStatement.getC_DocType_ID()); if (docTypeId == null)
{ return; } final IDocTypeDAO docTypeDAO = Services.get(IDocTypeDAO.class); final I_C_DocType docType = docTypeDAO.getById(docTypeId); final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(docType) .setOldDocumentNo(bankStatement.getDocumentNo()) .setDocumentModel(bankStatement) .buildOrNull(); if (documentNoInfo != null && documentNoInfo.isDocNoControlled()) { bankStatement.setDocumentNo(documentNoInfo.getDocumentNo()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\callout\C_BankStatement.java
1
请完成以下Java代码
private void buildSql() { if (sqlBuilt) { return; } final Operator operator = getOperator(); final String operand1ColumnName = operand1.getColumnName(); final String operand1ColumnSql = operand1Modifier.getColumnSql(operand1ColumnName); final String operatorSql = operator.getSql(); sqlParams = new ArrayList<>(); final String operand2Sql = operand2 == null ? null : operand2Modifier.getValueSql(operand2, sqlParams); if (operand2 == null && Operator.EQUAL == operator) { sqlWhereClause = operand1ColumnName + " IS NULL"; sqlParams = Collections.emptyList(); } else if (operand2 == null && Operator.NOT_EQUAL == operator) { sqlWhereClause = operand1ColumnName + " IS NOT NULL"; sqlParams = Collections.emptyList(); } else { sqlWhereClause = operand1ColumnSql + " " + operatorSql + " " + operand2Sql;
} // Corner case: we are asked for Operand1 <> SomeValue // => we need to create an SQL which is also taking care about the NULL value // i.e. (Operand1 <> SomeValue OR Operand1 IS NULL) if (operand2 != null && Operator.NOT_EQUAL == operator) { sqlWhereClause = "(" + sqlWhereClause + " OR " + operand1ColumnSql + " IS NULL" + ")"; } sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompareQueryFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class BulkController { private final CustomerService customerService; private final EnumMap<BulkActionType, Function<Customer, Optional<Customer>>> bulkActionFuncMap = new EnumMap<>(BulkActionType.class); public BulkController(CustomerService customerService) { this.customerService = customerService; bulkActionFuncMap.put(BulkActionType.CREATE, customerService::createCustomer); bulkActionFuncMap.put(BulkActionType.UPDATE, customerService::updateCustomer); bulkActionFuncMap.put(BulkActionType.DELETE, customerService::deleteCustomer); } @PostMapping(path = "/customers") public ResponseEntity<List<Customer>> createCustomers(@RequestHeader(value = "X-ActionType") String actionType, @RequestBody @Valid @Size(min = 1, max = 20) List<Customer> customers) { List<Customer> customerList = actionType.equals("bulk") ? customerService.createCustomers(customers) : Collections.singletonList(customerService.createCustomer(customers.get(0)).orElse(null)); return new ResponseEntity<>(customerList, HttpStatus.CREATED); } @PostMapping(path = "/customers/bulk") public ResponseEntity<List<CustomerBulkResponse>> bulkProcessCustomers(@RequestBody @Valid @Size(min = 1, max = 20) List<CustomerBulkRequest> customerBulkRequests) { List<CustomerBulkResponse> customerBulkResponseList = new ArrayList<>(); customerBulkRequests.forEach(customerBulkRequest -> { List<Customer> customers = customerBulkRequest.getCustomers().stream() .map(bulkActionFuncMap.get(customerBulkRequest.getBulkActionType())) .filter(Optional::isPresent) .map(Optional::get)
.collect(toList()); BulkStatus bulkStatus = getBulkStatus(customerBulkRequest.getCustomers(), customers); customerBulkResponseList.add(new CustomerBulkResponse(customers, customerBulkRequest.getBulkActionType(), bulkStatus)); }); return new ResponseEntity<>(customerBulkResponseList, HttpStatus.MULTI_STATUS); } private BulkStatus getBulkStatus(List<Customer> customersInRequest, List<Customer> customersProcessed) { if (!customersProcessed.isEmpty()) { return customersProcessed.size() == customersInRequest.size() ? BulkStatus.PROCESSED : BulkStatus.PARTIALLY_PROCESSED; } return BulkStatus.NOT_PROCESSED; } }
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\controller\BulkController.java
2
请在Spring Boot框架中完成以下Java代码
public Double getDoubleValue() { return null; } @Override public void setDoubleValue(Double doubleValue) { } @Override public byte[] getBytes() { return null; } @Override
public void setBytes(byte[] bytes) { } @Override public Object getCachedValue() { return null; } @Override public void setCachedValue(Object cachedValue) { } }
repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\entity\TransientVariableInstance.java
2
请完成以下Java代码
public String toCSVRow(@NonNull final ICountryDAO countryDAO) { final String recipientBankCountryName = row.getRecipientBankCountryId() != null ? countryDAO.getById(row.getRecipientBankCountryId()).getName() : null; final String recipientCountryName = row.getRecipientCountryId() != null ? countryDAO.getById(row.getRecipientCountryId()).getName() : null; return Stream.of(row.getName(), row.getRecipientType().getCode(), row.getAccountNo(), row.getRoutingNo(), row.getIBAN(), row.getSwiftCode(), recipientBankCountryName, row.getAmount().getCurrencyCode().toThreeLetterCode(), String.valueOf(row.getAmount().getAsBigDecimal()), row.getPaymentReference(), recipientCountryName, row.getRegionName(), row.getAddressLine1(), row.getAddressLine2(),
row.getCity(), row.getPostalCode()) .map(this::escapeCSV) .collect(Collectors.joining(",")); } @NonNull private String escapeCSV(@Nullable final String valueToEscape) { final String escapedQuote = "\""; return escapedQuote + StringUtils.nullToEmpty(valueToEscape).replace(escapedQuote, escapedQuote + escapedQuote) + escapedQuote; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.revolut\src\main\java\de\metas\payment\revolut\model\RevolutExportCsvRow.java
1
请完成以下Java代码
private QtyToDeliverMap getShipmentScheduleId2QtyToDeliver( @NonNull final Set<OLCandId> olCandIds, @NonNull final AsyncBatchId asyncBatchId) { final Map<OLCandId, OrderLineId> olCandId2OrderLineId = olCandDAO.retrieveOLCandIdToOrderLineId(olCandIds); if (olCandId2OrderLineId == null || olCandId2OrderLineId.isEmpty()) { return QtyToDeliverMap.EMPTY; } final Map<OLCandId, I_C_OLCand> olCandsById = olCandDAO.retrieveByIds(olCandIds); final ImmutableMap.Builder<ShipmentScheduleId, StockQtyAndUOMQty> scheduleId2QtyShipped = ImmutableMap.builder(); for (final Map.Entry<OLCandId, OrderLineId> olCand2OrderLineEntry : olCandId2OrderLineId.entrySet()) { final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentSchedule = shipmentScheduleBL.getByOrderLineId(olCand2OrderLineEntry.getValue()); if (shipmentSchedule == null || shipmentSchedule.isProcessed()) { continue; } final ShipmentScheduleId scheduleId = ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID()); final I_C_OLCand olCand = olCandsById.get(olCand2OrderLineEntry.getKey()); if (olCand.getC_Async_Batch_ID() != shipmentSchedule.getC_Async_Batch_ID() || olCand.getC_Async_Batch_ID() != asyncBatchId.getRepoId()) { throw new AdempiereException("olCand.getC_Async_Batch_ID() != shipmentSchedule.getC_Async_Batch_ID() || olCand.getC_Async_Batch_ID() != asyncBatchId") .appendParametersToMessage() .setParameter("C_OLCand_ID", olCand.getC_OLCand_ID()) .setParameter("M_ShipmentSchedule_ID", shipmentSchedule.getM_ShipmentSchedule_ID()) .setParameter("olCand.getC_Async_Batch_ID()", olCand.getC_Async_Batch_ID()) .setParameter("shipmentSchedule.getC_Async_Batch_ID()", shipmentSchedule.getC_Async_Batch_ID()) .setParameter("AsyncBatchId", asyncBatchId); } final StockQtyAndUOMQty qtyToDeliver = getQtyToDeliver(shipmentSchedule, olCand); if (qtyToDeliver != null) { scheduleId2QtyShipped.put(scheduleId, qtyToDeliver); } } return QtyToDeliverMap.ofMap(scheduleId2QtyShipped.build());
} /** * @return qty to deliver or null if the caller wants *no* shipment */ @Nullable private StockQtyAndUOMQty getQtyToDeliver(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule shipmentSchedule, final I_C_OLCand olCand) { final StockQtyAndUOMQty qtyShipped = olCandEffectiveValuesBL.getQtyShipped(olCand).orElse(null); if (qtyShipped == null) { // not specified; -> let metasfresh decide final Quantity qtyToDeliver = shipmentScheduleBL.getQtyToDeliver(shipmentSchedule); final ProductId productId = ProductId.ofRepoId(shipmentSchedule.getM_Product_ID()); return StockQtyAndUOMQtys.ofQtyInStockUOM(qtyToDeliver, productId); } else if (qtyShipped.signum() <= 0) { // the caller wants *no* shipment return null; } else { return qtyShipped; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentService.java
1
请完成以下Java代码
public String getTextMsg() { return state.getTextMsg(); } private void setTextMsg(@Nullable final String textMsg) { state.setTextMsg(textMsg); } void addTextMsg(@Nullable final String textMsg) { if (textMsg == null || textMsg.isEmpty()) { return; } final String oldText = StringUtils.trimBlankToNull(getTextMsg()); if (oldText == null) { setTextMsg(textMsg.trim()); } else { setTextMsg(oldText + "\n" + textMsg.trim()); } } private void addTextMsg(@Nullable final Throwable ex) { if (ex == null) { return; } addTextMsg(AdempiereException.extractMessage(ex)); final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex); final AdIssueId adIssueId = context.createIssue(metasfreshException); setIssueId(adIssueId); } void setProcessingResultMessage(@Nullable final String msg) {
this.processingResultMessage = msg; this.processingResultException = null; addTextMsg(msg); } void setProcessingResultMessage(@NonNull final Throwable ex) { this.processingResultMessage = AdempiereException.extractMessage(ex); this.processingResultException = ex; addTextMsg(ex); } @Nullable public String getProcessingResultMessage() { return processingResultMessage; } @Nullable public Throwable getProcessingResultException() { return processingResultException; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFProcess.java
1
请完成以下Java代码
private static ViewRowFieldNameAndJsonValuesHolder<InvoiceRow> buildViewRowFieldNameAndJsonValuesHolder( @NonNull final SOTrx soTrx) { final ImmutableMap.Builder<String, ViewEditorRenderMode> viewEditorRenderModes = ImmutableMap.<String, ViewEditorRenderMode>builder() .put(FIELD_DiscountAmt, ViewEditorRenderMode.ALWAYS) .put(FIELD_BankFeeAmt, ViewEditorRenderMode.ALWAYS); if (soTrx.isSales()) { viewEditorRenderModes.put(FIELD_ServiceFeeAmt, ViewEditorRenderMode.ALWAYS); } return ViewRowFieldNameAndJsonValuesHolder.builder(InvoiceRow.class) .viewEditorRenderModeByFieldName(viewEditorRenderModes.build()) .build(); } static DocumentId convertInvoiceIdToDocumentId(@NonNull final InvoiceId invoiceId) { return DocumentId.of(invoiceId); } static InvoiceId convertDocumentIdToInvoiceId(@NonNull final DocumentId rowId) { return rowId.toId(InvoiceId::ofRepoId); } @Override public String toString() { return MoreObjects.toStringHelper(this) .addValue(values.get(this)) .toString(); } @Override public DocumentId getId() { return rowId; } public ClientAndOrgId getClientAndOrgId() { return clientAndOrgId; } @Override public boolean isProcessed() { return false; }
@Override public DocumentPath getDocumentPath() { return null; } @Override public Set<String> getFieldNames() { return values.getFieldNames(); } @Override public ViewRowFieldNameAndJsonValues getFieldNameAndJsonValues() { return values.get(this); } @Override public Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName() { return values.getViewEditorRenderModeByFieldName(); } public BPartnerId getBPartnerId() { return bpartner.getIdAs(BPartnerId::ofRepoId); } public InvoiceRow withPreparedForAllocationSet() { return withPreparedForAllocation(true); } public InvoiceRow withPreparedForAllocationUnset() { return withPreparedForAllocation(false); } public InvoiceRow withPreparedForAllocation(final boolean isPreparedForAllocation) { return this.isPreparedForAllocation != isPreparedForAllocation ? toBuilder().isPreparedForAllocation(isPreparedForAllocation).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\payment_allocation\InvoiceRow.java
1
请完成以下Java代码
private OrderResponsePackageItemPart fromJAXB(@NonNull final BestellungAnteil soap) { return OrderResponsePackageItemPart.builder() .qty(Quantity.of(soap.getMenge())) .type(Type.ofStringValueOrNull(soap.getTyp().value())) .deliveryDate(JAXBDateUtils.toZonedDateTime(soap.getLieferzeitpunkt())) .defectReason(OrderDefectReason.fromV2SoapCode(soap.getGrund())) .tour(soap.getTour()) .tourId(soap.getTourId()) .tourDeviation(soap.isTourabweichung()) .build(); } private BestellungAnteil toJAXB(final OrderResponsePackageItemPart itemPart) { final BestellungAnteil soap = jaxbObjectFactory.createBestellungAnteil(); soap.setMenge(itemPart.getQty().getValueAsInt()); final String type = Type.getValueOrNull(itemPart.getType()); if (type != null) { soap.setTyp(BestellungRueckmeldungTyp.fromValue(type)); } soap.setLieferzeitpunkt(JAXBDateUtils.toXMLGregorianCalendar(itemPart.getDeliveryDate())); soap.setGrund(itemPart.getDefectReason().getV2SoapCode()); soap.setTour(itemPart.getTour()); soap.setTourId(itemPart.getTourId()); soap.setTourabweichung(itemPart.isTourDeviation()); return soap; } private OrderResponsePackageItemSubstitution fromJAXB(final BestellungSubstitution soap) {
if (soap == null) { return null; } return OrderResponsePackageItemSubstitution.builder() .substitutionReason(OrderSubstitutionReason.fromV2SoapCode(soap.getSubstitutionsgrund())) .defectReason(OrderDefectReason.fromV2SoapCode(soap.getGrund())) .pzn(PZN.of(soap.getLieferPzn())) .build(); } private BestellungSubstitution toJAXB(final OrderResponsePackageItemSubstitution itemSubstitution) { if (itemSubstitution == null) { return null; } final BestellungSubstitution soap = jaxbObjectFactory.createBestellungSubstitution(); soap.setSubstitutionsgrund(itemSubstitution.getSubstitutionReason().getV2SoapCode()); soap.setGrund(itemSubstitution.getDefectReason().getV2SoapCode()); soap.setLieferPzn(itemSubstitution.getPzn().getValueAsLong()); return soap; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\v2\OrderJAXBConvertersV2.java
1
请完成以下Java代码
public SpinJsonDataFormatException unableToConstructJavaType(String fromString, Exception cause) { return new SpinJsonDataFormatException( exceptionMessage("007", "Cannot construct java type from string '{}'", fromString), cause); } public SpinJsonDataFormatException unableToDetectCanonicalType(Object parameter) { return new SpinJsonDataFormatException(exceptionMessage("008", "Cannot detect canonical data type for parameter '{}'", parameter)); } public SpinJsonDataFormatException unableToMapInput(Object input, Exception cause) { return new SpinJsonDataFormatException(exceptionMessage("009", "Unable to map object '{}' to json node", input), cause); } public SpinJsonException unableToModifyNode(String nodeName) { return new SpinJsonException(exceptionMessage("010", "Unable to modify node of type '{}'. Node is not a list.", nodeName)); } public SpinJsonException unableToGetIndex(String nodeName) { return new SpinJsonException(exceptionMessage("011", "Unable to get index from '{}'. Node is not a list.", nodeName)); } public IndexOutOfBoundsException indexOutOfBounds(Integer index, Integer size) { return new IndexOutOfBoundsException(exceptionMessage("012", "Index is out of bound! Index: '{}', Size: '{}'", index, size)); } public SpinJsonPathException unableToEvaluateJsonPathExpressionOnNode(SpinJsonNode node, Exception cause) { return new SpinJsonPathException( exceptionMessage("013", "Unable to evaluate JsonPath expression on element '{}'", node.getClass().getName()), cause); }
public SpinJsonPathException unableToCompileJsonPathExpression(String expression, Exception cause) { return new SpinJsonPathException( exceptionMessage("014", "Unable to compile '{}'!", expression), cause); } public SpinJsonPathException unableToCastJsonPathResultTo(Class<?> castClass, Exception cause) { return new SpinJsonPathException( exceptionMessage("015", "Unable to cast JsonPath expression to '{}'", castClass.getName()), cause); } public SpinJsonPathException invalidJsonPath(Class<?> castClass, Exception cause) { return new SpinJsonPathException( exceptionMessage("017", "Invalid json path to '{}'", castClass.getName()), cause); } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\JacksonJsonLogger.java
1
请完成以下Java代码
private void clearCookie(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String domain, String cookieName) { Cookie cookie = new Cookie(cookieName, ""); setCookieProperties(cookie, httpServletRequest.isSecure(), domain); cookie.setMaxAge(0); httpServletResponse.addCookie(cookie); log.debug("clearing cookie {}", cookie.getName()); } /** * Returns the top level domain of the server from the request. This is used to limit the Cookie * to the top domain instead of the full domain name. * <p> * A lot of times, individual gateways of the same domain get their own subdomain but authentication * shall work across all subdomains of the top level domain. * <p> * For example, when sending a request to <code>app1.domain.com</code>, * this returns <code>.domain.com</code>. * * @param request the HTTP request we received from the client. * @return the top level domain to set the cookies for. * Returns null if the domain is not under a public suffix (.com, .co.uk), e.g. for localhost. */ private String getCookieDomain(HttpServletRequest request) { String domain = oAuth2Properties.getWebClientConfiguration().getCookieDomain(); if (domain != null) { return domain; } // if not explicitly defined, use top-level domain domain = request.getServerName().toLowerCase();
// strip off leading www. if (domain.startsWith("www.")) { domain = domain.substring(4); } // if it isn't an IP address if (!isIPv4Address(domain) && !isIPv6Address(domain)) { // strip off private subdomains, leaving public TLD only String suffix = suffixMatcher.getDomainRoot(domain); if (suffix != null && !suffix.equals(domain)) { // preserve leading dot return "." + suffix; } } // no top-level domain, stick with default domain return null; } /** * Strip our token cookies from the array. * * @param cookies the cookies we receive as input. * @return the new cookie array without our tokens. */ Cookie[] stripCookies(Cookie[] cookies) { CookieCollection cc = new CookieCollection(cookies); if (cc.removeAll(COOKIE_NAMES)) { return cc.toArray(); } return cookies; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\security\oauth2\OAuth2CookieHelper.java
1
请完成以下Java代码
public class RfQPublishException extends RfQException { public static final RfQPublishException wrapIfNeeded(final Throwable e) { if (e instanceof RfQPublishException) { return (RfQPublishException)e; } final Throwable cause = extractCause(e); return new RfQPublishException(cause.getMessage(), cause); } private RfQResponsePublisherRequest request; public RfQPublishException(final RfQResponsePublisherRequest request, final String message) { super(message); setRequest(request); } private RfQPublishException(final String message, final Throwable cause) { super(message, cause); }
public RfQPublishException setRequest(final RfQResponsePublisherRequest request) { this.request = request; resetMessageBuilt(); return this; } @Override protected ITranslatableString buildMessage() { final TranslatableStringBuilder message = TranslatableStrings.builder(); message.appendADMessage("Error"); if (request != null) { message.append(" ").append(request.getSummary()); } message.append(": "); message.append(getOriginalMessage()); return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\exceptions\RfQPublishException.java
1
请完成以下Java代码
public String toString() { return "||"; } }; public static final Operator SUB = new SimpleOperator() { @Override public Object apply(TypeConverter converter, Object o1, Object o2) { return NumberOperations.sub(converter, o1, o2); } @Override public String toString() { return "-"; } }; private final Operator operator; private final AstNode left, right; public AstBinary(AstNode left, AstNode right, Operator operator) { this.left = left; this.right = right; this.operator = operator; } public Operator getOperator() { return operator; } @Override public Object eval(Bindings bindings, ELContext context) { return operator.eval(bindings, context, left, right);
} @Override public String toString() { return "'" + operator.toString() + "'"; } @Override public void appendStructure(StringBuilder b, Bindings bindings) { left.appendStructure(b, bindings); b.append(' '); b.append(operator); b.append(' '); right.appendStructure(b, bindings); } public int getCardinality() { return 2; } public AstNode getChild(int i) { return i == 0 ? left : i == 1 ? right : null; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstBinary.java
1
请完成以下Java代码
public TenantId getId() { return super.getId(); } @Schema(description = "Timestamp of the tenant creation, in milliseconds", example = "1609459200000", accessMode = Schema.AccessMode.READ_ONLY) @Override public long getCreatedTime() { return super.getCreatedTime(); } @Schema(description = "Country", example = "US") @Override public String getCountry() { return super.getCountry(); } @Schema(description = "State", example = "NY") @Override public String getState() { return super.getState(); } @Schema(description = "City", example = "New York") @Override public String getCity() { return super.getCity(); } @Schema(description = "Address Line 1", example = "42 Broadway Suite 12-400") @Override public String getAddress() { return super.getAddress(); } @Schema(description = "Address Line 2", example = "") @Override public String getAddress2() { return super.getAddress2(); } @Schema(description = "Zip code", example = "10004") @Override public String getZip() { return super.getZip(); } @Schema(description = "Phone number", example = "+1(415)777-7777") @Override public String getPhone() { return super.getPhone(); } @Schema(description = "Email", example = "example@company.com") @Override public String getEmail() { return super.getEmail();
} @Schema(description = "Additional parameters of the device", implementation = com.fasterxml.jackson.databind.JsonNode.class) @Override public JsonNode getAdditionalInfo() { return super.getAdditionalInfo(); } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Tenant [title="); builder.append(title); builder.append(", region="); builder.append(region); builder.append(", tenantProfileId="); builder.append(tenantProfileId); builder.append(", additionalInfo="); builder.append(getAdditionalInfo()); builder.append(", country="); builder.append(country); builder.append(", state="); builder.append(state); builder.append(", city="); builder.append(city); builder.append(", address="); builder.append(address); builder.append(", address2="); builder.append(address2); builder.append(", zip="); builder.append(zip); builder.append(", phone="); builder.append(phone); builder.append(", email="); builder.append(email); builder.append(", createdTime="); builder.append(createdTime); builder.append(", id="); builder.append(id); builder.append("]"); return builder.toString(); } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\Tenant.java
1
请在Spring Boot框架中完成以下Java代码
public class AddressEntity { @Id @Column(name = "id") private String id; @Column(name = "street") private String street; @Column(name = "city") private String city; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getStreet() {
return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
repos\spring-examples-java-17\spring-data\src\main\java\itx\examples\springdata\entity\AddressEntity.java
2
请完成以下Java代码
public CmmnElement getTarget() { return targetRefAttribute.getReferenceTargetElement(this); } public void setTarget(CmmnElement target) { targetRefAttribute.setReferenceTargetElement(this, target); } public AssociationDirection getAssociationDirection() { return associationDirectionAttribute.getValue(this); } public void setAssociationDirection(AssociationDirection associationDirection) { associationDirectionAttribute.setValue(this, associationDirection); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Association.class, CMMN_ELEMENT_ASSOCIATION) .namespaceUri(CMMN11_NS) .extendsType(Artifact.class)
.instanceProvider(new ModelTypeInstanceProvider<Association>() { public Association newInstance(ModelTypeInstanceContext instanceContext) { return new AssociationImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(CmmnElement.class) .build(); targetRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_TARGET_REF) .idAttributeReference(CmmnElement.class) .build(); associationDirectionAttribute = typeBuilder.enumAttribute(CMMN_ATTRIBUTE_ASSOCIATION_DIRECTION, AssociationDirection.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\AssociationImpl.java
1
请完成以下Java代码
public void invalidateCandidatesFor(final Object model) { final Properties ctx = InterfaceWrapperHelper.getCtx(model); final String tableName = InterfaceWrapperHelper.getModelTableName(model); final List<IInvoiceCandidateHandler> handlersForTable = retrieveImplementationsForTable(ctx, tableName); for (final IInvoiceCandidateHandler handler : handlersForTable) { final OnInvalidateForModelAction onInvalidateForModelAction = handler.getOnInvalidateForModelAction(); switch (onInvalidateForModelAction) { case RECREATE_ASYNC: scheduleCreateMissingCandidatesFor(model, handler); break; case REVALIDATE: handler.invalidateCandidatesFor(model); break; default: // nothing logger.warn("Got no OnInvalidateForModelAction for " + model + ". Doing nothing."); break; } } } @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic) { final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic); return handler.calculatePriceAndTax(ic); } @Override public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic) { final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic); handler.setBPartnerData(ic); }
@Override public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate icRecord) { final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(icRecord); handler.setInvoiceScheduleAndDateToInvoice(icRecord); } @Override public void setPickedData(final I_C_Invoice_Candidate ic) { final InvoiceCandidateRecordService invoiceCandidateRecordService = SpringContextHolder.instance.getBean(InvoiceCandidateRecordService.class); final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic); handler.setShipmentSchedule(ic); final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(ic.getM_ShipmentSchedule_ID()); if (shipmentScheduleId == null) { return; } final StockQtyAndUOMQty qtysPicked = invoiceCandidateRecordService.ofRecord(ic).computeQtysPicked(); ic.setQtyPicked(qtysPicked.getStockQty().toBigDecimal()); ic.setQtyPickedInUOM(qtysPicked.getUOMQtyNotNull().toBigDecimal()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerBL.java
1
请完成以下Java代码
public String getID() { return PASSWORD_MODIFY_OID; } @Override public byte[] getEncodedValue() { return this.value.toByteArray(); } @Override public ExtendedResponse createExtendedResponse(String id, byte[] berValue, int offset, int length) { return null; } /** * Only minimal support for <a target="_blank" href= * "https://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf"> BER * encoding </a>; just what is necessary for the Password Modify request. * */ private void berEncode(byte type, byte[] src, ByteArrayOutputStream dest) { int length = src.length; dest.write(type); if (length < 128) { dest.write(length); } else if ((length & 0x0000_00FF) == length) { dest.write((byte) 0x81); dest.write((byte) (length & 0xFF)); } else if ((length & 0x0000_FFFF) == length) {
dest.write((byte) 0x82); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } else if ((length & 0x00FF_FFFF) == length) { dest.write((byte) 0x83); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } else { dest.write((byte) 0x84); dest.write((byte) ((length >> 24) & 0xFF)); dest.write((byte) ((length >> 16) & 0xFF)); dest.write((byte) ((length >> 8) & 0xFF)); dest.write((byte) (length & 0xFF)); } try { dest.write(src); } catch (IOException ex) { throw new IllegalArgumentException("Failed to BER encode provided value of type: " + type); } } } }
repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsManager.java
1
请完成以下Java代码
public void addHandler(final IPrintingQueueHandler handler) { if (handler == null) { return; } handlers.addIfAbsent(handler); } @Override public void afterEnqueueBeforeSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut) { for (final IPrintingQueueHandler handler : handlers) { afterEnqueueBeforeSave(queueItem, printOut, handler); } afterEnqueueBeforeSave(queueItem, printOut, lastHandler); } private void afterEnqueueBeforeSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut, final IPrintingQueueHandler handler) { if (handler.isApplyHandler(queueItem, printOut)) { handler.afterEnqueueBeforeSave(queueItem, printOut); } } @Override public void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut) { for (final IPrintingQueueHandler handler : handlers) { afterEnqueueAfterSave(queueItem, printOut, handler); }
afterEnqueueAfterSave(queueItem, printOut, lastHandler); } private void afterEnqueueAfterSave(final I_C_Printing_Queue queueItem, final I_AD_Archive printOut, final IPrintingQueueHandler handler) { if (handler.isApplyHandler(queueItem, printOut)) { handler.afterEnqueueAfterSave(queueItem, printOut); } } /** * Returns <code>true</code>, but note that handlers which are contained in this instance have their {@link #isApplyHandler(I_C_Printing_Queue, I_AD_Archive)} method invoked individually. */ @Override public boolean isApplyHandler(I_C_Printing_Queue queueItem, I_AD_Archive printOut) { return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\spi\impl\CompositePrintingQueueHandler.java
1
请完成以下Java代码
public boolean set(String key, V value) { int index = exactMatchSearch(key); if (index >= 0) { v[index] = value; return true; } return false; } /** * 从值数组中提取下标为index的值<br> * 注意为了效率,此处不进行参数校验 * * @param index 下标 * @return 值 */ public V get(int index) { return v[index]; } /** * 释放空闲的内存 */ private void shrink() { // if (HanLP.Config.DEBUG) // { // System.err.printf("释放内存 %d bytes\n", base.length - size - 65535); // } int nbase[] = new int[size + 65535]; System.arraycopy(base, 0, nbase, 0, size); base = nbase; int ncheck[] = new int[size + 65535]; System.arraycopy(check, 0, ncheck, 0, size); check = ncheck; }
/** * 打印统计信息 */ // public void report() // { // System.out.println("size: " + size); // int nonZeroIndex = 0; // for (int i = 0; i < base.length; i++) // { // if (base[i] != 0) nonZeroIndex = i; // } // System.out.println("BaseUsed: " + nonZeroIndex); // nonZeroIndex = 0; // for (int i = 0; i < check.length; i++) // { // if (check[i] != 0) nonZeroIndex = i; // } // System.out.println("CheckUsed: " + nonZeroIndex); // } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\DoubleArrayTrie.java
1
请在Spring Boot框架中完成以下Java代码
public class Seller { @Id @GeneratedValue @Column(name = "id") private int id; @Column(name = "name") private String sellerName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSellerName() { return sellerName;
} public void setSellerName(String sellerName) { this.sellerName = sellerName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Seller seller = (Seller) o; return Objects.equals(sellerName, seller.sellerName); } @Override public int hashCode() { return Objects.hash(sellerName); } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkeyjoincolumn\Seller.java
2
请在Spring Boot框架中完成以下Java代码
public void createDynamicAttrConfig() { log.info("init create dynamic box"); ConfigurableApplicationContext context = (ConfigurableApplicationContext) applicationContext; DefaultListableBeanFactory beanFactory = (DefaultListableBeanFactory) context.getBeanFactory(); for (int i = 1; i <= count; i++) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Person.class); /** * 设置属性 */ beanDefinitionBuilder.addPropertyValue("id", i); beanDefinitionBuilder.addPropertyValue("name", "wxc"); beanDefinitionBuilder.addPropertyValue("address", "earth"); beanDefinitionBuilder.addPropertyValue("age", 1000); beanDefinitionBuilder.addPropertyValue("birthday", new Date()); // beanDefinitionBuilder.addDependsOn() 可以添加依赖如注入其他bean等 /**
* 注册到spring容器中 */ beanFactory.registerBeanDefinition("person_" + i, beanDefinitionBuilder.getBeanDefinition()); } } @Bean @ConditionalOnProperty(prefix = "dynamic.", value = "annotate.switch") public void createDynamicAnnotationConfig() { for (int i = 0; i < values.length; i++) { DynamicPropertySource dynamicPropertySource = DynamicPropertySource.builder().setSourceName(SOURCE_NAME) .setProperty(key, values[i]).build(); environment.getPropertySources().addFirst(dynamicPropertySource); log.info("{}--->{}", key, environment.getProperty(key)); } } }
repos\spring-boot-quick-master\quick-dynamic-bean\src\main\java\com\dynamic\bean\config\BeanConfig.java
2
请完成以下Java代码
public byte[] getScript () { return (byte[])get_Value(COLUMNNAME_Script); } /** Set Roll the Script. @param ScriptRoll Roll the Script */ public void setScriptRoll (String ScriptRoll) { set_Value (COLUMNNAME_ScriptRoll, ScriptRoll); } /** Get Roll the Script. @return Roll the Script */ public String getScriptRoll () { return (String)get_Value(COLUMNNAME_ScriptRoll); } /** Status AD_Reference_ID=53239 */ public static final int STATUS_AD_Reference_ID=53239; /** In Progress = IP */ public static final String STATUS_InProgress = "IP"; /** Completed = CO */ public static final String STATUS_Completed = "CO"; /** Error = ER */ public static final String STATUS_Error = "ER"; /** Set Status. @param Status Status of the currently running check */
public void setStatus (String Status) { set_ValueNoCheck (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationScript.java
1
请完成以下Java代码
public class GuavaEventBusBeanFactoryPostProcessor implements BeanFactoryPostProcessor { private final Logger logger = LoggerFactory.getLogger(this.getClass()); private final SpelExpressionParser expressionParser = new SpelExpressionParser(); @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { for (Iterator<String> names = beanFactory.getBeanNamesIterator(); names.hasNext(); ) { Object proxy = this.getTargetObject(beanFactory.getBean(names.next())); final Subscriber annotation = AnnotationUtils.getAnnotation(proxy.getClass(), Subscriber.class); if (annotation == null) continue; this.logger.info("{}: processing bean of type {} during initialization", this.getClass().getSimpleName(), proxy.getClass().getName()); final String annotationValue = annotation.value(); try { final Expression expression = this.expressionParser.parseExpression(annotationValue); final Object value = expression.getValue(); if (!(value instanceof EventBus)) { this.logger.error("{}: expression {} did not evaluate to an instance of EventBus for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getSimpleName()); return; } final EventBus eventBus = (EventBus)value;
eventBus.register(proxy); } catch (ExpressionException ex) { this.logger.error("{}: unable to parse/evaluate expression {} for bean of type {}", this.getClass().getSimpleName(), annotationValue, proxy.getClass().getName()); } } } private Object getTargetObject(Object proxy) throws BeansException { if (AopUtils.isJdkDynamicProxy(proxy)) { try { return ((Advised)proxy).getTargetSource().getTarget(); } catch (Exception e) { throw new FatalBeanException("Error getting target of JDK proxy", e); } } return proxy; } }
repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\GuavaEventBusBeanFactoryPostProcessor.java
1
请完成以下Java代码
public final Timestamp getMovementDate() { return movementDate; } public final void setMovementDate(Timestamp dateShipped) { this.movementDate = dateShipped; } public final boolean isPreferBPartner() { return preferBPartner; } public final void setPreferBPartner(boolean preferBPartner) { this.preferBPartner = preferBPartner; } public final boolean isIgnorePostageFreeamount() {
return ignorePostageFreeamount; } public final void setIgnorePostageFreeamount(boolean ignorePostageFreeamount) { this.ignorePostageFreeamount = ignorePostageFreeamount; } public Set<Integer> getSelectedOrderLineIds() { return selectedOrderLineIds; } public void setSelectedOrderLineIds(Set<Integer> selectedOrderLineIds) { this.selectedOrderLineIds = selectedOrderLineIds; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\shipment\ShipmentParams.java
1
请完成以下Java代码
protected String databaseInstallationId(CommandContext commandContext) { try { PropertyEntity installationIdProperty = commandContext.getPropertyManager().findPropertyById(INSTALLATION_PROPERTY_NAME); return installationIdProperty != null ? installationIdProperty.getValue() : null; } catch (Exception e) { LOG.couldNotSelectInstallationId(e.getMessage()); return null; } } protected void checkInstallationIdLockExists(CommandContext commandContext) { PropertyEntity installationIdProperty = commandContext.getPropertyManager().findPropertyById("installationId.lock"); if (installationIdProperty == null) { LOG.noInstallationIdLockPropertyFound(); } } protected void updateTelemetryData(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = commandContext.getProcessEngineConfiguration(); String installationId = processEngineConfiguration.getInstallationId(); TelemetryDataImpl telemetryData = processEngineConfiguration.getTelemetryData(); // set installationId in the telemetry data telemetryData.setInstallation(installationId);
// set the persisted license key in the telemetry data and registry ManagementServiceImpl managementService = (ManagementServiceImpl) processEngineConfiguration.getManagementService(); String licenseKey = managementService.getLicenseKey(); if (licenseKey != null) { LicenseKeyDataImpl licenseKeyData = LicenseKeyDataImpl.fromRawString(licenseKey); managementService.setLicenseKeyForDiagnostics(licenseKeyData); telemetryData.getProduct().getInternals().setLicenseKey(licenseKeyData); } } protected void acquireExclusiveInstallationIdLock(CommandContext commandContext) { PropertyManager propertyManager = commandContext.getPropertyManager(); //exclusive lock propertyManager.acquireExclusiveLockForInstallationId(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\BootstrapEngineCommand.java
1
请完成以下Java代码
private void addPropertySource(List<PropertySource<?>> propertySources, String fileName, Function<File, String> propertySourceNamer) { File home = getHomeDirectory(); File file = (home != null) ? new File(home, fileName) : null; FileSystemResource resource = (file != null) ? new FileSystemResource(file) : null; if (resource != null && resource.exists() && resource.isFile()) { addPropertySource(propertySources, resource, propertySourceNamer); } } private void addPropertySource(List<PropertySource<?>> propertySources, FileSystemResource resource, Function<File, String> propertySourceNamer) { try { String name = propertySourceNamer.apply(resource.getFile()); for (PropertySourceLoader loader : PROPERTY_SOURCE_LOADERS) { if (canLoadFileExtension(loader, resource.getFilename())) { propertySources.addAll(loader.load(name, resource)); } } } catch (IOException ex) { throw new IllegalStateException("Unable to load " + resource.getFilename(), ex); } } private boolean canLoadFileExtension(PropertySourceLoader loader, String name) { return Arrays.stream(loader.getFileExtensions()) .anyMatch((fileExtension) -> StringUtils.endsWithIgnoreCase(name, fileExtension)); }
protected @Nullable File getHomeDirectory() { return getHomeDirectory(() -> this.environmentVariables.get("SPRING_DEVTOOLS_HOME"), () -> this.systemProperties.getProperty("spring.devtools.home"), () -> this.systemProperties.getProperty("user.home")); } @SafeVarargs private @Nullable File getHomeDirectory(Supplier<String>... pathSuppliers) { for (Supplier<String> pathSupplier : pathSuppliers) { String path = pathSupplier.get(); if (StringUtils.hasText(path)) { return new File(path); } } return null; } }
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\env\DevToolsHomePropertiesPostProcessor.java
1
请在Spring Boot框架中完成以下Java代码
private static List<AuthenticationProvider> createDefaultAuthenticationProviders(HttpSecurity httpSecurity) { List<AuthenticationProvider> authenticationProviders = new ArrayList<>(); RegisteredClientRepository registeredClientRepository = OAuth2ConfigurerUtils .getRegisteredClientRepository(httpSecurity); OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(httpSecurity); JwtClientAssertionAuthenticationProvider jwtClientAssertionAuthenticationProvider = new JwtClientAssertionAuthenticationProvider( registeredClientRepository, authorizationService); authenticationProviders.add(jwtClientAssertionAuthenticationProvider); X509ClientCertificateAuthenticationProvider x509ClientCertificateAuthenticationProvider = new X509ClientCertificateAuthenticationProvider( registeredClientRepository, authorizationService); authenticationProviders.add(x509ClientCertificateAuthenticationProvider);
ClientSecretAuthenticationProvider clientSecretAuthenticationProvider = new ClientSecretAuthenticationProvider( registeredClientRepository, authorizationService); PasswordEncoder passwordEncoder = OAuth2ConfigurerUtils.getOptionalBean(httpSecurity, PasswordEncoder.class); if (passwordEncoder != null) { clientSecretAuthenticationProvider.setPasswordEncoder(passwordEncoder); } authenticationProviders.add(clientSecretAuthenticationProvider); PublicClientAuthenticationProvider publicClientAuthenticationProvider = new PublicClientAuthenticationProvider( registeredClientRepository, authorizationService); authenticationProviders.add(publicClientAuthenticationProvider); return authenticationProviders; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2ClientAuthenticationConfigurer.java
2
请完成以下Java代码
public void setM_Allergen_Trace(final org.compiere.model.I_M_Allergen_Trace M_Allergen_Trace) { set_ValueFromPO(COLUMNNAME_M_Allergen_Trace_ID, org.compiere.model.I_M_Allergen_Trace.class, M_Allergen_Trace); } @Override public void setM_Allergen_Trace_ID (final int M_Allergen_Trace_ID) { if (M_Allergen_Trace_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Allergen_Trace_ID, M_Allergen_Trace_ID); } @Override public int getM_Allergen_Trace_ID()
{ return get_ValueAsInt(COLUMNNAME_M_Allergen_Trace_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Allergen_Trace_Trl.java
1
请完成以下Java代码
public class JsonRRequestUpsertRequest { @ApiModelProperty(value = SwaggerDocConstants.ORG_CODE_PARAMETER_DOC) @NonNull String orgCode; @NonNull String requestType; @ApiModelProperty(value = SwaggerDocConstants.BPARTNER_VALUE_DOC) @Nullable String bpartnerIdentifier; @ApiModelProperty(value = SwaggerDocConstants.CONTACT_IDENTIFIER_DOC) @Nullable String userIdentifier; @Nullable JsonRequestPriority priority; @NonNull String summary; @Nullable JsonConfidentialType confidentialityLevel; @ApiModelProperty(value = SwaggerDocConstants.BPARTNER_VALUE_DOC) @Nullable String vendorIdentifier; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @Nullable LocalDate dateDelivered; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
@Nullable LocalDate dateTrx; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") @Nullable LocalDate reminderDate; @Nullable String projectValue; @ApiModelProperty(value = SwaggerDocConstants.PRODUCT_IDENTIFIER_DOC) @Nullable String productIdentifier; @Nullable JsonMetasfreshId orderId; @Nullable JsonMetasfreshId inOutId; @Nullable JsonMetasfreshId invoiceId; @Nullable JsonMetasfreshId paymentId; @Nullable String qualityNote; @ApiModelProperty(value = SwaggerDocConstants.CONTACT_IDENTIFIER_DOC) @Nullable String salesRepIdentifier; @Nullable String statusName; }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api\src\main\java\de\metas\rest_api\request\JsonRRequestUpsertRequest.java
1
请在Spring Boot框架中完成以下Java代码
public final class OpenSamlInitializationService { private static final Log log = LogFactory.getLog(OpenSamlInitializationService.class); private static final AtomicBoolean initialized = new AtomicBoolean(false); private OpenSamlInitializationService() { } /** * Ready OpenSAML for use and configure it with reasonable defaults. * * Initialization is guaranteed to happen only once per application. This method will * passively return {@code false} if initialization already took place earlier in the * application. * @return whether or not initialization was performed. The first thread to initialize * OpenSAML will return {@code true} while the rest will return {@code false}. * @throws Saml2Exception if OpenSAML failed to initialize */ public static boolean initialize() { return initialize((registry) -> { }); } /** * Ready OpenSAML for use, configure it with reasonable defaults, and modify the * {@link XMLObjectProviderRegistry} using the provided {@link Consumer}. * * Initialization is guaranteed to happen only once per application. This method will * throw an exception if initialization already took place earlier in the application. * @param registryConsumer the {@link Consumer} to further configure the * {@link XMLObjectProviderRegistry} * @throws Saml2Exception if initialization already happened previously or if OpenSAML * failed to initialize */
public static void requireInitialize(Consumer<XMLObjectProviderRegistry> registryConsumer) { if (!initialize(registryConsumer)) { throw new Saml2Exception("OpenSAML was already initialized previously"); } } private static boolean initialize(Consumer<XMLObjectProviderRegistry> registryConsumer) { if (initialized.compareAndSet(false, true)) { log.trace("Initializing OpenSAML"); try { InitializationService.initialize(); } catch (Exception ex) { throw new Saml2Exception(ex); } registryConsumer.accept(ConfigurationService.get(XMLObjectProviderRegistry.class)); log.debug("Initialized OpenSAML"); return true; } log.debug("Refused to re-initialize OpenSAML"); return false; } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\core\OpenSamlInitializationService.java
2
请完成以下Java代码
private File mkTmpPrintFile(final PrintPackageRequest printRequest) { final PrintPackage printPackage = printRequest.getPrintPackage(); final PrintPackageInfo printPackageInfo = printRequest.getPrintPackageInfo(); final File dir = new File(redirectDirName); final String filename = "out" + "-" + printPackage.getTransactionId() + "-" + Context.getContext().getProperty(Context.CTX_SessionId) + "-" + printPackageInfo.getPrintService() + "-" + printPackageInfo.getTray() + "-" + printPackageInfo.getPageFrom() + "-" + printPackageInfo.getPageTo() + ".xps"; final File file = new File(dir, filename); return file; } private boolean isRedirectToFile() { return redirectDirName != null && !redirectDirName.isEmpty(); } public PrinterHWList createPrinterHW() { final List<PrinterHW> printerHWs = new ArrayList<>(); for (final PrintService printService : getPrintServices()) { final PrinterHW printerHW = new PrinterHW(); printerHW.setName(printService.getName()); final List<PrinterHWMediaSize> printerHWMediaSizes = new ArrayList<>(); printerHW.setPrinterHWMediaSizes(printerHWMediaSizes); final List<PrinterHWMediaTray> printerHWMediaTrays = new ArrayList<>(); printerHW.setPrinterHWMediaTrays(printerHWMediaTrays); // 04005: detect the default media tray final MediaTray defaultMediaTray = (MediaTray)printService.getDefaultAttributeValue(MediaTray.class); final Media[] medias = (Media[])printService.getSupportedAttributeValues(Media.class, null, null); // flavor=null, attributes=null for (final Media media : medias) { if (media instanceof MediaSizeName) { final String name = media.toString(); // final MediaSizeName mediaSize = (MediaSizeName)media; final PrinterHWMediaSize printerHWMediaSize = new PrinterHWMediaSize(); printerHWMediaSize.setName(name); // printerHWMediaSize.setIsDefault(isDefault); printerHWMediaSizes.add(printerHWMediaSize); } else if (media instanceof MediaTray) { final MediaTray mediaTray = (MediaTray)media; final String name = mediaTray.toString();
final String trayNumber = Integer.toString(mediaTray.getValue()); final PrinterHWMediaTray printerHWMediaTray = new PrinterHWMediaTray(); printerHWMediaTray.setName(name); printerHWMediaTray.setTrayNumber(trayNumber); // 04005: default media tray shall be first in the list if (mediaTray.equals(defaultMediaTray)) { printerHWMediaTrays.add(0, printerHWMediaTray); } else { printerHWMediaTrays.add(printerHWMediaTray); } } } printerHWs.add(printerHW); } final PrinterHWList list = new PrinterHWList(); list.setHwPrinters(printerHWs); return list; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintingEngine.java
1
请完成以下Java代码
public @Nullable Object getCredentials() { return this.credentials; } /** * Get the principal */ @Override public Object getPrincipal() { return this.principal; } @Override public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link PreAuthenticatedAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private Object principal; private @Nullable Object credentials; protected Builder(PreAuthenticatedAuthenticationToken token) { super(token); this.principal = token.principal; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) {
Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } @Override public B credentials(@Nullable Object credentials) { this.credentials = credentials; return (B) this; } @Override public PreAuthenticatedAuthenticationToken build() { return new PreAuthenticatedAuthenticationToken(this); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\PreAuthenticatedAuthenticationToken.java
1
请完成以下Java代码
private ZonedDateTime toZonedDateTime(@NonNull final OrgId orgId, @Nullable final LocalDateTime dateTime) { if (dateTime == null) { return null; } final ZoneId timeZoneId = orgRepo.getTimeZone(orgId); return TimeUtil.asZonedDateTime(dateTime, timeZoneId); } @Nullable private I_M_InOutLine getShipmentLine(@Nullable final JsonMetasfreshId shipmentScheduleId) { if (shipmentScheduleId == null) { return null; } final ShipmentScheduleId scheduleId = ShipmentScheduleId.ofRepoId(shipmentScheduleId.getValue()); final List<I_M_ShipmentSchedule_QtyPicked> pickedLines = shipmentScheduleAllocDAO.retrieveOnShipmentLineRecords(scheduleId); if (Check.isEmpty(pickedLines)) { return null; } //at this point we are sure there is a shipment line id present on all the retrieved `pickedLines` final InOutLineId shipmentLineId = InOutLineId.ofRepoId(pickedLines.get(0).getM_InOutLine_ID()); return inOutDAO.getLineByIdInTrx(shipmentLineId); } @Value private static class ReturnProductInfoProvider { Map<String, I_M_Product> searchKey2Product = new HashMap<>(); Map<String, OrgId> searchKey2Org = new HashMap<>(); IProductDAO productRepo = Services.get(IProductDAO.class); IOrgDAO orgDAO = Services.get(IOrgDAO.class); IUOMDAO uomDAO = Services.get(IUOMDAO.class); private static ReturnProductInfoProvider newInstance() { return new ReturnProductInfoProvider(); } private OrgId getOrgId(@NonNull final String orgCode) { return searchKey2Org.computeIfAbsent(orgCode, this::retrieveOrgId); } @NonNull private ProductId getProductId(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey);
return ProductId.ofRepoId(product.getM_Product_ID()); } @NonNull private I_C_UOM getStockingUOM(@NonNull final String productSearchKey) { final I_M_Product product = getProductNotNull(productSearchKey); return uomDAO.getById(UomId.ofRepoId(product.getC_UOM_ID())); } @NonNull private I_M_Product getProductNotNull(@NonNull final String productSearchKey) { final I_M_Product product = searchKey2Product.computeIfAbsent(productSearchKey, this::loadProduct); if (product == null) { throw new AdempiereException("No product could be found for the target search key!") .appendParametersToMessage() .setParameter("ProductSearchKey", productSearchKey); } return product; } private I_M_Product loadProduct(@NonNull final String productSearchKey) { return productRepo.retrieveProductByValue(productSearchKey); } private OrgId retrieveOrgId(@NonNull final String orgCode) { final OrgQuery query = OrgQuery.builder() .orgValue(orgCode) .failIfNotExists(true) .build(); return orgDAO.retrieveOrgIdBy(query).orElseThrow(() -> new AdempiereException("No AD_Org was found for the given search key!") .appendParametersToMessage() .setParameter("OrgSearchKey", orgCode)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\CustomerReturnRestService.java
1
请在Spring Boot框架中完成以下Java代码
public AppDefinitionQuery orderByAppDefinitionKey() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_KEY); } @Override public AppDefinitionQuery orderByAppDefinitionCategory() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_CATEGORY); } @Override public AppDefinitionQuery orderByAppDefinitionId() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_ID); } @Override public AppDefinitionQuery orderByAppDefinitionVersion() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_VERSION); } @Override public AppDefinitionQuery orderByAppDefinitionName() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_NAME); } @Override public AppDefinitionQuery orderByTenantId() { return orderBy(AppDefinitionQueryProperty.APP_DEFINITION_TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionCountByQueryCriteria(this); } @Override public List<AppDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getAppDefinitionEntityManager(commandContext).findAppDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public Integer getVersion() { return version;
} public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; } public Integer getVersionLt() { return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDefinitionQueryImpl.java
2
请在Spring Boot框架中完成以下Java代码
public int getNumberOfTasks() { return numberOfTasks; } public void setNumberOfTasks(int numberOfTasks) { this.numberOfTasks = numberOfTasks; } public int getNumberOfRetries() { return numberOfRetries; } public void setNumberOfRetries(int numberOfRetries) { this.numberOfRetries = numberOfRetries; }
public String getWorkerId() { return workerId; } public void setWorkerId(String workerId) { this.workerId = workerId; } public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } }
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\acquire\AcquireExternalWorkerJobRequest.java
2
请完成以下Java代码
public boolean isRunnable() { return true; } @Override public void run() { throw new UnsupportedOperationException(); } @Override public boolean createUI(java.awt.Container parent) { final VEditor editor = getEditor(); final GridField gridField = editor.getField(); final Container textComponent = (Container)editor;
final List<JMenuItem> items = BoilerPlateMenu.createMenuElements(textComponent, gridField); if (items == null || items.isEmpty()) { return false; } for (JMenuItem item : items) { parent.add(item); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\BoilerPlateMenuAction.java
1
请完成以下Java代码
public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public BoilerPlateContext getAttributes() { return boilerPlateMenu.getAttributes(); } public void setAttributes(final BoilerPlateContext attributes) { boilerPlateMenu.setAttributes(attributes); } public File getPDF(String fileNamePrefix) { throw new UnsupportedOperationException(); } private void actionPreview() { // final ReportEngine re = getReportEngine(); // ReportCtl.preview(re); File pdf = getPDF(null); if (pdf != null) { Env.startBrowser(pdf.toURI().toString()); } } private Dialog getParentDialog() { Dialog parent = null; Container e = getParent(); while (e != null) { if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() { throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null)
return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText) { if (plainText == null) return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setRoutingNo (final java.lang.String RoutingNo) { set_Value (COLUMNNAME_RoutingNo, RoutingNo); }
@Override public java.lang.String getRoutingNo() { return get_ValueAsString(COLUMNNAME_RoutingNo); } @Override public void setSwiftCode (final @Nullable java.lang.String SwiftCode) { set_Value (COLUMNNAME_SwiftCode, SwiftCode); } @Override public java.lang.String getSwiftCode() { return get_ValueAsString(COLUMNNAME_SwiftCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java
1
请完成以下Java代码
String getReturnType() { return this.returnType; } List<Parameter> getParameters() { return this.parameters; } int getModifiers() { return this.modifiers; } CodeBlock getCode() { return this.code; } @Override public AnnotationContainer annotations() { return this.annotations; } /** * Builder for creating a {@link GroovyMethodDeclaration}. */ public static final class Builder { private final String name; private List<Parameter> parameters = new ArrayList<>(); private String returnType = "void"; private int modifiers = Modifier.PUBLIC; private Builder(String name) { this.name = name; } /** * Sets the modifiers. * @param modifiers the modifiers
* @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /** * Sets the return type. * @param returnType the return type * @return this for method chaining */ public Builder returning(String returnType) { this.returnType = returnType; return this; } /** * Sets the parameters. * @param parameters the parameters * @return this for method chaining */ public Builder parameters(Parameter... parameters) { this.parameters = Arrays.asList(parameters); return this; } /** * Sets the body. * @param code the code for the body * @return the method for the body */ public GroovyMethodDeclaration body(CodeBlock code) { return new GroovyMethodDeclaration(this, code); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyMethodDeclaration.java
1
请完成以下Java代码
public class ReactiveAuthenticationManagerAdapter implements ReactiveAuthenticationManager { private final AuthenticationManager authenticationManager; private Scheduler scheduler = Schedulers.boundedElastic(); public ReactiveAuthenticationManagerAdapter(AuthenticationManager authenticationManager) { Assert.notNull(authenticationManager, "authenticationManager cannot be null"); this.authenticationManager = authenticationManager; } @Override public Mono<Authentication> authenticate(Authentication token) { // @formatter:off return Mono.just(token) .publishOn(this.scheduler) .flatMap(this::doAuthenticate) .filter(Authentication::isAuthenticated); // @formatter:on } private Mono<Authentication> doAuthenticate(Authentication authentication) { try { return Mono.just(this.authenticationManager.authenticate(authentication)); }
catch (Throwable ex) { return Mono.error(ex); } } /** * Set a scheduler that will be published on to perform the authentication logic. * @param scheduler a scheduler to be published on * @throws IllegalArgumentException if the scheduler is {@code null} */ public void setScheduler(Scheduler scheduler) { Assert.notNull(scheduler, "scheduler cannot be null"); this.scheduler = scheduler; } }
repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\ReactiveAuthenticationManagerAdapter.java
1
请完成以下Java代码
public class TreatmentType { @XmlAttribute(name = "apid") protected String apid; @XmlAttribute(name = "acid") protected String acid; /** * Gets the value of the apid property. * * @return * possible object is * {@link String } * */ public String getApid() { return apid; } /** * Sets the value of the apid property. * * @param value * allowed object is * {@link String } * */ public void setApid(String value) { this.apid = value; } /** * Gets the value of the acid property. * * @return * possible object is
* {@link String } * */ public String getAcid() { return acid; } /** * Sets the value of the acid property. * * @param value * allowed object is * {@link String } * */ public void setAcid(String value) { this.acid = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\TreatmentType.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean isReturnableContainer() { return returnableContainer; } /** * Sets the value of the returnableContainer property. * * @param value * allowed object is * {@link Boolean } * */ public void setReturnableContainer(Boolean value) { this.returnableContainer = value; } /** * Gets the value of the quantityInHigherLevelAssortmentUnit property. * * @return * possible object is
* {@link UnitType } * */ public UnitType getQuantityInHigherLevelAssortmentUnit() { return quantityInHigherLevelAssortmentUnit; } /** * Sets the value of the quantityInHigherLevelAssortmentUnit property. * * @param value * allowed object is * {@link UnitType } * */ public void setQuantityInHigherLevelAssortmentUnit(UnitType value) { this.quantityInHigherLevelAssortmentUnit = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\DESADVListLineItemExtensionType.java
2
请完成以下Java代码
public <V> V get(Object key) { return hasKey(key) ? (V) this.context.get(key) : null; } @Override public boolean hasKey(Object key) { Assert.notNull(key, "key cannot be null"); return this.context.containsKey(key); } /** * Returns the {@link RegisteredClient registered client}. * @return the {@link RegisteredClient} */ public RegisteredClient getRegisteredClient() { return get(RegisteredClient.class); } /** * Constructs a new {@link Builder} with the provided * {@link OAuth2ClientAuthenticationToken}. * @param authentication the {@link OAuth2ClientAuthenticationToken} * @return the {@link Builder} */ public static Builder with(OAuth2ClientAuthenticationToken authentication) { return new Builder(authentication); } /** * A builder for {@link OAuth2ClientAuthenticationContext}. */ public static final class Builder extends AbstractBuilder<OAuth2ClientAuthenticationContext, Builder> { private Builder(OAuth2ClientAuthenticationToken authentication) { super(authentication); } /** * Sets the {@link RegisteredClient registered client}. * @param registeredClient the {@link RegisteredClient} * @return the {@link Builder} for further configuration
*/ public Builder registeredClient(RegisteredClient registeredClient) { return put(RegisteredClient.class, registeredClient); } /** * Builds a new {@link OAuth2ClientAuthenticationContext}. * @return the {@link OAuth2ClientAuthenticationContext} */ @Override public OAuth2ClientAuthenticationContext build() { Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null"); return new OAuth2ClientAuthenticationContext(getContext()); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2ClientAuthenticationContext.java
1
请完成以下Java代码
private float computeEntropy(Map<Character, int[]> storage) { float sum = 0; for (Map.Entry<Character, int[]> entry : storage.entrySet()) { float p = entry.getValue()[0] / (float) frequency; sum -= p * Math.log(p); } return sum; } void update(char left, char right) { ++frequency; increaseFrequency(left, this.left); increaseFrequency(right, this.right); } void computeProbabilityEntropy(int length) { p = frequency / (float) length; leftEntropy = computeEntropy(left); rightEntropy = computeEntropy(right); entropy = Math.min(leftEntropy, rightEntropy);
} void computeAggregation(Map<String, WordInfo> word_cands) { if (text.length() == 1) { aggregation = (float) Math.sqrt(p); return; } for (int i = 1; i < text.length(); ++i) { aggregation = Math.min(aggregation, p / word_cands.get(text.substring(0, i)).p / word_cands.get(text.substring(i)).p); } } @Override public String toString() { return text; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word\WordInfo.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Post> getPosts() { return posts; } public void setPosts(Set<Post> posts) { this.posts = posts; } public int getAge() {
return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } }
repos\tutorials-master\persistence-modules\blaze-persistence\src\main\java\com\baeldung\model\Person.java
1
请完成以下Java代码
public void run() { try { collectMetrics(); } catch(Exception e) { try { LOG.couldNotCollectAndLogMetrics(e); } catch (Exception ex) { // ignore if log can't be written } } } protected void collectMetrics() { List<MeterLogEntity> logs = new ArrayList<>(); for (Meter meter : metricsRegistry.getDbMeters().values()) { logs.add(new MeterLogEntity(meter.getName(), reporterId, meter.getAndClear(), ClockUtil.getCurrentTime())); } commandExecutor.execute(new MetricsCollectionCmd(logs)); } public String getReporter() { return reporterId; }
public void setReporter(String reporterId) { this.reporterId = reporterId; } protected class MetricsCollectionCmd implements Command<Void> { protected List<MeterLogEntity> logs; public MetricsCollectionCmd(List<MeterLogEntity> logs) { this.logs = logs; } @Override public Void execute(CommandContext commandContext) { for (MeterLogEntity meterLogEntity : logs) { commandContext.getMeterLogManager().insert(meterLogEntity); } return null; } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\reporter\MetricsCollectionTask.java
1
请完成以下Java代码
public Object getBaseObject() { return user; } @Override public int getAD_Table_ID() { return InterfaceWrapperHelper.getModelTableId(user); } @Override public int getRecord_ID() { return user.getAD_User_ID(); } @Override public EMail sendEMail(final I_AD_User from, final String toEmail, final String subject, final BoilerPlateContext attributes) { final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder() .clientId(getClientId()) .orgId(getOrgId()) .adProcessId(getProcessInfo().getAdProcessId()) .fromUserId(getFromUserId()) .build()); return mailService.sendEMail(EMailRequest.builder() .mailbox(mailbox) .toList(toEMailAddresses(toEmail)) .subject(text.getSubject()) .message(text.getTextSnippetParsed(attributes)) .html(true) .build()); } }); } private void createNote(MADBoilerPlate text, I_AD_User user, Exception e) { final AdMessageId adMessageId = Services.get(IMsgBL.class).getIdByAdMessage(AD_Message_UserNotifyError) .orElseThrow(() -> new AdempiereException("@NotFound@ @AD_Message_ID@ " + AD_Message_UserNotifyError)); // final IMsgBL msgBL = Services.get(IMsgBL.class); final String reference = msgBL.parseTranslation(getCtx(), "@AD_BoilerPlate_ID@: " + text.get_Translation(MADBoilerPlate.COLUMNNAME_Name)) + ", " + msgBL.parseTranslation(getCtx(), "@AD_User_ID@: " + user.getName())
// +", "+Msg.parseTranslation(getCtx(), "@AD_PInstance_ID@: "+getAD_PInstance_ID()) ; final MNote note = new MNote(getCtx(), adMessageId.getRepoId(), getFromUserId().getRepoId(), InterfaceWrapperHelper.getModelTableId(user), user.getAD_User_ID(), reference, e.getLocalizedMessage(), get_TrxName()); note.setAD_Org_ID(0); note.saveEx(); m_count_notes++; } static List<EMailAddress> toEMailAddresses(final String string) { final StringTokenizer st = new StringTokenizer(string, " ,;", false); final ArrayList<EMailAddress> result = new ArrayList<>(); while (st.hasMoreTokens()) { result.add(EMailAddress.ofString(st.nextToken())); } return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToUsers.java
1
请在Spring Boot框架中完成以下Java代码
public Locale getCurrentLocale() { final HttpSession httpSession = getCurrentHttpSessionOrNull(); if (httpSession == null) { return Locale.getDefault(); } final LanguageKey languageKey = (LanguageKey)httpSession.getAttribute(HTTP_SESSION_language); return languageKey != null ? languageKey.toLocale() : Locale.getDefault(); } @Nullable private HttpSession getCurrentHttpSessionOrNull() { final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); if (servletRequestAttributes == null) { return null; } return servletRequestAttributes.getRequest().getSession(); } private LanguageData getLanguageData(@Nullable final LanguageKey language) { final LanguageKey languageEffective = language != null ? language : LanguageKey.getDefault(); return cache.computeIfAbsent(languageEffective, LanguageData::new); } public ImmutableMap<String, String> getMessagesMap(@NonNull final LanguageKey language) { return getLanguageData(language).getFrontendMessagesMap(); } private static class LanguageData { @Getter private final ResourceBundle resourceBundle; @Getter
private final ImmutableMap<String, String> frontendMessagesMap; private LanguageData(final @NonNull LanguageKey language) { resourceBundle = ResourceBundle.getBundle("messages", language.toLocale()); frontendMessagesMap = computeMessagesMap(resourceBundle); } private static ImmutableMap<String, String> computeMessagesMap(@NonNull final ResourceBundle bundle) { final Set<String> keys = bundle.keySet(); final HashMap<String, String> map = new HashMap<>(keys.size()); for (final String key : keys) { // shall not happen if (key == null || key.isBlank()) { continue; } final String value = Strings.nullToEmpty(bundle.getString(key)); map.put(key, value); } return ImmutableMap.copyOf(map); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\I18N.java
2
请在Spring Boot框架中完成以下Java代码
public class TestingGenericZoomIntoTableInfoRepository implements GenericZoomIntoTableInfoRepository { private final IQueryBL queryBL = Services.get(IQueryBL.class); @Override public GenericZoomIntoTableInfo retrieveTableInfo( @NonNull final String tableName, final boolean ignoreExcludeFromZoomTargetsFlag) { if (!Adempiere.isUnitTestMode()) { throw new AdempiereException("Repository " + this + " shall be used only for JUnit testing!!!"); } return GenericZoomIntoTableInfo.builder() .tableName(tableName) .keyColumnNames(ImmutableSet.of(InterfaceWrapperHelper.getKeyColumnName(tableName))) .windows(genericZoomIntoTableWindows(tableName)) .build(); } @NonNull private ImmutableList<GenericZoomIntoTableWindow> genericZoomIntoTableWindows(@NonNull final String tableName) { final AdWindowId windowId = queryBL.createQueryBuilder(I_AD_Table.class) .addEqualsFilter(I_AD_Table.COLUMNNAME_TableName, tableName)
.create() .firstOnlyOptional(I_AD_Table.class) .map(I_AD_Table::getAD_Window_ID) .map(AdWindowId::ofRepoIdOrNull) .orElse(null); if (windowId == null) { return ImmutableList.of(); } return ImmutableList.of( GenericZoomIntoTableWindow.builder() .adWindowId(windowId) .build() ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\zoom_into\TestingGenericZoomIntoTableInfoRepository.java
2
请完成以下Java代码
public boolean hasAccess(final Access access) { return accesses.contains(access); } public boolean hasReadAccess() { return accesses.contains(Access.READ); } public boolean hasWriteAccess() { return accesses.contains(Access.WRITE); } @Nullable public Boolean getReadWriteBoolean() { if (hasAccess(Access.WRITE)) { return Boolean.TRUE; } else if (hasAccess(Access.READ)) { return Boolean.FALSE; } else { return null; } } @Override public ElementPermission mergeWith(final Permission permissionFrom) { final ElementPermission elementPermissionFrom = PermissionInternalUtils.checkCompatibleAndCastToTarget(this, permissionFrom);
return withAccesses(ImmutableSet.<Access>builder() .addAll(this.accesses) .addAll(elementPermissionFrom.accesses) .build()); } private ElementPermission withAccesses(@NonNull final ImmutableSet<Access> accesses) { return !Objects.equals(this.accesses, accesses) ? new ElementPermission(this.resource, accesses) : this; } public ElementPermission withResource(@NonNull final ElementResource resource) { return !Objects.equals(this.resource, resource) ? new ElementPermission(resource, this.accesses) : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\ElementPermission.java
1