instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public OrgChangeBPartnerComposite getByIdAndOrgChangeDate( @NonNull final BPartnerId bpartnerId, @NonNull final Instant orgChangeDate) { final OrgMappingId orgMappingId = orgMappingRepo.getCreateOrgMappingId(bpartnerId); final BPartnerComposite bPartnerComposite = bPartnerCompositeRepo.getById(bpartnerId); return OrgChangeBPartnerComposite.builder() .bPartnerComposite(bPartnerComposite) .bPartnerOrgMappingId(orgMappingId) .membershipSubscriptions(getMembershipSubscriptions(bpartnerId, orgChangeDate, bPartnerComposite.getOrgId())) .allRunningSubscriptions(getAllRunningSubscriptions(bpartnerId, orgChangeDate, bPartnerComposite.getOrgId())) .groupCategoryId(getGroupCategoryId(bpartnerId, orgChangeDate, bPartnerComposite.getOrgId()).orElse(null)) .build(); } private Optional<GroupCategoryId> getGroupCategoryId(@NonNull final BPartnerId bpartnerId, final Instant orgChangeDate, final OrgId orgId) { return membershipContractRepo.queryMembershipRunningSubscription(bpartnerId, orgChangeDate, orgId) .stream() .map(term -> productDAO.getById(term.getM_Product_ID())) .filter(product -> product.getC_CompensationGroup_Schema_Category_ID() > 0) .map(product -> GroupCategoryId.ofRepoId(product.getC_CompensationGroup_Schema_Category_ID())) .findFirst(); } private Collection<FlatrateTerm> getAllRunningSubscriptions(@NonNull final BPartnerId bpartnerId, @NonNull final Instant orgChangeDate,
@NonNull final OrgId orgId) { final Set<FlatrateTermId> flatrateTermIds = flatrateDAO.retrieveAllRunningSubscriptionIds(bpartnerId, orgChangeDate, orgId); return flatrateTermIds.stream() .map(flatrateTermRepo::getById) .collect(ImmutableList.toImmutableList()); } private List<FlatrateTerm> getMembershipSubscriptions(final BPartnerId bpartnerId, final Instant orgChangeDate, final OrgId orgId) { final Set<FlatrateTermId> membershipFlatrateTermIds = membershipContractRepo.retrieveMembershipSubscriptionIds(bpartnerId, orgChangeDate, orgId); return membershipFlatrateTermIds.stream() .map(flatrateTermRepo::getById) .collect(ImmutableList.toImmutableList()); } public boolean hasAnyMembershipProduct(@NonNull final OrgId orgId) { return membershipContractRepo.queryMembershipProducts(orgId).anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\bpartner\repository\OrgChangeRepository.java
2
请完成以下Java代码
private int getCreateReplicationTrx(final Properties ctx, final String replicationTrxName, final String trxName) { final I_EXP_ReplicationTrx replicationTrx = Services.get(IReplicationTrxDAO.class).retrieveReplicationTrxByName(ctx, replicationTrxName, ITrx.TRXNAME_None); if (replicationTrx != null) { return replicationTrx.getEXP_ReplicationTrx_ID(); } final I_EXP_ReplicationTrx replicationTrxNew = newInstance( I_EXP_ReplicationTrx.class, PlainContextAware.newWithTrxName(ctx, trxName)); replicationTrxNew.setName(replicationTrxName); save(replicationTrxNew); return replicationTrxNew.getEXP_ReplicationTrx_ID(); } @Override public I_EXP_ReplicationTrxLine createAndMatchVoidReplicationTrxLine(final Properties ctx, final String tableName, final String replicationTrxName, final String trxName) { Check.assume(!isTableIgnored(tableName), "tableName not ignored"); final int replicationTrxId = getCreateReplicationTrx(ctx, replicationTrxName, trxName); // // Create a new ReplicationTrxLine final I_EXP_ReplicationTrxLine replicationTrxLine = newInstance( I_EXP_ReplicationTrxLine.class, PlainContextAware.newWithTrxName(ctx, trxName)); replicationTrxLine.setEXP_ReplicationTrx_ID(replicationTrxId);
return replicationTrxLine; } @Override public void addTableToIgnoreList(final String tableName) { Check.assumeNotEmpty(tableName, "tableName not empty"); excludeTableNames.add(tableName); } @Override public boolean isTableIgnored(final String tableName) { return excludeTableNames.contains(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\trx\api\impl\ReplicationTrxBL.java
1
请完成以下Java代码
public final class QueueToRuleEngineMsg extends TbRuleEngineActorMsg { @Getter private final TenantId tenantId; @Getter private final Set<String> relationTypes; @Getter private final String failureMessage; public QueueToRuleEngineMsg(TenantId tenantId, TbMsg tbMsg, Set<String> relationTypes, String failureMessage) { super(tbMsg); this.tenantId = tenantId; this.relationTypes = relationTypes; this.failureMessage = failureMessage; } @Override public MsgType getMsgType() { return MsgType.QUEUE_TO_RULE_ENGINE_MSG; } @Override public void onTbActorStopped(TbActorStopReason reason) { String message;
if (msg.getRuleChainId() != null) { message = reason == TbActorStopReason.STOPPED ? String.format("Rule chain [%s] stopped", msg.getRuleChainId().getId()) : String.format("Failed to initialize rule chain [%s]!", msg.getRuleChainId().getId()); } else { message = reason == TbActorStopReason.STOPPED ? "Rule chain stopped" : "Failed to initialize rule chain!"; } msg.getCallback().onFailure(new RuleEngineException(message)); } public boolean isTellNext() { return relationTypes != null && !relationTypes.isEmpty(); } }
repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\queue\QueueToRuleEngineMsg.java
1
请完成以下Java代码
public static class Scrubber implements RewriteFunction<JsonNode,JsonNode> { private final Pattern fields; private final String replacement; public Scrubber(Config config) { this.fields = Pattern.compile(config.getFields()); this.replacement = config.getReplacement(); } @Override public Publisher<JsonNode> apply(ServerWebExchange t, JsonNode u) { return Mono.just(scrubRecursively(u)); } private JsonNode scrubRecursively(JsonNode u) { if ( !u.isContainerNode()) { return u; } if ( u.isObject()) { ObjectNode node = (ObjectNode)u; node.fields().forEachRemaining((f) -> { if ( fields.matcher(f.getKey()).matches() && f.getValue().isTextual()) { f.setValue(TextNode.valueOf(replacement));
} else { f.setValue(scrubRecursively(f.getValue())); } }); } else if ( u.isArray()) { ArrayNode array = (ArrayNode)u; for ( int i = 0 ; i < array.size() ; i++ ) { array.set(i, scrubRecursively(array.get(i))); } } return u; } } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway-2\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ScrubResponseGatewayFilterFactory.java
1
请完成以下Java代码
public Timestamp getDateNextRun(boolean requery) { if (requery) load(get_TrxName()); return getDateNextRun(); } // getDateNextRun /** * Get Logs * * @return logs */ @Override public AdempiereProcessorLog[] getLogs() { List<MWorkflowProcessorLog> list = new Query(getCtx(), MWorkflowProcessorLog.Table_Name, "AD_WorkflowProcessor_ID=?", get_TrxName()) .setParameters(new Object[] { getAD_WorkflowProcessor_ID() }) .setOrderBy("Created DESC") .list(MWorkflowProcessorLog.class); MWorkflowProcessorLog[] retValue = new MWorkflowProcessorLog[list.size()]; list.toArray(retValue); return retValue; } // getLogs /** * Delete old Request Log * * @return number of records
*/ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_WorkflowProcessorLog " + "WHERE AD_WorkflowProcessor_ID=" + getAD_WorkflowProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MWorkflowProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\wf\MWorkflowProcessor.java
1
请完成以下Java代码
public static InOutId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new InOutId(repoId) : null; } public static Optional<InOutId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final InOutId id) { return id != null ? id.getRepoId() : -1; } int repoId; private InOutId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "M_InOut_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable InOutId id1, @Nullable InOutId id2) {return Objects.equals(id1, id2);} public TableRecordReference toRecordRef() {return TableRecordReference.of(I_M_InOut.Table_Name, repoId);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\inout\InOutId.java
1
请在Spring Boot框架中完成以下Java代码
public void handleCacheClearError(RuntimeException exception, Cache cache) { // 处理缓存清除错误 log.error("Cache Clear Error: {}",exception.getMessage()); } }; } /** * Value 序列化 * * @param <T> * @author / */ static class FastJsonRedisSerializer<T> implements RedisSerializer<T> { private final Class<T> clazz; FastJsonRedisSerializer(Class<T> clazz) { super(); this.clazz = clazz; } @Override
public byte[] serialize(T t) throws SerializationException { if (t == null) { return new byte[0]; } return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8); } @Override public T deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } String str = new String(bytes, StandardCharsets.UTF_8); return JSON.parseObject(str, clazz); } } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedisConfiguration.java
2
请完成以下Java代码
public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Time Pattern.
@param TimePattern Java Time Pattern */ public void setTimePattern (String TimePattern) { set_Value (COLUMNNAME_TimePattern, TimePattern); } /** Get Time Pattern. @return Java Time Pattern */ public String getTimePattern () { return (String)get_Value(COLUMNNAME_TimePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
1
请完成以下Java代码
protected void paintTabBackground(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { int sel = (isSelected) ? 0 : 1; g.setColor(selectColor); g.fillRect(x, y + sel, w, h / 2); g.fillRect(x - 1, y + sel + h / 2, w + 2, h - h / 2); } @Override protected void paintTabBorder(Graphics g, int tabIndex, int x, int y, int w, int h, boolean isSelected) { g.translate(x - 4, y); int top = 0; int right = w + 6; // Paint Border g.setColor(selectHighlight); // Paint left g.drawLine(1, h - 1, 4, top + 4); g.fillRect(5, top + 2, 1, 2); g.fillRect(6, top + 1, 1, 1); // Paint top g.fillRect(7, top, right - 12, 1); // Paint right g.setColor(darkShadow); g.drawLine(right, h - 1, right - 3, top + 4); g.fillRect(right - 4, top + 2, 1, 2); g.fillRect(right - 5, top + 1, 1, 1); g.translate(-x + 4, -y); } @Override protected void paintContentBorderTopEdge( Graphics g, int x, int y, int w, int h, boolean drawBroken, Rectangle selRect, boolean isContentBorderPainted) { int right = x + w - 1; int top = y; g.setColor(selectHighlight); if (drawBroken && selRect.x >= x && selRect.x <= x + w)
{ // Break line to show visual connection to selected tab g.fillRect(x, top, selRect.x - 2 - x, 1); if (selRect.x + selRect.width < x + w - 2) { g.fillRect(selRect.x + selRect.width + 2, top, right - 2 - selRect.x - selRect.width, 1); } else { g.fillRect(x + w - 2, top, 1, 1); } } else { g.fillRect(x, top, w - 1, 1); } } @Override protected int getTabsOverlay() { return 6; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereTabbedPaneUI.java
1
请完成以下Java代码
public PdxInstance[] convert(String json) { try { JsonNode jsonNode = getObjectMapper().readTree(json); List<PdxInstance> pdxList = new ArrayList<>(); if (isArray(jsonNode)) { ArrayNode arrayNode = (ArrayNode) jsonNode; JsonToPdxConverter converter = getJsonToPdxConverter(); for (JsonNode object : asIterable(CollectionUtils.nullSafeIterator(arrayNode.elements()))) { pdxList.add(converter.convert(object.toString())); } } else if (isObject(jsonNode)) { ObjectNode objectNode = (ObjectNode) jsonNode; pdxList.add(getJsonToPdxConverter().convert(objectNode.toString())); } else { String message = String.format("Unable to process JSON node of type [%s];" + " expected either an [%s] or an [%s]", jsonNode.getNodeType(), JsonNodeType.OBJECT, JsonNodeType.ARRAY);
throw new IllegalStateException(message); } return pdxList.toArray(new PdxInstance[0]); } catch (JsonProcessingException cause) { throw new DataRetrievalFailureException("Failed to read JSON content", cause); } } private boolean isArray(@Nullable JsonNode node) { return node != null && (node.isArray() || JsonNodeType.ARRAY.equals(node.getNodeType())); } private boolean isObject(@Nullable JsonNode node) { return node != null && (node.isObject() || JsonNodeType.OBJECT.equals(node.getNodeType())); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JacksonJsonToPdxConverter.java
1
请在Spring Boot框架中完成以下Java代码
public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getVariableName() { return variableName; } public void setVariableName(String variableName) { this.variableName = variableName; } public String getVariableNameLike() { return variableNameLike; } public void setVariableNameLike(String variableNameLike) { this.variableNameLike = variableNameLike; }
@JsonTypeInfo(use = Id.CLASS, defaultImpl = QueryVariable.class) public List<QueryVariable> getVariables() { return variables; } public void setVariables(List<QueryVariable> variables) { this.variables = variables; } public void setExcludeLocalVariables(Boolean excludeLocalVariables) { this.excludeLocalVariables = excludeLocalVariables; } public Boolean getExcludeLocalVariables() { return excludeLocalVariables; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricVariableInstanceQueryRequest.java
2
请完成以下Java代码
/* package */class LockedByOrNotLockedAtAllFilter implements IQueryFilter<I_C_Invoice_Candidate_Recompute>, ISqlQueryFilter { /** * @param lock lock or <code>null</code> */ public static final LockedByOrNotLockedAtAllFilter of(final ILock lock) { return new LockedByOrNotLockedAtAllFilter(lock); } // services private final transient ILockManager lockManager = Services.get(ILockManager.class); // parameters private final ILock lock; // status private boolean sqlBuilt = false; private String sql = null; private LockedByOrNotLockedAtAllFilter(final ILock lock) { super(); this.lock = lock; } @Override public String getSql() { buildSqlIfNeeded(); return sql; } @Override public List<Object> getSqlParams(final Properties ctx) { return Collections.emptyList(); } private final void buildSqlIfNeeded() { if (sqlBuilt) { return; } final String columnNameInvoiceCandidateId = I_C_Invoice_Candidate_Recompute.Table_Name + "." + I_C_Invoice_Candidate_Recompute.COLUMNNAME_C_Invoice_Candidate_ID; final String lockedWhereClause; // // Case: no Lock was mentioned // => we consider only those records which were NOT locked if (lock == null) { lockedWhereClause = lockManager.getNotLockedWhereClause(I_C_Invoice_Candidate.Table_Name, columnNameInvoiceCandidateId); } // // Case: Lock is set // => we consider only those records which were locked by given lock else
{ lockedWhereClause = lockManager.getLockedWhereClause(I_C_Invoice_Candidate.class, columnNameInvoiceCandidateId, lock.getOwner()); } sql = "(" + lockedWhereClause + ")"; sqlBuilt = true; } @Override public boolean accept(final I_C_Invoice_Candidate_Recompute model) { if (model == null) { return false; } final int invoiceCandidateId = model.getC_Invoice_Candidate_ID(); return acceptInvoiceCandidateId(invoiceCandidateId); } public boolean acceptInvoiceCandidateId(final int invoiceCandidateId) { // // Case: no Lock was mentioned // => we consider only those records which were NOT locked if (lock == null) { return !lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId); } // // Case: Lock is set // => we consider only those records which were locked by given lock else { return lockManager.isLocked(I_C_Invoice_Candidate.class, invoiceCandidateId, lock.getOwner()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\LockedByOrNotLockedAtAllFilter.java
1
请完成以下Java代码
public static MStatusCategory get (Properties ctx, int R_StatusCategory_ID) { Integer key = new Integer (R_StatusCategory_ID); MStatusCategory retValue = (MStatusCategory)s_cache.get (key); if (retValue != null) return retValue; retValue = new MStatusCategory (ctx, R_StatusCategory_ID, null); if (retValue.get_ID() != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MStatusCategory> s_cache = new CCache<Integer, MStatusCategory> ("R_StatusCategory", 20); /** Logger */ private static Logger s_log = LogManager.getLogger(MStatusCategory.class); /************************************************************************** * Default Constructor * @param ctx context * @param R_StatusCategory_ID id * @param trxName trx */ public MStatusCategory (Properties ctx, int R_StatusCategory_ID, String trxName) { super (ctx, R_StatusCategory_ID, trxName); if (R_StatusCategory_ID == 0) { // setName (null); setIsDefault (false); } } // RStatusCategory /** * Load Constructor * @param ctx context * @param rs result set * @param trxName trx */ public MStatusCategory (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } // RStatusCategory /** The Status */ private MStatus[] m_status = null; /** * Get all Status * @param reload reload * @return Status array */ public MStatus[] getStatus(boolean reload) { if (m_status != null && !reload) return m_status; String sql = "SELECT * FROM R_Status " + "WHERE R_StatusCategory_ID=? " + "ORDER BY SeqNo"; ArrayList<MStatus> list = new ArrayList<MStatus>(); PreparedStatement pstmt = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getR_StatusCategory_ID()); ResultSet rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MStatus (getCtx(), rs, null)); rs.close ();
pstmt.close (); pstmt = null; } catch (Exception e) { log.error(sql, e); } try { if (pstmt != null) pstmt.close (); pstmt = null; } catch (Exception e) { pstmt = null; } // m_status = new MStatus[list.size ()]; list.toArray (m_status); return m_status; } // getStatus /** * Get Default R_Status_ID * @return id or 0 */ public int getDefaultR_Status_ID() { if (m_status == null) getStatus(false); for (int i = 0; i < m_status.length; i++) { if (m_status[i].isDefault() && m_status[i].isActive()) return m_status[i].getR_Status_ID(); } if (m_status.length > 0 && m_status[0].isActive()) return m_status[0].getR_Status_ID(); return 0; } // getDefaultR_Status_ID /** * String Representation * @return info */ public String toString () { StringBuffer sb = new StringBuffer ("RStatusCategory["); sb.append (get_ID()).append ("-").append(getName()).append ("]"); return sb.toString (); } // toString } // RStatusCategory
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MStatusCategory.java
1
请完成以下Spring Boot application配置
spring.docker.compose.enabled=true spring.docker.compose.file=./connectiondetails/docker/docker-compose-neo4j.yml spring.docker.compose.skip.in-tests=false spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true spring.mustache.check-template-location=false spring.profiles.active=neo4j spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration, org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration, org.springframework.boot.autoconfigure.data.redis.RedisRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcDataAutoConfiguration, org.springframework.boot.autoconfigure.data.r2dbc.R2dbcRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.r2dbc.R2dbcAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration, org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.cassandra.Cassandra
AutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration, org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration, org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration, org.springframework.boot.autoconfigure.couchbase.CouchbaseAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseDataAutoConfiguration, org.springframework.boot.autoconfigure.data.couchbase.CouchbaseRepositoriesAutoConfiguration
repos\tutorials-master\spring-boot-modules\spring-boot-3-2\src\main\resources\connectiondetails\application-neo4j.properties
2
请完成以下Java代码
public class PageUtil extends LinkedHashMap<String, Object> { //当前页码 private int page; //每页条数 private int limit; public PageUtil(Map<String, Object> params) { this.putAll(params); //分页参数 this.page = Integer.parseInt(params.get("page").toString()); this.limit = Integer.parseInt(params.get("limit").toString()); this.put("start", (page - 1) * limit); this.put("page", page); this.put("limit", limit); } public int getPage() { return page; }
public void setPage(int page) { this.page = page; } public int getLimit() { return limit; } public void setLimit(int limit) { this.limit = limit; } @Override public String toString() { return "PageUtil{" + "page=" + page + ", limit=" + limit + '}'; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\utils\PageUtil.java
1
请完成以下Java代码
public BPartnerAwareAttributeUpdater setBPartnerAwareFactory(final IBPartnerAwareFactory bpartnerAwareFactory) { this.bpartnerAwareFactory = bpartnerAwareFactory; return this; } private IBPartnerAwareFactory getBPartnerAwareFactory() { Check.assumeNotNull(bpartnerAwareFactory, "bpartnerAwareFactory not null"); return bpartnerAwareFactory; } public final BPartnerAwareAttributeUpdater setBPartnerAwareAttributeService(final IBPartnerAwareAttributeService bpartnerAwareAttributeService) { this.bpartnerAwareAttributeService = bpartnerAwareAttributeService; return this; }
private IBPartnerAwareAttributeService getBPartnerAwareAttributeService() { Check.assumeNotNull(bpartnerAwareAttributeService, "bpartnerAwareAttributeService not null"); return bpartnerAwareAttributeService; } /** * Sets if we shall copy the attribute even if it's a sales transaction (i.e. IsSOTrx=true) */ public final BPartnerAwareAttributeUpdater setForceApplyForSOTrx(final boolean forceApplyForSOTrx) { this.forceApplyForSOTrx = forceApplyForSOTrx; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\BPartnerAwareAttributeUpdater.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getId() { return id; } public void setId(int id) {
this.id = id; } public Store getStore() { return store; } public void setStore(Store store) { this.store = store; } public void setNamePrefix(String prefix) { this.name = prefix + this.name; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\domain\Product.java
1
请完成以下Java代码
public void setTask(TaskEntity task) { this.task = task; this.taskId = task.getId(); } public ExecutionEntity getProcessInstance() { if ((processInstance == null) && (processInstanceId != null)) { this.processInstance = Context.getCommandContext().getExecutionEntityManager().findById(processInstanceId); } return processInstance; } public void setProcessInstance(ExecutionEntity processInstance) { this.processInstance = processInstance; this.processInstanceId = processInstance.getId(); } public ProcessDefinitionEntity getProcessDef() { if ((processDef == null) && (processDefId != null)) { this.processDef = Context.getCommandContext().getProcessDefinitionEntityManager().findById(processDefId); } return processDef; } public void setProcessDef(ProcessDefinitionEntity processDef) { this.processDef = processDef; this.processDefId = processDef.getId(); } @Override public String getProcessDefinitionId() { return this.processDefId; } public void setDetails(byte[] details) { this.details = details; }
public byte[] getDetails() { return this.details; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("IdentityLinkEntity[id=").append(id); sb.append(", type=").append(type); if (userId != null) { sb.append(", userId=").append(userId); } if (groupId != null) { sb.append(", groupId=").append(groupId); } if (taskId != null) { sb.append(", taskId=").append(taskId); } if (processInstanceId != null) { sb.append(", processInstanceId=").append(processInstanceId); } if (processDefId != null) { sb.append(", processDefId=").append(processDefId); } if (details != null) { sb.append(", details=").append(new String(details)); } sb.append("]"); return sb.toString(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\IdentityLinkEntityImpl.java
1
请完成以下Java代码
public void setUser2_ID (final int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, User2_ID); } @Override public int getUser2_ID() { return get_ValueAsInt(COLUMNNAME_User2_ID); } @Override public void setVoiceAuthCode (final @Nullable java.lang.String VoiceAuthCode) { set_Value (COLUMNNAME_VoiceAuthCode, VoiceAuthCode); } @Override public java.lang.String getVoiceAuthCode() {
return get_ValueAsString(COLUMNNAME_VoiceAuthCode); } @Override public void setWriteOffAmt (final @Nullable BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } @Override public BigDecimal getWriteOffAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WriteOffAmt); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Payment.java
1
请完成以下Java代码
public java.lang.String getFileName () { return (java.lang.String)get_Value(COLUMNNAME_FileName); } /** Set Datensatz-ID. @param Record_ID Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } /** * Type AD_Reference_ID=540751 * Reference name: AD_AttachmentEntry_Type */ public static final int TYPE_AD_Reference_ID=540751; /** Data = D */ public static final String TYPE_Data = "D"; /** URL = U */ public static final String TYPE_URL = "U"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_ValueNoCheck (COLUMNNAME_Type, Type); }
/** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ @Override public void setURL (java.lang.String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL. @return Full URL address - e.g. http://www.adempiere.org */ @Override public java.lang.String getURL () { return (java.lang.String)get_Value(COLUMNNAME_URL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry_ReferencedRecord_v.java
1
请完成以下Java代码
public void setIsGenerated (boolean IsGenerated) { set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated)); } /** Get Generated. @return This Line is generated */ @Override public boolean isGenerated () { Object oo = get_Value(COLUMNNAME_IsGenerated); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () {
Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */ @Override public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ @Override public java.math.BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CashLine.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean insert(String name, String password) { if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false; } User user = new User(); user.setName(name); user.setPassword(password); return userDao.insertUser(user) > 0; } // 修改一条记录 @GetMapping("/users/mybatis/update") public Boolean update(Integer id, String name, String password) { if (id == null || id < 1 || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) { return false; }
User user = new User(); user.setId(id); user.setName(name); user.setPassword(password); return userDao.updUser(user) > 0; } // 删除一条记录 @GetMapping("/users/mybatis/delete") public Boolean delete(Integer id) { if (id == null || id < 1) { return false; } return userDao.delUser(id) > 0; } }
repos\spring-boot-projects-main\SpringBoot入门案例源码\spring-boot-mybatis\src\main\java\cn\lanqiao\springboot3\controller\MyBatisController.java
2
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getPic() { return pic; } public void setPic(String pic) { this.pic = pic; } public Date getStartTime() { return startTime; } public void setStartTime(Date startTime) { this.startTime = startTime; } public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public Integer getClickCount() { return clickCount; } public void setClickCount(Integer clickCount) { this.clickCount = clickCount; } public Integer getOrderCount() { return orderCount; } public void setOrderCount(Integer orderCount) { this.orderCount = orderCount; } public String getUrl() {
return url; } public void setUrl(String url) { this.url = url; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", type=").append(type); sb.append(", pic=").append(pic); sb.append(", startTime=").append(startTime); sb.append(", endTime=").append(endTime); sb.append(", status=").append(status); sb.append(", clickCount=").append(clickCount); sb.append(", orderCount=").append(orderCount); sb.append(", url=").append(url); sb.append(", note=").append(note); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeAdvertise.java
1
请完成以下Java代码
public class ReportColumnSet_Copy extends JavaProcess { /** * Constructor */ public ReportColumnSet_Copy() { super(); } // ReportColumnSet_Copy /** Source Line Set */ private int m_PA_ReportColumnSet_ID = 0; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("PA_ReportColumnSet_ID")) m_PA_ReportColumnSet_ID = ((BigDecimal)para[i].getParameter()).intValue(); else log.error("prepare - Unknown Parameter: " + name);
} } // prepare /** * Perform process. * @return Message * @throws Exception */ protected String doIt() throws Exception { int to_ID = super.getRecord_ID(); log.info("From PA_ReportColumnSet_ID=" + m_PA_ReportColumnSet_ID + ", To=" + to_ID); if (to_ID < 1) throw new Exception(MSG_SaveErrorRowNotFound); // MReportColumnSet to = new MReportColumnSet(getCtx(), to_ID, get_TrxName()); MReportColumnSet rcSet = new MReportColumnSet(getCtx(), m_PA_ReportColumnSet_ID, get_TrxName()); MReportColumn[] rcs = rcSet.getColumns(); for (int i = 0; i < rcs.length; i++) { MReportColumn rc = MReportColumn.copy (getCtx(), to.getAD_Client_ID(), to.getAD_Org_ID(), to_ID, rcs[i], get_TrxName()); rc.save(); } // Oper 1/2 were set to Null ! return "@Copied@=" + rcs.length; } // doIt } // ReportColumnSet_Copy
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\ReportColumnSet_Copy.java
1
请在Spring Boot框架中完成以下Java代码
public void updateOrderStatus(OrderStatus body, String albertaApiKey, String id) throws ApiException { updateOrderStatusWithHttpInfo(body, albertaApiKey, id); } /** * Auftragsstatus (ggf. später auch Rezeptstatus) ändern * Szenario - ein Auftrag wurde im WaWi geändert und diese Änderungen sollen in Alberta übertragen werden ----- Aufruf &#x3D;&gt; orderStatus/[orderId] * @param body Der Bestellstatus (required) * @param albertaApiKey (required) * @param id die Id des zu ändernden Autrags (required) * @return ApiResponse&lt;Void&gt; * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body */ public ApiResponse<Void> updateOrderStatusWithHttpInfo(OrderStatus body, String albertaApiKey, String id) throws ApiException { com.squareup.okhttp.Call call = updateOrderStatusValidateBeforeCall(body, albertaApiKey, id, null, null); return apiClient.execute(call); } /** * Auftragsstatus (ggf. später auch Rezeptstatus) ändern (asynchronously) * Szenario - ein Auftrag wurde im WaWi geändert und diese Änderungen sollen in Alberta übertragen werden ----- Aufruf &#x3D;&gt; orderStatus/[orderId] * @param body Der Bestellstatus (required) * @param albertaApiKey (required) * @param id die Id des zu ändernden Autrags (required) * @param callback The callback to be executed when the API call finishes * @return The request call * @throws ApiException If fail to process the API call, e.g. serializing the request body object */ public com.squareup.okhttp.Call updateOrderStatusAsync(OrderStatus body, String albertaApiKey, String id, final ApiCallback<Void> callback) throws ApiException { ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null; if (callback != null) { progressListener = new ProgressResponseBody.ProgressListener() { @Override public void update(long bytesRead, long contentLength, boolean done) { callback.onDownloadProgress(bytesRead, contentLength, done); } }; progressRequestListener = new ProgressRequestBody.ProgressRequestListener() { @Override public void onRequestProgress(long bytesWritten, long contentLength, boolean done) { callback.onUploadProgress(bytesWritten, contentLength, done); } }; } com.squareup.okhttp.Call call = updateOrderStatusValidateBeforeCall(body, albertaApiKey, id, progressListener, progressRequestListener); apiClient.executeAsync(call, callback); return call; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\api\OrderStatusApi.java
2
请在Spring Boot框架中完成以下Java代码
public final class PurchaseCandidateCreatedHandler extends PurchaseCandidateCreatedOrUpdatedHandler<PurchaseCandidateCreatedEvent> { /** * @param candidateService needed in case we directly request a {@link PpOrderSuggestedEvent}'s proposed PP_Order to be created. */ public PurchaseCandidateCreatedHandler( @NonNull final CandidateChangeService candidateChangeHandler, @NonNull final CandidateRepositoryRetrieval candidateRepositoryRetrieval) { super(candidateChangeHandler, candidateRepositoryRetrieval); } @Override public Collection<Class<? extends PurchaseCandidateCreatedEvent>> getHandledEventType() { return ImmutableList.of(PurchaseCandidateCreatedEvent.class); } @Override public void validateEvent(@NonNull final PurchaseCandidateCreatedEvent event) { // nothing to do; the event was already validated on construction time } @Override public void handleEvent(@NonNull final PurchaseCandidateCreatedEvent event) { handlePurchaseCandidateEvent(event); } @Override protected CandidatesQuery createCandidatesQuery(@NonNull final PurchaseCandidateEvent eventt) { final PurchaseCandidateCreatedEvent event = (PurchaseCandidateCreatedEvent)eventt; if (event.getSupplyCandidateRepoId() <= 0)
{ return CandidatesQuery.FALSE; } return CandidatesQuery.fromId(CandidateId.ofRepoId(event.getSupplyCandidateRepoId())); } @Override protected CandidateBuilder updateBuilderFromEvent( @NonNull final CandidateBuilder candidateBuilder, @NonNull final PurchaseCandidateEvent event) { final PurchaseCandidateCreatedEvent createdEvent = PurchaseCandidateCreatedEvent.cast(event); final SupplyRequiredDescriptor supplyRequiredDescriptor = createdEvent.getSupplyRequiredDescriptor(); final DemandDetail demandDetail = DemandDetail.forSupplyRequiredDescriptorOrNull(supplyRequiredDescriptor); return candidateBuilder.additionalDemandDetail(demandDetail); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\purchasecandidate\PurchaseCandidateCreatedHandler.java
2
请完成以下Java代码
public static class DeploymentOperationBuilder { protected PlatformServiceContainer container; protected String name; protected boolean isUndeploymentOperation = false; protected List<DeploymentOperationStep> steps = new ArrayList<DeploymentOperationStep>(); protected Map<String, Object> initialAttachments = new HashMap<String, Object>(); public DeploymentOperationBuilder(PlatformServiceContainer container, String name) { this.container = container; this.name = name; } public DeploymentOperationBuilder addStep(DeploymentOperationStep step) { steps.add(step); return this; } public DeploymentOperationBuilder addSteps(Collection<DeploymentOperationStep> steps) { for (DeploymentOperationStep step: steps) { addStep(step); } return this; } public DeploymentOperationBuilder addAttachment(String name, Object value) { initialAttachments.put(name, value); return this;
} public DeploymentOperationBuilder setUndeploymentOperation() { isUndeploymentOperation = true; return this; } public void execute() { DeploymentOperation operation = new DeploymentOperation(name, container, steps); operation.isRollbackOnFailure = !isUndeploymentOperation; operation.attachments.putAll(initialAttachments); container.executeDeploymentOperation(operation); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\spi\DeploymentOperation.java
1
请完成以下Java代码
public final void invalidateView(final ViewId viewId) { final PricingConditionsView view = getByIdOrNull(viewId); if (view == null) { return; } view.invalidateAll(); } @Override public final PricingConditionsView createView(@NonNull final CreateViewRequest request) { final PricingConditionsRowData rowsData = createPricingConditionsRowData(request); return createView(rowsData); } protected abstract PricingConditionsRowData createPricingConditionsRowData(CreateViewRequest request); private PricingConditionsView createView(final PricingConditionsRowData rowsData) { return PricingConditionsView.builder() .viewId(ViewId.random(windowId)) .rowsData(rowsData) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_CopyRowToEditable.class)) .relatedProcessDescriptor(createProcessDescriptor(PricingConditionsView_SaveEditableRow.class)) .filterDescriptors(filtersFactory.getFilterDescriptorsProvider()) .build(); } protected final PricingConditionsRowsLoaderBuilder preparePricingConditionsRowData() { return PricingConditionsRowsLoader.builder() .lookups(lookups); } @Override
public PricingConditionsView filterView( @NonNull final IView view, @NonNull final JSONFilterViewRequest filterViewRequest, final Supplier<IViewsRepository> viewsRepo_IGNORED) { return PricingConditionsView.cast(view) .filter(filtersFactory.extractFilters(filterViewRequest)); } private final RelatedProcessDescriptor createProcessDescriptor(@NonNull final Class<?> processClass) { final IADProcessDAO adProcessDAO = Services.get(IADProcessDAO.class); return RelatedProcessDescriptor.builder() .processId(adProcessDAO.retrieveProcessIdByClass(processClass)) .anyTable() .anyWindow() .displayPlace(DisplayPlace.ViewQuickActions) .build(); } protected final DocumentFilterList extractFilters(final CreateViewRequest request) { return filtersFactory.extractFilters(request); } @lombok.Value(staticConstructor = "of") private static final class ViewLayoutKey { WindowId windowId; JSONViewDataType viewDataType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFactoryTemplate.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomerService { @Autowired CustomerRepository repo; @Autowired CustomerStructuredRepository repo2; @Autowired ContactPhoneRepository repo3; @Autowired CustomerMapper mapper; public Customer getCustomer(long id) { return repo.findById(id); } public void updateCustomerWithCustomQuery(long id, String phone) { repo.updatePhone(id, phone); } public Customer addCustomer(String name) { Customer myCustomer = new Customer(); myCustomer.name = name; repo.save(myCustomer); return myCustomer; } public Customer updateCustomer(long id, String phone) { Customer myCustomer = repo.findById(id); myCustomer.phone = phone; repo.save(myCustomer); return myCustomer; } public Customer addCustomer(CustomerDto dto) { Customer myCustomer = new Customer(); mapper.updateCustomerFromDto(dto, myCustomer); repo.save(myCustomer); return myCustomer; }
public Customer updateCustomer(CustomerDto dto) { Customer myCustomer = repo.findById(dto.getId()); mapper.updateCustomerFromDto(dto, myCustomer); repo.save(myCustomer); return myCustomer; } public CustomerStructured addCustomerStructured(String name) { CustomerStructured myCustomer = new CustomerStructured(); myCustomer.name = name; repo2.save(myCustomer); return myCustomer; } public void addCustomerPhone(long customerId, String phone) { ContactPhone myPhone = new ContactPhone(); myPhone.phone = phone; myPhone.customerId = customerId; repo3.save(myPhone); } public CustomerStructured updateCustomerStructured(long id, String name) { CustomerStructured myCustomer = repo2.findById(id); myCustomer.name = name; repo2.save(myCustomer); return myCustomer; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\partialupdate\service\CustomerService.java
2
请完成以下Java代码
final class AmountSourceAndAcct { public static final Builder builder() { return new Builder(); } public static final AmountSourceAndAcct of(final BigDecimal amtSource, final BigDecimal amtAcct) { return builder() .setAmtSource(amtSource) .setAmtAcct(amtAcct) .build(); } public static final AmountSourceAndAcct ZERO = of(BigDecimal.ZERO, BigDecimal.ZERO); private final BigDecimal amtSource; private final BigDecimal amtAcct; private AmountSourceAndAcct(final Builder builder) { super(); amtSource = builder.amtSource; Check.assumeNotNull(amtSource, "amtSource not null"); amtAcct = builder.amtAcct; Check.assumeNotNull(amtAcct, "amtAcct not null"); } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("source", amtSource) .add("acct", amtAcct) .toString(); } public BigDecimal getAmtSource() { return amtSource; } public BigDecimal getAmtAcct() { return amtAcct; } public static final class Builder { private BigDecimal amtSource = BigDecimal.ZERO; private BigDecimal amtAcct = BigDecimal.ZERO; private Builder() { super(); } public final AmountSourceAndAcct build() {
return new AmountSourceAndAcct(this); } public Builder setAmtSource(final BigDecimal amtSource) { this.amtSource = amtSource; return this; } public Builder setAmtAcct(final BigDecimal amtAcct) { this.amtAcct = amtAcct; return this; } public Builder addAmtSource(final BigDecimal amtSourceToAdd) { amtSource = amtSource.add(amtSourceToAdd); return this; } public Builder addAmtAcct(final BigDecimal amtAcctToAdd) { amtAcct = amtAcct.add(amtAcctToAdd); return this; } public Builder add(final AmountSourceAndAcct amtSourceAndAcctToAdd) { // Optimization: do nothing if zero if (amtSourceAndAcctToAdd == ZERO) { return this; } addAmtSource(amtSourceAndAcctToAdd.getAmtSource()); addAmtAcct(amtSourceAndAcctToAdd.getAmtAcct()); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\AmountSourceAndAcct.java
1
请完成以下Java代码
public static void deleteFileByPath(String filePath) { File file = new File(filePath); if (file.exists() && !file.delete()) { LOGGER.warn("压缩包源文件删除失败:{}!", filePath); } } /** * 删除目录及目录下的文件 * * @param dir 要删除的目录的文件路径 * @return 目录删除成功返回true,否则返回false */ public static boolean deleteDirectory(String dir) { // 如果dir不以文件分隔符结尾,自动添加文件分隔符 if (!dir.endsWith(File.separator)) { dir = dir + File.separator; } File dirFile = new File(dir); // 如果dir对应的文件不存在,或者不是一个目录,则退出 if ((!dirFile.exists()) || (!dirFile.isDirectory())) { LOGGER.info("删除目录失败:" + dir + "不存在!"); return false; } boolean flag = true; // 删除文件夹中的所有文件包括子目录 File[] files = dirFile.listFiles(); for (int i = 0; i < Objects.requireNonNull(files).length; i++) { // 删除子文件 if (files[i].isFile()) { flag = KkFileUtils.deleteFileByName(files[i].getAbsolutePath()); if (!flag) { break; } } else if (files[i].isDirectory()) { // 删除子目录 flag = KkFileUtils.deleteDirectory(files[i].getAbsolutePath()); if (!flag) { break; } } }
if (!dirFile.delete() || !flag) { LOGGER.info("删除目录失败!"); return false; } return true; } /** * 判断文件是否允许上传 * * @param file 文件扩展名 * @return 是否允许上传 */ public static boolean isAllowedUpload(String file) { String fileType = suffixFromFileName(file); for (String type : ConfigConstants.getProhibit()) { if (type.equals(fileType)){ return false; } } return !ObjectUtils.isEmpty(fileType); } /** * 判断文件是否存在 * * @param filePath 文件路径 * @return 是否存在 true:存在,false:不存在 */ public static boolean isExist(String filePath) { File file = new File(filePath); return file.exists(); } }
repos\kkFileView-master\server\src\main\java\cn\keking\utils\KkFileUtils.java
1
请完成以下Java代码
public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { throw new IllegalArgumentException ("VesselName is virtual column"); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } @Override public void setExternalHeaderId (final @Nullable String ExternalHeaderId) { set_Value (COLUMNNAME_ExternalHeaderId, ExternalHeaderId); } @Override public String getExternalHeaderId() { return get_ValueAsString(COLUMNNAME_ExternalHeaderId); } @Override public void setExternalLineId (final @Nullable String ExternalLineId) {
set_Value (COLUMNNAME_ExternalLineId, ExternalLineId); } @Override public String getExternalLineId() { return get_ValueAsString(COLUMNNAME_ExternalLineId); } @Override public void setExternalSystem_ID (final int ExternalSystem_ID) { if (ExternalSystem_ID < 1) set_Value (COLUMNNAME_ExternalSystem_ID, null); else set_Value (COLUMNNAME_ExternalSystem_ID, ExternalSystem_ID); } @Override public int getExternalSystem_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ReceiptSchedule.java
1
请在Spring Boot框架中完成以下Java代码
protected DataSource getDataSource() { return this.dataSource; } @Override protected PlatformTransactionManager getTransactionManager() { return this.transactionManager; } @Override protected String getTablePrefix() { String tablePrefix = this.properties.getTablePrefix(); return (tablePrefix != null) ? tablePrefix : super.getTablePrefix(); } @Override protected boolean getValidateTransactionState() { return this.properties.isValidateTransactionState(); } @Override protected Isolation getIsolationLevelForCreate() { Isolation isolation = this.properties.getIsolationLevelForCreate(); return (isolation != null) ? isolation : super.getIsolationLevelForCreate(); } @Override protected ConfigurableConversionService getConversionService() { ConfigurableConversionService conversionService = super.getConversionService(); for (BatchConversionServiceCustomizer customizer : this.batchConversionServiceCustomizers) { customizer.customize(conversionService); } return conversionService; } @Override protected ExecutionContextSerializer getExecutionContextSerializer() { return (this.executionContextSerializer != null) ? this.executionContextSerializer : super.getExecutionContextSerializer(); } @Override @Deprecated(since = "4.0.0", forRemoval = true) @SuppressWarnings("removal") protected JobParametersConverter getJobParametersConverter() { return (this.jobParametersConverter != null) ? this.jobParametersConverter
: super.getJobParametersConverter(); } @Override protected TaskExecutor getTaskExecutor() { return (this.taskExecutor != null) ? this.taskExecutor : super.getTaskExecutor(); } @Configuration(proxyBeanMethods = false) @Conditional(OnBatchDatasourceInitializationCondition.class) static class DataSourceInitializerConfiguration { @Bean @ConditionalOnMissingBean BatchDataSourceScriptDatabaseInitializer batchDataSourceInitializer(DataSource dataSource, @BatchDataSource ObjectProvider<DataSource> batchDataSource, BatchJdbcProperties properties) { return new BatchDataSourceScriptDatabaseInitializer(batchDataSource.getIfAvailable(() -> dataSource), properties); } } static class OnBatchDatasourceInitializationCondition extends OnDatabaseInitializationCondition { OnBatchDatasourceInitializationCondition() { super("Batch", "spring.batch.jdbc.initialize-schema"); } } } }
repos\spring-boot-4.0.1\module\spring-boot-batch-jdbc\src\main\java\org\springframework\boot\batch\jdbc\autoconfigure\BatchJdbcAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public class SpringBootVFS extends VFS { private static Charset urlDecodingCharset; private static Supplier<ClassLoader> classLoaderSupplier; private final ResourcePatternResolver resourceResolver; static { setUrlDecodingCharset(Charset.defaultCharset()); setClassLoaderSupplier(ClassUtils::getDefaultClassLoader); } public SpringBootVFS() { this.resourceResolver = new PathMatchingResourcePatternResolver(classLoaderSupplier.get()); } @Override public boolean isValid() { return true; } @Override protected List<String> list(URL url, String path) throws IOException { String urlString = URLDecoder.decode(url.toString(), urlDecodingCharset); String baseUrlString = urlString.endsWith("/") ? urlString : urlString.concat("/"); Resource[] resources = resourceResolver.getResources(baseUrlString + "**/*.class"); return Stream.of(resources).map(resource -> preserveSubpackageName(baseUrlString, resource, path)) .collect(Collectors.toList()); } /** * Set the charset for decoding an encoded URL string. * <p> * Default is system default charset. * </p> * * @param charset * the charset for decoding an encoded URL string * * @since 2.3.0 */ public static void setUrlDecodingCharset(Charset charset) { urlDecodingCharset = charset; }
/** * Set the supplier for providing {@link ClassLoader} to used. * <p> * Default is a returned instance from {@link ClassUtils#getDefaultClassLoader()}. * </p> * * @param supplier * the supplier for providing {@link ClassLoader} to used * * @since 3.0.2 */ public static void setClassLoaderSupplier(Supplier<ClassLoader> supplier) { classLoaderSupplier = supplier; } private static String preserveSubpackageName(final String baseUrlString, final Resource resource, final String rootPath) { try { return rootPath + (rootPath.endsWith("/") ? "" : "/") + Normalizer .normalize(URLDecoder.decode(resource.getURL().toString(), urlDecodingCharset), Normalizer.Form.NFC) .substring(baseUrlString.length()); } catch (IOException e) { throw new UncheckedIOException(e); } } }
repos\spring-boot-starter-master\mybatis-spring-boot-autoconfigure\src\main\java\org\mybatis\spring\boot\autoconfigure\SpringBootVFS.java
2
请在Spring Boot框架中完成以下Java代码
public class C_BPartner_UpdateStatsFromBPartner extends WorkpackageProcessorAdapter { final static private String PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP = "alsoResetCreditStatusFromBPGroup"; public static void createWorkpackage(@NonNull final BPartnerStatisticsUpdateRequest request) { for (final int bpartnerId : request.getBpartnerIds()) { SCHEDULER.schedule(BPartnerToUpdate.builder() .bpartnerId(bpartnerId) .alsoResetCreditStatusFromBPGroup(request.isAlsoResetCreditStatusFromBPGroup()) .build()); } } @Builder @Value private static final class BPartnerToUpdate { private final int bpartnerId; private final boolean alsoResetCreditStatusFromBPGroup; } private static final WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<BPartnerToUpdate>(C_BPartner_UpdateStatsFromBPartner.class) { @Override protected Properties extractCtxFromItem(final BPartnerToUpdate item) { return Env.getCtx(); } @Override protected String extractTrxNameFromItem(final BPartnerToUpdate item) { return ITrx.TRXNAME_ThreadInherited; } @Override protected Object extractModelToEnqueueFromItem(final Collector collector, final BPartnerToUpdate item) { return TableRecordReference.of(I_C_BPartner.Table_Name, item.getBpartnerId()); }
@Override protected Map<String, Object> extractParametersFromItem(BPartnerToUpdate item) { return ImmutableMap.of(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP, item.isAlsoResetCreditStatusFromBPGroup()); } }; @Override public Result processWorkPackage(final I_C_Queue_WorkPackage workpackage, final String localTrxName) { // Services final IBPartnerStatsDAO bpartnerStatsDAO = Services.get(IBPartnerStatsDAO.class); final List<I_C_BPartner> bpartners = retrieveAllItems(I_C_BPartner.class); final boolean alsoSetCreditStatusBaseOnBPGroup = getParameters().getParameterAsBool(PARAM_ALSO_RESET_CREDITSTATUS_FROM_BP_GROUP); for (final I_C_BPartner bpartner : bpartners) { if (alsoSetCreditStatusBaseOnBPGroup) { Services.get(IBPartnerStatsBL.class).resetCreditStatusFromBPGroup(bpartner); } final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(bpartner); bpartnerStatsDAO.updateBPartnerStatistics(stats); } return Result.SUCCESS; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\bpartner\service\async\spi\impl\C_BPartner_UpdateStatsFromBPartner.java
2
请完成以下Java代码
default List<ConsumerPostProcessor<K, V>> getPostProcessors() { return Collections.emptyList(); } /** * Update the consumer configuration map; useful for situations such as * credential rotation. * @param updates the configuration properties to update. * @since 2.7 */ default void updateConfigs(Map<String, Object> updates) { } /** * Remove the specified key from the configuration map. * @param configKey the key to remove. * @since 2.7 */ default void removeConfig(String configKey) { } /** * Called whenever a consumer is added or removed. * * @param <K> the key type. * @param <V> the value type. * * @since 2.5 * */ interface Listener<K, V> { /** * A new consumer was created. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer.
*/ default void consumerAdded(String id, Consumer<K, V> consumer) { } /** * An existing consumer was removed. * @param id the consumer id (factory bean name and client.id separated by a * period). * @param consumer the consumer. */ default void consumerRemoved(@Nullable String id, Consumer<K, V> consumer) { } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ConsumerFactory.java
1
请在Spring Boot框架中完成以下Java代码
public Result<?> delete(@RequestParam(name = "id", required = true) String id) { sysMessageService.removeById(id); return Result.ok("删除成功!"); } /** * 批量删除 * * @param ids * @return */ @DeleteMapping(value = "/deleteBatch") public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) { this.sysMessageService.removeByIds(Arrays.asList(ids.split(","))); return Result.ok("批量删除成功!"); } /** * 通过id查询 * * @param id * @return */ @GetMapping(value = "/queryById") public Result<?> queryById(@RequestParam(name = "id", required = true) String id) { SysMessage sysMessage = sysMessageService.getById(id); return Result.ok(sysMessage); }
/** * 导出excel * * @param request */ @GetMapping(value = "/exportXls") public ModelAndView exportXls(HttpServletRequest request, SysMessage sysMessage) { return super.exportXls(request,sysMessage,SysMessage.class, "推送消息模板"); } /** * excel导入 * * @param request * @param response * @return */ @PostMapping(value = "/importExcel") public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) { return super.importExcel(request, response, SysMessage.class); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\controller\SysMessageController.java
2
请完成以下Java代码
private UserSettings doSaveUserSettings(TenantId tenantId, UserSettings userSettings) { try { ConstraintValidator.validateFields(userSettings); validateJsonKeys(userSettings.getSettings()); UserSettings saved = userSettingsDao.save(tenantId, userSettings); publishEvictEvent(new UserSettingsEvictEvent(new UserSettingsCompositeKey(userSettings))); return saved; } catch (Exception t) { handleEvictEvent(new UserSettingsEvictEvent(new UserSettingsCompositeKey(userSettings))); throw t; } } @TransactionalEventListener(classes = UserSettingsEvictEvent.class) @Override public void handleEvictEvent(UserSettingsEvictEvent event) { cache.evict(event.getKey()); } private void validateJsonKeys(JsonNode userSettings) { Iterator<String> fieldNames = userSettings.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); if (fieldName.contains(".") || fieldName.contains(",")) { throw new DataValidationException("Json field name should not contain \".\" or \",\" symbols"); } } } public JsonNode update(JsonNode mainNode, JsonNode updateNode) { Iterator<String> fieldNames = updateNode.fieldNames(); while (fieldNames.hasNext()) { String fieldExpression = fieldNames.next(); String[] fieldPath = fieldExpression.trim().split("\\."); var node = (ObjectNode) mainNode; for (int i = 0; i < fieldPath.length; i++) {
var fieldName = fieldPath[i]; var last = i == (fieldPath.length - 1); if (last) { node.set(fieldName, updateNode.get(fieldExpression)); } else { if (!node.has(fieldName)) { node.set(fieldName, JacksonUtil.newObjectNode()); } node = (ObjectNode) node.get(fieldName); } } } return mainNode; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\user\UserSettingsServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderServiceImpl implements OrderService { @Resource private StateMachine<OrderStatusEnum, OrderStatusChangeEventEnum> orderStateMachine; private long id = 1L; private Map<Long, Order> orders = new ConcurrentHashMap<>(); @Override public Order create() { Order order = new Order(); order.setOrderStatus(OrderStatusEnum.WAIT_PAYMENT); order.setOrderId(id++); orders.put(order.getOrderId(), order); System.out.println("order create success:" + order.toString()); return order; } @Override public Order pay(long id) { Order order = orders.get(id); System.out.println("try to pay,order no:" + id); Message message = MessageBuilder.withPayload(OrderStatusChangeEventEnum.PAYED). setHeader("order", order).build(); if (!sendEvent(message)) { System.out.println(" pay fail, error,order no:" + id); } return orders.get(id); } @Override public Order deliver(long id) { Order order = orders.get(id); System.out.println(" try to deliver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.DELIVERY) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); } @Override public Order receive(long id) { Order order = orders.get(id); System.out.println(" try to receiver,order no:" + id); if (!sendEvent(MessageBuilder.withPayload(OrderStatusChangeEventEnum.RECEIVED) .setHeader("order", order).build())) { System.out.println(" deliver fail,error,order no:" + id); } return orders.get(id); }
@Override public Map<Long, Order> getOrders() { return orders; } /** * send transient event * @param message * @return */ private synchronized boolean sendEvent(Message<OrderStatusChangeEventEnum> message) { boolean result = false; try { orderStateMachine.start(); result = orderStateMachine.sendEvent(message); } catch (Exception e) { e.printStackTrace(); } finally { if (Objects.nonNull(message)) { Order order = (Order) message.getHeaders().get("order"); if (Objects.nonNull(order) && Objects.equals(order.getOrderStatus(), OrderStatusEnum.FINISH)) { orderStateMachine.stop(); } } } return result; } }
repos\springboot-demo-master\Statemachine\src\main\java\com\et\statemachine\service\OrderServiceImpl.java
2
请完成以下Java代码
public static HttpStatusHolder parse(String status) { final HttpStatus httpStatus = ServerWebExchangeUtils.parse(status); final Integer intStatus; if (httpStatus == null) { intStatus = Integer.parseInt(status); } else { intStatus = null; } return new HttpStatusHolder(httpStatus, intStatus); } public HttpStatus getHttpStatus() { return httpStatus; } public Integer getStatus() { return status; } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#INFORMATIONAL}. * @return <code>true</code> if status code is in the INFORMATIONAL http series */ public boolean is1xxInformational() { return HttpStatus.Series.INFORMATIONAL.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#SUCCESSFUL}. * @return <code>true</code> if status code is in the SUCCESSFUL http series */ public boolean is2xxSuccessful() { return HttpStatus.Series.SUCCESSFUL.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#REDIRECTION}. * @return <code>true</code> if status code is in the REDIRECTION http series */ public boolean is3xxRedirection() { return HttpStatus.Series.REDIRECTION.equals(getSeries()); }
/** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR}. * @return <code>true</code> if status code is in the CLIENT_ERROR http series */ public boolean is4xxClientError() { return HttpStatus.Series.CLIENT_ERROR.equals(getSeries()); } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if status code is in the SERVER_ERROR http series */ public boolean is5xxServerError() { return HttpStatus.Series.SERVER_ERROR.equals(getSeries()); } public HttpStatus.Series getSeries() { if (httpStatus != null) { return httpStatus.series(); } if (status != null) { return HttpStatus.Series.valueOf(status); } return null; } /** * Whether this status code is in the HTTP series * {@link org.springframework.http.HttpStatus.Series#CLIENT_ERROR} or * {@link org.springframework.http.HttpStatus.Series#SERVER_ERROR}. * @return <code>true</code> if is either CLIENT_ERROR or SERVER_ERROR */ public boolean isError() { return is4xxClientError() || is5xxServerError(); } @Override public String toString() { return new ToStringCreator(this).append("httpStatus", httpStatus).append("status", status).toString(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\HttpStatusHolder.java
1
请完成以下Java代码
public String getLanguage() { return language; } /** * The script language */ public void setLanguage(String language) { this.language = language; } /** * The name of the result variable where the * script return value is written to. */ public String getResultVariable() { return resultVariable; } /** * @see #getResultVariable */ public void setResultVariable(String resultVariable) { this.resultVariable = resultVariable; } /** * The actual script payload in the provided language.
*/ public String getScript() { return script; } /** * Set the script payload in the provided language. */ public void setScript(String script) { this.script = script; } @Override public ScriptInfo clone() { ScriptInfo clone = new ScriptInfo(); clone.setLanguage(this.language); clone.setScript(this.script); clone.setResultVariable(this.resultVariable); return clone; } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ScriptInfo.java
1
请完成以下Java代码
public void setTaxAmt(ActiveOrHistoricCurrencyAndAmount value) { this.taxAmt = value; } /** * Gets the value of the adjstmntAmtAndRsn 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 adjstmntAmtAndRsn property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdjstmntAmtAndRsn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DocumentAdjustment1 } * * */ public List<DocumentAdjustment1> getAdjstmntAmtAndRsn() { if (adjstmntAmtAndRsn == null) { adjstmntAmtAndRsn = new ArrayList<DocumentAdjustment1>(); }
return this.adjstmntAmtAndRsn; } /** * Gets the value of the rmtdAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getRmtdAmt() { return rmtdAmt; } /** * Sets the value of the rmtdAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setRmtdAmt(ActiveOrHistoricCurrencyAndAmount value) { this.rmtdAmt = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceAmount1.java
1
请完成以下Java代码
public static int getColumn_ID(String TableName, String columnName) { int m_table_id = MTable.getTable_ID(TableName); if (m_table_id == 0) return 0; int retValue = 0; String SQL = "SELECT AD_Column_ID FROM AD_Column WHERE AD_Table_ID = ? AND columnname = ?"; try { PreparedStatement pstmt = DB.prepareStatement(SQL, null); pstmt.setInt(1, m_table_id); pstmt.setString(2, columnName); ResultSet rs = pstmt.executeQuery(); if (rs.next()) retValue = rs.getInt(1); rs.close(); pstmt.close(); } catch (SQLException e) { s_log.error(SQL, e); retValue = -1; } return retValue; } // end vpj-cd e-evolution /** * Get Table Id for a column * * @param ctx context * @param AD_Column_ID id * @param trxName transaction * @return MColumn */ public static int getTable_ID(Properties ctx, int AD_Column_ID, String trxName) { final String sqlStmt = "SELECT AD_Table_ID FROM AD_Column WHERE AD_Column_ID=?"; return DB.getSQLValue(trxName, sqlStmt, AD_Column_ID); }
public static boolean isSuggestSelectionColumn(String columnName, boolean caseSensitive) { if (columnName == null || Check.isBlank(columnName)) return false; // if (columnName.equals("Value") || (!caseSensitive && columnName.equalsIgnoreCase("Value"))) return true; else if (columnName.equals("Name") || (!caseSensitive && columnName.equalsIgnoreCase("Name"))) return true; else if (columnName.equals("DocumentNo") || (!caseSensitive && columnName.equalsIgnoreCase("DocumentNo"))) return true; else if (columnName.equals("Description") || (!caseSensitive && columnName.equalsIgnoreCase("Description"))) return true; else if (columnName.contains("Name") || (!caseSensitive && columnName.toUpperCase().contains("Name".toUpperCase()))) return true; else if(columnName.equals("DocStatus") || (!caseSensitive && columnName.equalsIgnoreCase("DocStatus"))) return true; else return false; } } // MColumn
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MColumn.java
1
请完成以下Java代码
public int getContact_ID() { return Contact_ID; } @Override public int getC_Currency_ID() { return C_Currency_ID; } @Override public BigDecimal getTotalAmt() { return totalAmt; } @Override public BigDecimal getOpenAmt() { return openAmt; } @Override public Date getDueDate() { return (Date)dueDate.clone(); } @Override public Date getGraceDate() { if (graceDate == null) { return null; } return (Date)graceDate.clone(); } @Override
public int getDaysDue() { return daysDue; } @Override public String getTableName() { return tableName; } @Override public int getRecordId() { return record_id; } @Override public boolean isInDispute() { return inDispute; } @Override public String toString() { return "DunnableDoc [tableName=" + tableName + ", record_id=" + record_id + ", C_BPartner_ID=" + C_BPartner_ID + ", C_BPatner_Location_ID=" + C_BPatner_Location_ID + ", Contact_ID=" + Contact_ID + ", C_Currency_ID=" + C_Currency_ID + ", totalAmt=" + totalAmt + ", openAmt=" + openAmt + ", dueDate=" + dueDate + ", graceDate=" + graceDate + ", daysDue=" + daysDue + ", inDispute=" + inDispute + "]"; } @Override public String getDocumentNo() { return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunnableDoc.java
1
请完成以下Java代码
default void runAfterCommit(@NonNull final Runnable runnable) { newEventListener(TrxEventTiming.AFTER_COMMIT) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> runnable.run()); } default void runBeforeCommit(@NonNull final Runnable runnable) { newEventListener(TrxEventTiming.BEFORE_COMMIT) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> runnable.run()); } default void runAfterRollback(@NonNull final Runnable runnable) { newEventListener(TrxEventTiming.AFTER_ROLLBACK) .invokeMethodJustOnce(true) .registerHandlingMethod(trx -> runnable.run()); } default void runAfterClose(@NonNull final Consumer<ITrx> runnable) { newEventListener(TrxEventTiming.AFTER_CLOSE) .invokeMethodJustOnce(true)
.registerHandlingMethod(runnable::accept); } /** * This method shall only be called by the framework. */ void fireBeforeCommit(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterCommit(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterRollback(ITrx trx); /** * This method shall only be called by the framework. */ void fireAfterClose(ITrx trx); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\ITrxListenerManager.java
1
请完成以下Java代码
public String getClientSoftwareKennung() { return clientSoftwareKennung; } /** * Sets the value of the clientSoftwareKennung property. * * @param value * allowed object is * {@link String } * */ public void setClientSoftwareKennung(String value) { this.clientSoftwareKennung = value; } /** * Gets the value of the lieferavisAbfrageHistAbfrage property. * * @return * possible object is * {@link LieferavisAbfrageHistAbfrage }
* */ public LieferavisAbfrageHistAbfrage getLieferavisAbfrageHistAbfrage() { return lieferavisAbfrageHistAbfrage; } /** * Sets the value of the lieferavisAbfrageHistAbfrage property. * * @param value * allowed object is * {@link LieferavisAbfrageHistAbfrage } * */ public void setLieferavisAbfrageHistAbfrage(LieferavisAbfrageHistAbfrage value) { this.lieferavisAbfrageHistAbfrage = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfrageHist.java
1
请完成以下Java代码
private List<I_AD_User> getUsers() { return new Query(getCtx(), I_AD_User.Table_Name, p_WhereClause, get_TrxName()) .setClient_ID() .setOnlyActiveRecords(true) .list(I_AD_User.class); } private boolean notify(final MADBoilerPlate text, final I_AD_User user) { boolean ok = true; try { notifyEMail(text, user); } catch (Exception e) { createNote(text, user, e); ok = false; if (LogManager.isLevelFine()) { e.printStackTrace(); } } return ok; } private void notifyEMail(final MADBoilerPlate text, final I_AD_User user) { MADBoilerPlate.sendEMail(new IEMailEditor() { @Override 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
请完成以下Java代码
public GolfTournament buildPairings() { Assert.notEmpty(this.players, () -> String.format("No players are registered for this golf tournament [%s]", getName())); Assert.isTrue(this.players.size() % 2 == 0, () -> String.format("An even number of players must register to play this golf tournament [%s]; currently at [%d]", getName(), this.players.size())); List<Golfer> playersToPair = new ArrayList<>(this.players); Collections.shuffle(playersToPair); for (int index = 0, size = playersToPair.size(); index < size; index += 2) { this.pairings.add(Pairing.of(playersToPair.get(index), playersToPair.get(index + 1))); } return this; } @Override public Iterator<GolfTournament.Pairing> iterator() { return Collections.unmodifiableList(this.pairings).iterator(); } public GolfTournament play() { Assert.state(this.golfCourse != null, "No golf course was declared"); Assert.state(!this.players.isEmpty(), "Golfers must register to play before the golf tournament is played"); Assert.state(!this.pairings.isEmpty(), "Pairings must be formed before the golf tournament is played"); Assert.state(!isFinished(), () -> String.format("Golf tournament [%s] has already been played", getName())); return this; } public GolfTournament register(Golfer... players) { return register(Arrays.asList(ArrayUtils.nullSafeArray(players, Golfer.class))); } public GolfTournament register(Iterable<Golfer> players) { StreamSupport.stream(CollectionUtils.nullSafeIterable(players).spliterator(), false) .filter(Objects::nonNull) .forEach(this.players::add); return this; } @Getter @ToString @EqualsAndHashCode @RequiredArgsConstructor(staticName = "of") public static class Pairing {
private final AtomicBoolean signedScorecard = new AtomicBoolean(false); @NonNull private final Golfer playerOne; @NonNull private final Golfer playerTwo; public synchronized void setHole(int hole) { this.playerOne.setHole(hole); this.playerTwo.setHole(hole); } public synchronized int getHole() { return getPlayerOne().getHole(); } public boolean in(@NonNull Golfer golfer) { return this.playerOne.equals(golfer) || this.playerTwo.equals(golfer); } public synchronized int nextHole() { return getHole() + 1; } public synchronized boolean signScorecard() { return getHole() >= 18 && this.signedScorecard.compareAndSet(false, true); } } }
repos\spring-boot-data-geode-main\spring-geode-samples\caching\inline-async\src\main\java\example\app\caching\inline\async\client\model\GolfTournament.java
1
请完成以下Java代码
public class JsonUrlReader { public static void main(String[] args) throws Exception { String url = args[0]; JsonNode node = JsonUrlReader.get(url); System.out.println(node.toPrettyString()); } public static String stream(String url) throws Exception { try (InputStream input = new URI(url).toURL().openStream()) { InputStreamReader isr = new InputStreamReader(input, Charset.forName("UTF-8")); BufferedReader reader = new BufferedReader(isr); StringBuilder json = new StringBuilder(); int c; while ((c = reader.read()) != -1) { json.append((char) c); } return json.toString(); } } public static JsonNode get(String url) throws StreamReadException, DatabindException, MalformedURLException, Exception { ObjectMapper mapper = new ObjectMapper(); JsonNode json = mapper.readTree(new URI(url).toURL());
return json; } public static <T> T get(String url, Class<T> type) throws StreamReadException, DatabindException, MalformedURLException, Exception { ObjectMapper mapper = new ObjectMapper(); T entity = mapper.readValue(new URI(url).toURL(), type); return entity; } public static String getString(String url) throws Exception { return get(url).toPrettyString(); } public static JSONObject getJson(String url) throws Exception { String json = IOUtils.toString(new URI(url).toURL(), Charset.forName("UTF-8")); JSONObject object = new JSONObject(json); return object; } }
repos\tutorials-master\jackson-modules\jackson-conversions-3\src\main\java\com\baeldung\jackson\jsonurlreader\JsonUrlReader.java
1
请完成以下Java代码
public java.lang.String getDIM_Dimension_Type_InternalName () { return (java.lang.String)get_Value(COLUMNNAME_DIM_Dimension_Type_InternalName); } /** Set Interner Name. @param InternalName Generally used to give records a name that can be safely referenced from code. */ @Override public void setInternalName (java.lang.String InternalName) { set_ValueNoCheck (COLUMNNAME_InternalName, InternalName); } /** Get Interner Name. @return Generally used to give records a name that can be safely referenced from code. */ @Override public java.lang.String getInternalName () { return (java.lang.String)get_Value(COLUMNNAME_InternalName); } /** Set inkl. "leer"-Eintrag. @param IsIncludeEmpty Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll */ @Override public void setIsIncludeEmpty (boolean IsIncludeEmpty) { set_Value (COLUMNNAME_IsIncludeEmpty, Boolean.valueOf(IsIncludeEmpty)); } /** Get inkl. "leer"-Eintrag. @return Legt fest, ob die Dimension einen dezidierten "Leer" Eintrag enthalten soll */ @Override public boolean isIncludeEmpty () { Object oo = get_Value(COLUMNNAME_IsIncludeEmpty); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set inkl. "sonstige"-Eintrag. @param IsIncludeOtherGroup Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll */ @Override
public void setIsIncludeOtherGroup (boolean IsIncludeOtherGroup) { set_Value (COLUMNNAME_IsIncludeOtherGroup, Boolean.valueOf(IsIncludeOtherGroup)); } /** Get inkl. "sonstige"-Eintrag. @return Legt fest, ob die Dimension einen dezidierten "Sonstige" Eintrag enthalten soll */ @Override public boolean isIncludeOtherGroup () { Object oo = get_Value(COLUMNNAME_IsIncludeOtherGroup); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dimension\src\main\java-gen\de\metas\dimension\model\X_DIM_Dimension_Spec.java
1
请完成以下Java代码
private TbResultSetFuture executeAsyncWrite(TbContext ctx, Statement statement) { return executeAsync(ctx, statement, defaultWriteLevel); } private TbResultSetFuture executeAsync(TbContext ctx, Statement statement, ConsistencyLevel level) { if (log.isDebugEnabled()) { log.debug("Execute cassandra async statement {}", statementToString(statement)); } if (statement.getConsistencyLevel() == null) { statement.setConsistencyLevel(level); } return ctx.submitCassandraWriteTask(new CassandraStatementTask(ctx.getTenantId(), getSession(), statement)); } private static String statementToString(Statement statement) { if (statement instanceof BoundStatement) { return ((BoundStatement) statement).getPreparedStatement().getQuery(); } else { return statement.toString(); } } @Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException { boolean hasChanges = false; switch (fromVersion) { case 0: if (!oldConfiguration.has("defaultTtl")) { hasChanges = true; ((ObjectNode) oldConfiguration).put("defaultTtl", 0); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbSaveToCustomCassandraTableNode.java
1
请完成以下Java代码
private VerfuegbarkeitsantwortArtikel toJAXB(final StockAvailabilityResponseItem item) { final VerfuegbarkeitsantwortArtikel soapItem = jaxbObjectFactory.createVerfuegbarkeitsantwortArtikel(); soapItem.setAnfragePzn(item.getPzn().getValueAsLong()); soapItem.setAnfrageMenge(item.getQty().getValueAsInt()); soapItem.setSubstitution(toJAXB(item.getSubstitution())); soapItem.getAnteile().addAll(item.getParts().stream() .map(this::toJAXB) .collect(ImmutableList.toImmutableList())); return soapItem; } private StockAvailabilityResponseItem fromJAXB(final VerfuegbarkeitsantwortArtikel soap) { return StockAvailabilityResponseItem.builder() .pzn(PZN.of(soap.getAnfragePzn())) .qty(Quantity.of(soap.getAnfrageMenge())) .substitution(fromJAXBorNull(soap.getSubstitution())) .parts(soap.getAnteile().stream() .map(this::fromJAXB) .collect(ImmutableList.toImmutableList())) .build(); } private VerfuegbarkeitSubstitution toJAXB(final StockAvailabilitySubstitution substitution) { if (substitution == null) { return null; } final VerfuegbarkeitSubstitution soap = jaxbObjectFactory.createVerfuegbarkeitSubstitution(); soap.setLieferPzn(substitution.getPzn().getValueAsLong()); soap.setGrund(substitution.getReason().getV1SoapCode()); soap.setSubstitutionsgrund(substitution.getType().getV1SoapCode()); return soap; }
private StockAvailabilitySubstitution fromJAXBorNull(@Nullable final VerfuegbarkeitSubstitution soap) { if (soap == null) { return null; } return StockAvailabilitySubstitution.builder() .pzn(PZN.of(soap.getLieferPzn())) .reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund())) .type(StockAvailabilitySubstitutionType.fromV1SoapCode(soap.getSubstitutionsgrund())) .build(); } private VerfuegbarkeitAnteil toJAXB(final StockAvailabilityResponseItemPart itemPart) { final VerfuegbarkeitAnteil soap = jaxbObjectFactory.createVerfuegbarkeitAnteil(); soap.setMenge(itemPart.getQty().getValueAsInt()); soap.setTyp(itemPart.getType().getV1SoapCode()); soap.setLieferzeitpunkt(itemPart.getDeliveryDate() != null ? JAXBDateUtils.toXMLGregorianCalendar(itemPart.getDeliveryDate()) : null); soap.setTour(itemPart.getTour()); soap.setGrund(itemPart.getReason() != null ? itemPart.getReason().getV1SoapCode() : null); // soap.setTourabweichung(itemPart.isTourDeviation()); return soap; } private StockAvailabilityResponseItemPart fromJAXB(@NonNull final VerfuegbarkeitAnteil soap) { return StockAvailabilityResponseItemPart.builder() .qty(Quantity.of(soap.getMenge())) .type(StockAvailabilityResponseItemPartType.fromV1SoapCode(soap.getTyp())) .deliveryDate(JAXBDateUtils.toZonedDateTime(soap.getLieferzeitpunkt())) .reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund())) .tour(soap.getTour()) // .tourDeviation(soap.isTourabweichung()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\stockAvailability\v1\StockAvailabilityJAXBConvertersV1.java
1
请在Spring Boot框架中完成以下Java代码
public String getDepartment() { return department; } /** * Sets the value of the department property. * * @param value * allowed object is * {@link String } * */ public void setDepartment(String value) { this.department = value; } /** * Gets the value of the customerReferenceNumber property. * * @return * possible object is * {@link String } * */ public String getCustomerReferenceNumber() { return customerReferenceNumber; } /** * Sets the value of the customerReferenceNumber property. * * @param value * allowed object is * {@link String } * */ public void setCustomerReferenceNumber(String value) { this.customerReferenceNumber = value; }
/** * Fiscal number of the customer * * @return * possible object is * {@link String } * */ public String getFiscalNumber() { return fiscalNumber; } /** * Sets the value of the fiscalNumber property. * * @param value * allowed object is * {@link String } * */ public void setFiscalNumber(String value) { this.fiscalNumber = 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\CustomerExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
private static final class IntegrationPropertiesPropertySource extends PropertySource<Map<String, Object>> implements OriginLookup<String> { private static final String PREFIX = "spring.integration."; private static final Map<String, String> KEYS_MAPPING; static { Map<String, String> mappings = new HashMap<>(); mappings.put(PREFIX + "channel.auto-create", IntegrationProperties.CHANNELS_AUTOCREATE); mappings.put(PREFIX + "channel.max-unicast-subscribers", IntegrationProperties.CHANNELS_MAX_UNICAST_SUBSCRIBERS); mappings.put(PREFIX + "channel.max-broadcast-subscribers", IntegrationProperties.CHANNELS_MAX_BROADCAST_SUBSCRIBERS); mappings.put(PREFIX + "error.require-subscribers", IntegrationProperties.ERROR_CHANNEL_REQUIRE_SUBSCRIBERS); mappings.put(PREFIX + "error.ignore-failures", IntegrationProperties.ERROR_CHANNEL_IGNORE_FAILURES); mappings.put(PREFIX + "endpoint.default-timeout", IntegrationProperties.ENDPOINTS_DEFAULT_TIMEOUT); mappings.put(PREFIX + "endpoint.throw-exception-on-late-reply", IntegrationProperties.THROW_EXCEPTION_ON_LATE_REPLY); mappings.put(PREFIX + "endpoint.read-only-headers", IntegrationProperties.READ_ONLY_HEADERS); mappings.put(PREFIX + "endpoint.no-auto-startup", IntegrationProperties.ENDPOINTS_NO_AUTO_STARTUP); KEYS_MAPPING = Collections.unmodifiableMap(mappings); } private final OriginTrackedMapPropertySource delegate;
IntegrationPropertiesPropertySource(OriginTrackedMapPropertySource delegate) { super("META-INF/spring.integration.properties", delegate.getSource()); this.delegate = delegate; } @Override public @Nullable Object getProperty(String name) { String mapped = KEYS_MAPPING.get(name); return (mapped != null) ? this.delegate.getProperty(mapped) : null; } @Override public @Nullable Origin getOrigin(String key) { String mapped = KEYS_MAPPING.get(key); return (mapped != null) ? this.delegate.getOrigin(mapped) : null; } } }
repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationPropertiesEnvironmentPostProcessor.java
2
请完成以下Java代码
private RawData loadRawData() { final List<I_C_Invoice_Line_Alloc> ilaRecords = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice_Line_Alloc.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_Invoice_Line_Alloc.COLUMN_C_Invoice_Candidate_ID, invoiceCandidateIds) .create() .list(); final ImmutableListMultimap<Integer, I_C_Invoice_Line_Alloc> invoiceCandidateId2IlaRecords = Multimaps.index(ilaRecords, I_C_Invoice_Line_Alloc::getC_Invoice_Candidate_ID); final ImmutableList<Integer> invoiceLineRepoIds = ilaRecords.stream() .map(ilaRecord -> ilaRecord.getC_InvoiceLine_ID()) .distinct() .collect(ImmutableList.toImmutableList()); final List<I_C_InvoiceLine> invoiceLineRecords = Services.get(IQueryBL.class) .createQueryBuilder(I_C_InvoiceLine.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_InvoiceLine.COLUMN_C_InvoiceLine_ID, invoiceLineRepoIds) .create() .list(); final ImmutableMap<Integer, I_C_InvoiceLine> invoiceLineId2InvoiceLineRecord = Maps.uniqueIndex(invoiceLineRecords, I_C_InvoiceLine::getC_InvoiceLine_ID); final ImmutableList<Integer> invoiceRepoIds = invoiceLineRecords.stream() .map(I_C_InvoiceLine::getC_Invoice_ID) .distinct() .collect(ImmutableList.toImmutableList()); final List<I_C_Invoice> invoiceRecords = Services.get(IQueryBL.class) .createQueryBuilder(I_C_Invoice.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_Invoice.COLUMN_C_Invoice_ID, invoiceRepoIds) .create() .list();
final ImmutableMap<Integer, I_C_Invoice> invoiceId2InvoiceRecord = Maps.uniqueIndex(invoiceRecords, I_C_Invoice::getC_Invoice_ID); return new RawData(invoiceId2InvoiceRecord, invoiceLineId2InvoiceLineRecord, invoiceCandidateId2IlaRecords); } @Value private static class RawData { ImmutableMap<Integer, I_C_Invoice> invoiceId2InvoiceRecord; ImmutableMap<Integer, I_C_InvoiceLine> invoiceLineId2InvoiceLineRecord; ImmutableListMultimap<Integer, I_C_Invoice_Line_Alloc> invoiceCandidateId2IlaRecords; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoicedDataLoader.java
1
请在Spring Boot框架中完成以下Java代码
public String getMerchantNo() { return merchantNo; } public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo; } public String getMerchantName() { return merchantName; } public void setMerchantName(String merchantName) { this.merchantName = merchantName; } public String getPayWayName() { return payWayName; } public void setPayWayName(String payWayName) { this.payWayName = payWayName; } public String getPayTypeName() { return payTypeName; } public void setPayTypeName(String payTypeName) { this.payTypeName = payTypeName; } public String getFundIntoType() { return fundIntoType; } public void setFundIntoType(String fundIntoType) { this.fundIntoType = fundIntoType; } public String getMerchantOrderNo() { return merchantOrderNo; }
public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getOrderDateBegin() { return orderDateBegin; } public void setOrderDateBegin(String orderDateBegin) { this.orderDateBegin = orderDateBegin; } public String getOrderDateEnd() { return orderDateEnd; } public void setOrderDateEnd(String orderDateEnd) { this.orderDateEnd = orderDateEnd; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\PaymentOrderQueryParam.java
2
请完成以下Java代码
public HeaderSecurityProperties getHeaderSecurity() { return headerSecurity; } public void setHeaderSecurity(HeaderSecurityProperties headerSecurity) { this.headerSecurity = headerSecurity; } public AuthenticationProperties getAuth() { return auth; } public void setAuth(AuthenticationProperties authentication) { this.auth = authentication; }
@Override public String toString() { return joinOn(this.getClass()) .add("indexRedirectEnabled=" + indexRedirectEnabled) .add("webjarClasspath='" + webjarClasspath + '\'') .add("securityConfigFile='" + securityConfigFile + '\'') .add("webappPath='" + applicationPath + '\'') .add("csrf='" + csrf + '\'') .add("headerSecurityProperties='" + headerSecurity + '\'') .add("sessionCookie='" + sessionCookie + '\'') .add("auth='" + auth + '\'') .toString(); } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\WebappProperty.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderService { @Autowired private OrderMapper orderMapper; @Autowired private UserMapper userMapper; private OrderService self() { return (OrderService) AopContext.currentProxy(); } public void method01() { // 查询订单 OrderDO order = orderMapper.selectById(1); System.out.println(order); // 查询用户 UserDO user = userMapper.selectById(1); System.out.println(user); } @Transactional public void method02() { // 查询订单 OrderDO order = orderMapper.selectById(1); System.out.println(order); // 查询用户 UserDO user = userMapper.selectById(1); System.out.println(user); } public void method03() { // 查询订单 self().method031(); // 查询用户 self().method032(); } @Transactional // 报错,因为此时获取的是 primary 对应的 DataSource ,即 users 。 public void method031() { OrderDO order = orderMapper.selectById(1); System.out.println(order); } @Transactional public void method032() { UserDO user = userMapper.selectById(1); System.out.println(user); } public void method04() { // 查询订单 self().method041(); // 查询用户 self().method042(); } @Transactional
@DS(DBConstants.DATASOURCE_ORDERS) public void method041() { OrderDO order = orderMapper.selectById(1); System.out.println(order); } @Transactional @DS(DBConstants.DATASOURCE_USERS) public void method042() { UserDO user = userMapper.selectById(1); System.out.println(user); } @Transactional @DS(DBConstants.DATASOURCE_ORDERS) public void method05() { // 查询订单 OrderDO order = orderMapper.selectById(1); System.out.println(order); // 查询用户 self().method052(); } @Transactional(propagation = Propagation.REQUIRES_NEW) @DS(DBConstants.DATASOURCE_USERS) public void method052() { UserDO user = userMapper.selectById(1); System.out.println(user); } }
repos\SpringBoot-Labs-master\lab-17\lab-17-dynamic-datasource-baomidou-01\src\main\java\cn\iocoder\springboot\lab17\dynamicdatasource\service\OrderService.java
2
请完成以下Java代码
public ImmutableListMultimap<ShipmentScheduleId, I_M_ShipmentSchedule_QtyPicked> retrieveOnShipmentLineRecordsByScheduleIds(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return retrieveRecordsByScheduleIds( scheduleIds, true, I_M_ShipmentSchedule_QtyPicked.class); } private <T extends I_M_ShipmentSchedule_QtyPicked> ImmutableListMultimap<ShipmentScheduleId, T> retrieveRecordsByScheduleIds( @NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds, final boolean onShipmentLine, @NonNull final Class<T> type) { if (scheduleIds.isEmpty()) { return ImmutableListMultimap.of(); } return stream( type, ShipmentScheduleAllocQuery.builder() .scheduleIds(scheduleIds) .alreadyShipped(onShipmentLine) .build() ) .collect(ImmutableListMultimap.toImmutableListMultimap( record -> ShipmentScheduleId.ofRepoId(record.getM_ShipmentSchedule_ID()), record -> record )); } @NonNull public <T extends I_M_ShipmentSchedule_QtyPicked> List<T> retrievePickedOnTheFlyAndNotDelivered( @NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull final Class<T> modelClass) { return queryBL .createQueryBuilder(I_M_ShipmentSchedule_QtyPicked.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID, shipmentScheduleId) .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_Processed, false) .addEqualsFilter(I_M_ShipmentSchedule_QtyPicked.COLUMNNAME_IsAnonymousHuPickedOnTheFly, true) .create()
.list(modelClass); } @Override @NonNull public Set<OrderId> retrieveOrderIds(@NonNull final org.compiere.model.I_M_InOut inOut) { return queryBL.createQueryBuilder(I_M_InOutLine.class, inOut) .addEqualsFilter(I_M_InOutLine.COLUMN_M_InOut_ID, inOut.getM_InOut_ID()) .andCollectChildren(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_InOutLine_ID, I_M_ShipmentSchedule_QtyPicked.class) .andCollect(I_M_ShipmentSchedule_QtyPicked.COLUMN_M_ShipmentSchedule_ID) .andCollect(I_M_ShipmentSchedule.COLUMN_C_Order_ID) .create() .listIds() .stream() .map(OrderId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentScheduleAllocDAO.java
1
请完成以下Java代码
private Instant getExpirationTime(RedisIndexedSessionRepository.RedisSession session) { return session.getLastAccessedTime().plus(session.getMaxInactiveInterval()); } /** * Checks if the session exists. By trying to access the session we only trigger a * deletion if the TTL is expired. This is done to handle * <a href="https://github.com/spring-projects/spring-session/issues/93">gh-93</a> * @param sessionKey the key */ private void touch(String sessionKey) { this.redisOps.hasKey(sessionKey); } private String getSessionKey(String sessionId) { return this.namespace + ":sessions:" + sessionId; } /** * Set the namespace for the keys. * @param namespace the namespace */ public void setNamespace(String namespace) { Assert.hasText(namespace, "namespace cannot be null or empty"); this.namespace = namespace; this.expirationsKey = this.namespace + ":sessions:expirations"; } /**
* Configure the clock used when retrieving expired sessions for clean-up. * @param clock the clock */ public void setClock(Clock clock) { Assert.notNull(clock, "clock cannot be null"); this.clock = clock; } /** * Configures how many sessions will be queried at a time to be cleaned up. Defaults * to 100. * @param cleanupCount how many sessions to be queried, must be bigger than 0. */ public void setCleanupCount(int cleanupCount) { Assert.state(cleanupCount > 0, "cleanupCount must be greater than 0"); this.cleanupCount = cleanupCount; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\SortedSetRedisSessionExpirationStore.java
1
请完成以下Java代码
public class CopyColumnsFromTable extends JavaProcess { private int p_target_AD_Table_ID; private int p_source_AD_Table_ID; private boolean p_IsTest = false; private boolean p_IsSyncDatabase = false; @Override protected void prepare() { for (final ProcessInfoParameter para : getParametersAsArray()) { String name = para.getParameterName(); if (para.getParameter() == null) { continue; } else if (name.equals("AD_Table_ID")) { p_source_AD_Table_ID = para.getParameterAsInt(); } else if (name.equals("IsTest")) { p_IsTest = para.getParameterAsBoolean(); } else if (name.equals("IsSyncDatabase")) { p_IsSyncDatabase = para.getParameterAsBoolean(); } } p_target_AD_Table_ID = getRecord_ID(); } // prepare @Override @RunOutOfTrx protected String doIt() { final I_AD_Table targetTable = getTargetTable(); final CopyColumnsResult result = CopyColumnsProducer.newInstance() .setLogger(Loggables.nop()) .setTargetTable(targetTable)
.setSourceColumns(getSourceColumns()) .setSyncDatabase(p_IsSyncDatabase) .setDryRun(p_IsTest) .create(); // return "" + result; } private I_AD_Table getTargetTable() { if (p_target_AD_Table_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_target_AD_Table_ID); } final MTable targetTable = new MTable(getCtx(), p_target_AD_Table_ID, get_TrxName()); return targetTable; } private List<I_AD_Column> getSourceColumns() { if (p_source_AD_Table_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_source_AD_Table_ID); } final MTable sourceTable = new MTable(getCtx(), p_source_AD_Table_ID, get_TrxName()); final MColumn[] sourceColumnsArr = sourceTable.getColumns(true); if (sourceColumnsArr == null || sourceColumnsArr.length == 0) { throw new AdempiereException("@NotFound@ @AD_Column_ID@ (@AD_Table_ID@:" + sourceTable.getTableName() + ")"); } final List<I_AD_Column> sourceColumns = new ArrayList<>(sourceColumnsArr.length); for (final I_AD_Column sourceColumn : sourceColumnsArr) { sourceColumns.add(sourceColumn); } return sourceColumns; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\CopyColumnsFromTable.java
1
请在Spring Boot框架中完成以下Java代码
public void setTransportMeansCode(String value) { this.transportMeansCode = value; } /** * Gets the value of the transportMeansIdentification property. * * @return * possible object is * {@link String } * */ public String getTransportMeansIdentification() { return transportMeansIdentification; } /** * Sets the value of the transportMeansIdentification property. * * @param value * allowed object is * {@link String } * */ public void setTransportMeansIdentification(String value) { this.transportMeansIdentification = value; } /** * Gets the value of the carrierIdentifier property. * * @return
* possible object is * {@link String } * */ public String getCarrierIdentifier() { return carrierIdentifier; } /** * Sets the value of the carrierIdentifier property. * * @param value * allowed object is * {@link String } * */ public void setCarrierIdentifier(String value) { this.carrierIdentifier = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\TransportDetailType.java
2
请完成以下Java代码
public static BPartnerLocationAndCaptureId ofNullableLocationWithUnknownCapture(@Nullable final BPartnerLocationId bpartnerLocationId) { return bpartnerLocationId != null ? new BPartnerLocationAndCaptureId(bpartnerLocationId, null) : null; } public static boolean equals(@Nullable BPartnerLocationAndCaptureId o1, @Nullable BPartnerLocationAndCaptureId o2) { return Objects.equals(o1, o2); } public BPartnerId getBpartnerId() { return getBpartnerLocationId().getBpartnerId(); } public int getBpartnerRepoId() { return getBpartnerLocationId().getBpartnerId().getRepoId(); }
public int getBPartnerLocationRepoId() { return getBpartnerLocationId().getRepoId(); } public static int toBPartnerLocationRepoId(@Nullable BPartnerLocationAndCaptureId value) { return value != null ? value.getBPartnerLocationRepoId() : -1; } public int getLocationCaptureRepoId() { return LocationId.toRepoId(getLocationCaptureId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerLocationAndCaptureId.java
1
请完成以下Java代码
public java.sql.Timestamp getDateAcct () { return (java.sql.Timestamp)get_Value(COLUMNNAME_DateAcct); } /** 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); } @Override public org.compiere.model.I_Fact_Acct getFact_Acct() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class); } @Override public void setFact_Acct(org.compiere.model.I_Fact_Acct Fact_Acct) { set_ValueFromPO(COLUMNNAME_Fact_Acct_ID, org.compiere.model.I_Fact_Acct.class, Fact_Acct); } /** Set Accounting Fact. @param Fact_Acct_ID Accounting Fact */ @Override public void setFact_Acct_ID (int Fact_Acct_ID) { if (Fact_Acct_ID < 1) set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null); else set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID)); } /** Get Accounting Fact.
@return Accounting Fact */ @Override public int getFact_Acct_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zeile Nr.. @param Line Unique line for this document */ @Override public void setLine (int Line) { set_Value (COLUMNNAME_Line, Integer.valueOf(Line)); } /** Get Zeile Nr.. @return Unique line for this document */ @Override public int getLine () { Integer ii = (Integer)get_Value(COLUMNNAME_Line); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxDeclarationAcct.java
1
请在Spring Boot框架中完成以下Java代码
public class NamedParameterJdbcBookRepository extends JdbcBookRepository { @Autowired private NamedParameterJdbcTemplate namedParameterJdbcTemplate; @Override public int update(Book book) { return namedParameterJdbcTemplate.update( "update books set price = :price where id = :id", new BeanPropertySqlParameterSource(book)); } @Override public Optional<Book> findById(Long id) { return namedParameterJdbcTemplate.queryForObject( "select * from books where id = :id", new MapSqlParameterSource("id", id), (rs, rowNum) -> Optional.of(new Book( rs.getLong("id"), rs.getString("name"), rs.getBigDecimal("price") ))
); } @Override public List<Book> findByNameAndPrice(String name, BigDecimal price) { MapSqlParameterSource mapSqlParameterSource = new MapSqlParameterSource(); mapSqlParameterSource.addValue("name", "%" + name + "%"); mapSqlParameterSource.addValue("price", price); return namedParameterJdbcTemplate.query( "select * from books where name like :name and price <= :price", mapSqlParameterSource, (rs, rowNum) -> new Book( rs.getLong("id"), rs.getString("name"), rs.getBigDecimal("price") ) ); } }
repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\repository\NamedParameterJdbcBookRepository.java
2
请完成以下Java代码
public void beforeAll(ExtensionContext context) throws Exception { getTestContextManager(context).beforeTestClass(); } @Override public void afterAll(ExtensionContext context) throws Exception { try { getTestContextManager(context).afterTestClass(); } finally { context.getStore(namespace) .remove(context.getTestClass() .get()); } } @Override public void postProcessTestInstance(Object testInstance, ExtensionContext context) throws Exception { getTestContextManager(context).prepareTestInstance(testInstance); } @Override public void beforeEach(ExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); Method testMethod = context.getTestMethod() .get(); getTestContextManager(context).beforeTestMethod(testInstance, testMethod); } @Override public void afterEach(ExtensionContext context) throws Exception { Object testInstance = context.getTestInstance(); Method testMethod = context.getTestMethod() .get(); Throwable testException = context.getExecutionException() .orElse(null); getTestContextManager(context).afterTestMethod(testInstance, testMethod, testException);
} @Override public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Parameter parameter = parameterContext.getParameter(); Executable executable = parameter.getDeclaringExecutable(); return ((executable instanceof Constructor) && AnnotatedElementUtils.hasAnnotation(executable, Autowired.class)) || ParameterAutowireUtils.isAutowirable(parameter); } @Override public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException { Parameter parameter = parameterContext.getParameter(); Class<?> testClass = extensionContext.getTestClass() .get(); ApplicationContext applicationContext = getApplicationContext(extensionContext); return ParameterAutowireUtils.resolveDependency(parameter, testClass, applicationContext); } private ApplicationContext getApplicationContext(ExtensionContext context) { return getTestContextManager(context).getTestContext() .getApplicationContext(); } private TestContextManager getTestContextManager(ExtensionContext context) { Assert.notNull(context, "ExtensionContext must not be null"); Class<?> testClass = context.getTestClass() .get(); ExtensionContext.Store store = context.getStore(namespace); return store.getOrComputeIfAbsent(testClass, TestContextManager::new, TestContextManager.class); } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\jupiter\SpringExtension.java
1
请完成以下Java代码
public class CompositeDbHistoryEventHandler extends CompositeHistoryEventHandler { /** * Non-argument constructor that adds {@link DbHistoryEventHandler} to the * list of {@link HistoryEventHandler}. */ public CompositeDbHistoryEventHandler() { super(); addDefaultDbHistoryEventHandler(); } /** * Constructor that takes a varargs parameter {@link HistoryEventHandler} that * consume the event and adds {@link DbHistoryEventHandler} to the list of * {@link HistoryEventHandler}. * * @param historyEventHandlers * the list of {@link HistoryEventHandler} that consume the event. */ public CompositeDbHistoryEventHandler(final HistoryEventHandler... historyEventHandlers) { super(historyEventHandlers); addDefaultDbHistoryEventHandler(); } /** * Constructor that takes a list of {@link HistoryEventHandler} that consume * the event and adds {@link DbHistoryEventHandler} to the list of * {@link HistoryEventHandler}. * * @param historyEventHandlers
* the list of {@link HistoryEventHandler} that consume the event. */ public CompositeDbHistoryEventHandler(final List<HistoryEventHandler> historyEventHandlers) { super(historyEventHandlers); addDefaultDbHistoryEventHandler(); } /** * Add {@link DbHistoryEventHandler} to the list of * {@link HistoryEventHandler}. */ private void addDefaultDbHistoryEventHandler() { historyEventHandlers.add(new DbHistoryEventHandler()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\handler\CompositeDbHistoryEventHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class SAPGLJournalTaxProvider { private final ITaxBL taxBL = Services.get(ITaxBL.class); private final TaxAccountsRepository taxAccountsRepository; private final MoneyService moneyService; public SAPGLJournalTaxProvider( @NonNull final TaxAccountsRepository taxAccountsRepository, @NonNull final MoneyService moneyService) { this.taxAccountsRepository = taxAccountsRepository; this.moneyService = moneyService; } public boolean isReverseCharge(final TaxId taxId) { final Tax tax = taxBL.getTaxById(taxId); return tax.isReverseCharge(); } @NonNull public Account getTaxAccount( @NonNull final TaxId taxId, @NonNull final AcctSchemaId acctSchemaId, @NonNull final PostingSign postingSign) { final TaxAcctType taxAcctType = postingSign.isDebit() ? TaxAcctType.TaxCredit : TaxAcctType.TaxDue; return taxAccountsRepository.getAccounts(taxId, acctSchemaId) .getAccount(taxAcctType) .orElseThrow(() -> new AdempiereException("No account found for " + taxId + ", " + acctSchemaId + ", " + taxAcctType)); }
public Money calculateTaxAmt( @NonNull final Money lineAmt, @NonNull final TaxId taxId, final boolean isTaxIncluded) { // final CurrencyId currencyId = lineAmt.getCurrencyId(); final CurrencyPrecision precision = moneyService.getStdPrecision(currencyId); final Tax tax = taxBL.getTaxById(taxId); final CalculateTaxResult taxResult = tax.calculateTax(lineAmt.toBigDecimal(), isTaxIncluded, precision.toInt()); return tax.isReverseCharge() ? Money.of(taxResult.getReverseChargeAmt(), currencyId) : Money.of(taxResult.getTaxAmount(), currencyId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\service\SAPGLJournalTaxProvider.java
2
请完成以下Java代码
public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getChangeType() { return changeType; } public void setChangeType(Integer changeType) { this.changeType = changeType; } public Integer getChangeCount() { return changeCount; } public void setChangeCount(Integer changeCount) { this.changeCount = changeCount; } public String getOperateMan() { return operateMan; } public void setOperateMan(String operateMan) { this.operateMan = operateMan; } public String getOperateNote() { return operateNote; } public void setOperateNote(String operateNote) { this.operateNote = operateNote;
} public Integer getSourceType() { return sourceType; } public void setSourceType(Integer sourceType) { this.sourceType = sourceType; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", memberId=").append(memberId); sb.append(", createTime=").append(createTime); sb.append(", changeType=").append(changeType); sb.append(", changeCount=").append(changeCount); sb.append(", operateMan=").append(operateMan); sb.append(", operateNote=").append(operateNote); sb.append(", sourceType=").append(sourceType); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsGrowthChangeHistory.java
1
请完成以下Java代码
public int getC_Invoice_Candidate_HeaderAggregation_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_HeaderAggregation_ID); } @Override public void setHeaderAggregationKey (final java.lang.String HeaderAggregationKey) { set_ValueNoCheck (COLUMNNAME_HeaderAggregationKey, HeaderAggregationKey); } @Override public java.lang.String getHeaderAggregationKey() { return get_ValueAsString(COLUMNNAME_HeaderAggregationKey); } @Override public void setHeaderAggregationKeyBuilder_ID (final int HeaderAggregationKeyBuilder_ID) { if (HeaderAggregationKeyBuilder_ID < 1) set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, null); else set_Value (COLUMNNAME_HeaderAggregationKeyBuilder_ID, HeaderAggregationKeyBuilder_ID); } @Override public int getHeaderAggregationKeyBuilder_ID() { return get_ValueAsInt(COLUMNNAME_HeaderAggregationKeyBuilder_ID); } @Override public void setInvoicingGroupNo (final int InvoicingGroupNo) { set_ValueNoCheck (COLUMNNAME_InvoicingGroupNo, InvoicingGroupNo); } @Override public int getInvoicingGroupNo() { return get_ValueAsInt(COLUMNNAME_InvoicingGroupNo); }
@Override public void setIsSOTrx (final boolean IsSOTrx) { set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public boolean isSOTrx() { return get_ValueAsBoolean(COLUMNNAME_IsSOTrx); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\invoicecandidate\model\X_C_Invoice_Candidate_HeaderAggregation.java
1
请完成以下Java代码
public Result<T> success(String message) { this.message = message; this.code = CommonConstant.SC_OK_200; this.success = true; return this; } public static<T> Result<T> ok() { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); return r; } public static<T> Result<T> ok(String msg) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); //Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D r.setResult((T) msg); r.setMessage(msg); return r; } public static<T> Result<T> ok(T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(data); return r; } public static<T> Result<T> OK() { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); return r; } /** * 此方法是为了兼容升级所创建 * * @param msg * @param <T> * @return */ public static<T> Result<T> OK(String msg) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setMessage(msg); //Result OK(String msg)方法会造成兼容性问题 issues/I4IP3D r.setResult((T) msg); return r; } public static<T> Result<T> OK(T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setResult(data); return r; } public static<T> Result<T> OK(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(true); r.setCode(CommonConstant.SC_OK_200); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg, T data) { Result<T> r = new Result<T>(); r.setSuccess(false);
r.setCode(CommonConstant.SC_INTERNAL_SERVER_ERROR_500); r.setMessage(msg); r.setResult(data); return r; } public static<T> Result<T> error(String msg) { return error(CommonConstant.SC_INTERNAL_SERVER_ERROR_500, msg); } public static<T> Result<T> error(int code, String msg) { Result<T> r = new Result<T>(); r.setCode(code); r.setMessage(msg); r.setSuccess(false); return r; } public Result<T> error500(String message) { this.message = message; this.code = CommonConstant.SC_INTERNAL_SERVER_ERROR_500; this.success = false; return this; } /** * 无权限访问返回结果 */ public static<T> Result<T> noauth(String msg) { return error(CommonConstant.SC_JEECG_NO_AUTHZ, msg); } @JsonIgnore private String onlTable; }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\api\vo\Result.java
1
请完成以下Java代码
public ClearingSystemMemberIdentification2 getClrSysMmbId() { return clrSysMmbId; } /** * Sets the value of the clrSysMmbId property. * * @param value * allowed object is * {@link ClearingSystemMemberIdentification2 } * */ public void setClrSysMmbId(ClearingSystemMemberIdentification2 value) { this.clrSysMmbId = value; } /** * Gets the value of the nm property. * * @return * possible object is * {@link String } * */ public String getNm() { return nm; } /** * Sets the value of the nm property. * * @param value * allowed object is * {@link String } * */ public void setNm(String value) { this.nm = value; } /** * Gets the value of the pstlAdr property. * * @return * possible object is * {@link PostalAddress6 } * */ public PostalAddress6 getPstlAdr() {
return pstlAdr; } /** * Sets the value of the pstlAdr property. * * @param value * allowed object is * {@link PostalAddress6 } * */ public void setPstlAdr(PostalAddress6 value) { this.pstlAdr = value; } /** * Gets the value of the othr property. * * @return * possible object is * {@link GenericFinancialIdentification1 } * */ public GenericFinancialIdentification1 getOthr() { return othr; } /** * Sets the value of the othr property. * * @param value * allowed object is * {@link GenericFinancialIdentification1 } * */ public void setOthr(GenericFinancialIdentification1 value) { this.othr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\FinancialInstitutionIdentification7.java
1
请在Spring Boot框架中完成以下Java代码
private void addValueHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getValueHints().addAll(hint.getValueHints()); property.getHints().getValueProviders().addAll(hint.getValueProviders()); } private void addMapHints(ConfigurationMetadataProperty property, ConfigurationMetadataHint hint) { property.getHints().getKeyHints().addAll(hint.getValueHints()); property.getHints().getKeyProviders().addAll(hint.getValueProviders()); } /** * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default * charset and the specified JSON resource. * @param inputStreams the source input streams * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. * @throws IOException on error */ public static ConfigurationMetadataRepositoryJsonBuilder create(InputStream... inputStreams) throws IOException { ConfigurationMetadataRepositoryJsonBuilder builder = create(); for (InputStream inputStream : inputStreams) { builder = builder.withJsonResource(inputStream); }
return builder; } /** * Create a new builder instance using {@link StandardCharsets#UTF_8} as the default * charset. * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ public static ConfigurationMetadataRepositoryJsonBuilder create() { return create(StandardCharsets.UTF_8); } /** * Create a new builder instance using the specified default {@link Charset}. * @param defaultCharset the default charset to use * @return a new {@link ConfigurationMetadataRepositoryJsonBuilder} instance. */ public static ConfigurationMetadataRepositoryJsonBuilder create(Charset defaultCharset) { return new ConfigurationMetadataRepositoryJsonBuilder(defaultCharset); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataRepositoryJsonBuilder.java
2
请完成以下Java代码
public class TMDictionaryMaker implements ISaveAble { Map<String, Map<String, Integer>> transferMatrix; public TMDictionaryMaker() { transferMatrix = new TreeMap<String, Map<String, Integer>>(); } /** * 添加一个转移例子,会在内部完成统计 * @param first * @param second */ public void addPair(String first, String second) { Map<String, Integer> firstMatrix = transferMatrix.get(first); if (firstMatrix == null) { firstMatrix = new TreeMap<String, Integer>(); transferMatrix.put(first, firstMatrix); } Integer frequency = firstMatrix.get(second); if (frequency == null) frequency = 0; firstMatrix.put(second, frequency + 1); } @Override public String toString() { Set<String> labelSet = new TreeSet<String>(); for (Map.Entry<String, Map<String, Integer>> first : transferMatrix.entrySet()) { labelSet.add(first.getKey()); labelSet.addAll(first.getValue().keySet()); } final StringBuilder sb = new StringBuilder(); sb.append(' '); for (String key : labelSet) { sb.append(','); sb.append(key); } sb.append('\n');
for (String first : labelSet) { Map<String, Integer> firstMatrix = transferMatrix.get(first); if (firstMatrix == null) firstMatrix = new TreeMap<String, Integer>(); sb.append(first); for (String second : labelSet) { sb.append(','); Integer frequency = firstMatrix.get(second); if (frequency == null) frequency = 0; sb.append(frequency); } sb.append('\n'); } return sb.toString(); } @Override public boolean saveTxtTo(String path) { try { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8")); bw.write(toString()); bw.close(); } catch (Exception e) { Predefine.logger.warning("在保存转移矩阵词典到" + path + "时发生异常" + e); return false; } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\TMDictionaryMaker.java
1
请完成以下Java代码
private String computeEffectiveAdLanguage() { if (_adLanguage != null) { return _adLanguage; } // // Contact/User Language final I_AD_User user = getBPartnerContact(); if (user != null && !Check.isEmpty(user.getAD_Language(), true)) { final String userAdLanguage = StringUtils.trimBlankToNull(user.getAD_Language()); if (userAdLanguage != null) { return userAdLanguage; } } // // BPartner Language final I_C_BPartner bpartner = getBPartner(); if (bpartner != null) { final String bpAdLanguage = StringUtils.trimBlankToNull(bpartner.getAD_Language()); if (bpAdLanguage != null) { return bpAdLanguage; } } // // Fallback to system base language return Language.getBaseAD_Language(); } /** Optionally, set the AD_Language to be used. If not set, the partner language will be used */ public MailTextBuilder adLanguage(final String adLanguage) { _adLanguage = adLanguage; invalidateCache(); return this; } private void invalidateCache() { _adLanguageEffective = null; _text2parsedText.clear(); } public MailTextBuilder record(final Object record) { _record = record; invalidateCache(); return this; } public MailTextBuilder recordAndUpdateBPartnerAndContact(final Object record) { record(record); if (record != null) { updateBPartnerAndContactFromRecord(record); } return this; } private void updateBPartnerAndContactFromRecord(@NonNull final Object record) { final BPartnerId bpartnerId = extractBPartnerId(record); if (bpartnerId != null) { bpartner(bpartnerId); } final UserId bpartnerContactId = extractBPartnerContactId(record); if (bpartnerContactId != null) { bpartnerContact(bpartnerContactId);
} } private BPartnerId extractBPartnerId(final Object record) { final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID"); if (!(bpartnerIdObj instanceof Integer)) { return null; } final int bpartnerRepoId = (Integer)bpartnerIdObj; return BPartnerId.ofRepoIdOrNull(bpartnerRepoId); } private UserId extractBPartnerContactId(final Object record) { final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID"); if (!(userIdObj instanceof Integer)) { return null; } final int userRepoId = userIdObj.intValue(); return UserId.ofRepoIdOrNull(userRepoId); } private Object getRecord() { return _record; } public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value) { return customVariable(name, TranslatableStrings.anyLanguage(value)); } public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value) { _customVariables.put(name, value); invalidateCache(); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java
1
请在Spring Boot框架中完成以下Java代码
protected void setOwner(TenantId tenantId, TbResource resource, IdProvider idProvider) { resource.setTenantId(tenantId); } @Override protected TbResource prepare(EntitiesImportCtx ctx, TbResource resource, TbResource oldResource, EntityExportData<TbResource> exportData, IdProvider idProvider) { return resource; } @Override protected TbResource findExistingEntity(EntitiesImportCtx ctx, TbResource resource, IdProvider idProvider) { TbResource existingResource = super.findExistingEntity(ctx, resource, idProvider); if (existingResource == null && ctx.isFindExistingByName()) { existingResource = resourceService.findResourceByTenantIdAndKey(ctx.getTenantId(), resource.getResourceType(), resource.getResourceKey()); } return existingResource; } @Override protected TbResource deepCopy(TbResource resource) { return new TbResource(resource); } @Override protected void cleanupForComparison(TbResource resource) { super.cleanupForComparison(resource); resource.setSearchText(null); if (resource.getDescriptor() != null && resource.getDescriptor().isNull()) { resource.setDescriptor(null); } } @Override protected TbResource saveOrUpdate(EntitiesImportCtx ctx, TbResource resource, EntityExportData<TbResource> exportData, IdProvider idProvider, CompareResult compareResult) { if (resource.getResourceType() == ResourceType.IMAGE) { return new TbResource(imageService.saveImage(resource)); } else { if (compareResult.isExternalIdChangedOnly()) { resource = resourceService.saveResource(resource, false); } else {
resource = resourceService.saveResource(resource); } resource.setData(null); resource.setPreview(null); return resource; } } @Override protected void onEntitySaved(User user, TbResource savedResource, TbResource oldResource) throws ThingsboardException { super.onEntitySaved(user, savedResource, oldResource); clusterService.onResourceChange(savedResource, null); } @Override public EntityType getEntityType() { return EntityType.TB_RESOURCE; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\ResourceImportService.java
2
请完成以下Java代码
public void setHUStorageFactory(final IHUStorageFactory huStorageFactory) { Check.assumeNotNull(huStorageFactory, "huStorageFactory not null"); this.huStorageFactory = huStorageFactory; } @Override public IAttributeStorageFactory getHUAttributeStorageFactory() { if (_attributesStorageFactoryInitialized) { // shall not be null at this point return _attributesStorageFactory; } if (_attributesStorageFactory == null) { _attributesStorageFactory = Services.get(IAttributeStorageFactoryService.class) .prepareHUAttributeStorageFactory(HUAttributesDAO.instance); } final IHUStorageFactory huStorageFactory = getHUStorageFactory(); _attributesStorageFactory.setHUStorageFactory(huStorageFactory); _attributesStorageFactoryInitialized = true; return _attributesStorageFactory; } @Override public void setHUAttributeStorageFactory(final IAttributeStorageFactory attributesStorageFactory) { Check.assumeNotNull(attributesStorageFactory, "attributesStorageFactory not null"); Check.assume(!_attributesStorageFactoryInitialized, "attributesStorageFactory not already initialized"); _attributesStorageFactory = attributesStorageFactory; } @Override public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> getHUPackingMaterialsCollector() { return _huPackingMaterialsCollector; } @Override public IMutableHUContext setHUPackingMaterialsCollector(@NonNull final IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> huPackingMaterialsCollector) { this._huPackingMaterialsCollector = huPackingMaterialsCollector; return this; } @Override public CompositeHUTrxListener getTrxListeners() { if (_trxListeners == null) { final CompositeHUTrxListener trxListeners = new CompositeHUTrxListener(); // Add system registered listeners final IHUTrxBL huTrxBL = Services.get(IHUTrxBL.class); trxListeners.addListeners(huTrxBL.getHUTrxListenersList()); _trxListeners = trxListeners; }
return _trxListeners; } @Override public void addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener) { emptyHUListeners.add(emptyHUListener); } @Override public List<EmptyHUListener> getEmptyHUListeners() { return ImmutableList.copyOf(emptyHUListeners); } @Override public void flush() { final IAttributeStorageFactory attributesStorageFactory = _attributesStorageFactory; if(attributesStorageFactory != null) { attributesStorageFactory.flush(); } } @Override public IAutoCloseable temporarilyDontDestroyHU(@NonNull final HuId huId) { huIdsToNotDestroy.add(huId); return () -> huIdsToNotDestroy.remove(huId); } @Override public boolean isDontDestroyHu(@NonNull final HuId huId) { return huIdsToNotDestroy.contains(huId); } @Override public boolean isPropertyTrue(@NonNull final String propertyName) { final Boolean isPropertyTrue = getProperty(propertyName); return isPropertyTrue != null && isPropertyTrue; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\MutableHUContext.java
1
请完成以下Java代码
public void setCM_Container_ID (int CM_Container_ID) { if (CM_Container_ID < 1) set_Value (COLUMNNAME_CM_Container_ID, null); else set_Value (COLUMNNAME_CM_Container_ID, Integer.valueOf(CM_Container_ID)); } /** Get Web Container. @return Web Container contains content like images, text etc. */ public int getCM_Container_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Container URL. @param CM_Container_URL_ID Contains info on used URLs */ public void setCM_Container_URL_ID (int CM_Container_URL_ID) { if (CM_Container_URL_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_Container_URL_ID, Integer.valueOf(CM_Container_URL_ID)); } /** Get Container URL. @return Contains info on used URLs */ public int getCM_Container_URL_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_Container_URL_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Last Result. @param Last_Result Contains data on the last check result */ public void setLast_Result (String Last_Result) { set_Value (COLUMNNAME_Last_Result, Last_Result);
} /** Get Last Result. @return Contains data on the last check result */ public String getLast_Result () { return (String)get_Value(COLUMNNAME_Last_Result); } /** Set Status. @param Status Status of the currently running check */ public void setStatus (String Status) { set_Value (COLUMNNAME_Status, Status); } /** Get Status. @return Status of the currently running check */ public String getStatus () { return (String)get_Value(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Container_URL.java
1
请在Spring Boot框架中完成以下Java代码
public List<String> processUserDataFromUserList() { ResponseEntity<List<User>> responseEntity = restTemplate.exchange( BASE_URL, HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {} ); List<User> users = responseEntity.getBody(); return users.stream() .map(User::getName) .collect(Collectors.toList()); } @Override public List<String> processNestedUserDataFromUserArray() { ResponseEntity<User[]> responseEntity = restTemplate.getForEntity(BASE_URL, User[].class); User[] userArray = responseEntity.getBody(); //we can get more info if we need : MediaType contentType = responseEntity.getHeaders().getContentType(); HttpStatusCode statusCode = responseEntity.getStatusCode();
return Arrays.stream(userArray) .flatMap(user -> user.getAddressList().stream()) .map(Address::getPostCode) .collect(Collectors.toList()); } @Override public List<String> processNestedUserDataFromUserList() { ResponseEntity<List<User>> responseEntity = restTemplate.exchange( BASE_URL, HttpMethod.GET, null, new ParameterizedTypeReference<List<User>>() {} ); List<User> userList = responseEntity.getBody(); return userList.stream() .flatMap(user -> user.getAddressList().stream()) .map(Address::getPostCode) .collect(Collectors.toList()); } }
repos\tutorials-master\spring-web-modules\spring-resttemplate-2\src\main\java\com\baeldung\resttemplate\json\consumer\service\UserConsumerServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public Object getPrincipal() { return this.principal; } /** * Returns the SAML response object, as decoded XML. May contain encrypted elements * @return string representation of the SAML Response XML object */ public String getSaml2Response() { return this.saml2Response; } @Override public Object getCredentials() { return getSaml2Response(); } abstract static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private Object principal;
String saml2Response; Builder(Saml2Authentication token) { super(token); this.principal = token.principal; this.saml2Response = token.saml2Response; } @Override public B principal(@Nullable Object principal) { Assert.notNull(principal, "principal cannot be null"); this.principal = principal; return (B) this; } void saml2Response(String saml2Response) { this.saml2Response = saml2Response; } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\Saml2Authentication.java
2
请完成以下Java代码
protected void doResume(@Nullable Object transaction, Object suspendedResources) { KafkaResourceHolder<K, V> producerHolder = (KafkaResourceHolder<K, V>) suspendedResources; if (transaction != null) { KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) transaction; txObject.setResourceHolder(producerHolder); } TransactionSynchronizationManager.bindResource(getProducerFactory(), producerHolder); } @Override protected void doCommit(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.commit(); } } @Override protected void doRollback(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> resourceHolder = txObject.getResourceHolder(); if (resourceHolder != null) { resourceHolder.rollback(); } } @Override protected void doSetRollbackOnly(DefaultTransactionStatus status) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) status.getTransaction(); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.setRollbackOnly(); } } @Override protected void doCleanupAfterCompletion(Object transaction) { @SuppressWarnings(UNCHECKED) KafkaTransactionObject<K, V> txObject = (KafkaTransactionObject<K, V>) transaction;
TransactionSynchronizationManager.unbindResource(getProducerFactory()); KafkaResourceHolder<K, V> kafkaResourceHolder = txObject.getResourceHolder(); if (kafkaResourceHolder != null) { kafkaResourceHolder.close(); kafkaResourceHolder.clear(); } } /** * Kafka transaction object, representing a KafkaResourceHolder. Used as transaction object by * KafkaTransactionManager. * @see KafkaResourceHolder */ private static class KafkaTransactionObject<K, V> implements SmartTransactionObject { private @Nullable KafkaResourceHolder<K, V> resourceHolder; KafkaTransactionObject() { } public void setResourceHolder(@Nullable KafkaResourceHolder<K, V> resourceHolder) { this.resourceHolder = resourceHolder; } public @Nullable KafkaResourceHolder<K, V> getResourceHolder() { return this.resourceHolder; } @Override public boolean isRollbackOnly() { return this.resourceHolder != null && this.resourceHolder.isRollbackOnly(); } @Override public void flush() { // no-op } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\transaction\KafkaTransactionManager.java
1
请在Spring Boot框架中完成以下Java代码
public GMetric.UDPAddressingMode getAddressingMode() { return this.addressingMode; } public void setAddressingMode(GMetric.UDPAddressingMode addressingMode) { this.addressingMode = addressingMode; } public Integer getTimeToLive() { return this.timeToLive; } public void setTimeToLive(Integer timeToLive) { this.timeToLive = timeToLive; } public String getHost() { return this.host;
} public void setHost(String host) { this.host = host; } public Integer getPort() { return this.port; } public void setPort(Integer port) { this.port = port; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\ganglia\GangliaProperties.java
2
请完成以下Java代码
public void setMD_Candidate(final de.metas.material.dispo.model.I_MD_Candidate MD_Candidate) { set_ValueFromPO(COLUMNNAME_MD_Candidate_ID, de.metas.material.dispo.model.I_MD_Candidate.class, MD_Candidate); } @Override public void setMD_Candidate_ID (final int MD_Candidate_ID) { if (MD_Candidate_ID < 1) set_Value (COLUMNNAME_MD_Candidate_ID, null); else set_Value (COLUMNNAME_MD_Candidate_ID, MD_Candidate_ID); } @Override public int getMD_Candidate_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_ID);
} @Override public void setMD_Candidate_StockChange_Detail_ID (final int MD_Candidate_StockChange_Detail_ID) { if (MD_Candidate_StockChange_Detail_ID < 1) set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, null); else set_ValueNoCheck (COLUMNNAME_MD_Candidate_StockChange_Detail_ID, MD_Candidate_StockChange_Detail_ID); } @Override public int getMD_Candidate_StockChange_Detail_ID() { return get_ValueAsInt(COLUMNNAME_MD_Candidate_StockChange_Detail_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java-gen\de\metas\material\dispo\model\X_MD_Candidate_StockChange_Detail.java
1
请完成以下Java代码
public static QuantityTU ofBigDecimal(@NonNull final BigDecimal value) { final int valueInt; try { valueInt = value.intValueExact(); } catch (Exception ex) { throw new AdempiereException("Quantity TUs shall be integer: " + value, ex); } return ofInt(valueInt); } public static final QuantityTU ZERO = new QuantityTU(0); public static final QuantityTU ONE = new QuantityTU(1); private static final QuantityTU[] cache = new QuantityTU[] { ZERO, ONE, new QuantityTU(2), new QuantityTU(3), new QuantityTU(4), new QuantityTU(5), new QuantityTU(6), new QuantityTU(7), new QuantityTU(8), new QuantityTU(9), new QuantityTU(10), }; private final int value; private QuantityTU(final int value) { this.value = value; } @Override public String toString() { return String.valueOf(value); } @JsonValue public int toInt() { return value; } public BigDecimal toBigDecimal() { return BigDecimal.valueOf(value); } @Override public int compareTo(@NonNull final QuantityTU other) { return this.value - other.value; }
public QuantityTU add(@NonNull final QuantityTU toAdd) { if (this.value == 0) { return toAdd; } else if (toAdd.value == 0) { return this; } else { return ofInt(this.value + toAdd.value); } } public QuantityTU subtract(@NonNull final QuantityTU toSubtract) { if (toSubtract.value == 0) { return this; } else { return ofInt(this.value - toSubtract.value); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityTU.java
1
请完成以下Java代码
public static List<Integer> primeNumbersBruteForce(int max) { final List<Integer> primeNumbers = new LinkedList<Integer>(); for (int i = 2; i <= max; i++) { if (isPrimeBruteForce(i)) { primeNumbers.add(i); } } return primeNumbers; } private static boolean isPrimeBruteForce(int x) { for (int i = 2; i < x; i++) { if (x % i == 0) { return false; } }
return true; } public static List<Integer> primeNumbersTill(int max) { return IntStream.rangeClosed(2, max) .filter(x -> isPrime(x)) .boxed() .collect(Collectors.toList()); } private static boolean isPrime(int x) { return IntStream.rangeClosed(2, (int) (Math.sqrt(x))) .allMatch(n -> x % n != 0); } }
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\prime\PrimeGenerator.java
1
请完成以下Java代码
public void migrateDependentEntities() { } @Override public boolean isDetached() { return userTask.getExecutionId() == null; } @Override public void detachState() { userTask.getExecution().removeTask(userTask); userTask.setExecution(null); } @Override public void attachState(MigratingScopeInstance owningInstance) { ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution(); representativeExecution.addTask(userTask); for (VariableInstanceEntity variable : userTask.getVariablesInternal()) { variable.setExecution(representativeExecution); } userTask.setExecution(representativeExecution); } @Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) { throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this); } @Override public void migrateState() { userTask.setProcessDefinitionId(migratingActivityInstance.getTargetScope().getProcessDefinition().getId()); userTask.setTaskDefinitionKey(migratingActivityInstance.getTargetScope().getId()); migrateHistory(); } protected void migrateHistory() { HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel(); if (historyLevel.isHistoryEventProduced(HistoryEventTypes.TASK_INSTANCE_MIGRATE, this)) { HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() { @Override public HistoryEvent createHistoryEvent(HistoryEventProducer producer) { return producer.createTaskInstanceMigrateEvt(userTask); } }); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingUserTaskInstance.java
1
请完成以下Java代码
private @Nullable String deserialize(@Nullable ByteBuffer data) { if (data == null) { return null; } if (data.hasArray()) { return new String(data.array(), data.position() + data.arrayOffset(), data.remaining(), this.charset); } return new String(Utils.toArray(data), this.charset); } /** * Set a charset to use when converting byte[] to {@link String}. Default UTF-8. * @param charset the charset. */ public void setCharset(Charset charset) { Assert.notNull(charset, "'charset' cannot be null"); this.charset = charset; }
/** * Get the configured charset. * @return the charset. */ public Charset getCharset() { return this.charset; } /** * Get the configured parser function. * @return the function. */ public BiFunction<String, Headers, T> getParser() { return this.parser; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ParseStringDeserializer.java
1
请完成以下Spring Boot application配置
#配置数据源 spring: datasource: druid: db-type: com.alibaba.druid.pool.DruidDataSource driverClassName: com.p6spy.engine.spy.P6SpyDriver url: jdbc:p6spy:mysql://localhost:3306/eladmin?serverTimezone=Asia/Shanghai&characterEncoding=utf8&useSSL=false username: root password: 123456 # 初始连接数,建议设置为与最小空闲连接数相同 initial-size: 20 # 最小空闲连接数,保持足够的空闲连接以应对请求 min-idle: 20 # 最大连接数,根据并发需求适当增加 max-active: 50 # 获取连接超时时间(毫秒),调整以满足响应时间要求 max-wait: 3000 # 启用KeepAlive机制,保持长连接 keep-alive: true # 连接有效性检测间隔时间(毫秒),定期检查连接的健康状态 time-between-eviction-runs-millis: 60000 # 连接在池中最小生存时间(毫秒),确保连接在池中至少存在一段时间 min-evictable-idle-time-millis: 300000 # 连接在池中最大生存时间(毫秒),防止连接在池中停留过长 max-evictable-idle-time-millis: 900000 # 指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除 test-while-idle: true # 指明是否在从池中取出连接前进行检验,如果检验失败, 则从池中去除连接并尝试取出另一个 test-on-borrow: true # 是否在归还到池中前进行检验 test-on-return: false # 停用 com_ping 探活机制 use-ping-method: false # 检测连接是否有效 validation-query: SELECT 1 # 配置监控统计 webStatFilter: enabled: true stat-view-servlet: enabled: true url-pattern: /druid/* reset-enable: false filter: stat: enabled: true # 记录慢SQL log-slow-sql: true slow-sql-millis: 2000 merge-sql: true wall: config: multi-statement-allow: true # 登录相关配置 login: # 是否限制单用户登录 single-login: false # Redis用户登录缓存配置 user-cache: # 存活时间/秒 idle-time: 21600 # 验证码 code: # 验证码类型配置 查看 LoginProperties 类 code-type: arithmetic # 登录图形验证码有效时间/分钟 expiration: 2 # 验证码高度 width: 111 # 验证码宽度 height: 36 # 内容长度 length: 2 # 字体名称,为空则使用默认字体 font-name: # 字体大小 font-size: 25 #jwt jwt: header: Authorization # 令牌前缀 token-start-with: Bearer # 必须使用最少88位的Base64对该令牌进行编码 base64-secret: ZmQ0ZGI5NjQ0MDQwY2I4MjMxY2Y3ZmI3MjdhN2ZmMjNhODViOTg1ZGE0NTBjMGM4NDA5NzYxMjdjOWMwYWRmZTBlZjlhNGY3ZTg4Y2U3YTE1ODVkZDU5Y2Y3OGYwZWE1NzUzNWQ2YjFjZDc0NGMxZWU2MmQ3MjY1NzJmNTE0MzI= # 令牌过期时间 此处单位/毫秒 ,默认4小时,可在此网站生成 https://www.convertworld.com/zh
-hans/time/milliseconds.html token-validity-in-seconds: 14400000 # 在线用户key online-key: "online_token:" # 验证码 code-key: "captcha_code:" # token 续期检查时间范围(默认30分钟,单位毫秒),在token即将过期的一段时间内用户操作了,则给用户的token续期 detect: 1800000 # 续期时间范围,默认1小时,单位毫秒 renew: 3600000 #是否允许生成代码,生产环境设置为false generator: enabled: true #是否开启 swagger-ui swagger: enabled: true # 文件存储路径 file: mac: path: ~/file/ avatar: ~/avatar/ linux: path: /home/eladmin/file/ avatar: /home/eladmin/avatar/ windows: path: C:\eladmin\file\ avatar: C:\eladmin\avatar\ # 文件大小 /M maxSize: 100 avatarMaxSize: 5 # 亚马逊S3协议云存储配置 #支持七牛云,阿里云OSS,腾讯云COS,华为云OBS,移动云EOS等 amz: s3: # 地域 region: test # 地域对应的 endpoint endPoint: https://s3.test.com # 访问的域名 domain: https://s3.test.com # 账号的认证信息,或者子账号的认证信息 accessKey: 填写你的AccessKey secretKey: 填写你的SecretKey # 存储桶(Bucket) defaultBucket: 填写你的存储桶名称 # 文件存储路径 timeformat: yyyy-MM
repos\eladmin-master\eladmin-system\src\main\resources\config\application-dev.yml
2
请完成以下Java代码
private PO retrievePO(final Properties ctx, final String tableName, final String whereClause, final Object[] params, final String trxName) { if (whereClause == null || whereClause.length() == 0) { return null; } // PO po = null; final POInfo info = POInfo.getPOInfo(tableName); if (info == null) { return null; } final StringBuilder sqlBuffer = info.buildSelect(); sqlBuffer.append(" WHERE ").append(whereClause); final String sql = sqlBuffer.toString(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sql, trxName); DB.setParameters(pstmt, params); rs = pstmt.executeQuery(); if (rs.next()) { po = getPO(ctx, tableName, rs, trxName); } } catch (Exception e) { log.error(sql, e); MetasfreshLastError.saveError(log, "Error", e); } finally { DB.close(rs, pstmt); } return po; } public <ModelType> ModelType retrieveModel(final Properties ctx, final String tableName, final Class<?> modelClass, final ResultSet rs, final String trxName) { final PO po = getPO(ctx, tableName, rs, trxName); // // Case: we have a modelClass specified if (modelClass != null) { final Class<? extends PO> poClass = po.getClass(); if (poClass.isAssignableFrom(modelClass)) {
@SuppressWarnings("unchecked") final ModelType model = (ModelType)po; return model; } else { @SuppressWarnings("unchecked") final ModelType model = (ModelType)InterfaceWrapperHelper.create(po, modelClass); return model; } } // // Case: no "clazz" and no "modelClass" else { if (log.isDebugEnabled()) { final AdempiereException ex = new AdempiereException("Query does not have a modelClass defined and no 'clazz' was specified as parameter." + "We need to avoid this case, but for now we are trying to do a force casting" + "\nQuery: " + this + "\nPO: " + po); log.debug(ex.getLocalizedMessage(), ex); } @SuppressWarnings("unchecked") final ModelType model = (ModelType)po; return model; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\persistence\TableModelLoader.java
1
请完成以下Java代码
public boolean hasNext() { return cursor != size; } public E next() { return getNextElement(); } private E getNextElement() { int current = cursor; exist(current); E[] elements = ShoppingCart.this.elementData; validate(elements, current); cursor = current + 1; lastReturned = current; return elements[lastReturned];
} private void exist(int current) { if (current >= size) { throw new NoSuchElementException(); } } private void validate(E[] elements, int current) { if (current >= elements.length) { throw new ConcurrentModificationException(); } } } }
repos\tutorials-master\core-java-modules\core-java-collections-2\src\main\java\com\baeldung\collections\iterable\ShoppingCart.java
1
请在Spring Boot框架中完成以下Java代码
public class SysAdminPermissions extends AbstractPermissions { public SysAdminPermissions() { super(); put(Resource.ADMIN_SETTINGS, PermissionChecker.allowAllPermissionChecker); put(Resource.DASHBOARD, new PermissionChecker.GenericPermissionChecker(Operation.READ)); put(Resource.TENANT, PermissionChecker.allowAllPermissionChecker); put(Resource.RULE_CHAIN, systemEntityPermissionChecker); put(Resource.USER, userPermissionChecker); put(Resource.WIDGETS_BUNDLE, systemEntityPermissionChecker); put(Resource.WIDGET_TYPE, systemEntityPermissionChecker); put(Resource.OAUTH2_CLIENT, systemEntityPermissionChecker); put(Resource.MOBILE_APP, systemEntityPermissionChecker); put(Resource.MOBILE_APP_BUNDLE, systemEntityPermissionChecker); put(Resource.DOMAIN, PermissionChecker.allowAllPermissionChecker); put(Resource.OAUTH2_CONFIGURATION_TEMPLATE, PermissionChecker.allowAllPermissionChecker); put(Resource.TENANT_PROFILE, PermissionChecker.allowAllPermissionChecker); put(Resource.TB_RESOURCE, systemEntityPermissionChecker); put(Resource.QUEUE, systemEntityPermissionChecker); put(Resource.NOTIFICATION, systemEntityPermissionChecker); put(Resource.MOBILE_APP_SETTINGS, PermissionChecker.allowAllPermissionChecker); put(Resource.API_KEY, PermissionChecker.allowAllPermissionChecker); } private static final PermissionChecker systemEntityPermissionChecker = new PermissionChecker() { @Override public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, HasTenantId entity) { if (entity.getTenantId() != null && !entity.getTenantId().isNullUid()) { return false; } return true;
} }; private static final PermissionChecker userPermissionChecker = new PermissionChecker<UserId, User>() { @Override public boolean hasPermission(SecurityUser user, Operation operation, UserId userId, User userEntity) { if (Authority.CUSTOMER_USER.equals(userEntity.getAuthority())) { return false; } return true; } }; private static final PermissionChecker<ApiKeyId, ApiKeyInfo> apiKeysPermissionChecker = new PermissionChecker<>() { @Override public boolean hasPermission(SecurityUser user, Operation operation) { return true; } }; }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\permission\SysAdminPermissions.java
2
请完成以下Java代码
public final class StandardPasswordEncoder extends AbstractValidatingPasswordEncoder { private static final int DEFAULT_ITERATIONS = 1024; private final Digester digester; private final byte[] secret; private final BytesKeyGenerator saltGenerator; /** * Constructs a standard password encoder with no additional secret value. */ public StandardPasswordEncoder() { this(""); } /** * Constructs a standard password encoder with a secret value which is also included * in the password hash. * @param secret the secret key used in the encoding process (should not be shared) */ public StandardPasswordEncoder(CharSequence secret) { this("SHA-256", secret); } @Override protected String encodeNonNullPassword(String rawPassword) { return encodedNonNullPassword(rawPassword, this.saltGenerator.generateKey()); } @Override protected boolean matchesNonNull(String rawPassword, String encodedPassword) { byte[] digested = decode(encodedPassword); byte[] salt = EncodingUtils.subArray(digested, 0, this.saltGenerator.getKeyLength()); return MessageDigest.isEqual(digested, digest(rawPassword, salt)); } private StandardPasswordEncoder(String algorithm, CharSequence secret) { this.digester = new Digester(algorithm, DEFAULT_ITERATIONS); this.secret = Utf8.encode(secret);
this.saltGenerator = KeyGenerators.secureRandom(); } private String encodedNonNullPassword(CharSequence rawPassword, byte[] salt) { byte[] digest = digest(rawPassword, salt); return new String(Hex.encode(digest)); } private byte[] digest(CharSequence rawPassword, byte[] salt) { byte[] digest = this.digester.digest(EncodingUtils.concatenate(salt, this.secret, Utf8.encode(rawPassword))); return EncodingUtils.concatenate(salt, digest); } private byte[] decode(CharSequence encodedPassword) { return Hex.decode(encodedPassword); } }
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\StandardPasswordEncoder.java
1
请完成以下Java代码
public void setHelp (final java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } @Override public java.lang.String getHelp() { return get_ValueAsString(COLUMNNAME_Help); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_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); }
@Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setStandardQty (final BigDecimal StandardQty) { set_Value (COLUMNNAME_StandardQty, StandardQty); } @Override public BigDecimal getStandardQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phase.java
1
请在Spring Boot框架中完成以下Java代码
public int deleteBrand(Long id) { return brandMapper.deleteByPrimaryKey(id); } @Override public int deleteBrand(List<Long> ids) { PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.deleteByExample(pmsBrandExample); } @Override public List<PmsBrand> listBrand(String keyword, Integer showStatus, int pageNum, int pageSize) { PageHelper.startPage(pageNum, pageSize); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.setOrderByClause("sort desc"); PmsBrandExample.Criteria criteria = pmsBrandExample.createCriteria(); if (!StrUtil.isEmpty(keyword)) { criteria.andNameLike("%" + keyword + "%"); } if(showStatus!=null){ criteria.andShowStatusEqualTo(showStatus); } return brandMapper.selectByExample(pmsBrandExample); } @Override public PmsBrand getBrand(Long id) { return brandMapper.selectByPrimaryKey(id); } @Override
public int updateShowStatus(List<Long> ids, Integer showStatus) { PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setShowStatus(showStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample); } @Override public int updateFactoryStatus(List<Long> ids, Integer factoryStatus) { PmsBrand pmsBrand = new PmsBrand(); pmsBrand.setFactoryStatus(factoryStatus); PmsBrandExample pmsBrandExample = new PmsBrandExample(); pmsBrandExample.createCriteria().andIdIn(ids); return brandMapper.updateByExampleSelective(pmsBrand, pmsBrandExample); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsBrandServiceImpl.java
2
请完成以下Java代码
public boolean schedule(Runnable runnable, boolean isLongRunning) { if(isLongRunning) { return executeLongRunning(runnable); } else { return executeShortRunning(runnable); } } protected boolean executeLongRunning(Runnable runnable) { new Thread(runnable).start(); return true; } protected boolean executeShortRunning(Runnable runnable) {
try { threadPoolExecutor.execute(runnable); return true; } catch (RejectedExecutionException e) { LOG.debugRejectedExecutionException(e); return false; } } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\threading\se\SeExecutorService.java
1
请完成以下Java代码
private Object invokeGetIdMethod(Object object, Class<?> typeClass) { try { Method method = typeClass.getMethod("getId", new Class[] {}); return method.invoke(object); } catch (Exception ex) { throw new IdentityUnavailableException("Could not extract identity from object " + object, ex); } } /** * Important so caching operates properly. * <p> * Considers an object of the same class equal if it has the same * <code>classname</code> and <code>id</code> properties. * <p> * Numeric identities (Integer and Long values) are considered equal if they are * numerically equal. Other serializable types are evaluated using a simple equality. * @param obj object to compare * @return <code>true</code> if the presented object matches this object */ @Override public boolean equals(Object obj) { if (obj == null || !(obj instanceof ObjectIdentityImpl)) { return false; } ObjectIdentityImpl other = (ObjectIdentityImpl) obj; if (this.identifier instanceof Number && other.identifier instanceof Number) { // Integers and Longs with same value should be considered equal if (((Number) this.identifier).longValue() != ((Number) other.identifier).longValue()) { return false; } } else { // Use plain equality for other serializable types if (!this.identifier.equals(other.identifier)) { return false; } } return this.type.equals(other.type); } @Override public Serializable getIdentifier() { return this.identifier; }
@Override public String getType() { return this.type; } /** * Important so caching operates properly. * @return the hash */ @Override public int hashCode() { int result = this.type.hashCode(); result = 31 * result + this.identifier.hashCode(); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(this.getClass().getName()).append("["); sb.append("Type: ").append(this.type); sb.append("; Identifier: ").append(this.identifier).append("]"); return sb.toString(); } }
repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\ObjectIdentityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class EventDeployer implements EngineDeployer { private static final Logger LOGGER = LoggerFactory.getLogger(EventDeployer.class); @Override public void deploy(EngineDeployment deployment, Map<String, Object> deploymentSettings) { if (!deployment.isNew()) { return; } LOGGER.debug("EventDeployer: processing deployment {}", deployment.getName()); EventDeploymentBuilder eventDeploymentBuilder = null; Map<String, EngineResource> resources = deployment.getResources(); for (String resourceName : resources.keySet()) { if (resourceName.endsWith(".event")) { LOGGER.info("EventDeployer: processing resource {}", resourceName); if (eventDeploymentBuilder == null) { EventRepositoryService eventRepositoryService = CommandContextUtil.getEventRepositoryService(); eventDeploymentBuilder = eventRepositoryService.createDeployment().name(deployment.getName()); } eventDeploymentBuilder.addEventDefinitionBytes(resourceName, resources.get(resourceName).getBytes()); } else if (resourceName.endsWith(".channel")) { LOGGER.info("EventDeployer: processing resource {}", resourceName); if (eventDeploymentBuilder == null) { EventRepositoryService eventRepositoryService = CommandContextUtil.getEventRepositoryService(); eventDeploymentBuilder = eventRepositoryService.createDeployment().name(deployment.getName()); } eventDeploymentBuilder.addChannelDefinitionBytes(resourceName, resources.get(resourceName).getBytes()); } } if (eventDeploymentBuilder != null) { eventDeploymentBuilder.parentDeploymentId(deployment.getId()); if (deployment.getTenantId() != null && deployment.getTenantId().length() > 0) {
eventDeploymentBuilder.tenantId(deployment.getTenantId()); } eventDeploymentBuilder.deploy(); } } @Override public void undeploy(EngineDeployment parentDeployment, boolean cascade) { EventRepositoryService repositoryService = CommandContextUtil.getEventRepositoryService(); List<EventDeployment> eventDeployments = repositoryService.createDeploymentQuery() .parentDeploymentId(parentDeployment.getId()) .list(); for (EventDeployment eventDeployment : eventDeployments) { repositoryService.deleteDeployment(eventDeployment.getId()); } } }
repos\flowable-engine-main\modules\flowable-event-registry-configurator\src\main\java\org\flowable\eventregistry\impl\configurator\deployer\EventDeployer.java
2
请完成以下Java代码
public class JWTUtil { private static final Logger log = LoggerFactory.getLogger(JWTUtil.class); // 过期时间5分钟 private static final long EXPIRE_TIME = 5 * 60 * 1000; /** * 生成签名,5min后过期 * * @param username 用户名 * @param secret 用户的密码 * @return 加密的token */ public static String sign(String username, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } /** * 校验token是否正确 * * @param token 密钥 * @param secret 用户的密码
* @return 是否正确 */ public static boolean verify(String token, String username, String secret) { Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username) .build(); DecodedJWT jwt = verifier.verify(token); return true; } /** * 获得token中的信息无需secret解密也能获得 * * @return token中包含的用户名 */ public static String getUsername(String token) { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\common\util\JWTUtil.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectWithInternalReason("one and only one order shall be selected"); } final I_C_Order salesOrder = context.getSelectedModel(I_C_Order.class); // NOTE: we allow sales and purchase orders too; see https://github.com/metasfresh/metasfresh/issues/4017 final DocStatus docStatus = DocStatus.ofCode(salesOrder.getDocStatus()); if (!docStatus.isDrafted()) { return ProcessPreconditionsResolution.rejectWithInternalReason("only draft orders are allowed"); } // Make sure only one line is selected final Set<TableRecordReference> selectedOrderLineRefs = context.getSelectedIncludedRecords(); if (selectedOrderLineRefs.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (selectedOrderLineRefs.size() > 1) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } return ProcessPreconditionsResolution.accept(); }
@Override protected String doIt() { final Set<TableRecordReference> salesOrderLineRefs = getSelectedIncludedRecordIds(I_C_OrderLine.class) .stream() .map(recordId -> TableRecordReference.of(I_C_OrderLine.Table_Name, recordId)) .collect(ImmutableSet.toImmutableSet()); CollectionUtils.singleElement(salesOrderLineRefs); getResult().setRecordsToOpen(salesOrderLineRefs, OrderLinePricingConditionsViewFactory.WINDOW_ID_STRING); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\process\WEBUI_SalesOrder_PricingConditionsView_Launcher.java
1
请完成以下Java代码
public DefaultPrintFormats getDefaultPrintFormats(@NonNull final ClientId clientId) { return defaultPrintFormatsRepository.getByClientId(clientId); } @NonNull public AdProcessId getReportProcessIdByPrintFormatId(@NonNull final PrintFormatId printFormatId) { return getReportProcessIdByPrintFormatIdIfExists(printFormatId).get(); } @NonNull public ExplainedOptional<AdProcessId> getReportProcessIdByPrintFormatIdIfExists(@NonNull final PrintFormatId printFormatId) { final PrintFormat printFormat = printFormatRepository.getById(printFormatId); final AdProcessId reportProcessId = printFormat.getReportProcessId(); return reportProcessId != null ? ExplainedOptional.of(reportProcessId) : ExplainedOptional.emptyBecause("No report process defined by " + printFormat); } @NonNull public I_C_DocType getDocTypeById(@NonNull final DocTypeId docTypeId) { return docTypeDAO.getById(docTypeId); }
public PrintCopies getDocumentCopies( @Nullable final I_C_DocType docType, @Nullable final BPPrintFormatQuery bpPrintFormatQuery) { final BPPrintFormat bpPrintFormat = bpPrintFormatQuery == null ? null : bPartnerPrintFormatRepository.getByQuery(bpPrintFormatQuery); if(bpPrintFormat == null) { return getDocumentCopies(docType); } return bpPrintFormat.getPrintCopies(); } private static PrintCopies getDocumentCopies(@Nullable final I_C_DocType docType) { return docType != null && !InterfaceWrapperHelper.isNull(docType, I_C_DocType.COLUMNNAME_DocumentCopies) ? PrintCopies.ofInt(docType.getDocumentCopies()) : PrintCopies.ONE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportAdvisorUtil.java
1