instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
final class AnnotatedTablePopupMenu extends JPopupMenu { /** * */ private static final long serialVersionUID = 6618408337499167870L; private final WeakReference<JTable> tableRef; private final PopupMenuListener popupListener = new PopupMenuListenerAdapter() { @Override public void popupMenuWillBecomeVisible(final PopupMenuEvent e) { AnnotatedTablePopupMenu.this.popupMenuWillBecomeVisible(e); } @Override public void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { AnnotatedTablePopupMenu.this.popupMenuWillBecomeInvisible(e); } }; public AnnotatedTablePopupMenu(final JTable table) { super(); Check.assumeNotNull(table, "table not null"); tableRef = new WeakReference<>(table); addPopupMenuListener(popupListener); } private final JTable getTable() { final JTable table = tableRef.get(); Check.assumeNotNull(table, "table not null"); return table; } private final List<AnnotatedTableAction> getTableActions() { final List<AnnotatedTableAction> tableActions = new ArrayList<>(); for (final MenuElement me : getSubElements())
{ if (!(me instanceof AbstractButton)) { continue; } final AbstractButton button = (AbstractButton)me; final Action action = button.getAction(); if (action instanceof AnnotatedTableAction) { final AnnotatedTableAction tableAction = (AnnotatedTableAction)action; tableActions.add(tableAction); } } return tableActions; } private final void popupMenuWillBecomeVisible(final PopupMenuEvent e) { for (final AnnotatedTableAction tableAction : getTableActions()) { tableAction.setTable(getTable()); tableAction.updateBeforeDisplaying(); } } private final void popupMenuWillBecomeInvisible(final PopupMenuEvent e) { // nothing atm } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTablePopupMenu.java
1
请完成以下Java代码
public int getPO_DiscountSchema_ID() { int ii = super.getPO_DiscountSchema_ID(); if (ii == 0) { ii = getBPGroup().getPO_DiscountSchema_ID(); } return ii; } // getPO_DiscountSchema_ID // metas public static int getDefaultContactId(final int cBPartnerId) { for (final I_AD_User user : Services.get(IBPartnerDAO.class).retrieveContacts(Env.getCtx(), cBPartnerId, ITrx.TRXNAME_None)) { if (user.isDefaultContact()) { return user.getAD_User_ID(); } } LogManager.getLogger(MBPartner.class).warn("Every BPartner with associated contacts is expected to have exactly one default contact, but C_BPartner_ID {} doesn't have one.", cBPartnerId); return -1; } // end metas /** * Before Save * * @param newRecord new * @return true */ @Override protected boolean beforeSave(final boolean newRecord) { if (newRecord || is_ValueChanged("C_BP_Group_ID")) { final I_C_BP_Group grp = getBPGroup(); if (grp == null) { throw new AdempiereException("@NotFound@: @C_BP_Group_ID@"); } final BPGroupId parentGroupId = BPGroupId.ofRepoIdOrNull(grp.getParent_BP_Group_ID()); if (parentGroupId != null) { final I_C_BP_Group parentGroup = bpGroupsRepo.getById(parentGroupId); setBPGroup(parentGroup); // attempt to set from parent group first } setBPGroup(grp); // setDefaults } return true; } // beforeSave /************************************************************************** * After Save * * @param newRecord * new * @param success * success * @return success */ @Override protected boolean afterSave(final boolean newRecord, final boolean success) { if (newRecord && success) { // Trees insert_Tree(MTree_Base.TREETYPE_BPartner); // Accounting insert_Accounting("C_BP_Customer_Acct", "C_BP_Group_Acct", "p.C_BP_Group_ID=" + getC_BP_Group_ID()); insert_Accounting("C_BP_Vendor_Acct", "C_BP_Group_Acct", "p.C_BP_Group_ID=" + getC_BP_Group_ID()); insert_Accounting("C_BP_Employee_Acct", "C_AcctSchema_Default", null); }
// Value/Name change if (success && !newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) { MAccount.updateValueDescription(getCtx(), "C_BPartner_ID=" + getC_BPartner_ID(), get_TrxName()); } return success; } // afterSave /** * Before Delete * * @return true */ @Override protected boolean beforeDelete() { return delete_Accounting("C_BP_Customer_Acct") && delete_Accounting("C_BP_Vendor_Acct") && delete_Accounting("C_BP_Employee_Acct"); } // beforeDelete /** * After Delete * * @param success * @return deleted */ @Override protected boolean afterDelete(final boolean success) { if (success) { delete_Tree(MTree_Base.TREETYPE_BPartner); } return success; } // afterDelete } // MBPartner
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MBPartner.java
1
请完成以下Java代码
public void setTelephone(String telephone) { this.telephone = telephone; } public List<Pet> getPets() { return this.pets; } public void addPet(Pet pet) { if (pet.isNew()) { getPets().add(pet); } } /** * Return the Pet with the given name, or null if none found for this Owner. * @param name to test * @return the Pet with the given name, or null if no such Pet exists for this Owner */ public Pet getPet(String name) { return getPet(name, false); } /** * Return the Pet with the given id, or null if none found for this Owner. * @param id to test * @return the Pet with the given id, or null if no such Pet exists for this Owner */ public Pet getPet(Integer id) { for (Pet pet : getPets()) { if (!pet.isNew()) { Integer compId = pet.getId(); if (Objects.equals(compId, id)) { return pet; } } } return null; } /** * Return the Pet with the given name, or null if none found for this Owner. * @param name to test * @param ignoreNew whether to ignore new pets (pets that are not saved yet) * @return the Pet with the given name, or null if no such Pet exists for this Owner */ public Pet getPet(String name, boolean ignoreNew) { for (Pet pet : getPets()) { String compName = pet.getName(); if (compName != null && compName.equalsIgnoreCase(name)) { if (!ignoreNew || !pet.isNew()) { return pet; } } } return null; } @Override public String toString() { return new ToStringCreator(this).append("id", this.getId())
.append("new", this.isNew()) .append("lastName", this.getLastName()) .append("firstName", this.getFirstName()) .append("address", this.address) .append("city", this.city) .append("telephone", this.telephone) .toString(); } /** * Adds the given {@link Visit} to the {@link Pet} with the given identifier. * @param petId the identifier of the {@link Pet}, must not be {@literal null}. * @param visit the visit to add, must not be {@literal null}. */ public void addVisit(Integer petId, Visit visit) { Assert.notNull(petId, "Pet identifier must not be null!"); Assert.notNull(visit, "Visit must not be null!"); Pet pet = getPet(petId); Assert.notNull(pet, "Invalid Pet identifier!"); pet.addVisit(visit); } }
repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\owner\Owner.java
1
请在Spring Boot框架中完成以下Java代码
public class LoginVM { @NotNull @Size(min = 1, max = 50) private String username; @NotNull @Size(min = 4, max = 100) private String password; private boolean rememberMe; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; }
public void setPassword(String password) { this.password = password; } public boolean isRememberMe() { return rememberMe; } public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } // prettier-ignore @Override public String toString() { return "LoginVM{" + "username='" + username + '\'' + ", rememberMe=" + rememberMe + '}'; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\web\rest\vm\LoginVM.java
2
请完成以下Java代码
public void setAD_PInstance_ID (final int AD_PInstance_ID) { if (AD_PInstance_ID < 1) set_Value (COLUMNNAME_AD_PInstance_ID, null); else set_Value (COLUMNNAME_AD_PInstance_ID, AD_PInstance_ID); } @Override public int getAD_PInstance_ID() { return get_ValueAsInt(COLUMNNAME_AD_PInstance_ID); } @Override public void setC_Async_Batch_ID (final int C_Async_Batch_ID) { if (C_Async_Batch_ID < 1) set_Value (COLUMNNAME_C_Async_Batch_ID, null); else set_Value (COLUMNNAME_C_Async_Batch_ID, C_Async_Batch_ID); } @Override public int getC_Async_Batch_ID() { return get_ValueAsInt(COLUMNNAME_C_Async_Batch_ID); } @Override public void setChunkUUID (final @Nullable java.lang.String ChunkUUID) { set_Value (COLUMNNAME_ChunkUUID, ChunkUUID); } @Override public java.lang.String getChunkUUID() { return get_ValueAsString(COLUMNNAME_ChunkUUID); }
@Override public de.metas.inoutcandidate.model.I_M_ShipmentSchedule getM_ShipmentSchedule() { return get_ValueAsPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class); } @Override public void setM_ShipmentSchedule(final de.metas.inoutcandidate.model.I_M_ShipmentSchedule M_ShipmentSchedule) { set_ValueFromPO(COLUMNNAME_M_ShipmentSchedule_ID, de.metas.inoutcandidate.model.I_M_ShipmentSchedule.class, M_ShipmentSchedule); } @Override public void setM_ShipmentSchedule_ID (final int M_ShipmentSchedule_ID) { if (M_ShipmentSchedule_ID < 1) set_Value (COLUMNNAME_M_ShipmentSchedule_ID, null); else set_Value (COLUMNNAME_M_ShipmentSchedule_ID, M_ShipmentSchedule_ID); } @Override public int getM_ShipmentSchedule_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipmentSchedule_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_Recompute.java
1
请在Spring Boot框架中完成以下Java代码
public class GlobalProperties { //thread-pool , relax binding private int threadPool; private String email; public int getThreadPool() { return threadPool; } public void setThreadPool(int threadPool) { this.threadPool = threadPool; } public String getEmail() {
return email; } public void setEmail(String email) { this.email = email; } @Override public String toString() { return "GlobalProperties{" + "threadPool=" + threadPool + ", email='" + email + '\'' + '}'; } }
repos\spring-boot-master\yaml-simple\src\main\java\com\mkyong\config\GlobalProperties.java
2
请完成以下Java代码
public void setFieldExtensions(List<FieldExtension> fieldExtensions) { this.fieldExtensions = fieldExtensions; } public Object getInstance() { return instance; } public void setInstance(Object instance) { this.instance = instance; } @Override public ScriptInfo getScriptInfo() { return scriptInfo; } @Override public void setScriptInfo(ScriptInfo scriptInfo) { this.scriptInfo = scriptInfo;
} @Override public abstract AbstractFlowableHttpHandler clone(); public void setValues(AbstractFlowableHttpHandler otherHandler) { super.setValues(otherHandler); setImplementation(otherHandler.getImplementation()); setImplementationType(otherHandler.getImplementationType()); if (otherHandler.getScriptInfo() != null) { setScriptInfo(otherHandler.getScriptInfo().clone()); } fieldExtensions = new ArrayList<>(); if (otherHandler.getFieldExtensions() != null && !otherHandler.getFieldExtensions().isEmpty()) { for (FieldExtension extension : otherHandler.getFieldExtensions()) { fieldExtensions.add(extension.clone()); } } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\AbstractFlowableHttpHandler.java
1
请完成以下Java代码
public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day)
*/ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxDefinition.java
1
请完成以下Java代码
public void setMultiplier(Double multiplier) { this.multiplier = multiplier; } /** * Return the maximum delay for any retry attempt. * @return the maximum delay */ public Duration getMaxDelay() { return this.maxDelay; } /** * Specify the maximum delay for any retry attempt, limiting how far * {@linkplain #getJitter() jitter} and the {@linkplain #getMultiplier() multiplier} * can increase the {@linkplain #getDelay() delay}. * <p> * The default is unlimited. * @param maxDelay the maximum delay (must be positive)
* @see #DEFAULT_MAX_DELAY */ public void setMaxDelay(Duration maxDelay) { this.maxDelay = maxDelay; } /** * Set the factory to use to create the {@link RetryPolicy}, or {@code null} to use * the default. The function takes a {@link Builder RetryPolicy.Builder} initialized * with the state of this instance that can be further configured, or ignored to * restart from scratch. * @param factory a factory to customize the retry policy. */ public void setFactory(@Nullable Function<RetryPolicy.Builder, RetryPolicy> factory) { this.factory = factory; } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\retry\RetryPolicySettings.java
1
请完成以下Java代码
public class LinesReader implements Tasklet, StepExecutionListener { private final Logger logger = LoggerFactory.getLogger(LinesReader.class); private List<Line> lines; private FileUtils fu; @Override public void beforeStep(StepExecution stepExecution) { lines = new ArrayList<>(); fu = new FileUtils("taskletsvschunks/input/tasklets-vs-chunks.csv"); logger.debug("Lines Reader initialized."); } @Override public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception { Line line = fu.readLine(); while (line != null) { lines.add(line); logger.debug("Read line: " + line.toString()); line = fu.readLine();
} return RepeatStatus.FINISHED; } @Override public ExitStatus afterStep(StepExecution stepExecution) { fu.closeReader(); stepExecution .getJobExecution() .getExecutionContext() .put("lines", this.lines); logger.debug("Lines Reader ended."); return ExitStatus.COMPLETED; } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\tasklets\LinesReader.java
1
请完成以下Java代码
private void process() { if (segments.isEmpty()) { return; } final List<IShipmentScheduleSegment> segmentsCopy = new ArrayList<>(segments); segments.clear(); shipmentScheduleInvalidator.flagSegmentForRecompute(segmentsCopy); } public void addSegment(final IShipmentScheduleSegment segment) { if (segment == null)
{ return; } this.segments.add(segment); } public void addSegments(final Collection<IShipmentScheduleSegment> segments) { if (segments == null || segments.isEmpty()) { return; } this.segments.addAll(segments); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\invalidation\impl\ShipmentScheduleSegmentChangedProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public class FlushOnSaveRepositoryImpl<T> implements FlushOnSaveRepository<T> { final @NonNull EntityManager entityManager; /* * (non-Javadoc) * @see example.springdata.jpa.compositions.FlushOnSaveRepository#save(java.lang.Object) */ @Transactional @Override public <S extends T> S save(S entity) { doSave(entity); entityManager.flush(); return entity; } /** * @param entity */ private <S extends T> void doSave(S entity) { var entityInformation = getEntityInformation(entity); if (entityInformation.isNew(entity)) { entityManager.persist(entity); } else { entityManager.merge(entity); } } /* * (non-Javadoc) * @see example.springdata.jpa.compositions.FlushOnSaveRepository#saveAll(java.lang.Iterable) */ @Transactional
@Override public <S extends T> Iterable<S> saveAll(Iterable<S> entities) { entities.forEach(this::doSave); entityManager.flush(); return entities; } @SuppressWarnings({ "unchecked", "rawtypes" }) private <S extends T> EntityInformation<Object, S> getEntityInformation(S entity) { var userClass = ClassUtils.getUserClass(entity.getClass()); if (entity instanceof AbstractPersistable<?>) { return new JpaPersistableEntityInformation(userClass, entityManager.getMetamodel(),entityManager.getEntityManagerFactory().getPersistenceUnitUtil() ); } return new JpaMetamodelEntityInformation(userClass, entityManager.getMetamodel(), entityManager.getEntityManagerFactory().getPersistenceUnitUtil()); } }
repos\spring-data-examples-main\jpa\example\src\main\java\example\springdata\jpa\compositions\FlushOnSaveRepositoryImpl.java
2
请完成以下Java代码
public boolean isExpired() { return isExpired(Instant.now()); } boolean isExpired(Instant now) { if (this.maxInactiveInterval.isNegative()) { return false; } return now.minus(this.maxInactiveInterval).compareTo(this.lastAccessedTime) >= 0; } @Override @SuppressWarnings("unchecked") public <T> T getAttribute(String attributeName) { return (T) this.sessionAttrs.get(attributeName); } @Override public Set<String> getAttributeNames() { return new HashSet<>(this.sessionAttrs.keySet()); } @Override public void setAttribute(String attributeName, Object attributeValue) { if (attributeValue == null) { removeAttribute(attributeName); } else { this.sessionAttrs.put(attributeName, attributeValue); } } @Override public void removeAttribute(String attributeName) { this.sessionAttrs.remove(attributeName); } /** * Sets the time that this {@link Session} was created. The default is when the * {@link Session} was instantiated. * @param creationTime the time that this {@link Session} was created. */ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime;
} /** * Sets the identifier for this {@link Session}. The id should be a secure random * generated value to prevent malicious users from guessing this value. The default is * a secure random generated identifier. * @param id the identifier for this session. */ public void setId(String id) { this.id = id; } @Override public boolean equals(Object obj) { return obj instanceof Session && this.id.equals(((Session) obj).getId()); } @Override public int hashCode() { return this.id.hashCode(); } private static String generateId() { return UUID.randomUUID().toString(); } /** * Sets the {@link SessionIdGenerator} to use when generating a new session id. * @param sessionIdGenerator the {@link SessionIdGenerator} to use. * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } private static final long serialVersionUID = 7160779239673823561L; }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java
1
请完成以下Java代码
public class BizException extends RuntimeException { private static final long serialVersionUID = -5875371379845226068L; /** * 数据库操作,insert返回0 */ public static final BizException DB_INSERT_RESULT_0 = new BizException( 10040001, "数据库操作,insert返回0"); /** * 数据库操作,update返回0 */ public static final BizException DB_UPDATE_RESULT_0 = new BizException( 10040002, "数据库操作,update返回0"); /** * 数据库操作,selectOne返回null */ public static final BizException DB_SELECTONE_IS_NULL = new BizException( 10040003, "数据库操作,selectOne返回null"); /** * 数据库操作,list返回null */ public static final BizException DB_LIST_IS_NULL = new BizException( 10040004, "数据库操作,list返回null"); /** * Token 验证不通过 */ public static final BizException TOKEN_IS_ILLICIT = new BizException( 10040005, "Token 验证非法"); /** * 会话超时 获取session时,如果是空,throws 下面这个异常 拦截器会拦截爆会话超时页面 */ public static final BizException SESSION_IS_OUT_TIME = new BizException( 10040006, "会话超时"); /** * 生成序列异常时 */ public static final BizException DB_GET_SEQ_NEXT_VALUE_ERROR = new BizException( 10040007, "序列生成超时"); /** * 异常信息 */ protected String msg; /** * 具体异常码 */ protected int code;
public BizException(int code, String msgFormat, Object... args) { super(String.format(msgFormat, args)); this.code = code; this.msg = String.format(msgFormat, args); } public BizException() { super(); } public BizException(String message, Throwable cause) { super(message, cause); } public BizException(Throwable cause) { super(cause); } public BizException(String message) { super(message); } public String getMsg() { return msg; } public int getCode() { return code; } /** * 实例化异常 * * @param msgFormat * @param args * @return */ public BizException newInstance(String msgFormat, Object... args) { return new BizException(this.code, msgFormat, args); } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\exception\BizException.java
1
请完成以下Java代码
public void setM_InventoryLine(final org.compiere.model.I_M_InventoryLine M_InventoryLine) { set_ValueFromPO(COLUMNNAME_M_InventoryLine_ID, org.compiere.model.I_M_InventoryLine.class, M_InventoryLine); } @Override public void setM_InventoryLine_ID (final int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InventoryLine_ID, M_InventoryLine_ID); } @Override public int getM_InventoryLine_ID() { return get_ValueAsInt(COLUMNNAME_M_InventoryLine_ID); } @Override public void setQtyBook (final @Nullable BigDecimal QtyBook) { set_Value (COLUMNNAME_QtyBook, QtyBook); } @Override public BigDecimal getQtyBook() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyBook); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCount (final @Nullable BigDecimal QtyCount)
{ set_Value (COLUMNNAME_QtyCount, QtyCount); } @Override public BigDecimal getQtyCount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyInternalUse (final @Nullable BigDecimal QtyInternalUse) { set_Value (COLUMNNAME_QtyInternalUse, QtyInternalUse); } @Override public BigDecimal getQtyInternalUse() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInternalUse); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setRenderedQRCode (final @Nullable java.lang.String RenderedQRCode) { set_Value (COLUMNNAME_RenderedQRCode, RenderedQRCode); } @Override public java.lang.String getRenderedQRCode() { return get_ValueAsString(COLUMNNAME_RenderedQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_InventoryLine_HU.java
1
请完成以下Java代码
public boolean unregisterJMX(final ObjectName jmxObjectName, final boolean failOnError) { if (jmxObjectName == null) { if (failOnError) { throw new JMXException("Invalid JMX ObjectName: " + jmxObjectName); } return false; } final MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); boolean success = false; try {
mbs.unregisterMBean(jmxObjectName); success = true; } catch (Exception e) { if (failOnError) { throw new JMXException("Cannot unregister " + jmxObjectName, e); } success = false; } return success; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\jmx\JMXRegistry.java
1
请完成以下Java代码
public void preStart() { log.info("Starting WordCounterActor {}", this); } @Override public Receive createReceive() { return receiveBuilder() .match(CountWords.class, r -> { try { log.info("Received CountWords message from " + getSender()); int numberOfWords = countWordsFromLine(r.line); getSender().tell(numberOfWords, getSelf()); } catch (Exception ex) { getSender().tell(new akka.actor.Status.Failure(ex), getSelf()); throw ex; } }) .build(); }
private int countWordsFromLine(String line) throws Exception { if (line == null) { throw new IllegalArgumentException("The text to process can't be null!"); } int numberOfWords = 0; String[] words = line.split(" "); for (String possibleWord : words) { if (possibleWord.trim().length() > 0) { numberOfWords++; } } return numberOfWords; } }
repos\tutorials-master\akka-modules\akka-actors\src\main\java\com\baeldung\akkaactors\WordCounterActor.java
1
请完成以下Java代码
public float getUA() { return U / A; } public float getLA() { return L / A; } public float getDA() { return D / (A - sentenceCount); } @Override public String toString() { NumberFormat percentFormat = NumberFormat.getPercentInstance(); percentFormat.setMinimumFractionDigits(2); StringBuilder sb = new StringBuilder(); sb.append("UA: ");
sb.append(percentFormat.format(getUA())); sb.append('\t'); sb.append("LA: "); sb.append(percentFormat.format(getLA())); sb.append('\t'); sb.append("DA: "); sb.append(percentFormat.format(getDA())); sb.append('\t'); sb.append("sentences: "); sb.append(sentenceCount); sb.append('\t'); sb.append("speed: "); sb.append(sentenceCount / (float)(System.currentTimeMillis() - start) * 1000); sb.append(" sent/s"); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\Evaluator.java
1
请在Spring Boot框架中完成以下Java代码
private JSONObject getItemHintValue(ItemHint.ValueHint value) throws Exception { JSONObject result = new JSONObject(); putHintValue(result, value.getValue()); result.putOpt("description", value.getDescription()); return result; } private JSONArray getItemHintProviders(ItemHint hint) throws Exception { JSONArray providers = new JSONArray(); for (ItemHint.ValueProvider provider : hint.getProviders()) { providers.put(getItemHintProvider(provider)); } return providers; } private JSONObject getItemHintProvider(ItemHint.ValueProvider provider) throws Exception { JSONObject result = new JSONObject(); result.put("name", provider.getName()); if (provider.getParameters() != null && !provider.getParameters().isEmpty()) { JSONObject parameters = new JSONObject(); for (Map.Entry<String, Object> entry : provider.getParameters().entrySet()) { parameters.put(entry.getKey(), extractItemValue(entry.getValue())); } result.put("parameters", parameters); } return result; } private void putHintValue(JSONObject jsonObject, Object value) throws Exception { Object hintValue = extractItemValue(value); jsonObject.put("value", hintValue); } private void putDefaultValue(JSONObject jsonObject, Object value) throws Exception { Object defaultValue = extractItemValue(value); jsonObject.put("defaultValue", defaultValue); } private Object extractItemValue(Object value) { Object defaultValue = value; if (value.getClass().isArray()) { JSONArray array = new JSONArray(); int length = Array.getLength(value); for (int i = 0; i < length; i++) { array.put(Array.get(value, i)); } defaultValue = array;
} return defaultValue; } private static final class ItemMetadataComparator implements Comparator<ItemMetadata> { private static final Comparator<ItemMetadata> GROUP = Comparator.comparing(ItemMetadata::getName) .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); private static final Comparator<ItemMetadata> ITEM = Comparator.comparing(ItemMetadataComparator::isDeprecated) .thenComparing(ItemMetadata::getName) .thenComparing(ItemMetadata::getSourceType, Comparator.nullsFirst(Comparator.naturalOrder())); @Override public int compare(ItemMetadata o1, ItemMetadata o2) { if (o1.isOfItemType(ItemType.GROUP)) { return GROUP.compare(o1, o2); } return ITEM.compare(o1, o2); } private static boolean isDeprecated(ItemMetadata item) { return item.getDeprecation() != null; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\metadata\JsonConverter.java
2
请完成以下Java代码
public String getExtensionProperty(String propertyKey) { if(extensionProperties != null) { return extensionProperties.get(propertyKey); } return null; } @Override public String toString() { return "ExternalTaskImpl [" + "activityId=" + activityId + ", " + "activityInstanceId=" + activityInstanceId + ", " + "businessKey=" + businessKey + ", " + "errorDetails=" + errorDetails + ", " + "errorMessage=" + errorMessage + ", " + "executionId=" + executionId + ", " + "id=" + id + ", " + formatTimeField("lockExpirationTime", lockExpirationTime) + ", " + formatTimeField("createTime", createTime) + ", " + "priority=" + priority + ", " + "processDefinitionId=" + processDefinitionId + ", "
+ "processDefinitionKey=" + processDefinitionKey + ", " + "processDefinitionVersionTag=" + processDefinitionVersionTag + ", " + "processInstanceId=" + processInstanceId + ", " + "receivedVariableMap=" + receivedVariableMap + ", " + "retries=" + retries + ", " + "tenantId=" + tenantId + ", " + "topicName=" + topicName + ", " + "variables=" + variables + ", " + "workerId=" + workerId + "]"; } protected String formatTimeField(String timeField, Date time) { return timeField + "=" + (time == null ? null : DateFormat.getDateTimeInstance().format(time)); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\task\impl\ExternalTaskImpl.java
1
请完成以下Java代码
public String toString() { return "CommissionShareHandler"; } @NonNull private DocTypeId getDoctypeId(@NonNull final I_C_Commission_Share shareRecord) { final CommissionConstants.CommissionDocType commissionDocType = getCommissionDocType(shareRecord); return docTypeDAO.getDocTypeId( DocTypeQuery.builder() .docBaseType(commissionDocType.getDocBaseType()) .docSubType(DocSubType.ofCode(commissionDocType.getDocSubType())) .adClientId(shareRecord.getAD_Client_ID()) .adOrgId(shareRecord.getAD_Org_ID()) .build()); } @NonNull private CommissionConstants.CommissionDocType getCommissionDocType(@NonNull final I_C_Commission_Share shareRecord) {
if (!shareRecord.isSOTrx()) { // note that SOTrx is about the share record's settlement. // I.e. if the sales-rep receives money from the commission, then it's a purchase order trx return CommissionConstants.CommissionDocType.COMMISSION; } else if (shareRecord.getC_LicenseFeeSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.LICENSE_COMMISSION; } else if (shareRecord.getC_MediatedCommissionSettingsLine_ID() > 0) { return CommissionConstants.CommissionDocType.MEDIATED_COMMISSION; } throw new AdempiereException("Unhandled commission type! ") .appendParametersToMessage() .setParameter("C_CommissionShare_ID", shareRecord.getC_Commission_Share_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\invoicecandidate\CommissionShareHandler.java
1
请完成以下Java代码
public IUnlockCommand setRecordByTableRecordId(final int tableId, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableId, recordId); return this; } @Override public IUnlockCommand setRecordByTableRecordId(final String tableName, final int recordId) { _recordsToUnlock.setRecordByTableRecordId(tableName, recordId); return this; } @Override public IUnlockCommand setRecordsBySelection(final Class<?> modelClass, final PInstanceId adPIstanceId) { _recordsToUnlock.setRecordsBySelection(modelClass, adPIstanceId); return this; } @Override public final AdTableId getSelectionToUnlock_AD_Table_ID()
{ return _recordsToUnlock.getSelection_AD_Table_ID(); } @Override public final PInstanceId getSelectionToUnlock_AD_PInstance_ID() { return _recordsToUnlock.getSelection_PInstanceId(); } @Override public final Iterator<TableRecordReference> getRecordsToUnlockIterator() { return _recordsToUnlock.getRecordsIterator(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\UnlockCommand.java
1
请完成以下Java代码
public void setCookieName(String cookieName) { Assert.hasLength(cookieName, "cookieName can't be null"); this.cookieName = cookieName; } /** * Sets the parameter name * @param parameterName The parameter name */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName can't be null"); this.parameterName = parameterName; } /** * Sets the header name * @param headerName The header name */ public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName can't be null"); this.headerName = headerName; } /** * Sets the cookie path * @param cookiePath The cookie path */ public void setCookiePath(String cookiePath) { this.cookiePath = cookiePath;
} private CsrfToken createCsrfToken() { return createCsrfToken(createNewToken()); } private CsrfToken createCsrfToken(String tokenValue) { return new DefaultCsrfToken(this.headerName, this.parameterName, tokenValue); } private String createNewToken() { return UUID.randomUUID().toString(); } private String getRequestContext(ServerHttpRequest request) { String contextPath = request.getPath().contextPath().value(); return StringUtils.hasLength(contextPath) ? contextPath : "/"; } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\CookieServerCsrfTokenRepository.java
1
请完成以下Java代码
public class VariableNameDto { protected String name; protected boolean local; public VariableNameDto() { } public VariableNameDto(String name) { this.name = name; this.local = false; } public VariableNameDto(String name, boolean local) { this.name = name; this.local = local; }
public String getName() { return name; } public void setName(String name) { this.name = name; } public boolean isLocal() { return local; } public void setLocal(boolean local) { this.local = local; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\VariableNameDto.java
1
请完成以下Java代码
private Map<Integer, InvoiceCandidateInfo> createCheckInfo(@NonNull final Iterable<I_C_Invoice_Candidate> candidates) { final ICNetAmtToInvoiceChecker totalNetAmtToInvoiceChecker = new ICNetAmtToInvoiceChecker() .setNetAmtToInvoiceExpected(totalNetAmtToInvoiceChecksum); final Map<Integer, InvoiceCandidateInfo> invoiceCandidateId2info = new HashMap<>(); for (final I_C_Invoice_Candidate ic : candidates) { final InvoiceCandidateInfo icInfo = new InvoiceCandidateInfo(ic); invoiceCandidateId2info.put(icInfo.getC_Invoice_Candidate_ID(), icInfo); totalNetAmtToInvoiceChecker.add(ic); } totalNetAmtToInvoiceChecker.assertExpectedNetAmtToInvoiceIfSet(); return invoiceCandidateId2info; } /** * POJO containing the informations which are relevant for change tracking. */ private static final class InvoiceCandidateInfo { private final int invoiceCandidateId; private final BigDecimal netAmtToInvoice; private final int taxId; public InvoiceCandidateInfo(@NonNull final I_C_Invoice_Candidate ic) { this.invoiceCandidateId = ic.getC_Invoice_Candidate_ID(); this.netAmtToInvoice = ic.getNetAmtToInvoice(); final int taxId = ic.getC_Tax_ID(); this.taxId = taxId <= 0 ? -1 : taxId; } @Override public String toString() { return invoiceCandidateId + ": " + "@NetAmtToInvoice@: " + netAmtToInvoice + ", @C_Tax_ID@: " + taxId; } /** * Compares this invoice candidate info (old version) object with given info (new version) and logs if there are any differences. * * @return <code>true</code> if the objects are equal. */ public boolean checkEquals(final InvoiceCandidateInfo infoAfterChange) { final InvoiceCandidateInfo infoBeforeChange = this; Check.assume(infoAfterChange.getC_Invoice_Candidate_ID() == infoBeforeChange.getC_Invoice_Candidate_ID(), "Old info {} and New info {} shall share the same C_Invoice_Candidate_ID", infoBeforeChange, infoAfterChange); boolean hasChanges = false; final TokenizedStringBuilder changesInfo = new TokenizedStringBuilder(", "); if (infoAfterChange.getLineNetAmt().compareTo(infoBeforeChange.getLineNetAmt()) != 0) { changesInfo.append("@LineNetAmt@: " + infoBeforeChange.getLineNetAmt() + "->" + infoAfterChange.getLineNetAmt()); hasChanges = true; } if (infoAfterChange.getC_Tax_ID() != infoBeforeChange.getC_Tax_ID())
{ changesInfo.append("@C_Tax_ID@: " + infoBeforeChange.getC_Tax_ID() + "->" + infoAfterChange.getC_Tax_ID()); hasChanges = true; } if (hasChanges) { Loggables.addLog(infoAfterChange.getC_Invoice_Candidate_ID() + ": " + changesInfo); } return !hasChanges; } public int getC_Invoice_Candidate_ID() { return invoiceCandidateId; } public BigDecimal getLineNetAmt() { return netAmtToInvoice; } public int getC_Tax_ID() { return taxId; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidatesChangesChecker.java
1
请在Spring Boot框架中完成以下Java代码
public void setWeight(UnitType value) { this.weight = value; } /** * The number of boxes where the products of the given list line item are stored in. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getBoxes() { return boxes; } /** * Sets the value of the boxes property. * * @param value * allowed object is * {@link BigInteger } * */ public void setBoxes(BigInteger value) { this.boxes = value; } /** * The color of the product of the given list line item. * * @return * possible object is * {@link String } * */ public String getColor() { return color; } /** * Sets the value of the color property. * * @param value * allowed object is * {@link String } * */ public void setColor(String value) { this.color = value; } /** * Gets the value of the countryOfOrigin 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 countryOfOrigin property. * * <p> * For example, to add a new item, do as follows: * <pre> * getCountryOfOrigin().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CountryType } * * */ public List<CountryType> getCountryOfOrigin() { if (countryOfOrigin == null) { countryOfOrigin = new ArrayList<CountryType>();
} return this.countryOfOrigin; } /** * Gets the value of the confirmedCountryOfOrigin 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 confirmedCountryOfOrigin property. * * <p> * For example, to add a new item, do as follows: * <pre> * getConfirmedCountryOfOrigin().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link CountryType } * * */ public List<CountryType> getConfirmedCountryOfOrigin() { if (confirmedCountryOfOrigin == null) { confirmedCountryOfOrigin = new ArrayList<CountryType>(); } return this.confirmedCountryOfOrigin; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\AdditionalInformationType.java
2
请完成以下Java代码
public static final class SessionDescriptor { private final String id; private final Set<String> attributeNames; private final Instant creationTime; private final Instant lastAccessedTime; private final long maxInactiveInterval; private final boolean expired; SessionDescriptor(Session session) { this.id = session.getId(); this.attributeNames = session.getAttributeNames(); this.creationTime = session.getCreationTime(); this.lastAccessedTime = session.getLastAccessedTime(); this.maxInactiveInterval = session.getMaxInactiveInterval().getSeconds(); this.expired = session.isExpired(); } public String getId() { return this.id; } public Set<String> getAttributeNames() { return this.attributeNames;
} public Instant getCreationTime() { return this.creationTime; } public Instant getLastAccessedTime() { return this.lastAccessedTime; } public long getMaxInactiveInterval() { return this.maxInactiveInterval; } public boolean isExpired() { return this.expired; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\actuate\endpoint\SessionsDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
protected void configureSpringEngine(SpringEngineConfiguration engineConfiguration, PlatformTransactionManager transactionManager) { engineConfiguration.setTransactionManager(transactionManager); } /** * Get the Object provided by the {@code availableProvider}, otherwise get a unique object from {@code uniqueProvider}. * This can be used when we allow users to provide specific implementations per engine. For example to provide a specific * {@link org.springframework.core.task.TaskExecutor} and / or {@link org.flowable.spring.job.service.SpringRejectedJobsHandler} for the CMMN Async * Executor. Example: * <pre><code> * &#064;Configuration * public class MyCustomConfiguration { * * &#064;Bean * &#064;Cmmn * public TaskExecutor cmmnTaskExecutor() { * return new MyCustomTaskExecutor() * } * * &#064;@Bean * &#064;Primary * public TaskExecutor primaryTaskExecutor() { * return new SimpleAsyncTaskExecutor() * } * * } * </code></pre> * Then when using: * <pre><code> * &#064;Configuration * public class FlowableJobConfiguration { * * public SpringAsyncExecutor cmmnAsyncExecutor( * ObjectProvider&lt;TaskExecutor&gt; taskExecutor, * &#064;Cmmn ObjectProvider&lt;TaskExecutor&gt; cmmnTaskExecutor * ) { * TaskExecutor executor = getIfAvailable( * cmmnTaskExecutor, * taskExecutor * ); * // executor is an instance of MyCustomTaskExecutor
* } * * public SpringAsyncExecutor processAsyncExecutor( * ObjectProvider&lt;TaskExecutor&gt; taskExecutor, * &#064;Process ObjectProvider&lt;TaskExecutor&gt; processTaskExecutor * ) { * TaskExecutor executor = getIfAvailable( * processTaskExecutor, * taskExecutor * ); * // executor is an instance of SimpleAsyncTaskExecutor * } * } * </code></pre> * * @param availableProvider * a provider that can provide an available object * @param uniqueProvider * a provider that would be used if there is no available object, but only if it is unique * @param <T> * the type of the object being provided * @return the available object from {@code availableProvider} if there, otherwise the unique object from {@code uniqueProvider} */ protected <T> T getIfAvailable(ObjectProvider<T> availableProvider, ObjectProvider<T> uniqueProvider) { return availableProvider.getIfAvailable(uniqueProvider::getIfUnique); } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\AbstractSpringEngineAutoConfiguration.java
2
请完成以下Java代码
public Collection<InputDecisionParameter> getInputs() { return inputCollection.get(this); } public Collection<OutputDecisionParameter> getOutputs() { return outputCollection.get(this); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Decision.class, CMMN_ELEMENT_DECISION) .extendsType(CmmnElement.class) .namespaceUri(CMMN11_NS) .instanceProvider(new ModelTypeInstanceProvider<Decision>() { public Decision newInstance(ModelTypeInstanceContext instanceContext) { return new DecisionImpl(instanceContext); } });
nameAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_NAME) .build(); implementationTypeAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_IMPLEMENTATION_TYPE) .defaultValue("http://www.omg.org/spec/CMMN/DecisionType/Unspecified") .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); inputCollection = sequenceBuilder.elementCollection(InputDecisionParameter.class) .build(); outputCollection = sequenceBuilder.elementCollection(OutputDecisionParameter.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\DecisionImpl.java
1
请完成以下Java代码
protected AcquiredJobs acquireJobs( JobAcquisitionContext context, JobAcquisitionStrategy acquisitionStrategy, ProcessEngineImpl currentProcessEngine) { CommandExecutor commandExecutor = currentProcessEngine.getProcessEngineConfiguration() .getCommandExecutorTxRequired(); int numJobsToAcquire = acquisitionStrategy.getNumJobsToAcquire(currentProcessEngine.getName()); LOG.jobsToAcquire(currentProcessEngine.getName(), numJobsToAcquire); AcquiredJobs acquiredJobs = null; if (numJobsToAcquire > 0) { jobExecutor.logAcquisitionAttempt(currentProcessEngine); acquiredJobs = commandExecutor.execute(jobExecutor.getAcquireJobsCmd(numJobsToAcquire)); } else {
acquiredJobs = new AcquiredJobs(numJobsToAcquire); } context.submitAcquiredJobs(currentProcessEngine.getName(), acquiredJobs); jobExecutor.logAcquiredJobs(currentProcessEngine, acquiredJobs.size()); jobExecutor.logAcquisitionFailureJobs(currentProcessEngine, acquiredJobs.getNumberOfJobsFailedToLock()); LOG.acquiredJobs(currentProcessEngine.getName(), acquiredJobs); LOG.failedAcquisitionLocks(currentProcessEngine.getName(), acquiredJobs); return acquiredJobs; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\SequentialJobAcquisitionRunnable.java
1
请完成以下Java代码
public ExpressionEvaluationException addExpression(final IExpression<?> expression) { if (expression == null) { return this; } expressions.add(expression); resetMessageBuilt(); return this; } public ExpressionEvaluationException setPartialEvaluatedExpression(final String partialEvaluatedExpression) { this.partialEvaluatedExpression = partialEvaluatedExpression; resetMessageBuilt(); return this; } @Override protected ITranslatableString buildMessage() { final TranslatableStringBuilder message = TranslatableStrings.builder(); final ITranslatableString originalMessage = getOriginalMessage(); if (!TranslatableStrings.isBlank(originalMessage)) { message.append(originalMessage); } else { message.append("Unknown evaluation error");
} if (!expressions.isEmpty()) { message.append("\nExpressions trace:"); for (final IExpression<?> expression : expressions) { message.append("\n * ").appendObj(expression); } } if (!Check.isEmpty(partialEvaluatedExpression)) { message.append("\nPartial evaluated expression: ").append(partialEvaluatedExpression); } return message.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\exceptions\ExpressionEvaluationException.java
1
请完成以下Java代码
public String getGroupNameAttribute() { return groupNameAttribute; } public void setGroupNameAttribute(String groupNameAttribute) { this.groupNameAttribute = groupNameAttribute; } public String getGroupNameDelimiter() { return groupNameDelimiter; } public void setGroupNameDelimiter(String groupNameDelimiter) { this.groupNameDelimiter = groupNameDelimiter; } }
public OAuth2SSOLogoutProperties getSsoLogout() { return ssoLogout; } public void setSsoLogout(OAuth2SSOLogoutProperties ssoLogout) { this.ssoLogout = ssoLogout; } public OAuth2IdentityProviderProperties getIdentityProvider() { return identityProvider; } public void setIdentityProvider(OAuth2IdentityProviderProperties identityProvider) { this.identityProvider = identityProvider; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-security\src\main\java\org\camunda\bpm\spring\boot\starter\security\oauth2\OAuth2Properties.java
1
请完成以下Java代码
private static UserGroupUserAssignment toUserGroupUserAssignment(final I_AD_UserGroup_User_Assign record) { return UserGroupUserAssignment.builder() .userId(UserId.ofRepoId(record.getAD_User_ID())) .userGroupId(UserGroupId.ofRepoId(record.getAD_UserGroup_ID())) .validDates(extractValidDates(record)) .build(); } private static Range<Instant> extractValidDates(final I_AD_UserGroup_User_Assign record) { final Instant validFrom = TimeUtil.asInstant(record.getValidFrom()); final Instant validTo = TimeUtil.asInstant(record.getValidTo()); if (validFrom == null) { if (validTo == null) { return Range.all(); }
else { return Range.atMost(validTo); } } else { if (validTo == null) { return Range.atLeast(validFrom); } else { return Range.closed(validFrom, validTo); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserGroupRepository.java
1
请完成以下Java代码
public @Nullable List<String> getDataLocations() { return this.dataLocations; } /** * Sets the locations of data (DML) scripts to apply to the database. By default, * initialization will fail if a location does not exist. To prevent a failure, a * location can be made optional by prefixing it with {@code optional:}. * @param dataLocations locations of the data scripts */ public void setDataLocations(@Nullable List<String> dataLocations) { this.dataLocations = dataLocations; } /** * Returns whether to continue when an error occurs while applying a schema or data * script. * @return whether to continue on error */ public boolean isContinueOnError() { return this.continueOnError; } /** * Sets whether initialization should continue when an error occurs when applying a * schema or data script. * @param continueOnError whether to continue when an error occurs. */ public void setContinueOnError(boolean continueOnError) { this.continueOnError = continueOnError; } /** * Returns the statement separator used in the schema and data scripts. * @return the statement separator */ public String getSeparator() { return this.separator; } /** * Sets the statement separator to use when reading the schema and data scripts. * @param separator statement separator used in the schema and data scripts
*/ public void setSeparator(String separator) { this.separator = separator; } /** * Returns the encoding to use when reading the schema and data scripts. * @return the script encoding */ public @Nullable Charset getEncoding() { return this.encoding; } /** * Sets the encoding to use when reading the schema and data scripts. * @param encoding encoding to use when reading the schema and data scripts */ public void setEncoding(@Nullable Charset encoding) { this.encoding = encoding; } /** * Gets the mode to use when determining whether database initialization should be * performed. * @return the initialization mode * @since 2.5.1 */ public DatabaseInitializationMode getMode() { return this.mode; } /** * Sets the mode the use when determining whether database initialization should be * performed. * @param mode the initialization mode * @since 2.5.1 */ public void setMode(DatabaseInitializationMode mode) { this.mode = mode; } }
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\DatabaseInitializationSettings.java
1
请完成以下Java代码
public void setBatchId(String batchId) { this.batchId = batchId; } @CamundaQueryParam("type") public void setType(String type) { this.type = type; } @CamundaQueryParam(value = "tenantIdIn", converter = StringListConverter.class) public void setTenantIdIn(List<String> tenantIds) { this.tenantIds = tenantIds; } @CamundaQueryParam(value = "withoutTenantId", converter = BooleanConverter.class) public void setWithoutTenantId(Boolean withoutTenantId) { this.withoutTenantId = withoutTenantId; } @CamundaQueryParam(value="suspended", converter = BooleanConverter.class) public void setSuspended(Boolean suspended) { this.suspended = suspended; } protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } protected BatchQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchQuery(); }
protected void applyFilters(BatchQuery query) { if (batchId != null) { query.batchId(batchId); } if (type != null) { query.type(type); } if (TRUE.equals(withoutTenantId)) { query.withoutTenantId(); } if (tenantIds != null && !tenantIds.isEmpty()) { query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()])); } if (TRUE.equals(suspended)) { query.suspended(); } if (FALSE.equals(suspended)) { query.active(); } } protected void applySortBy(BatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) { query.orderById(); } else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) { query.orderByTenantId(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchQueryDto.java
1
请在Spring Boot框架中完成以下Java代码
public class MaterialNeedsPlannerRow { @Nullable WarehouseId warehouseId; @NonNull ProductId productId; @NonNull BigDecimal levelMin; @NonNull BigDecimal levelMax; @NonNull public static MaterialNeedsPlannerRow ofViewRow(@NonNull final IViewRow row) { return MaterialNeedsPlannerRow.builder() .warehouseId(row.getFieldValueAsNullableRepoId(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Warehouse_ID, WarehouseId::ofRepoIdOrNull)) .productId(row.getFieldValueAsRepoId(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Product_ID, ProductId::ofRepoId)) .levelMin(row.getFieldValueAsBigDecimal(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Min, BigDecimal.ZERO)) .levelMax(row.getFieldValueAsBigDecimal(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Max, BigDecimal.ZERO)) .build(); } @NonNull public static MaterialNeedsPlannerRow ofDocument(@NonNull final Document document) { final ProductId productId = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Product_ID).getValueAsId(ProductId.class) .orElseThrow(() -> new FillMandatoryException(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Product_ID)); final WarehouseId warehouseId = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Warehouse_ID).getValueAsId(WarehouseId.class) .orElse(null); final BigDecimal levelMin = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Min).getValueAsBigDecimal().orElse(BigDecimal.ZERO); final BigDecimal levelMax = document.getFieldView(I_M_Material_Needs_Planner_V.COLUMNNAME_Level_Max).getValueAsBigDecimal().orElse(BigDecimal.ZERO); return MaterialNeedsPlannerRow.builder() .warehouseId(warehouseId) .productId(productId) .levelMin(levelMin) .levelMax(levelMax) .build(); } public boolean isDemandFilled() { if (getWarehouseId() == null) { return false;
} return getLevelMin().compareTo(BigDecimal.ZERO) > 0; } public ReplenishInfo toReplenishInfo() { if (warehouseId == null) { throw new FillMandatoryException(I_M_Material_Needs_Planner_V.COLUMNNAME_M_Warehouse_ID); } return ReplenishInfo.builder() .identifier(ReplenishInfo.Identifier.builder() .productId(productId) .warehouseId(warehouseId) .build()) .min(StockQtyAndUOMQtys.ofQtyInStockUOM(levelMin, productId)) .max(StockQtyAndUOMQtys.ofQtyInStockUOM(levelMax, productId)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\MaterialNeedsPlannerRow.java
2
请完成以下Java代码
public CmmnRuntimeService getCmmnRuntimeService() { return cmmnRuntimeService; } public void setCmmnRuntimeService(CmmnRuntimeService cmmnRuntimeService) { this.cmmnRuntimeService = cmmnRuntimeService; } @Override public DynamicCmmnService getDynamicCmmnService() { return dynamicCmmnService; } public void setDynamicCmmnService(DynamicCmmnService dynamicCmmnService) { this.dynamicCmmnService = dynamicCmmnService; } @Override public CmmnTaskService getCmmnTaskService() { return cmmnTaskService; } public void setCmmnTaskService(CmmnTaskService cmmnTaskService) { this.cmmnTaskService = cmmnTaskService; } @Override public CmmnManagementService getCmmnManagementService() { return cmmnManagementService; } public void setCmmnManagementService(CmmnManagementService cmmnManagementService) { this.cmmnManagementService = cmmnManagementService; }
@Override public CmmnRepositoryService getCmmnRepositoryService() { return cmmnRepositoryService; } public void setCmmnRepositoryService(CmmnRepositoryService cmmnRepositoryService) { this.cmmnRepositoryService = cmmnRepositoryService; } @Override public CmmnHistoryService getCmmnHistoryService() { return cmmnHistoryService; } public void setCmmnHistoryService(CmmnHistoryService cmmnHistoryService) { this.cmmnHistoryService = cmmnHistoryService; } @Override public CmmnMigrationService getCmmnMigrationService() { return cmmnMigrationService; } public void setCmmnMigrationService(CmmnMigrationService cmmnMigrationService) { this.cmmnMigrationService = cmmnMigrationService; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnEngineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public void registerAuthor() { Author a1 = new Author(); a1.setName("Quartis Young"); a1.setGenre("Anthology"); a1.setAge(34); Author a2 = new Author(); a2.setName("Mark Janel"); a2.setGenre("Anthology"); a2.setAge(23); Book b1 = new Book(); b1.setIsbn("001"); b1.setTitle("The Beatles Anthology"); Book b2 = new Book(); b2.setIsbn("002"); b2.setTitle("A People's Anthology"); Book b3 = new Book(); b3.setIsbn("003"); b3.setTitle("Anthology Myths"); a1.addBook(b1); a1.addBook(b2); a2.addBook(b3); authorRepository.save(a1);
authorRepository.save(a2); } @Transactional public void updateAuthor() { Author author = authorRepository.findByName("Mark Janel"); author.setAge(45); } @Transactional public void updateBooks() { Author author = authorRepository.findByName("Quartis Young"); List<Book> books = author.getBooks(); for (Book book : books) { book.setIsbn("not available"); } } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootAudit\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable() { if (getSelectedRowIds().size() <= 0) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } if (!externalSystemConfigRepo.isAnyConfigActive(getExternalSystemType())) { return ProcessPreconditionsResolution.reject(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() throws Exception { addLog("Calling with params: externalSystemChildConfigId: {}", getExternalSystemChildConfigId()); final Set<I_M_HU> hus = getHUsToExport(); final IExternalSystemChildConfigId externalSystemChildConfigId = getExternalSystemChildConfigId(); for (final I_M_HU hu : hus) { final TableRecordReference topLevelHURecordRef = TableRecordReference.of(hu);
getExportToHUExternalSystem().exportToExternalSystem(externalSystemChildConfigId, topLevelHURecordRef, getPinstanceId()); } return JavaProcess.MSG_OK; } protected abstract Set<I_M_HU> getHUsToExport(); protected abstract IExternalSystemChildConfigId getExternalSystemChildConfigId(); protected abstract ExportHUToExternalSystemService getExportToHUExternalSystem(); protected abstract ExternalSystemType getExternalSystemType(); protected abstract String getExternalSystemParam(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\M_HU_SyncTo_ExternalSystem.java
1
请完成以下Java代码
public void setHostname(String hostname) { this.hostname = hostname; } public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public Integer getPort() { return port; } public void setPort(Integer port) { this.port = port; } public MachineInfo toMachineInfo() { MachineInfo machineInfo = new MachineInfo(); machineInfo.setApp(app); machineInfo.setHostname(hostname); machineInfo.setIp(ip); machineInfo.setPort(port); machineInfo.setLastHeartbeat(timestamp.getTime()); machineInfo.setHeartbeatVersion(timestamp.getTime());
return machineInfo; } @Override public String toString() { return "MachineEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", ip='" + ip + '\'' + ", hostname='" + hostname + '\'' + ", timestamp=" + timestamp + ", port=" + port + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\MachineEntity.java
1
请完成以下Java代码
private PaySelectionLinesToUpdate getPaySelectionLinesToUpdate() { return _paySelectionLinesToUpdate.get(); } private PaySelectionLinesToUpdate retrievePaySelectionLinesToUpdate() { if (paySelectionLineIdsToUpdate.isEmpty()) { return new PaySelectionLinesToUpdate(ImmutableList.of()); } final List<I_C_PaySelectionLine> lines = queryBL.createQueryBuilder(I_C_PaySelectionLine.class) .addEqualsFilter(I_C_PaySelectionLine.COLUMNNAME_C_PaySelection_ID, getPaySelectionId()) .addInArrayFilter(I_C_PaySelectionLine.COLUMNNAME_C_PaySelectionLine_ID, paySelectionLineIdsToUpdate) .create() .list(); return new PaySelectionLinesToUpdate(lines); } // // // private static class PaySelectionLinesToUpdate { private final HashMap<InvoiceId, I_C_PaySelectionLine> byInvoiceId = new HashMap<>(); private final HashMap<OrderPayScheduleId, I_C_PaySelectionLine> byOrderPaySchedId = new HashMap<>(); PaySelectionLinesToUpdate(final List<I_C_PaySelectionLine> lines) { for (final I_C_PaySelectionLine line : lines) { final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(line.getC_Invoice_ID()); final OrderPayScheduleId orderPaySchedId = OrderPayScheduleId.ofRepoIdOrNull(line.getC_OrderPaySchedule_ID()); if (invoiceId != null) { final I_C_PaySelectionLine paySelectionLineOld = byInvoiceId.put(invoiceId, line); Check.assumeNull(paySelectionLineOld, "Only one pay selection line shall exist for an invoice but we found: {}, {}", line, paySelectionLineOld); // shall not happen
} else if (orderPaySchedId != null) { final I_C_PaySelectionLine old = byOrderPaySchedId.put(orderPaySchedId, line); Check.assumeNull(old, "Duplicate pay selection line for orderpay scheduele: {}, {}", line, old); } } } private Optional<I_C_PaySelectionLine> dequeueFor(@NonNull final PaySelectionLineCandidate candidate) { if (candidate.getInvoiceId() != null) { return Optional.ofNullable(byInvoiceId.remove(candidate.getInvoiceId())); } else if (candidate.getOrderPayScheduleId() != null) { return Optional.ofNullable(byOrderPaySchedId.remove(candidate.getOrderPayScheduleId())); } else { return Optional.empty(); } } private List<I_C_PaySelectionLine> dequeueAll() { final List<I_C_PaySelectionLine> result = new ArrayList<>(byInvoiceId.values()); result.addAll(byOrderPaySchedId.values()); byInvoiceId.clear(); byOrderPaySchedId.clear(); return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\PaySelectionUpdater.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleController { private final ArticleService articleService; public ArticleController(ArticleService articleService) { this.articleService = articleService; } @PostMapping public ArticleDto createArticle(@RequestBody ArticleDto dto) { var article = mapToEntity(dto); var entity = articleService.create(article); return mapToDto(entity); } @PutMapping public ArticleDto update(@RequestBody ArticleDto dto) { var updatedArticle = articleService.update(dto.id(), dto.content()); return mapToDto(updatedArticle);
} @GetMapping("{id}") public ResponseEntity<ArticleDto> readArticle(@PathVariable Long id) { var article = articleService.findById(id) .map(ArticleController::mapToDto); return ResponseEntity.of(article); } private static ArticleDto mapToDto(Article entity) { return new ArticleDto(entity.getId(), entity.getName(), entity.getContent(), entity.getSlug()); } private static Article mapToEntity(ArticleDto dto) { return new Article(dto.id(), dto.name(), dto.content(), dto.slug()); } }
repos\tutorials-master\patterns-modules\vertical-slice-architecture\src\main\java\com\baeldung\hexagonal\controller\ArticleController.java
2
请完成以下Java代码
public void setR_Project_Status_ID (final int R_Project_Status_ID) { if (R_Project_Status_ID < 1) set_Value (COLUMNNAME_R_Project_Status_ID, null); else set_Value (COLUMNNAME_R_Project_Status_ID, R_Project_Status_ID); } @Override public int getR_Project_Status_ID() { return get_ValueAsInt(COLUMNNAME_R_Project_Status_ID); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); }
@Override public void setstartdatetime (final @Nullable java.sql.Timestamp startdatetime) { set_Value (COLUMNNAME_startdatetime, startdatetime); } @Override public java.sql.Timestamp getstartdatetime() { return get_ValueAsTimestamp(COLUMNNAME_startdatetime); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project.java
1
请完成以下Java代码
private static <T> List<T> readChunkOrNull( @NonNull final PeekIterator<T> iterator, final int maxChunkSize, @Nullable final Function<T, Object> groupByKeyExtractor) { Object previousGroupKey = null; boolean isFirstItem = true; final List<T> list = new ArrayList<>(maxChunkSize); while (iterator.hasNext() && list.size() < maxChunkSize) { final T item = iterator.peek(); if(groupByKeyExtractor != null) { final Object groupKey = groupByKeyExtractor.apply(item); if (isFirstItem) { previousGroupKey = groupKey; } else if (!Objects.equals(previousGroupKey, groupKey)) { break; } } list.add(iterator.next()); isFirstItem = false; } return !list.isEmpty() ? list : null; } /** * Thanks to <a href="https://stackoverflow.com/a/27872852/1012103">https://stackoverflow.com/a/27872852/1012103</a> */ public static <T> Predicate<T> distinctByKey(@NonNull final Function<? super T, Object> keyExtractor) { final Map<Object, Boolean> seen = new ConcurrentHashMap<>(); return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null; } @SafeVarargs public static <T> Stream<T> concat(final Stream<T>... streams) {
if (streams.length == 0) { return Stream.empty(); } else if (streams.length == 1) { return streams[0]; } else if (streams.length == 2) { return Stream.concat(streams[0], streams[1]); } else { Stream<T> result = streams[0]; for (int i = 1; i < streams.length; i++) { result = Stream.concat(result, streams[i]); } return result; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StreamUtils.java
1
请完成以下Java代码
public class GetTasksPayload implements Payload { private String id; private String assigneeId; private List<String> groups; private String processInstanceId; private String parentTaskId; public GetTasksPayload() { this.id = UUID.randomUUID().toString(); } public GetTasksPayload(String assigneeId, List<String> groups, String processInstanceId, String parentTaskId) { this(); this.assigneeId = assigneeId; this.groups = groups; this.processInstanceId = processInstanceId; this.parentTaskId = parentTaskId; } @Override public String getId() { return id; } public String getAssigneeId() { return assigneeId; } public void setAssigneeId(String assigneeId) { this.assigneeId = assigneeId; } public List<String> getGroups() { return groups; }
public void setGroups(List<String> groups) { this.groups = groups; } public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public boolean isStandalone() { return getProcessInstanceId() == null; } }
repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\GetTasksPayload.java
1
请完成以下Java代码
public Saldo getAnfangsSaldo() { return anfangsSaldo; } public void setAnfangsSaldo(Saldo anfangsSaldo) { this.anfangsSaldo = anfangsSaldo; } public Saldo getSchlussSaldo() { return schlussSaldo; } public void setSchlussSaldo(Saldo schlussSaldo) { this.schlussSaldo = schlussSaldo; } public Saldo getAktuellValutenSaldo() { return aktuellValutenSaldo; }
public void setAktuellValutenSaldo(Saldo aktuellValutenSaldo) { this.aktuellValutenSaldo = aktuellValutenSaldo; } public Saldo getZukunftValutenSaldo() { return zukunftValutenSaldo; } public void setZukunftValutenSaldo(Saldo zukunftValutenSaldo) { this.zukunftValutenSaldo = zukunftValutenSaldo; } public List<BankstatementLine> getLines() { return lines; } public void setLines(List<BankstatementLine> lines) { this.lines = lines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\schaeffer\compiere\mt940\Bankstatement.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_Attachment_MultiRef_ID (final int AD_Attachment_MultiRef_ID) { if (AD_Attachment_MultiRef_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Attachment_MultiRef_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Attachment_MultiRef_ID, AD_Attachment_MultiRef_ID); } @Override public int getAD_Attachment_MultiRef_ID() { return get_ValueAsInt(COLUMNNAME_AD_Attachment_MultiRef_ID); } @Override public org.compiere.model.I_AD_AttachmentEntry getAD_AttachmentEntry() { return get_ValueAsPO(COLUMNNAME_AD_AttachmentEntry_ID, org.compiere.model.I_AD_AttachmentEntry.class); } @Override public void setAD_AttachmentEntry(final org.compiere.model.I_AD_AttachmentEntry AD_AttachmentEntry) { set_ValueFromPO(COLUMNNAME_AD_AttachmentEntry_ID, org.compiere.model.I_AD_AttachmentEntry.class, AD_AttachmentEntry); } @Override public void setAD_AttachmentEntry_ID (final int AD_AttachmentEntry_ID) { if (AD_AttachmentEntry_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, AD_AttachmentEntry_ID); } @Override public int getAD_AttachmentEntry_ID() { return get_ValueAsInt(COLUMNNAME_AD_AttachmentEntry_ID); } @Override public void setAD_Table_ID (final int AD_Table_ID) { if (AD_Table_ID < 1) set_Value (COLUMNNAME_AD_Table_ID, null);
else set_Value (COLUMNNAME_AD_Table_ID, AD_Table_ID); } @Override public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setFileName_Override (final @Nullable java.lang.String FileName_Override) { set_Value (COLUMNNAME_FileName_Override, FileName_Override); } @Override public java.lang.String getFileName_Override() { return get_ValueAsString(COLUMNNAME_FileName_Override); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Attachment_MultiRef.java
1
请完成以下Spring Boot application配置
spring.datasource.url=jdbc:mysql://localhost:3306/bookstoredb?createDatabaseIfNotExist=true spring.datasource.username=root spring.datasource.passw
ord=root spring.jpa.show-sql=true spring.jpa.open-in-view=false
repos\Hibernate-SpringBoot-master\HibernateSpringBootTablesMetadata\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the date property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getDate() {
return date; } /** * Sets the value of the date property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setDate(XMLGregorianCalendar value) { this.date = 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\ORDERSListLineItemExtensionType.java
2
请在Spring Boot框架中完成以下Java代码
static class DefaultCodecsConfiguration { @Bean DefaultCodecCustomizer defaultCodecCustomizer(HttpCodecsProperties httpCodecProperties) { return new DefaultCodecCustomizer(httpCodecProperties.isLogRequestDetails(), httpCodecProperties.getMaxInMemorySize()); } static final class DefaultCodecCustomizer implements CodecCustomizer, Ordered { private final boolean logRequestDetails; private final @Nullable DataSize maxInMemorySize; DefaultCodecCustomizer(boolean logRequestDetails, @Nullable DataSize maxInMemorySize) { this.logRequestDetails = logRequestDetails; this.maxInMemorySize = maxInMemorySize; } @Override public void customize(CodecConfigurer configurer) { PropertyMapper map = PropertyMapper.get(); CodecConfigurer.DefaultCodecs defaultCodecs = configurer.defaultCodecs(); defaultCodecs.enableLoggingRequestDetails(this.logRequestDetails); map.from(this.maxInMemorySize).asInt(DataSize::toBytes).to(defaultCodecs::maxInMemorySize); } @Override
public int getOrder() { return 0; } } } static class NoJacksonOrJackson2Preferred extends AnyNestedCondition { NoJacksonOrJackson2Preferred() { super(ConfigurationPhase.PARSE_CONFIGURATION); } @ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper") static class NoJackson { } @ConditionalOnProperty(name = "spring.http.codecs.preferred-json-mapper", havingValue = "jackson2") static class Jackson2Preferred { } } }
repos\spring-boot-4.0.1\module\spring-boot-http-codec\src\main\java\org\springframework\boot\http\codec\autoconfigure\CodecsAutoConfiguration.java
2
请完成以下Java代码
protected void initializeActivity(Case element, CmmnActivity activity, CmmnHandlerContext context) { CaseDefinitionEntity definition = (CaseDefinitionEntity) activity; Deployment deployment = context.getDeployment(); definition.setKey(element.getId()); definition.setName(element.getName()); definition.setDeploymentId(deployment.getId()); definition.setTaskDefinitions(new HashMap<>()); boolean skipEnforceTtl = !((DeploymentEntity) deployment).isNew(); validateAndSetHTTL(element, definition, skipEnforceTtl); CmmnModelInstance model = context.getModel(); Definitions definitions = model.getDefinitions(); String category = definitions.getTargetNamespace();
definition.setCategory(category); } protected void validateAndSetHTTL(Case element, CaseDefinitionEntity definition, boolean skipEnforceTtl) { String caseDefinitionKey = definition.getKey(); Integer historyTimeToLive = HistoryTimeToLiveParser.create().parse(element, caseDefinitionKey, skipEnforceTtl); definition.setHistoryTimeToLive(historyTimeToLive); } protected CaseDefinitionEntity createActivity(CmmnElement element, CmmnHandlerContext context) { CaseDefinitionEntity definition = new CaseDefinitionEntity(); definition.setCmmnElement(element); return definition; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CaseHandler.java
1
请在Spring Boot框架中完成以下Java代码
protected RedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } protected RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; } @Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() {
return this.sessionRepositoryCustomizers; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected RedisTemplate<String, Object> createRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); if (getDefaultRedisSerializer() != null) { redisTemplate.setDefaultSerializer(getDefaultRedisSerializer()); } redisTemplate.setConnectionFactory(getRedisConnectionFactory()); redisTemplate.setBeanClassLoader(this.classLoader); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
2
请完成以下Java代码
public class ContactDetails2CH { @XmlElement(name = "Nm") protected String nm; @XmlElement(name = "Othr") protected String othr; /** * 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 othr property. * * @return * possible object is * {@link String } * */ public String getOthr() { return othr; } /** * Sets the value of the othr property. * * @param value * allowed object is * {@link String } * */ public void setOthr(String value) { this.othr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ContactDetails2CH.java
1
请在Spring Boot框架中完成以下Java代码
public class DistributedSystemIdConfiguration extends AbstractAnnotationConfigSupport implements ImportAware { private static final String GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY = "distributed-system-id"; private Integer distributedSystemId; private final Logger logger = LoggerFactory.getLogger(getClass()); @Override protected Class<? extends Annotation> getAnnotationType() { return UseDistributedSystemId.class; } @Override @SuppressWarnings("all") public void setImportMetadata(AnnotationMetadata importMetadata) { if (isAnnotationPresent(importMetadata)) { AnnotationAttributes distributedSystemIdAttributes = getAnnotationAttributes(importMetadata); setDistributedSystemId(distributedSystemIdAttributes.containsKey("value") ? distributedSystemIdAttributes.getNumber("value") : null); setDistributedSystemId(distributedSystemIdAttributes.containsKey("id") ? distributedSystemIdAttributes.getNumber("id") : null); } } protected void setDistributedSystemId(Integer distributedSystemId) { this.distributedSystemId = Optional.ofNullable(distributedSystemId) .filter(id -> id > -1) .orElse(this.distributedSystemId); } protected Optional<Integer> getDistributedSystemId() { return Optional.ofNullable(this.distributedSystemId) .filter(id -> id > -1); } protected Logger getLogger() { return this.logger; }
private int validateDistributedSystemId(int distributedSystemId) { Assert.isTrue(distributedSystemId >= -1 && distributedSystemId < 256, String.format("Distributed System ID [%d] must be between -1 and 255", distributedSystemId)); return distributedSystemId; } @Bean ClientCacheConfigurer clientCacheDistributedSystemIdConfigurer() { return (beanName, clientCacheFactoryBean) -> getDistributedSystemId().ifPresent(distributedSystemId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Distributed System Id [{}] was set on the ClientCache instance, which will not have any effect", distributedSystemId); } }); } @Bean PeerCacheConfigurer peerCacheDistributedSystemIdConfigurer() { return (beanName, cacheFactoryBean) -> getDistributedSystemId().ifPresent(id -> cacheFactoryBean.getProperties() .setProperty(GEMFIRE_DISTRIBUTED_SYSTEM_ID_PROPERTY, String.valueOf(validateDistributedSystemId(id)))); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DistributedSystemIdConfiguration.java
2
请完成以下Java代码
public void setCurrency(String value) { this.currency = value; } /** * Gets the value of the amount property. * * @return * possible object is * {@link String } * */ public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link String } * */ public void setAmount(BigDecimal value) { this.amount = value; } /** * Gets the value of the amountReminder property. * * @return * possible object is * {@link String } * */ public BigDecimal getAmountReminder() { if (amountReminder == null) { return new Adapter1().unmarshal("0"); } else { return amountReminder; } } /** * Sets the value of the amountReminder property. * * @param value * allowed object is * {@link String } * */ public void setAmountReminder(BigDecimal value) { this.amountReminder = value; } /** * Gets the value of the amountPrepaid property. * * @return * possible object is * {@link String } * */ public BigDecimal getAmountPrepaid() { if (amountPrepaid == null) { return new Adapter1().unmarshal("0"); } else { return amountPrepaid; } } /** * Sets the value of the amountPrepaid property. * * @param value * allowed object is
* {@link String } * */ public void setAmountPrepaid(BigDecimal value) { this.amountPrepaid = value; } /** * Gets the value of the amountDue property. * * @return * possible object is * {@link String } * */ public BigDecimal getAmountDue() { return amountDue; } /** * Sets the value of the amountDue property. * * @param value * allowed object is * {@link String } * */ public void setAmountDue(BigDecimal value) { this.amountDue = value; } /** * Gets the value of the amountObligations property. * * @return * possible object is * {@link String } * */ public BigDecimal getAmountObligations() { if (amountObligations == null) { return new Adapter1().unmarshal("0"); } else { return amountObligations; } } /** * Sets the value of the amountObligations property. * * @param value * allowed object is * {@link String } * */ public void setAmountObligations(BigDecimal value) { this.amountObligations = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\BalanceType.java
1
请完成以下Java代码
public void setW_Basket_ID (int W_Basket_ID) { if (W_Basket_ID < 1) set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null); else set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID)); } /** Get W_Basket_ID. @return Web Basket */ public int getW_Basket_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Basket Line. @param W_BasketLine_ID Web Basket Line */
public void setW_BasketLine_ID (int W_BasketLine_ID) { if (W_BasketLine_ID < 1) set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, null); else set_ValueNoCheck (COLUMNNAME_W_BasketLine_ID, Integer.valueOf(W_BasketLine_ID)); } /** Get Basket Line. @return Web Basket Line */ public int getW_BasketLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_W_BasketLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_BasketLine.java
1
请完成以下Java代码
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Collection<?> recordIds) { final InArrayQueryFilter<?> builder = new InArrayQueryFilter<>(columnName, recordIds) .setEmbedSqlParams(false); final SqlAndParams sqlAndParams = SqlAndParams.of(builder.getSql(), builder.getSqlParams(Env.getCtx())); return new RecordsToAlwaysIncludeSql(sqlAndParams); } public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Object... recordIds) { return ofColumnNameAndRecordIds(columnName, Arrays.asList(recordIds)); } @Nullable public static RecordsToAlwaysIncludeSql mergeOrNull(@Nullable final Collection<RecordsToAlwaysIncludeSql> collection) { if (collection == null || collection.isEmpty()) { return null; } else if (collection.size() == 1) { return collection.iterator().next(); } else { return SqlAndParams.orNullables(
collection.stream() .filter(Objects::nonNull) .map(RecordsToAlwaysIncludeSql::toSqlAndParams) .collect(ImmutableSet.toImmutableSet())) .map(RecordsToAlwaysIncludeSql::new) .orElse(null); } } public SqlAndParams toSqlAndParams() { return sqlAndParams; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\FilterSql.java
1
请完成以下Java代码
public void changeJsonEngineConfiguration( @RequestParam(value = "failOnUnknownProperties", required = false) final Boolean failOnUnknownProperties) { if (failOnUnknownProperties != null) { sharedJsonObjectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, failOnUnknownProperties); } } @GetMapping("/conext") public Map<String, String> getContext() { userSession.assertLoggedIn(); final LinkedHashMap<String, String> map = new LinkedHashMap<>(); final Properties ctx = Env.getCtx(); final ArrayList<String> keys = new ArrayList<>(ctx.stringPropertyNames()); Collections.sort(keys); for (final String key : keys) { final String value = ctx.getProperty(key); map.put(key, value); } return map; } @GetMapping("/stressTest/massCacheInvalidation") public void stressTest_massCacheInvalidation( @RequestParam(name = "tableName") @NonNull final String tableName, @RequestParam(name = "eventsCount", defaultValue = "1000") final int eventsCount, @RequestParam(name = "batchSize", defaultValue = "10") final int batchSize) { userSession.assertLoggedIn(); Check.assumeGreaterThanZero(eventsCount, "eventsCount"); Check.assumeGreaterThanZero(batchSize, "batchSize"); final CacheMgt cacheMgt = CacheMgt.get(); final int tableSize = DB.getSQLValueEx(ITrx.TRXNAME_None, "SELECT COUNT(1) FROM " + tableName); if (tableSize <= 0) { throw new AdempiereException("Table " + tableName + " is empty"); } if (tableSize < batchSize) { throw new AdempiereException("Table size(" + tableSize + ") shall be bigger than batch size(" + batchSize + ")"); } int countEventsGenerated = 0; final ArrayList<CacheInvalidateRequest> buffer = new ArrayList<>(batchSize); while (countEventsGenerated <= eventsCount) { PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement("SELECT " + tableName + "_ID FROM " + tableName + " ORDER BY " + tableName + "_ID", ITrx.TRXNAME_None);
rs = pstmt.executeQuery(); while (rs.next()) { if (buffer.size() >= batchSize) { final Stopwatch stopwatch = Stopwatch.createStarted(); cacheMgt.reset(CacheInvalidateMultiRequest.of(buffer)); stopwatch.stop(); // logger.info("Sent a CacheInvalidateMultiRequest of {} events. So far we sent {} of {}. It took {}.", // buffer.size(), countEventsGenerated, eventsCount, stopwatch); buffer.clear(); } final int recordId = rs.getInt(1); buffer.add(CacheInvalidateRequest.rootRecord(tableName, recordId)); countEventsGenerated++; } } catch (final SQLException ex) { throw new DBException(ex); } finally { DB.close(rs, pstmt); } } if (buffer.size() >= batchSize) { cacheMgt.reset(CacheInvalidateMultiRequest.of(buffer)); buffer.clear(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\debug\DebugRestController.java
1
请完成以下Java代码
public class SynchronizedHashMapWithRWLock { private static Map<String, String> syncHashMap = new HashMap<>(); private Logger logger = LoggerFactory.getLogger(SynchronizedHashMapWithRWLock.class); private final ReadWriteLock lock = new ReentrantReadWriteLock(); private final Lock readLock = lock.readLock(); private final Lock writeLock = lock.writeLock(); public void put(String key, String value) throws InterruptedException { try { writeLock.lock(); logger.info(Thread.currentThread().getName() + " writing"); syncHashMap.put(key, value); sleep(1000); } finally { writeLock.unlock(); } } public String get(String key) { try { readLock.lock(); logger.info(Thread.currentThread().getName() + " reading"); return syncHashMap.get(key); } finally { readLock.unlock(); } } public String remove(String key) { try { writeLock.lock(); return syncHashMap.remove(key); } finally { writeLock.unlock(); } } public boolean containsKey(String key) { try { readLock.lock(); return syncHashMap.containsKey(key); } finally { readLock.unlock(); } } boolean isReadLockAvailable() { return readLock.tryLock(); } public static void main(String[] args) throws InterruptedException { final int threadCount = 3; final ExecutorService service = Executors.newFixedThreadPool(threadCount); SynchronizedHashMapWithRWLock object = new SynchronizedHashMapWithRWLock(); service.execute(new Thread(new Writer(object), "Writer")); service.execute(new Thread(new Reader(object), "Reader1")); service.execute(new Thread(new Reader(object), "Reader2"));
service.shutdown(); } private static class Reader implements Runnable { SynchronizedHashMapWithRWLock object; Reader(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { object.get("key" + i); } } } private static class Writer implements Runnable { SynchronizedHashMapWithRWLock object; public Writer(SynchronizedHashMapWithRWLock object) { this.object = object; } @Override public void run() { for (int i = 0; i < 10; i++) { try { object.put("key" + i, "value" + i); sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced\src\main\java\com\baeldung\concurrent\locks\SynchronizedHashMapWithRWLock.java
1
请在Spring Boot框架中完成以下Java代码
SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception { ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry registry = httpSecurity .authorizeRequests(); //不需要保护的资源路径允许访问 for (String url : ignoreUrlsConfig.getUrls()) { registry.antMatchers(url).permitAll(); } //允许跨域请求的OPTIONS请求 registry.antMatchers(HttpMethod.OPTIONS) .permitAll(); //任何请求都需要身份认证 registry.and() .authorizeRequests() .anyRequest() .authenticated() //关闭跨站请求防护及不使用session .and() .csrf()
.disable() .sessionManagement() .sessionCreationPolicy(SessionCreationPolicy.STATELESS) //自定义权限拒绝处理类 .and() .exceptionHandling() .accessDeniedHandler(restfulAccessDeniedHandler) .authenticationEntryPoint(restAuthenticationEntryPoint) //自定义权限拦截器JWT过滤器 .and() .addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); //有动态权限配置时添加动态权限校验过滤器 if(dynamicSecurityService!=null){ registry.and().addFilterBefore(dynamicSecurityFilter, FilterSecurityInterceptor.class); } return httpSecurity.build(); } }
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\config\SecurityConfig.java
2
请完成以下Java代码
public OrderId getContractOrderId(@NonNull final I_C_Flatrate_Term term) { if (term.getC_OrderLine_Term_ID() <= 0) { return null; } final IOrderDAO orderRepo = Services.get(IOrderDAO.class); final de.metas.interfaces.I_C_OrderLine ol = orderRepo.getOrderLineById(term.getC_OrderLine_Term_ID()); if (ol == null) { return null; } return OrderId.ofRepoId(ol.getC_Order_ID()); } public boolean isContractSalesOrder(@NonNull final OrderId orderId) { return Services.get(IQueryBL.class) .createQueryBuilder(I_C_OrderLine.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_OrderLine.COLUMNNAME_C_Order_ID, orderId) .addNotNull(I_C_OrderLine.COLUMNNAME_C_Flatrate_Conditions_ID)
.create() .anyMatch(); } public void save(@NonNull final I_C_Order order) { InterfaceWrapperHelper.save(order); } public void setOrderContractStatusAndSave(@NonNull final I_C_Order order, @NonNull final String contractStatus) { order.setContractStatus(contractStatus); save(order); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\order\ContractOrderService.java
1
请完成以下Java代码
private List<BaseComponent> initComponentList(InjectComponents injectComponents) throws IllegalAccessException, InstantiationException { List<BaseComponent> componentList = Lists.newArrayList(); // 获取Components Class[] componentClassList = injectComponents.value(); if (componentClassList == null || componentClassList.length <= 0) { return componentList; } // 遍历components for (Class<BaseComponent> componentClass : componentClassList) { // 获取IOC容器中的Component对象 BaseComponent componentInstance = applicationContext.getBean(componentClass); // 加入容器 componentList.add(componentInstance); }
return componentList; } /** * 获取需要扫描的包名 */ private String getPackage() { PackageScan packageScan = AnnotationUtil.getAnnotationValueByClass(this.getClass(), PackageScan.class); return packageScan.value(); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\init\InitComponentList.java
1
请完成以下Java代码
private void closeGroupAndCollect(final GroupType group) { closeGroup(group); if (closedGroupsCollector != null) { closedGroupsCollector.add(group); } } /** * Close all groups from buffer. As a result, after this call the groups buffer will be empty. */ public final void closeAllGroups() { final GroupType exceptGroup = null; // no exception closeAllGroupsExcept(exceptGroup); } /** * Close all groups, but not the last used one. Last used one is considered that group where we added last item. */ public final void closeAllGroupExceptLastUsed() { closeAllGroupsExcept(_lastGroupUsed); } /** * Close all groups. * * @param exceptGroup optional group to except from closing */ private void closeAllGroupsExcept(@Nullable final GroupType exceptGroup) { final Iterator<GroupType> groups = _itemHashKey2group.values().iterator(); while (groups.hasNext()) { final GroupType group = groups.next(); if (group == null) { continue; }
// Skip the excepted group if (group == exceptGroup) { continue; } closeGroupAndCollect(group); groups.remove(); } } /** * @return how many groups were created */ public final int getGroupsCount() { return _countGroups; } /** * @return how many items were added */ public final int getItemsCount() { return _countItems; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\MapReduceAggregator.java
1
请完成以下Java代码
protected void prepare () { p_HR_Payroll_ID = getRecord_ID(); } // prepare /** * Process * @return info * @throws Exception */ protected String doIt () throws Exception { int count = 0; for(MHRConcept concept : MHRConcept.getConcepts(p_HR_Payroll_ID, 0, 0, null)) { if(!existsPayrollConcept(concept.get_ID())) { MHRPayrollConcept payrollConcept = new MHRPayrollConcept (concept, p_HR_Payroll_ID, get_TrxName());
payrollConcept.saveEx(); count++; } } return "@Created@/@Updated@ #" + count; } // doIt private boolean existsPayrollConcept(int HR_Concept_ID) { final String whereClause = "HR_Payroll_ID=? AND HR_Concept_ID=?"; return new Query(getCtx(), MHRPayrollConcept.Table_Name, whereClause, get_TrxName()) .setParameters(new Object[]{p_HR_Payroll_ID, HR_Concept_ID}) .anyMatch(); } } // Create Concept of the current Payroll
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\process\HRCreateConcept.java
1
请完成以下Java代码
public ArrayList<Pair<String, V>> commonPrefixSearch(String key, int offset, int maxResults) { byte[] keyBytes = key.getBytes(utf8); List<Pair<Integer, Integer>> pairList = commonPrefixSearch(keyBytes, offset, maxResults); ArrayList<Pair<String, V>> resultList = new ArrayList<Pair<String, V>>(pairList.size()); for (Pair<Integer, Integer> pair : pairList) { resultList.add(new Pair<String, V>(new String(keyBytes, 0, pair.first), valueArray[pair.second])); } return resultList; } public ArrayList<Pair<String, V>> commonPrefixSearch(String key) { return commonPrefixSearch(key, 0, Integer.MAX_VALUE); } @Override public V put(String key, V value) { throw new UnsupportedOperationException("双数组不支持增量式插入"); } @Override public V remove(Object key) { throw new UnsupportedOperationException("双数组不支持删除"); }
@Override public void putAll(Map<? extends String, ? extends V> m) { throw new UnsupportedOperationException("双数组不支持增量式插入"); } @Override public void clear() { throw new UnsupportedOperationException("双数组不支持"); } @Override public Set<String> keySet() { throw new UnsupportedOperationException("双数组不支持"); } @Override public Collection<V> values() { return Arrays.asList(valueArray); } @Override public Set<Entry<String, V>> entrySet() { throw new UnsupportedOperationException("双数组不支持"); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\DartMap.java
1
请完成以下Java代码
public int retrieveDueDays( @NonNull final PaymentTermId paymentTermId, final Date dateInvoiced, final Date date) { return DB.getSQLValueEx(ITrx.TRXNAME_None, "SELECT paymentTermDueDays(?,?,?)", paymentTermId.getRepoId(), dateInvoiced, date); } @Override public Iterator<I_C_Dunning_Candidate_Invoice_v1> retrieveDunningCandidateInvoices(final IDunningContext context) { final Properties ctx = context.getCtx(); final String trxName = context.getTrxName(); final IQueryBL queryBL = Services.get(IQueryBL.class); final I_C_DunningLevel dunningLevel = context.getC_DunningLevel(); Check.assumeNotNull(dunningLevel, "Context shall have DuningLevel set: {}", context); Check.assumeNotNull(context.getDunningDate(), "Context shall have DunningDate set: {}", context); final Date dunningDate = TimeUtil.getDay(context.getDunningDate()); final ICompositeQueryFilter<I_C_Dunning_Candidate_Invoice_v1> dunningGraceFilter = queryBL .createCompositeQueryFilter(I_C_Dunning_Candidate_Invoice_v1.class) .setJoinOr() .addEqualsFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, null) .addCompareFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, Operator.LESS, dunningDate);
return queryBL.createQueryBuilder(I_C_Dunning.class, ctx, trxName) .addOnlyActiveRecordsFilter() .addOnlyContextClient(ctx) .addEqualsFilter(I_C_Dunning.COLUMNNAME_C_Dunning_ID, dunningLevel.getC_Dunning_ID()) // Dunning Level is for current assigned Dunning .andCollectChildren(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Dunning_ID) .addOnlyActiveRecordsFilter() .addOnlyContextClient(ctx) .filter(dunningGraceFilter) // Validate Dunning Grace (if any) .orderBy() .addColumn(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Invoice_ID).endOrderBy() .setOption(IQuery.OPTION_IteratorBufferSize, 1000 /* iterator shall load 1000 records at a time */) .setOption(IQuery.OPTION_GuaranteedIteratorRequired, false /* the result is not changing while the iterator is iterated */) .create() .iterate(I_C_Dunning_Candidate_Invoice_v1.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\api\impl\InvoiceSourceDAO.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getMemberId() { return memberId; } public void setMemberId(Long memberId) { this.memberId = memberId; } 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 void setXPosition (final int XPosition) { set_Value (COLUMNNAME_XPosition, XPosition); } @Override public int getXPosition() { return get_ValueAsInt(COLUMNNAME_XPosition); } @Override public void setYield (final int Yield) { set_Value (COLUMNNAME_Yield, Yield); } @Override public int getYield() {
return get_ValueAsInt(COLUMNNAME_Yield); } @Override public void setYPosition (final int YPosition) { set_Value (COLUMNNAME_YPosition, YPosition); } @Override public int getYPosition() { return get_ValueAsInt(COLUMNNAME_YPosition); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Node.java
1
请完成以下Java代码
public class X_ESR_PostFinanceUserNumber extends org.compiere.model.PO implements I_ESR_PostFinanceUserNumber, org.compiere.model.I_Persistent { private static final long serialVersionUID = 806167320L; /** Standard Constructor */ public X_ESR_PostFinanceUserNumber (final Properties ctx, final int ESR_PostFinanceUserNumber_ID, @Nullable final String trxName) { super (ctx, ESR_PostFinanceUserNumber_ID, trxName); } /** Load Constructor */ public X_ESR_PostFinanceUserNumber (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_BP_BankAccount_ID (final int C_BP_BankAccount_ID) { if (C_BP_BankAccount_ID < 1) set_Value (COLUMNNAME_C_BP_BankAccount_ID, null); else set_Value (COLUMNNAME_C_BP_BankAccount_ID, C_BP_BankAccount_ID); } @Override public int getC_BP_BankAccount_ID() { return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_ID); } @Override
public void setESR_PostFinanceUserNumber_ID (final int ESR_PostFinanceUserNumber_ID) { if (ESR_PostFinanceUserNumber_ID < 1) set_ValueNoCheck (COLUMNNAME_ESR_PostFinanceUserNumber_ID, null); else set_ValueNoCheck (COLUMNNAME_ESR_PostFinanceUserNumber_ID, ESR_PostFinanceUserNumber_ID); } @Override public int getESR_PostFinanceUserNumber_ID() { return get_ValueAsInt(COLUMNNAME_ESR_PostFinanceUserNumber_ID); } @Override public void setESR_RenderedAccountNo (final java.lang.String ESR_RenderedAccountNo) { set_Value (COLUMNNAME_ESR_RenderedAccountNo, ESR_RenderedAccountNo); } @Override public java.lang.String getESR_RenderedAccountNo() { return get_ValueAsString(COLUMNNAME_ESR_RenderedAccountNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_PostFinanceUserNumber.java
1
请完成以下Java代码
public int[] addTwoVectorsWithMasks(int[] arr1, int[] arr2) { int[] finalResult = new int[arr1.length]; int i = 0; for (; i < SPECIES.loopBound(arr1.length); i += SPECIES.length()) { var mask = SPECIES.indexInRange(i, arr1.length); var v1 = IntVector.fromArray(SPECIES, arr1, i, mask); var v2 = IntVector.fromArray(SPECIES, arr2, i, mask); var result = v1.add(v2, mask); result.intoArray(finalResult, i, mask); } // tail cleanup loop for (; i < arr1.length; i++) { finalResult[i] = arr1[i] + arr2[i]; } return finalResult; } public float[] scalarNormOfTwoArrays(float[] arr1, float[] arr2) { float[] finalResult = new float[arr1.length]; for (int i = 0; i < arr1.length; i++) { finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]); } return finalResult; } public float[] vectorNormalForm(float[] arr1, float[] arr2) { float[] finalResult = new float[arr1.length]; int i = 0; int upperBound = SPECIES.loopBound(arr1.length); for (; i < upperBound; i += SPECIES.length()) {
var va = FloatVector.fromArray(PREFERRED_SPECIES, arr1, i); var vb = FloatVector.fromArray(PREFERRED_SPECIES, arr2, i); var vc = va.mul(va) .add(vb.mul(vb)) .sqrt(); vc.intoArray(finalResult, i); } // tail cleanup for (; i < arr1.length; i++) { finalResult[i] = (float) Math.sqrt(arr1[i] * arr1[i] + arr2[i] * arr2[i]); } return finalResult; } public double averageOfaVector(int[] arr) { double sum = 0; for (int i = 0; i < arr.length; i += SPECIES.length()) { var mask = SPECIES.indexInRange(i, arr.length); var V = IntVector.fromArray(SPECIES, arr, i, mask); sum += V.reduceLanes(VectorOperators.ADD, mask); } return sum / arr.length; } }
repos\tutorials-master\core-java-modules\core-java-19\src\main\java\com\baeldung\vectors\VectorAPIExamples.java
1
请完成以下Java代码
public static LocalDateTime fromTimeStamp(Long timeStamp) { return LocalDateTime.ofEpochSecond(timeStamp, 0, OffsetDateTime.now().getOffset()); } /** * LocalDateTime 转 Date * Jdk8 后 不推荐使用 {@link Date} Date * * @param localDateTime / * @return / */ public static Date toDate(LocalDateTime localDateTime) { return Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant()); } /** * LocalDate 转 Date * Jdk8 后 不推荐使用 {@link Date} Date * * @param localDate / * @return / */ public static Date toDate(LocalDate localDate) { return toDate(localDate.atTime(LocalTime.now(ZoneId.systemDefault()))); } /** * Date转 LocalDateTime * Jdk8 后 不推荐使用 {@link Date} Date * * @param date / * @return / */ public static LocalDateTime toLocalDateTime(Date date) { return LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault()); } /** * 日期 格式化 * * @param localDateTime / * @param patten / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, String patten) { DateTimeFormatter df = DateTimeFormatter.ofPattern(patten); return df.format(localDateTime); } /** * 日期 格式化 * * @param localDateTime / * @param df / * @return / */ public static String localDateTimeFormat(LocalDateTime localDateTime, DateTimeFormatter df) { return df.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return / */ public static String localDateTimeFormatyMdHms(LocalDateTime localDateTime) { return DFY_MD_HMS.format(localDateTime); } /** * 日期格式化 yyyy-MM-dd *
* @param localDateTime / * @return / */ public String localDateTimeFormatyMd(LocalDateTime localDateTime) { return DFY_MD.format(localDateTime); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, String pattern) { DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(pattern); return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormat(String localDateTime, DateTimeFormatter dateTimeFormatter) { return LocalDateTime.from(dateTimeFormatter.parse(localDateTime)); } /** * 字符串转 LocalDateTime ,字符串格式 yyyy-MM-dd HH:mm:ss * * @param localDateTime / * @return / */ public static LocalDateTime parseLocalDateTimeFormatyMdHms(String localDateTime) { return LocalDateTime.from(DFY_MD_HMS.parse(localDateTime)); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\DateUtil.java
1
请完成以下Java代码
public class ESProductDO { /** * ID 主键 */ @Id private Integer id; /** * SPU 名字 */ @Field(analyzer = FieldAnalyzer.IK_MAX_WORD, type = FieldType.Text) private String name; /** * 卖点 */ @Field(analyzer = FieldAnalyzer.IK_MAX_WORD, type = FieldType.Text) private String sellPoint; /** * 描述 */ @Field(analyzer = FieldAnalyzer.IK_MAX_WORD, type = FieldType.Text) private String description; /** * 分类编号 */ private Integer cid; /** * 分类名 */ @Field(analyzer = FieldAnalyzer.IK_MAX_WORD, type = FieldType.Text) private String categoryName; public Integer getId() { return id; } public ESProductDO setId(Integer id) { this.id = id; return this; } public String getName() { return name; } public ESProductDO setName(String name) { this.name = name; return this; }
public String getSellPoint() { return sellPoint; } public ESProductDO setSellPoint(String sellPoint) { this.sellPoint = sellPoint; return this; } public String getDescription() { return description; } public ESProductDO setDescription(String description) { this.description = description; return this; } public Integer getCid() { return cid; } public ESProductDO setCid(Integer cid) { this.cid = cid; return this; } public String getCategoryName() { return categoryName; } public ESProductDO setCategoryName(String categoryName) { this.categoryName = categoryName; return this; } @Override public String toString() { return "ProductDO{" + "id=" + id + ", name='" + name + '\'' + ", sellPoint='" + sellPoint + '\'' + ", description='" + description + '\'' + ", cid=" + cid + ", categoryName='" + categoryName + '\'' + '}'; } }
repos\SpringBoot-Labs-master\lab-15-spring-data-es\lab-15-spring-data-jest\src\main\java\cn\iocoder\springboot\lab15\springdatajest\dataobject\ESProductDO.java
1
请完成以下Java代码
public WFProcess getWFProcessById(final WFProcessId wfProcessId) { final Inventory inventory = jobService.getById(toInventoryId(wfProcessId)); return toWFProcess(inventory); } @Override public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess) { final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache(); final Inventory inventory = getInventory(wfProcess); return WFProcessHeaderProperties.builder() .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("DocumentNo")) .value(inventory.getDocumentNo()) .build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("MovementDate")) .value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate())) .build()) .entry(WFProcessHeaderProperty.builder() .caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID")) .value(inventory.getWarehouseId() != null ? warehouses.getById(inventory.getWarehouseId()).getWarehouseName()
: "") .build()) .build(); } @NonNull public static Inventory getInventory(final @NonNull WFProcess wfProcess) { return wfProcess.getDocumentAs(Inventory.class); } public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper) { final Inventory inventory = getInventory(wfProcess); final Inventory inventoryChanged = mapper.apply(inventory); return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java
1
请完成以下Java代码
private boolean deleteTourInstanceIfGenericAndNoDeliveryDays(final I_M_Tour_Instance tourInstance) { // Skip tour instances which are null or not already saved if (tourInstance == null) { return false; } if (tourInstance.getM_Tour_Instance_ID() <= 0) { return false; } // If it's not a generic tour instance => don't touch it if (!Services.get(ITourInstanceBL.class).isGenericTourInstance(tourInstance)) { return false; } // If tour instance has assigned delivery days => don't touch it if (Services.get(ITourInstanceDAO.class).hasDeliveryDays(tourInstance)) { return false; } // // Delete tour instance InterfaceWrapperHelper.delete(tourInstance); return true; // deleted }
/** * Make sure that delivery date time max is updated when delivery date or buffer are changed */ @ModelChange (timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = {I_M_DeliveryDay.COLUMNNAME_DeliveryDate, I_M_DeliveryDay.COLUMNNAME_BufferHours}) public void changeDeliveryDateMax(final I_M_DeliveryDay deliveryDay) { // Services final IDeliveryDayBL deliveryDayBL = Services.get(IDeliveryDayBL.class); deliveryDayBL.setDeliveryDateTimeMax(deliveryDay); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_DeliveryDay.java
1
请在Spring Boot框架中完成以下Java代码
public class ValueHint implements Serializable { private Object value; private String description; private String shortDescription; /** * Return the hint value. * @return the value */ public Object getValue() { return this.value; } public void setValue(Object value) { this.value = value; } /** * A description of this value, if any. Can be multi-lines. * @return the description * @see #getShortDescription() */ public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; }
/** * A single-line, single-sentence description of this hint, if any. * @return the short description * @see #getDescription() */ public String getShortDescription() { return this.shortDescription; } public void setShortDescription(String shortDescription) { this.shortDescription = shortDescription; } @Override public String toString() { return "ValueHint{value=" + this.value + ", description='" + this.description + '\'' + '}'; } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ValueHint.java
2
请完成以下Java代码
protected String doIt() throws Exception { if (p_role_id == 0) { throw new Exception("No Role defined or cannot assign menus to System Administrator"); } String sqlStmt = "SELECT U_WebMenu_ID, IsActive FROM U_WebMenu"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement(sqlStmt, get_TrxName()); rs = pstmt.executeQuery();
while (rs.next()) { int menuId = rs.getInt(1); boolean active = "Y".equals(rs.getString(2)); addUpdateRole(getCtx(), p_role_id, menuId, active, get_TrxName()); } } finally { DB.close(rs, pstmt); } return "Role updated successfully"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\UpdateRoleMenu.java
1
请在Spring Boot框架中完成以下Java代码
SpanContext spanContext(ObjectProvider<Tracer> tracerProvider) { return new LazyTracingSpanContext(tracerProvider); } /** * Since the MeterRegistry can depend on the {@link Tracer} (Exemplars) and the * {@link Tracer} can depend on the MeterRegistry (recording metrics), this * {@link SpanContext} breaks the cycle by lazily loading the {@link Tracer}. */ static class LazyTracingSpanContext implements SpanContext { private final SingletonSupplier<Tracer> tracer; LazyTracingSpanContext(ObjectProvider<Tracer> tracerProvider) { this.tracer = SingletonSupplier.of(tracerProvider::getObject); } @Override public @Nullable String getCurrentTraceId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().traceId() : null; } @Override public @Nullable String getCurrentSpanId() { Span currentSpan = currentSpan(); return (currentSpan != null) ? currentSpan.context().spanId() : null; }
@Override public boolean isCurrentSpanSampled() { Span currentSpan = currentSpan(); if (currentSpan == null) { return false; } Boolean sampled = currentSpan.context().sampled(); return sampled != null && sampled; } @Override public void markCurrentSpanAsExemplar() { } private @Nullable Span currentSpan() { return this.tracer.obtain().currentSpan(); } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\prometheus\PrometheusExemplarsAutoConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String assignMenuUI(HttpServletRequest req, Model model, Long roleId) { PmsRole role = pmsRoleService.getDataById(roleId); if (role == null) { return operateError("无法获取角色信息", model); } // 普通操作员没有修改超级管理员角色的权限 if (OperatorTypeEnum.USER.name().equals(this.getPmsOperator().getType()) && "admin".equals(role.getRoleName())) { return operateError("权限不足", model); } String menuIds = pmsMenuService.getMenuIdsByRoleId(roleId); // 根据角色查找角色对应的菜单ID集 List menuList = pmsMenuService.getListByParent(null); List<PmsOperator> operatorList = pmsOperatorRoleService.listOperatorByRoleId(roleId); model.addAttribute("menuIds", menuIds); model.addAttribute("menuList", menuList); model.addAttribute("operatorList", operatorList); model.addAttribute("role", role); return "/pms/assignMenuUI"; } /** * 分配角色菜单 */ @RequiresPermissions("pms:role:assignmenu") @RequestMapping("/assignMenu") public String assignMenu(HttpServletRequest req, Model model, @RequestParam("roleId") Long roleId, DwzAjax dwz, @RequestParam("selectVal") String selectVal) { try { String roleMenuStr = getRolePermissionStr(selectVal); pmsMenuRoleService.saveRoleMenu(roleId, roleMenuStr); return operateSuccess(model, dwz); } catch (Exception e) { log.error("== assignPermission exception:", e); return operateError("保存失败", model); }
} /** * 得到角色和权限关联的ID字符串 * * @return */ private String getRolePermissionStr(String selectVal) throws Exception { String roleStr = selectVal; if (StringUtils.isNotBlank(roleStr) && roleStr.length() > 0) { roleStr = roleStr.substring(0, roleStr.length() - 1); } return roleStr; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\controller\PmsRoleController.java
2
请完成以下Java代码
protected String doIt() throws Exception { final PInstanceId pinstanceId = getPinstanceId(); final EnqueuePPOrderCandidateRequest enqueuePPOrderCandidateRequest = EnqueuePPOrderCandidateRequest.builder() .adPInstanceId(pinstanceId) .ctx(Env.getCtx()) .isCompleteDocOverride(isDocComplete) .autoProcessCandidatesAfterProduction(autoProcessCandidatesAfterProduction) .autoCloseCandidatesAfterProduction(autoCloseCandidatesAfterProduction) .build(); ppOrderCandidateEnqueuer.enqueueSelection(enqueuePPOrderCandidateRequest); return MSG_OK; } @Override @RunOutOfTrx protected void prepare() { if (createSelection() <= 0) { throw new AdempiereException("@NoSelection@"); } } protected int createSelection() { final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder(); final PInstanceId adPInstanceId = getPinstanceId(); Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null"); DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited); return queryBuilder .create() .setRequiredAccess(Access.READ)
.createSelection(adPInstanceId); } protected IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder() { final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null); if (userSelectionFilter == null) { throw new AdempiereException("@NoSelection@"); } return queryBL .createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_Processed, false) .addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false) .addCompareFilter(I_PP_Order_Candidate.COLUMNNAME_QtyToProcess, CompareQueryFilter.Operator.GREATER, BigDecimal.ZERO) .filter(userSelectionFilter) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .orderBy(I_PP_Order_Candidate.COLUMNNAME_SeqNo) .orderBy(I_PP_Order_Candidate.COLUMNNAME_PP_Order_Candidate_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_EnqueueSelectionForOrdering.java
1
请完成以下Java代码
public BigDecimal getHuQtyCU() { return huQtyCU; } public ProductId getHuProductId() { return huProduct != null ? ProductId.ofRepoId(huProduct.getKeyAsInt()) : null; } @Override public ViewId getIncludedViewId() { return includedViewId; } public LocatorId getPickingSlotLocatorId() { return pickingSlotLocatorId; } public int getBPartnerId() { return pickingSlotBPartner != null ? pickingSlotBPartner.getIdAsInt() : -1; } public int getBPartnerLocationId() { return pickingSlotBPLocation != null ? pickingSlotBPLocation.getIdAsInt() : -1; } @NonNull public Optional<PickingSlotRow> findRowMatching(@NonNull final Predicate<PickingSlotRow> predicate) { return streamThisRowAndIncludedRowsRecursivelly() .filter(predicate) .findFirst(); } public boolean thereIsAnOpenPickingForOrderId(@NonNull final OrderId orderId) { final HuId huId = getHuId(); if (huId == null) { throw new AdempiereException("Not a PickedHURow!") .appendParametersToMessage() .setParameter("PickingSlotRow", this);
} final boolean hasOpenPickingForOrderId = getPickingOrderIdsForHUId(huId).contains(orderId); if (hasOpenPickingForOrderId) { return true; } if (isLU()) { return findRowMatching(row -> !row.isLU() && row.thereIsAnOpenPickingForOrderId(orderId)) .isPresent(); } return false; } @NonNull private ImmutableSet<OrderId> getPickingOrderIdsForHUId(@NonNull final HuId huId) { return Optional.ofNullable(huId2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotRow.java
1
请完成以下Java代码
private HashMap<String, JSONIncludedTabInfo> getIncludedTabsInfo() { if (includedTabsInfoByTabId == null) { includedTabsInfoByTabId = new HashMap<>(); } return includedTabsInfoByTabId; } private JSONIncludedTabInfo getIncludedTabInfo(final DetailId tabId) { return getIncludedTabsInfo().computeIfAbsent(tabId.toJson(), k -> JSONIncludedTabInfo.newInstance(tabId)); } void addIncludedTabInfo(@NonNull final JSONIncludedTabInfo tabInfo) { getIncludedTabsInfo().compute(tabInfo.getTabId().toJson(), (tabId, existingTabInfo) -> { if (existingTabInfo == null) { return tabInfo.copy(); } else { existingTabInfo.mergeFrom(tabInfo); return existingTabInfo; } }); } @Override @JsonIgnore public WebsocketTopicName getWebsocketEndpoint() { return WebsocketTopicNames.buildDocumentTopicName(windowId, id); } public void staleTabs(@NonNull final Collection<DetailId> tabIds) {
tabIds.stream().map(this::getIncludedTabInfo).forEach(JSONIncludedTabInfo::markAllRowsStaled); } public void staleIncludedRows(@NonNull final DetailId tabId, @NonNull final DocumentIdsSelection rowIds) { getIncludedTabInfo(tabId).staleRows(rowIds); } void mergeFrom(@NonNull final JSONDocumentChangedWebSocketEvent from) { if (!Objects.equals(windowId, from.windowId) || !Objects.equals(id, from.id)) { throw new AdempiereException("Cannot merge events because they are not matching") .setParameter("from", from) .setParameter("to", this) .appendParametersToMessage(); } if (from.stale != null && from.stale) { stale = from.stale; } from.getIncludedTabsInfo().values().forEach(this::addIncludedTabInfo); if (from.activeTabStaled != null && from.activeTabStaled) { activeTabStaled = from.activeTabStaled; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\events\JSONDocumentChangedWebSocketEvent.java
1
请在Spring Boot框架中完成以下Java代码
public class ProductsProposalRowAddRequest { @NonNull LookupValue product; @NonNull @Default ProductASIDescription asiDescription = ProductASIDescription.NONE; @Nullable AttributeSetInstanceId asiId; @NonNull Amount priceListPrice; @Nullable Integer lastShipmentDays;
@Nullable ProductPriceId copiedFromProductPriceId; @Nullable HUPIItemProductId packingMaterialId; @Nullable ITranslatableString packingDescription; public ProductId getProductId() { return getProduct().getIdAs(ProductId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductsProposalRowAddRequest.java
2
请在Spring Boot框架中完成以下Java代码
public class ExternalSystemShopware6Config implements IExternalSystemChildConfig { @NonNull ExternalSystemShopware6ConfigId id; @NonNull ExternalSystemParentConfigId parentId; @NonNull String baseUrl; @NonNull String clientId; @NonNull String clientSecret; @NonNull List<ExternalSystemShopware6ConfigMapping> externalSystemShopware6ConfigMappingList; @NonNull List<UOMShopwareMapping> uomShopwareMappingList; @Nullable String bPartnerLocationIdJSONPath; @Nullable String salesRepJSONPath; @Nullable String emailJSONPath; @Nullable FreightCostConfig freightCostNormalVatConfig; @Nullable FreightCostConfig freightCostReducedVatConfig; @Nullable PriceListId priceListId; @NonNull Boolean isActive; @NonNull String value; @NonNull ProductLookup productLookup; @Nullable String metasfreshIdJSONPath; @Nullable String shopwareIdJSONPath; @Builder(toBuilder = true) public ExternalSystemShopware6Config(final @NonNull ExternalSystemShopware6ConfigId id, final @NonNull ExternalSystemParentConfigId parentId, final @NonNull String baseUrl, final @NonNull String clientId, final @NonNull String clientSecret, final @NonNull List<ExternalSystemShopware6ConfigMapping> externalSystemShopware6ConfigMappingList, final @NonNull List<UOMShopwareMapping> uomShopwareMappingList, final @Nullable String bPartnerLocationIdJSONPath, final @Nullable String salesRepJSONPath, final @Nullable String emailJSONPath, final @Nullable FreightCostConfig freightCostNormalVatConfig, final @Nullable FreightCostConfig freightCostReducedVatConfig, final @Nullable PriceListId priceListId, final @NonNull Boolean isActive, final @NonNull String value, final @NonNull ProductLookup productLookup, final @Nullable String metasfreshIdJSONPath, final @Nullable String shopwareIdJSONPath)
{ this.id = id; this.parentId = parentId; this.clientId = clientId; this.clientSecret = clientSecret; this.externalSystemShopware6ConfigMappingList = externalSystemShopware6ConfigMappingList; this.uomShopwareMappingList = uomShopwareMappingList; this.baseUrl = baseUrl; this.bPartnerLocationIdJSONPath = bPartnerLocationIdJSONPath; this.salesRepJSONPath = salesRepJSONPath; this.emailJSONPath = emailJSONPath; this.freightCostNormalVatConfig = freightCostNormalVatConfig; this.freightCostReducedVatConfig = freightCostReducedVatConfig; this.priceListId = priceListId; this.isActive = isActive; this.value = value; this.productLookup = productLookup; this.metasfreshIdJSONPath = metasfreshIdJSONPath; this.shopwareIdJSONPath = shopwareIdJSONPath; } public static ExternalSystemShopware6Config cast(@NonNull final IExternalSystemChildConfig childConfig) { return (ExternalSystemShopware6Config)childConfig; } @Value @Builder public static class FreightCostConfig { @NonNull ProductId productId; @NonNull String vatRates; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\shopware6\ExternalSystemShopware6Config.java
2
请完成以下Java代码
public String getId() { return id; } public String getBusinessKey() { return businessKey; } public void setBusinessKey(String businessKey) { this.businessKey = businessKey; } public Set<String> getProcessDefinitionKeys() { return processDefinitionKeys; } public void setProcessDefinitionKeys(Set<String> processDefinitionKeys) { this.processDefinitionKeys = processDefinitionKeys; } public boolean isSuspendedOnly() { return suspendedOnly;
} public void setSuspendedOnly(boolean suspendedOnly) { this.suspendedOnly = suspendedOnly; } public boolean isActiveOnly() { return activeOnly; } public void setActiveOnly(boolean activeOnly) { this.activeOnly = activeOnly; } public String getParentProcessInstanceId() { return parentProcessInstanceId; } public void setParentProcessInstanceId(String parentProcessInstanceId) { this.parentProcessInstanceId = parentProcessInstanceId; } }
repos\Activiti-develop\activiti-api\activiti-api-process-model\src\main\java\org\activiti\api\process\model\payloads\GetProcessInstancesPayload.java
1
请完成以下Java代码
public void setWarehouseLocatorIdentifier (final @Nullable java.lang.String WarehouseLocatorIdentifier) { set_Value (COLUMNNAME_WarehouseLocatorIdentifier, WarehouseLocatorIdentifier); } @Override public java.lang.String getWarehouseLocatorIdentifier() { return get_ValueAsString(COLUMNNAME_WarehouseLocatorIdentifier); } @Override public void setWarehouseValue (final @Nullable java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } @Override public void setX (final @Nullable java.lang.String X) { set_Value (COLUMNNAME_X, X); } @Override public java.lang.String getX() { return get_ValueAsString(COLUMNNAME_X); } @Override public void setX1 (final @Nullable java.lang.String X1) { set_Value (COLUMNNAME_X1, X1); } @Override public java.lang.String getX1() { return get_ValueAsString(COLUMNNAME_X1); } @Override public void setY (final @Nullable java.lang.String Y)
{ set_Value (COLUMNNAME_Y, Y); } @Override public java.lang.String getY() { return get_ValueAsString(COLUMNNAME_Y); } @Override public void setZ (final @Nullable java.lang.String Z) { set_Value (COLUMNNAME_Z, Z); } @Override public java.lang.String getZ() { return get_ValueAsString(COLUMNNAME_Z); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Inventory.java
1
请完成以下Java代码
public class FreeMarkerScriptEngine extends AbstractScriptEngine implements Compilable { protected ScriptEngineFactory scriptEngineFactory; protected Configuration configuration; public FreeMarkerScriptEngine() { this(null); } public FreeMarkerScriptEngine(ScriptEngineFactory scriptEngineFactory) { this.scriptEngineFactory = scriptEngineFactory; } public Object eval(String script, ScriptContext context) throws ScriptException { return eval(new StringReader(script), context); } public Object eval(Reader script, ScriptContext context) throws ScriptException { initConfiguration(); String filename = getFilename(context); Writer writer = new StringWriter(); Bindings bindings = context.getBindings(ScriptContext.ENGINE_SCOPE); try { Template template = new Template(filename, script, configuration); template.process(bindings, writer); writer.flush(); } catch (Exception e) { throw new ScriptException(e); } return writer.toString(); } public Bindings createBindings() { return new SimpleBindings(); } public ScriptEngineFactory getFactory() { if (scriptEngineFactory == null) { synchronized (this) { if (scriptEngineFactory == null) { scriptEngineFactory = new FreeMarkerScriptEngineFactory(); } }
} return scriptEngineFactory; } public void initConfiguration() { if (configuration == null) { synchronized (this) { if (configuration == null) { configuration = new Configuration(Configuration.VERSION_2_3_29); } } } } protected String getFilename(ScriptContext context) { String filename = (String) context.getAttribute(ScriptEngine.FILENAME); if (filename != null) { return filename; } else { return "unknown"; } } public CompiledScript compile(String script) throws ScriptException { return compile(new StringReader(script)); } public CompiledScript compile(Reader script) throws ScriptException { initConfiguration(); return new FreeMarkerCompiledScript(this, script, configuration); } }
repos\camunda-bpm-platform-master\freemarker-template-engine\src\main\java\org\camunda\templateengines\FreeMarkerScriptEngine.java
1
请在Spring Boot框架中完成以下Java代码
public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPostCode() { return postCode; }
public void setPostCode(String postCode) { this.postCode = postCode; } @Override public String toString() { return "LocationCreateReq{" + "location='" + location + '\'' + ", name='" + name + '\'' + ", phone='" + phone + '\'' + ", postCode='" + postCode + '\'' + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\LocationCreateReq.java
2
请完成以下Java代码
public int getId() { return id; } public void setId(int id) { this.id = id; } public String getItemName() { return itemName; } public void setItemName(String itemName) { this.itemName = itemName; } public double getItemPrice() { return itemPrice; } public void setItemPrice(double itemPrice) { this.itemPrice = itemPrice; } public ItemType getItemType() { return itemType; }
public void setItemType(ItemType itemType) { this.itemType = itemType; } public Date getCreatedOn() { return createdOn; } public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Item item = (Item) o; return id == item.id && Double.compare(item.itemPrice, itemPrice) == 0 && Objects.equals(itemName, item.itemName) && itemType == item.itemType && Objects.equals(createdOn, item.createdOn); } @Override public int hashCode() { return Objects.hash(id, itemName, itemPrice, itemType, createdOn); } }
repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\persistmaps\mapkey\Item.java
1
请完成以下Java代码
public I_R_Request getR_Request() throws RuntimeException { return (I_R_Request)MTable.get(getCtx(), I_R_Request.Table_Name) .getPO(getR_Request_ID(), get_TrxName()); } /** Set Request. @param R_Request_ID Request from a Business Partner or Prospect */ public void setR_Request_ID (int R_Request_ID) { if (R_Request_ID < 1) set_Value (COLUMNNAME_R_Request_ID, null); else set_Value (COLUMNNAME_R_Request_ID, Integer.valueOf(R_Request_ID)); } /** Get Request. @return Request from a Business Partner or Prospect */ public int getR_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Source Class. @param SourceClassName Source Class Name */ public void setSourceClassName (String SourceClassName) { set_Value (COLUMNNAME_SourceClassName, SourceClassName); } /** Get Source Class. @return Source Class Name */ public String getSourceClassName () {
return (String)get_Value(COLUMNNAME_SourceClassName); } /** Set Source Method. @param SourceMethodName Source Method Name */ public void setSourceMethodName (String SourceMethodName) { set_Value (COLUMNNAME_SourceMethodName, SourceMethodName); } /** Get Source Method. @return Source Method Name */ public String getSourceMethodName () { return (String)get_Value(COLUMNNAME_SourceMethodName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueKnown.java
1
请在Spring Boot框架中完成以下Java代码
public class Campaign implements DataRecord { String name; /** * the remote system's ID which we can use to sync with the campaign on the remote marketing tool */ String remoteId; @NonNull PlatformId platformId; /** * might be null, if the campaign wasn't stored yet */ CampaignId campaignId; @Builder(toBuilder = true)
public Campaign( @NonNull final String name, @Nullable final String remoteId, @NonNull final PlatformId platformId, @Nullable final CampaignId campaignId) { this.name = name; this.remoteId = StringUtils.trimBlankToNull(remoteId); this.platformId = platformId; this.campaignId = campaignId; } public static Campaign cast(@Nullable final DataRecord dataRecord) { return (Campaign)dataRecord; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\Campaign.java
2
请完成以下Java代码
public Builder scope(String scope) { authority(new SimpleGrantedAuthority(AUTHORITIES_SCOPE_PREFIX + scope)); return this; } /** * Adds a {@link GrantedAuthority} to the collection of {@code authorities} in the * resulting {@link OAuth2AuthorizationConsent}. * @param authority the {@link GrantedAuthority} * @return the {@code Builder} for further configuration */ public Builder authority(GrantedAuthority authority) { this.authorities.add(authority); return this; } /** * A {@code Consumer} of the {@code authorities}, allowing the ability to add, * replace or remove. * @param authoritiesConsumer a {@code Consumer} of the {@code authorities} * @return the {@code Builder} for further configuration */ public Builder authorities(Consumer<Set<GrantedAuthority>> authoritiesConsumer) { authoritiesConsumer.accept(this.authorities); return this;
} /** * Validate the authorities and build the {@link OAuth2AuthorizationConsent}. * There must be at least one {@link GrantedAuthority}. * @return the {@link OAuth2AuthorizationConsent} */ public OAuth2AuthorizationConsent build() { Assert.notEmpty(this.authorities, "authorities cannot be empty"); return new OAuth2AuthorizationConsent(this.registeredClientId, this.principalName, this.authorities); } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2AuthorizationConsent.java
1
请完成以下Java代码
private void zoom() { if (m_WF_Window_ID == null) { m_WF_Window_ID = Services.get(IADTableDAO.class).retrieveWindowId(I_AD_Workflow.Table_Name).orElse(null); } if (m_WF_Window_ID == null) { throw new AdempiereException("@NotFound@ @AD_Window_ID@"); } MQuery query = null; if (workflowModel != null) { query = MQuery.getEqualQuery("AD_Workflow_ID", workflowModel.getId().getRepoId()); } AWindow frame = new AWindow(); if (!frame.initWindow(m_WF_Window_ID, query)) { return; } AEnv.addToWindowManager(frame); AEnv.showCenterScreen(frame);
frame = null; } // zoom /** * String Representation * * @return info */ @Override public String toString() { final StringBuilder sb = new StringBuilder("WFPanel["); if (workflowModel != null) { sb.append(workflowModel.getId().getRepoId()); } sb.append("]"); return sb.toString(); } // toString } // WFPanel
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\wf\WFPanel.java
1
请在Spring Boot框架中完成以下Java代码
Output cast(Output value, DataType dtype) { return g.opBuilder("Cast", "Cast", scope).addInput(value).setAttr("DstT", dtype).build().output(0); } Output decodeJpeg(Output contents, long channels) { return g.opBuilder("DecodeJpeg", "DecodeJpeg", scope) .addInput(contents) .setAttr("channels", channels) .build() .output(0); } Output<? extends TType> constant(String name, Tensor t) { return g.opBuilder("Const", name, scope) .setAttr("dtype", t.dataType()) .setAttr("value", t) .build() .output(0); } private Output binaryOp(String type, Output in1, Output in2) { return g.opBuilder(type, type, scope).addInput(in1).addInput(in2).build().output(0); }
private final Graph g; } @PreDestroy public void close() { session.close(); } @Data @NoArgsConstructor @AllArgsConstructor public static class LabelWithProbability { private String label; private float probability; private long elapsed; } }
repos\springboot-demo-master\Tensorflow\src\main\java\com\et\tf\service\ClassifyImageService.java
2
请完成以下Java代码
public static List<WebSite> parse(String path) { List<WebSite> websites = new ArrayList<WebSite>(); WebSite website = null; XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); try { XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(path)); while (reader.hasNext()) { XMLEvent nextEvent = reader.nextEvent(); if (nextEvent.isStartElement()) { StartElement startElement = nextEvent.asStartElement(); switch (startElement.getName() .getLocalPart()) { case "website": website = new WebSite(); Attribute url = startElement.getAttributeByName(new QName("url")); if (url != null) { website.setUrl(url.getValue()); } break; case "name": nextEvent = reader.nextEvent(); website.setName(nextEvent.asCharacters() .getData()); break; case "category": nextEvent = reader.nextEvent(); website.setCategory(nextEvent.asCharacters() .getData()); break; case "status": nextEvent = reader.nextEvent();
website.setStatus(nextEvent.asCharacters() .getData()); break; } } if (nextEvent.isEndElement()) { EndElement endElement = nextEvent.asEndElement(); if (endElement.getName() .getLocalPart() .equals("website")) { websites.add(website); } } } } catch (XMLStreamException xse) { System.out.println("XMLStreamException"); xse.printStackTrace(); } catch (FileNotFoundException fnfe) { System.out.println("FileNotFoundException"); fnfe.printStackTrace(); } return websites; } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\stax\StaxParser.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getA_Asset_Info_Ins_ID())); } /** Set Insurance Premium. @param A_Ins_Premium Insurance Premium */ public void setA_Ins_Premium (BigDecimal A_Ins_Premium) { set_Value (COLUMNNAME_A_Ins_Premium, A_Ins_Premium); } /** Get Insurance Premium. @return Insurance Premium */ public BigDecimal getA_Ins_Premium () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Premium); if (bd == null) return Env.ZERO; return bd; } /** Set Insurance Company. @param A_Insurance_Co Insurance Company */ public void setA_Insurance_Co (String A_Insurance_Co) { set_Value (COLUMNNAME_A_Insurance_Co, A_Insurance_Co); } /** Get Insurance Company. @return Insurance Company */ public String getA_Insurance_Co () { return (String)get_Value(COLUMNNAME_A_Insurance_Co); } /** Set Insured Value. @param A_Ins_Value Insured Value */ public void setA_Ins_Value (BigDecimal A_Ins_Value) { set_Value (COLUMNNAME_A_Ins_Value, A_Ins_Value); } /** Get Insured Value. @return Insured Value */ public BigDecimal getA_Ins_Value () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Value); if (bd == null) return Env.ZERO; return bd; } /** Set Policy Number. @param A_Policy_No Policy Number */ public void setA_Policy_No (String A_Policy_No) { set_Value (COLUMNNAME_A_Policy_No, A_Policy_No); } /** Get Policy Number. @return Policy Number */ public String getA_Policy_No () { return (String)get_Value(COLUMNNAME_A_Policy_No); } /** Set Policy Renewal Date. @param A_Renewal_Date Policy Renewal Date */ public void setA_Renewal_Date (Timestamp A_Renewal_Date) { set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date); } /** Get Policy Renewal Date. @return Policy Renewal Date */ public Timestamp getA_Renewal_Date () {
return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date); } /** Set Replacement Costs. @param A_Replace_Cost Replacement Costs */ public void setA_Replace_Cost (BigDecimal A_Replace_Cost) { set_Value (COLUMNNAME_A_Replace_Cost, A_Replace_Cost); } /** Get Replacement Costs. @return Replacement Costs */ public BigDecimal getA_Replace_Cost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Replace_Cost); if (bd == null) return Env.ZERO; return bd; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Ins.java
1
请完成以下Java代码
public class SysThirdAppConfig { /**编号*/ @TableId(type = IdType.ASSIGN_ID) @Schema(description = "编号") private String id; /**租户id*/ @Excel(name = "租户id", width = 15) @Schema(description = "租户id") private Integer tenantId; /**钉钉/企业微信第三方企业应用标识*/ @Excel(name = "钉钉/企业微信第三方企业应用标识", width = 15) @Schema(description = "钉钉/企业微信第三方企业应用标识") private String agentId; /**钉钉/企业微信 应用id*/ @Excel(name = "钉钉/企业微信 应用id", width = 15) @Schema(description = "钉钉/企业微信 应用id") private String clientId; /**钉钉/企业微信应用id对应的秘钥*/ @Excel(name = "钉钉/企业微信应用id对应的秘钥", width = 15) @Schema(description = "钉钉/企业微信应用id对应的秘钥") private String clientSecret; /**钉钉企业id*/ @Excel(name = "钉钉企业id", width = 15) @Schema(description = "钉钉企业id") private String corpId; /**第三方类别(dingtalk 钉钉 wechat_enterprise 企业微信)*/ @Excel(name = "第三方类别(dingtalk 钉钉 wechat_enterprise 企业微信)", width = 15) @Schema(description = "第三方类别(dingtalk 钉钉 wechat_enterprise 企业微信)") private String thirdType;
/**是否启用(0-否,1-是)*/ @Excel(name = "是否启用(0-否,1-是)", width = 15) @Schema(description = "是否启用(0-否,1-是)") private Integer status; /**创建日期*/ @Excel(name = "创建日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date createTime; /**修改日期*/ @Excel(name = "修改日期", width = 20, format = "yyyy-MM-dd HH:mm:ss") @JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") private Date updateTime; }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysThirdAppConfig.java
1
请完成以下Java代码
public String getColumnName() { return I_C_ValidCombination.Table_Name + "." + I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID; } // getColumnName @Override public String getColumnNameNotFQ() { return I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID; } // getColumnName /** * Return data as sorted Array. Used in Web Interface * * @param mandatory mandatory * @param onlyValidated only valid * @param onlyActive only active * @param temporary force load for temporary display * @return ArrayList with KeyNamePair */ @Override public ArrayList<Object> getData(boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary) { ArrayList<Object> list = new ArrayList<>(); if (!mandatory) list.add(KeyNamePair.EMPTY); // ArrayList<Object> params = new ArrayList<>(); String whereClause = "AD_Client_ID=?"; params.add(Env.getAD_Client_ID(m_ctx)); List<MAccount> accounts = new Query(m_ctx, MAccount.Table_Name, whereClause, ITrx.TRXNAME_None) .setParameters(params) .setOrderBy(MAccount.COLUMNNAME_Combination) .setOnlyActiveRecords(onlyActive)
.list(MAccount.class); for (final I_C_ValidCombination account : accounts) { list.add(new KeyNamePair(account.getC_ValidCombination_ID(), account.getCombination() + " - " + account.getDescription())); } // Sort & return return list; } // getData public int getC_ValidCombination_ID() { return C_ValidCombination_ID; } } // MAccountLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAccountLookup.java
1
请完成以下Java代码
protected BeanManager getBeanManager() { return BeanManagerLookup.getBeanManager(); } protected javax.el.ELResolver getWrappedResolver() { BeanManager beanManager = getBeanManager(); javax.el.ELResolver resolver = beanManager.getELResolver(); return resolver; } @Override public Class< ? > getCommonPropertyType(ELContext context, Object base) { return getWrappedResolver().getCommonPropertyType(wrapContext(context), base); } @Override public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base) { return getWrappedResolver().getFeatureDescriptors(wrapContext(context), base); } @Override public Class< ? > getType(ELContext context, Object base, Object property) { return getWrappedResolver().getType(wrapContext(context), base, property); } @Override public Object getValue(ELContext context, Object base, Object property) { //we need to resolve a bean only for the first "member" of expression, e.g. bean.property1.property2 if (base == null) { Object result = ProgrammaticBeanLookup.lookup(property.toString(), getBeanManager()); if (result != null) { context.setPropertyResolved(true); } return result;
} else { return null; } } @Override public boolean isReadOnly(ELContext context, Object base, Object property) { return getWrappedResolver().isReadOnly(wrapContext(context), base, property); } @Override public void setValue(ELContext context, Object base, Object property, Object value) { getWrappedResolver().setValue(wrapContext(context), base, property, value); } @Override public Object invoke(ELContext context, Object base, Object method, java.lang.Class< ? >[] paramTypes, Object[] params) { return getWrappedResolver().invoke(wrapContext(context), base, method, paramTypes, params); } protected javax.el.ELContext wrapContext(ELContext context) { return new ElContextDelegate(context, getWrappedResolver()); } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\el\CdiResolver.java
1
请完成以下Java代码
public boolean isMatching(@NonNull final DataEntryTab tab) { return isMatching(tab.getInternalName()) || isMatching(tab.getCaption()); } public boolean isMatching(@NonNull final DataEntrySubTab subTab) { return isMatching(subTab.getInternalName()) || isMatching(subTab.getCaption()); } public boolean isMatching(@NonNull final DataEntrySection section) { return isMatching(section.getInternalName()) || isMatching(section.getCaption()); } public boolean isMatching(@NonNull final DataEntryLine line) { return isMatching(String.valueOf(line.getSeqNo())); } public boolean isMatching(@NonNull final DataEntryField field) { return isAny() || isMatching(field.getCaption()); } private boolean isMatching(final ITranslatableString trl) { if (isAny()) { return true;
} if (isMatching(trl.getDefaultValue())) { return true; } for (final String adLanguage : trl.getAD_Languages()) { if (isMatching(trl.translate(adLanguage))) { return true; } } return false; } @VisibleForTesting boolean isMatching(final String name) { if (isAny()) { return true; } final String nameNorm = normalizeString(name); if (nameNorm == null) { return false; } return pattern.equalsIgnoreCase(nameNorm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\impexp\NamePattern.java
1
请完成以下Java代码
public class ParserException extends DeviceException { /** * */ private static final long serialVersionUID = 6780262709879240414L; /** * Create a new exception. The parameters match the method parameters of {@link IParser#parse(ICmd, String, String, Class)}. * * @param cmd * @param stringToParse * @param elementName * @param clazz * @param cause */ public ParserException(final ICmd cmd, final String stringToParse,
final String elementName, final Class<?> clazz, final Throwable cause) { super(buildMessage(cmd, stringToParse, elementName, clazz, cause), cause); } private static String buildMessage(final ICmd cmd, final String stringToParse, final String elementName, final Class<?> clazz, final Throwable cause) { final String exceptionClass = cause == null ? "<throwable class NULL>" : cause.getClass().getName(); return StringUtils.formatMessage("Caught {} while parsing elementName={} from stringToParse={}; (cmd={})", exceptionClass, elementName, stringToParse, cmd); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\impl\ParserException.java
1