instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public static List<IValidationRule> unbox(@Nullable final IValidationRule rule) { if (rule == null || NullValidationRule.isNull(rule)) { return ImmutableList.of(); } final ArrayList<IValidationRule> result = new ArrayList<>(); unboxAndAppendToList(rule, result); return result; } public static List<IValidationRule> unbox(@Nullable final Collection<IValidationRule> rules) { if (rules == null || rules.isEmpty()) { return ImmutableList.of(); } final ArrayList<IValidationRule> result = new ArrayList<>(); for (final IValidationRule rule : rules) { unboxAndAppendToList(rule, result); } return result; } private static void unboxAndAppendToList(@Nullable final IValidationRule rule, @NonNull final ArrayList<IValidationRule> list) { if (rule instanceof CompositeValidationRule) { final CompositeValidationRule compositeRule = (CompositeValidationRule)rule; for (final IValidationRule childRule : compositeRule.rules) { unboxAndAppendToList(childRule, list); } } else if (rule != null && !NullValidationRule.isNull(rule)) { list.add(rule); } } @SuppressWarnings("UnusedReturnValue") public static final class Builder { private final List<IValidationRule> rules = new ArrayList<>(); private Builder() {} public IValidationRule build() { if (rules.isEmpty()) { return NullValidationRule.instance; } else if (rules.size() == 1) { return rules.get(0); } else { return new CompositeValidationRule(this); } } public Builder add(final IValidationRule rule) { add(rule, false); return this; } public Builder addExploded(final IValidationRule rule) { add(rule, true); return this; }
private Builder add(final IValidationRule rule, final boolean explodeComposite) { // Don't add null rules if (NullValidationRule.isNull(rule)) { return this; } // Don't add if already exists if (rules.contains(rule)) { return this; } if (explodeComposite && rule instanceof CompositeValidationRule) { final CompositeValidationRule compositeRule = (CompositeValidationRule)rule; addAll(compositeRule.getValidationRules(), true); } else { rules.add(rule); } return this; } private Builder addAll(final Collection<IValidationRule> rules) { return addAll(rules, false); } private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite) { rules.forEach(includedRule -> add(includedRule, explodeComposite)); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java
1
请完成以下Java代码
public Integer delete(Long id) { return super.deleteById(id); } /** * 更新用户 * * @param user 用户对象 * @param id 主键id * @return 操作影响行数 */ public Integer update(User user, Long id) { return super.updateById(user, id, true); } /** * 根据主键获取用户
* * @param id 主键id * @return id对应的用户 */ public User selectById(Long id) { return super.findOneById(id); } /** * 根据查询条件获取用户列表 * * @param user 用户查询条件 * @return 用户列表 */ public List<User> selectUserList(User user) { return super.findByExample(user); } }
repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\dao\UserDao.java
1
请完成以下Java代码
protected AbstractEngineConfiguration getEngineConfigurationForAllType(CommandContext commandContext) { AbstractEngineConfiguration engineConfiguration = commandContext.getEngineConfigurations().get(ScopeTypes.BPMN); if (engineConfiguration == null) { engineConfiguration = commandContext.getEngineConfigurations().get(ScopeTypes.CMMN); if (engineConfiguration == null) { engineConfiguration = getFirstEngineConfigurationWithByteArrayEntityManager(commandContext); } } if (engineConfiguration == null) { throw new IllegalStateException("Cannot initialize byte array. No engine configuration found"); } return engineConfiguration; } protected AbstractEngineConfiguration getFirstEngineConfigurationWithByteArrayEntityManager(CommandContext commandContext) { AbstractEngineConfiguration engineConfiguration = null; for (AbstractEngineConfiguration possibleEngineConfiguration : commandContext.getEngineConfigurations().values()) { if (possibleEngineConfiguration.getByteArrayEntityManager() != null) { engineConfiguration = possibleEngineConfiguration; break;
} } if (engineConfiguration == null) { throw new IllegalStateException("Cannot initialize byte array. No engine configuration found"); } return engineConfiguration; } @Override public String toString() { return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]"); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\ByteArrayRef.java
1
请完成以下Java代码
public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** MediaType AD_Reference_ID=388 */ public static final int MEDIATYPE_AD_Reference_ID=388; /** image/gif = GIF */ public static final String MEDIATYPE_ImageGif = "GIF"; /** image/jpeg = JPG */ public static final String MEDIATYPE_ImageJpeg = "JPG"; /** image/png = PNG */ public static final String MEDIATYPE_ImagePng = "PNG"; /** application/pdf = PDF */ public static final String MEDIATYPE_ApplicationPdf = "PDF"; /** text/css = CSS */ public static final String MEDIATYPE_TextCss = "CSS"; /** text/js = JS */ public static final String MEDIATYPE_TextJs = "JS"; /** Set Media Type. @param MediaType Defines the media type for the browser */ public void setMediaType (String MediaType) { set_Value (COLUMNNAME_MediaType, MediaType); } /** Get Media Type.
@return Defines the media type for the browser */ public String getMediaType () { return (String)get_Value(COLUMNNAME_MediaType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media.java
1
请完成以下Java代码
protected BatchStatisticsQuery createNewQuery(ProcessEngine engine) { return engine.getManagementService().createBatchStatisticsQuery(); } protected void applyFilters(BatchStatisticsQuery 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(); } if (userId != null) { query.createdBy(userId); } if (startedBefore != null) { query.startedBefore(startedBefore); } if (startedAfter != null) {
query.startedAfter(startedAfter); } if (TRUE.equals(withFailures)) { query.withFailures(); } if (TRUE.equals(withoutFailures)) { query.withoutFailures(); } } protected void applySortBy(BatchStatisticsQuery 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(); } else if (sortBy.equals(SORT_BY_START_TIME_VALUE)) { query.orderByStartTime(); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchStatisticsQueryDto.java
1
请完成以下Java代码
public Date getCurrentDate() { return new Date(); } @JsonFormat(shape = JsonFormat.Shape.NUMBER) public Date getDateNum() { return new Date(); } } @JsonFormat(with = JsonFormat.Feature.ACCEPT_CASE_INSENSITIVE_PROPERTIES) class UserIgnoreCase { private String firstName; private String lastName; @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ") private Date createdDate; public UserIgnoreCase() { } public UserIgnoreCase(String firstName, String lastName) { this.firstName = firstName; this.lastName = lastName; this.createdDate = new Date(); } public String getFirstName() {
return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Date getCreatedDate() { return createdDate; } @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd@HH:mm:ss.SSSZ", locale = "en_GB") public Date getCurrentDate() { return new Date(); } @JsonFormat(shape = JsonFormat.Shape.NUMBER) public Date getDateNum() { return new Date(); } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\format\User.java
1
请完成以下Java代码
protected String doIt() { getView().streamByIds(getSelectedRowIds()) .map(row -> row.getId().toInt()) .distinct() .forEach(this::createQuarantineHUsByLotNoQuarantineId); ddOrderService.createQuarantineDDOrderForHUs(husToQuarantine); setInvoiceCandsInDispute(); return MSG_OK; } private void setInvoiceCandsInDispute() { husToQuarantine.stream().map(HUToDistribute::getHu) .flatMap(hu -> huInOutDAO.retrieveInOutLinesForHU(hu).stream()) .forEach(invoiceCandBL::markInvoiceCandInDisputeForReceiptLine); } @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } private void createQuarantineHUsByLotNoQuarantineId(final int lotNoQuarantineId) { final LotNumberQuarantine lotNoQuarantine = lotNoQuarantineRepo.getById(lotNoQuarantineId); final I_M_Attribute lotNoAttribute = lotNumberDateAttributeDAO.getLotNumberAttribute(); if (lotNoAttribute == null) { throw new AdempiereException("Not lotNo attribute found."); } final List<I_M_HU> husForAttributeStringValue = retrieveHUsForAttributeStringValue( lotNoQuarantine.getProductId(), lotNoAttribute, lotNoQuarantine.getLotNo()); for (final I_M_HU hu : husForAttributeStringValue) { final HuId huId = HuId.ofRepoId(hu.getM_HU_ID()); if (ddOrderMoveScheduleService.isScheduledToMove(huId)) {
// the HU is already quarantined continue; } final List<de.metas.handlingunits.model.I_M_InOutLine> inOutLinesForHU = huInOutDAO.retrieveInOutLinesForHU(hu); if (Check.isEmpty(inOutLinesForHU)) { continue; } huLotNoQuarantineService.markHUAsQuarantine(hu); final I_M_InOut firstReceipt = inOutLinesForHU.get(0).getM_InOut(); final BPartnerLocationId bpLocationId = BPartnerLocationId.ofRepoId(firstReceipt.getC_BPartner_ID(), firstReceipt.getC_BPartner_Location_ID()); husToQuarantine.add(HUToDistribute.builder() .hu(hu) .quarantineLotNo(lotNoQuarantine) .bpartnerLocationId(bpLocationId) .build()); } } private List<I_M_HU> retrieveHUsForAttributeStringValue( final int productId, final I_M_Attribute attribute, final String value) { final IHUQueryBuilder huQueryBuilder = Services.get(IHandlingUnitsDAO.class) .createHUQueryBuilder() .addOnlyWithAttribute(attribute, value) .addHUStatusesToInclude(ImmutableList.of(X_M_HU.HUSTATUS_Picked, X_M_HU.HUSTATUS_Active)); if (productId > 0) { huQueryBuilder.addOnlyWithProductId(ProductId.ofRepoId(productId)); } return huQueryBuilder.list(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\product\process\WEBUI_M_Product_LotNumber_Quarantine.java
1
请完成以下Java代码
public static Optional<CCacheStatsOrderBy> parse(@Nullable final String string) { final String stringNorm = StringUtils.trimBlankToNull(string); if (stringNorm == null) { return Optional.empty(); } try { final ImmutableList<Part> parts = Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToStream(stringNorm) .map(Part::parse) .collect(ImmutableList.toImmutableList()); return Optional.of(new CCacheStatsOrderBy(parts)); } catch (final Exception ex) { throw new AdempiereException("Invalid order by string `" + string + "`", ex); } } @Override public int compare(final CCacheStats o1, final CCacheStats o2) { return getActualComparator().compare(o1, o2); } private Comparator<CCacheStats> getActualComparator() { Comparator<CCacheStats> comparator = this._actualComparator; if (comparator == null) { comparator = this._actualComparator = createActualComparator(); } return comparator; } private Comparator<CCacheStats> createActualComparator() { Comparator<CCacheStats> result = parts.get(0).toComparator(); for (int i = 1; i < parts.size(); i++) { final Comparator<CCacheStats> partComparator = parts.get(i).toComparator(); result = result.thenComparing(partComparator); } return result; } // // // public enum Field { name, size, hitRate, missRate, } @NonNull @Value(staticConstructor = "of") public static class Part { @NonNull Field field; boolean ascending; Comparator<CCacheStats> toComparator() { Comparator<CCacheStats> comparator; switch (field) { case name: comparator = Comparator.comparing(CCacheStats::getName); break; case size: comparator = Comparator.comparing(CCacheStats::getSize); break; case hitRate:
comparator = Comparator.comparing(CCacheStats::getHitRate); break; case missRate: comparator = Comparator.comparing(CCacheStats::getMissRate); break; default: throw new AdempiereException("Unknown field type!"); } if (!ascending) { comparator = comparator.reversed(); } return comparator; } static Part parse(@NonNull final String string) { final String stringNorm = StringUtils.trimBlankToNull(string); if (stringNorm == null) { throw new AdempiereException("Invalid part: `" + string + "`"); } final String fieldName; final boolean ascending; if (stringNorm.charAt(0) == '+') { fieldName = stringNorm.substring(1); ascending = true; } else if (stringNorm.charAt(0) == '-') { fieldName = stringNorm.substring(1); ascending = false; } else { fieldName = stringNorm; ascending = true; } final Field field = Field.valueOf(fieldName); return of(field, ascending); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CCacheStatsOrderBy.java
1
请完成以下Java代码
public class DeleteDeploymentCmd implements Command<Void>, Serializable { private final static TransactionLogger TX_LOG = ProcessEngineLogger.TX_LOGGER; private static final long serialVersionUID = 1L; protected String deploymentId; protected boolean cascade; protected boolean skipCustomListeners; protected boolean skipIoMappings; public DeleteDeploymentCmd(String deploymentId, boolean cascade, boolean skipCustomListeners, boolean skipIoMappings) { this.deploymentId = deploymentId; this.cascade = cascade; this.skipCustomListeners = skipCustomListeners; this.skipIoMappings = skipIoMappings; } public Void execute(final CommandContext commandContext) { ensureNotNull("deploymentId", deploymentId); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkDeleteDeployment(deploymentId); } UserOperationLogManager logManager = commandContext.getOperationLogManager(); List<PropertyChange> propertyChanges = Arrays.asList(new PropertyChange("cascade", null, cascade)); DeploymentEntity deployment = commandContext.getDeploymentManager().findDeploymentById(deploymentId); String tenantId = deployment != null ? deployment.getTenantId() : null; logManager.logDeploymentOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, deploymentId, tenantId, propertyChanges); commandContext .getDeploymentManager() .deleteDeployment(deploymentId, cascade, skipCustomListeners, skipIoMappings);
ProcessApplicationReference processApplicationReference = Context .getProcessEngineConfiguration() .getProcessApplicationManager() .getProcessApplicationForDeployment(deploymentId); DeleteDeploymentFailListener listener = new DeleteDeploymentFailListener(deploymentId, processApplicationReference, Context.getProcessEngineConfiguration().getCommandExecutorTxRequiresNew()); try { commandContext.runWithoutAuthorization(new UnregisterProcessApplicationCmd(deploymentId, false)); commandContext.runWithoutAuthorization(new UnregisterDeploymentCmd(Collections.singleton(deploymentId))); } finally { try { commandContext.getTransactionContext().addTransactionListener(TransactionState.ROLLED_BACK, listener); } catch (Exception e) { TX_LOG.debugTransactionOperation("Could not register transaction synchronization. Probably the TX has already been rolled back by application code."); listener.execute(commandContext); } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteDeploymentCmd.java
1
请完成以下Java代码
public void setMultiTier(boolean multiTier) { this.multiTier = multiTier; } private static final class LoginConfig extends Configuration { private boolean debug; private LoginConfig(boolean debug) { super(); this.debug = debug; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<String, String>(); options.put("storeKey", "true"); if (this.debug) { options.put("debug", "true"); } return new AppConfigurationEntry[] { new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options), }; } } static final class KerberosClientCallbackHandler implements CallbackHandler { private String username; private String password; private KerberosClientCallbackHandler(String username, String password) { this.username = username; this.password = password; } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) { if (callback instanceof NameCallback) { NameCallback ncb = (NameCallback) callback; ncb.setName(this.username); } else if (callback instanceof PasswordCallback) { PasswordCallback pwcb = (PasswordCallback) callback; pwcb.setPassword(this.password.toCharArray()); } else { throw new UnsupportedCallbackException(callback, "We got a " + callback.getClass().getCanonicalName() + ", but only NameCallback and PasswordCallback is supported"); } } } } }
repos\spring-security-main\kerberos\kerberos-core\src\main\java\org\springframework\security\kerberos\authentication\sun\SunJaasKerberosClient.java
1
请完成以下Java代码
public class CopyOnWriteBenchmark { @State(Scope.Thread) public static class MyState { CopyOnWriteArrayList<Employee> employeeList = new CopyOnWriteArrayList<>(); long iterations = 100000; Employee employee = new Employee(100L, "Harry"); int employeeIndex = -1; @Setup(Level.Trial) public void setUp() { for (long i = 0; i < iterations; i++) { employeeList.add(new Employee(i, "John")); } employeeList.add(employee); employeeIndex = employeeList.indexOf(employee); } } @Benchmark public void testAdd(MyState state) { state.employeeList.add(new Employee(state.iterations + 1, "John")); } @Benchmark public void testAddAt(MyState state) { state.employeeList.add((int) (state.iterations), new Employee(state.iterations, "John")); }
@Benchmark public boolean testContains(MyState state) { return state.employeeList.contains(state.employee); } @Benchmark public int testIndexOf(MyState state) { return state.employeeList.indexOf(state.employee); } @Benchmark public Employee testGet(MyState state) { return state.employeeList.get(state.employeeIndex); } @Benchmark public boolean testRemove(MyState state) { return state.employeeList.remove(state.employee); } public static void main(String[] args) throws Exception { Options options = new OptionsBuilder() .include(CopyOnWriteBenchmark.class.getSimpleName()).threads(1) .forks(1).shouldFailOnError(true) .shouldDoGC(true) .jvmArgs("-server").build(); new Runner(options).run(); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\performance\CopyOnWriteBenchmark.java
1
请完成以下Java代码
public String getCity_7bitlc() { return city_7bitlc; } public void setCity_7bitlc(String city_7bitlc) { this.city_7bitlc = city_7bitlc; } public String getStringRepresentation() { return stringRepresentation; } public void setStringRepresentation(String stringRepresentation) { this.stringRepresentation = stringRepresentation; } @Override public boolean equals(Object obj) { if (! (obj instanceof GeodbObject)) return false; if (this == obj) return true; //
GeodbObject go = (GeodbObject)obj; return this.geodb_loc_id == go.geodb_loc_id && this.zip.equals(go.zip) ; } @Override public String toString() { String str = getStringRepresentation(); if (str != null) return str; return city+", "+zip+" - "+countryName; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\gui\search\GeodbObject.java
1
请完成以下Java代码
public ViewId getViewId() { return viewId; } public void setFullyChanged() { fullyChanged = true; } public boolean isHeaderPropertiesChanged() { return headerPropertiesChanged; } public void setHeaderPropertiesChanged() { this.headerPropertiesChanged = true; } public boolean isFullyChanged() { return fullyChanged; } public boolean hasChanges() { if (fullyChanged) { return true; } if (headerPropertiesChanged) { return true; } return changedRowIds != null && !changedRowIds.isEmpty(); } public void addChangedRowIds(@Nullable final DocumentIdsSelection rowIds) { // Don't collect rowIds if this was already flagged as fully changed. if (fullyChanged) { return; } if (rowIds == null || rowIds.isEmpty()) { return; } else if (rowIds.isAll()) { fullyChanged = true; changedRowIds = null; } else { if (changedRowIds == null) { changedRowIds = new HashSet<>(); } changedRowIds.addAll(rowIds.toSet()); } }
public void addChangedRowIds(final Collection<DocumentId> rowIds) { if (rowIds.isEmpty()) { return; } if (changedRowIds == null) { changedRowIds = new HashSet<>(); } changedRowIds.addAll(rowIds); } public void addChangedRowId(@NonNull final DocumentId rowId) { if (changedRowIds == null) { changedRowIds = new HashSet<>(); } changedRowIds.add(rowId); } public DocumentIdsSelection getChangedRowIds() { final boolean fullyChanged = this.fullyChanged; final Set<DocumentId> changedRowIds = this.changedRowIds; if (fullyChanged) { return DocumentIdsSelection.ALL; } else if (changedRowIds == null || changedRowIds.isEmpty()) { return DocumentIdsSelection.EMPTY; } else { return DocumentIdsSelection.of(changedRowIds); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChanges.java
1
请在Spring Boot框架中完成以下Java代码
public TimeBookingId save(@NonNull final TimeBooking timeBooking) { final I_S_TimeBooking record = InterfaceWrapperHelper.loadOrNew(timeBooking.getTimeBookingId(), I_S_TimeBooking.class); record.setAD_Org_ID(timeBooking.getOrgId().getRepoId()); record.setAD_User_Performing_ID(timeBooking.getPerformingUserId().getRepoId()); record.setS_Issue_ID(timeBooking.getIssueId().getRepoId()); record.setHoursAndMinutes(timeBooking.getHoursAndMins()); record.setBookedSeconds(BigDecimal.valueOf(timeBooking.getBookedSeconds())); record.setBookedDate(Timestamp.from(timeBooking.getBookedDate())); InterfaceWrapperHelper.saveRecord(record); return TimeBookingId.ofRepoId(record.getS_TimeBooking_ID()); } public Optional<TimeBooking> getByIdOptional(@NonNull final TimeBookingId timeBookingId) { return queryBL .createQueryBuilder(I_S_TimeBooking.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_TimeBooking_ID, timeBookingId.getRepoId()) .create() .firstOnlyOptional(I_S_TimeBooking.class) .map(this::buildTimeBooking); } public ImmutableList<TimeBooking> getAllByIssueId(@NonNull final IssueId issueId) { return queryBL .createQueryBuilder(I_S_TimeBooking.class)
.addOnlyActiveRecordsFilter() .addEqualsFilter(I_S_TimeBooking.COLUMNNAME_S_Issue_ID, issueId.getRepoId()) .create() .list() .stream() .map(this::buildTimeBooking) .collect(ImmutableList.toImmutableList()); } private TimeBooking buildTimeBooking(@NonNull final I_S_TimeBooking record) { return TimeBooking.builder() .timeBookingId(TimeBookingId.ofRepoId(record.getS_TimeBooking_ID())) .issueId(IssueId.ofRepoId(record.getS_Issue_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .performingUserId(UserId.ofRepoId(record.getAD_User_Performing_ID())) .bookedDate(record.getBookedDate().toInstant()) .bookedSeconds(record.getBookedSeconds().longValue()) .hoursAndMins(record.getHoursAndMinutes()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\TimeBookingRepository.java
2
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setAD_NotificationGroup_CC_ID (final int AD_NotificationGroup_CC_ID) { if (AD_NotificationGroup_CC_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_CC_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_CC_ID, AD_NotificationGroup_CC_ID); } @Override public int getAD_NotificationGroup_CC_ID() { return get_ValueAsInt(COLUMNNAME_AD_NotificationGroup_CC_ID); } @Override public org.compiere.model.I_AD_NotificationGroup getAD_NotificationGroup() { return get_ValueAsPO(COLUMNNAME_AD_NotificationGroup_ID, org.compiere.model.I_AD_NotificationGroup.class); } @Override public void setAD_NotificationGroup(final org.compiere.model.I_AD_NotificationGroup AD_NotificationGroup) { set_ValueFromPO(COLUMNNAME_AD_NotificationGroup_ID, org.compiere.model.I_AD_NotificationGroup.class, AD_NotificationGroup); } @Override public void setAD_NotificationGroup_ID (final int AD_NotificationGroup_ID) { if (AD_NotificationGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_NotificationGroup_ID, AD_NotificationGroup_ID); } @Override public int getAD_NotificationGroup_ID() { return get_ValueAsInt(COLUMNNAME_AD_NotificationGroup_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_User_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_NotificationGroup_CC.java
1
请完成以下Java代码
public BPPurchaseSchedule save(@NonNull final BPPurchaseSchedule schedule) { final I_C_BP_PurchaseSchedule scheduleRecord = createOrUpdateRecord(schedule); saveRecord(scheduleRecord); return schedule.toBuilder() .bpPurchaseScheduleId(BPPurchaseScheduleId.ofRepoId(scheduleRecord.getC_BP_PurchaseSchedule_ID())) .build(); } private I_C_BP_PurchaseSchedule createOrUpdateRecord(@NonNull final BPPurchaseSchedule schedule) { final I_C_BP_PurchaseSchedule scheduleRecord; if (schedule.getBpPurchaseScheduleId() != null) { final int repoId = schedule.getBpPurchaseScheduleId().getRepoId(); scheduleRecord = load(repoId, I_C_BP_PurchaseSchedule.class); } else { scheduleRecord = newInstance(I_C_BP_PurchaseSchedule.class); } scheduleRecord.setC_BPartner_ID(BPartnerId.toRepoIdOr(schedule.getBpartnerId(), 0)); scheduleRecord.setValidFrom(TimeUtil.asTimestamp(schedule.getValidFrom())); scheduleRecord.setReminderTimeInMin((int)schedule.getReminderTime().toMinutes()); final Frequency frequency = schedule.getFrequency(); scheduleRecord.setFrequencyType(toFrequencyTypeString(frequency.getType())); if (frequency.getType() == FrequencyType.Weekly) { scheduleRecord.setFrequency(frequency.getEveryNthWeek()); } else if (frequency.getType() == FrequencyType.Monthly) { scheduleRecord.setFrequency(frequency.getEveryNthMonth()); scheduleRecord.setMonthDay(frequency.getOnlyDaysOfMonth() .stream() .findFirst() .orElseThrow(() -> new AdempiereException("No month of the day " + Frequency.class + ": " + frequency))); } final ImmutableSet<DayOfWeek> daysOfWeek = frequency.getOnlyDaysOfWeek(); setDaysOfWeek(scheduleRecord, daysOfWeek); return scheduleRecord;
} private static void setDaysOfWeek(@NonNull final I_C_BP_PurchaseSchedule scheduleRecord, @NonNull final ImmutableSet<DayOfWeek> daysOfWeek) { if (daysOfWeek.contains(DayOfWeek.MONDAY)) { scheduleRecord.setOnMonday(true); } if (daysOfWeek.contains(DayOfWeek.TUESDAY)) { scheduleRecord.setOnTuesday(true); } if (daysOfWeek.contains(DayOfWeek.WEDNESDAY)) { scheduleRecord.setOnWednesday(true); } if (daysOfWeek.contains(DayOfWeek.THURSDAY)) { scheduleRecord.setOnThursday(true); } if (daysOfWeek.contains(DayOfWeek.FRIDAY)) { scheduleRecord.setOnFriday(true); } if (daysOfWeek.contains(DayOfWeek.SATURDAY)) { scheduleRecord.setOnSaturday(true); } if (daysOfWeek.contains(DayOfWeek.SUNDAY)) { scheduleRecord.setOnSunday(true); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\BPPurchaseScheduleRepository.java
1
请完成以下Java代码
public IModelInterceptor registerHandler(final ICounterDocHandler handler, final String tableName) { Check.assumeNotNull(handler, "Param 'handler' is not null"); Check.assumeNotNull(tableName, "Param 'tableName' is not null"); final ICounterDocHandler oldHandler = handlers.put(tableName, handler); Check.errorIf(oldHandler != null, "Can't register ICounterDocumentHandler {} for table name {}, because ICounterDocumentHandler {} was already regoistered", handler, tableName, oldHandler); final CounterDocHandlerInterceptor counterDocHandlerInterceptor = CounterDocHandlerInterceptor.builder() .setTableName(I_C_Order.Table_Name) .setAsync(true) .build(); return counterDocHandlerInterceptor; } /** *
* @param document * @return may return the {@link NullCounterDocumentHandler}, but never <code>null</code>. */ private Pair<ICounterDocHandler, IDocument> getHandlerOrNull(final Object document) { final String tableName = InterfaceWrapperHelper.getModelTableNameOrNull(document); if (Check.isEmpty(tableName) || !handlers.containsKey(tableName)) { return new Pair<ICounterDocHandler, IDocument>(NullCounterDocumentHandler.instance, null); } final IDocument docAction = Services.get(IDocumentBL.class).getDocumentOrNull(document); if (docAction == null) { return new Pair<ICounterDocHandler, IDocument>(NullCounterDocumentHandler.instance, null); } return new Pair<ICounterDocHandler, IDocument>(handlers.get(tableName), docAction); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\impl\CounterDocBL.java
1
请完成以下Java代码
public List<ChannelDefinition> executeList(CommandContext commandContext) { return CommandContextUtil.getChannelDefinitionEntityManager(commandContext).findChannelDefinitionsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getDeploymentId() { return deploymentId; } public Set<String> getDeploymentIds() { return deploymentIds; } public String getParentDeploymentId() { return parentDeploymentId; } public String getId() { return id; } public Set<String> getIds() { return ids; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public String getKey() { return key; } public String getKeyLike() { return keyLike; } public String getKeyLikeIgnoreCase() { return keyLikeIgnoreCase; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; } public Integer getVersion() { return version; } public Integer getVersionGt() { return versionGt; } public Integer getVersionGte() { return versionGte; } public Integer getVersionLt() { return versionLt; } public Integer getVersionLte() { return versionLte; } public boolean isLatest() { return latest; } public boolean isOnlyInbound() { return onlyInbound; }
public boolean isOnlyOutbound() { return onlyOutbound; } public String getImplementation() { return implementation; } public Date getCreateTime() { return createTime; } public Date getCreateTimeAfter() { return createTimeAfter; } public Date getCreateTimeBefore() { return createTimeBefore; } public String getResourceName() { return resourceName; } public String getResourceNameLike() { return resourceNameLike; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\ChannelDefinitionQueryImpl.java
1
请完成以下Java代码
public boolean supports(Class<?> authentication) { return OAuth2LoginAuthenticationToken.class.isAssignableFrom(authentication); } private OidcIdToken createOidcToken(ClientRegistration clientRegistration, OAuth2AccessTokenResponse accessTokenResponse) { JwtDecoder jwtDecoder = this.jwtDecoderFactory.createDecoder(clientRegistration); Jwt jwt = getJwt(accessTokenResponse, jwtDecoder); OidcIdToken idToken = new OidcIdToken(jwt.getTokenValue(), jwt.getIssuedAt(), jwt.getExpiresAt(), jwt.getClaims()); return idToken; } private Jwt getJwt(OAuth2AccessTokenResponse accessTokenResponse, JwtDecoder jwtDecoder) { try { Map<String, Object> parameters = accessTokenResponse.getAdditionalParameters();
return jwtDecoder.decode((String) parameters.get(OidcParameterNames.ID_TOKEN)); } catch (JwtException ex) { OAuth2Error invalidIdTokenError = new OAuth2Error(INVALID_ID_TOKEN_ERROR_CODE, ex.getMessage(), null); throw new OAuth2AuthenticationException(invalidIdTokenError, invalidIdTokenError.toString(), ex); } } static String createHash(String nonce) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] digest = md.digest(nonce.getBytes(StandardCharsets.US_ASCII)); return Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\OidcAuthorizationCodeAuthenticationProvider.java
1
请在Spring Boot框架中完成以下Java代码
class AdminParser extends AbstractSingleBeanDefinitionParser { private static final String CONNECTION_FACTORY_ATTRIBUTE = "connection-factory"; private static final String AUTO_STARTUP_ATTRIBUTE = "auto-startup"; private static final String IGNORE_DECLARATION_EXCEPTIONS = "ignore-declaration-exceptions"; @Override protected String getBeanClassName(Element element) { return "org.springframework.amqp.rabbit.core.RabbitAdmin"; } @Override protected boolean shouldGenerateId() { return false; } @Override protected boolean shouldGenerateIdAsFallback() { return true; } @Override protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) { String connectionFactoryRef = element.getAttribute(CONNECTION_FACTORY_ATTRIBUTE);
// At least one of 'templateRef' or 'connectionFactoryRef' attribute must be set. if (!StringUtils.hasText(connectionFactoryRef)) { parserContext.getReaderContext().error("A '" + CONNECTION_FACTORY_ATTRIBUTE + "' attribute must be set.", element); } if (StringUtils.hasText(connectionFactoryRef)) { // Use constructor with connectionFactory parameter builder.addConstructorArgReference(connectionFactoryRef); } String attributeValue; attributeValue = element.getAttribute(AUTO_STARTUP_ATTRIBUTE); if (StringUtils.hasText(attributeValue)) { builder.addPropertyValue("autoStartup", attributeValue); } NamespaceUtils.setValueIfAttributeDefined(builder, element, IGNORE_DECLARATION_EXCEPTIONS); NamespaceUtils.setValueIfAttributeDefined(builder, element, "explicit-declarations-only"); } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\config\AdminParser.java
2
请完成以下Java代码
public AdempiereServer[] getAll() { AdempiereServer[] retValue = new AdempiereServer[m_servers.size()]; m_servers.toArray(retValue); return retValue; } // getAll /** * Get Server with ID * * @param serverID server id * @return server or null */ public AdempiereServer getServer(String serverID) { if (serverID == null) return null; for (int i = 0; i < m_servers.size(); i++) { AdempiereServer server = m_servers.get(i); if (serverID.equals(server.getServerID())) return server; } return null; } // getServer /** * Remove Server with ID * * @param serverID server id */ public void removeServerWithId(@NonNull final String serverID) { int matchedIndex = -1; for (int i = 0; i < m_servers.size(); i++) { final AdempiereServer server = m_servers.get(i); if (serverID.equals(server.getServerID())) { matchedIndex = i; break; } } if (matchedIndex > -1) { m_servers.remove(matchedIndex); } } /** * String Representation * * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("AdempiereServerMgr["); sb.append("Servers=").append(m_servers.size()) .append(",ContextSize=").append(_ctx.size()) .append(",Started=").append(m_start) .append("]"); return sb.toString(); } // toString /** * Get Description * * @return description */ public String getDescription() {
return "1.4"; } // getDescription /** * Get Number Servers * * @return no of servers */ public String getServerCount() { int noRunning = 0; int noStopped = 0; for (int i = 0; i < m_servers.size(); i++) { AdempiereServer server = m_servers.get(i); if (server.isAlive()) noRunning++; else noStopped++; } String info = String.valueOf(m_servers.size()) + " - Running=" + noRunning + " - Stopped=" + noStopped; return info; } // getServerCount /** * Get start date * * @return start date */ public Timestamp getStartTime() { return new Timestamp(m_start.getTime()); } // getStartTime } // AdempiereServerMgr
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServerMgr.java
1
请在Spring Boot框架中完成以下Java代码
public class ProcessDefinitionImageResource extends BaseProcessDefinitionResource { @ApiOperation(value = "Get a process definition image", tags = { "Process Definitions" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates request was successful and the process-definitions are returned"), @ApiResponse(code = 404, message = "Indicates the requested process definition was not found.") }) @GetMapping(value = "/repository/process-definitions/{processDefinitionId}/image", produces = MediaType.IMAGE_PNG_VALUE) public ResponseEntity<byte[]> getModelResource(@ApiParam(name = "processDefinitionId") @PathVariable String processDefinitionId) { ProcessDefinition processDefinition = getProcessDefinitionFromRequest(processDefinitionId); try (final InputStream imageStream = repositoryService.getProcessDiagram(processDefinition.getId())) { if (imageStream != null) { HttpHeaders responseHeaders = new HttpHeaders(); responseHeaders.set("Content-Type", MediaType.IMAGE_PNG_VALUE);
try { return new ResponseEntity<>(IOUtils.toByteArray(imageStream), responseHeaders, HttpStatus.OK); } catch (Exception e) { throw new FlowableException("Error reading image stream", e); } } else { throw new FlowableIllegalArgumentException("Process definition with id '" + processDefinition.getId() + "' has no image."); } } catch (IOException e) { throw new FlowableException("Error reading image stream", e); } } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\repository\ProcessDefinitionImageResource.java
2
请完成以下Java代码
public String printArrayUsingForEachLoop(String[] empArray) { StringBuilder result = new StringBuilder(); for (String arr : empArray) { result.append(arr).append("\n"); } return result.toString().trim(); } // Print array content using Arrays.toString public String printArrayUsingToString(int[] empIDs) { return Arrays.toString(empIDs); } // Print array content using Arrays.asList public String printArrayUsingAsList(String[] empArray) {
return Arrays.asList(empArray).toString(); } // Print array content using Streams public String printArrayUsingStreams(String[] empArray) { StringBuilder result = new StringBuilder(); Arrays.stream(empArray).forEach(e -> result.append(e).append("\n")); return result.toString().trim(); } // Print array content using string.join() public String printArrayUsingJoin(String[] empArray) { return String.join("\n", empArray).trim(); } }
repos\tutorials-master\core-java-modules\core-java-arrays-guides\src\main\java\com\baeldung\printarrays\PrintArrayJava.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonPickingJobStep { @NonNull String pickingStepId; @NonNull JsonCompleteStatus completeStatus; @NonNull String productId; @NonNull String productName; @NonNull String uom; @NonNull BigDecimal qtyToPick; @NonNull JsonPickingJobStepPickFrom mainPickFrom; @NonNull List<JsonPickingJobStepPickFrom> pickFromAlternatives; public static JsonPickingJobStep of( final PickingJobStep step, final JsonOpts jsonOpts, @NonNull final Function<UomId, ITranslatableString> getUOMSymbolById) { final String adLanguage = jsonOpts.getAdLanguage();
final JsonPickingJobStepPickFrom mainPickFrom = JsonPickingJobStepPickFrom.of(step.getPickFrom(PickingJobStepPickFromKey.MAIN), jsonOpts, getUOMSymbolById); final List<JsonPickingJobStepPickFrom> pickFromAlternatives = step.getPickFromKeys() .stream() .filter(PickingJobStepPickFromKey::isAlternative) .map(step::getPickFrom) .map(pickFrom -> JsonPickingJobStepPickFrom.of(pickFrom, jsonOpts, getUOMSymbolById)) .collect(ImmutableList.toImmutableList()); return builder() .pickingStepId(step.getId().getAsString()) .completeStatus(JsonCompleteStatus.of(step.getProgress())) .productId(step.getProductId().getAsString()) .productName(step.getProductName().translate(adLanguage)) .uom(step.getQtyToPick().getUOMSymbol()) .qtyToPick(step.getQtyToPick().toBigDecimal()) .mainPickFrom(mainPickFrom) .pickFromAlternatives(pickFromAlternatives) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\rest_api\json\JsonPickingJobStep.java
2
请完成以下Java代码
protected void prepare() { // Defaults p_DunningDate = Env.getContextAsDate(getCtx(), "#Date"); p_IsFullUpdate = false; for (ProcessInfoParameter para : getParametersAsArray()) { if (para.getParameter() == null) { // skip if no parameter value continue; } final String name = para.getParameterName(); if (PARAM_DunningDate.equals(name)) { p_DunningDate = para.getParameterAsTimestamp(); } else if (PARAM_IsFullUpdate.equals(name)) { p_IsFullUpdate = para.getParameterAsBoolean(); } } } @Override protected String doIt() { final IDunningDAO dunningDAO = Services.get(IDunningDAO.class); // // Generate dunning candidates for (final I_C_Dunning dunning : dunningDAO.retrieveDunnings()) {
for (final I_C_DunningLevel dunningLevel : dunningDAO.retrieveDunningLevels(dunning)) { generateCandidates(dunningLevel); } } return MSG_OK; } private void generateCandidates(final I_C_DunningLevel dunningLevel) { final IDunningBL dunningBL = Services.get(IDunningBL.class); trxManager.runInNewTrx(new TrxRunnableAdapter() { @Override public void run(String localTrxName) throws Exception { final IDunningContext context = dunningBL.createDunningContext(getCtx(), dunningLevel, p_DunningDate, get_TrxName()); context.setProperty(IDunningCandidateProducer.CONTEXT_FullUpdate, p_IsFullUpdate); final int countDelete = Services.get(IDunningDAO.class).deleteNotProcessedCandidates(context, dunningLevel); addLog("@C_DunningLevel@ " + dunningLevel.getName() + ": " + countDelete + " record(s) deleted"); final int countCreateUpdate = dunningBL.createDunningCandidates(context); addLog("@C_DunningLevel@ " + dunningLevel.getName() + ": " + countCreateUpdate + " record(s) created/updated"); } }); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\process\C_Dunning_Candidate_Create.java
1
请在Spring Boot框架中完成以下Java代码
public void setCredentials(List<Credential> credentials) { this.credentials = credentials; } public static class Credential { /** * Locations of the X.509 certificate used for verification of incoming * SAML messages. */ private @Nullable Resource certificate; public @Nullable Resource getCertificateLocation() { return this.certificate; } public void setCertificateLocation(@Nullable Resource certificate) { this.certificate = certificate; } } } } /** * Single logout details. */ public static class Singlelogout { /** * Location where SAML2 LogoutRequest gets sent to. */ private @Nullable String url; /** * Location where SAML2 LogoutResponse gets sent to. */ private @Nullable String responseUrl;
/** * Whether to redirect or post logout requests. */ private @Nullable Saml2MessageBinding binding; public @Nullable String getUrl() { return this.url; } public void setUrl(@Nullable String url) { this.url = url; } public @Nullable String getResponseUrl() { return this.responseUrl; } public void setResponseUrl(@Nullable String responseUrl) { this.responseUrl = responseUrl; } public @Nullable Saml2MessageBinding getBinding() { return this.binding; } public void setBinding(@Nullable Saml2MessageBinding binding) { this.binding = binding; } } }
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyProperties.java
2
请完成以下Java代码
public CountResultDto getCleanableHistoricBatchesReportCount(UriInfo uriInfo) { CleanableHistoricBatchReportDto queryDto = new CleanableHistoricBatchReportDto(objectMapper, uriInfo.getQueryParameters()); queryDto.setObjectMapper(objectMapper); CleanableHistoricBatchReport query = queryDto.toQuery(processEngine); long count = query.count(); CountResultDto result = new CountResultDto(); result.setCount(count); return result; } @Override public BatchDto setRemovalTimeAsync(SetRemovalTimeToHistoricBatchesDto dto) { HistoryService historyService = processEngine.getHistoryService(); HistoricBatchQuery historicBatchQuery = null; if (dto.getHistoricBatchQuery() != null) { historicBatchQuery = dto.getHistoricBatchQuery().toQuery(processEngine); } SetRemovalTimeSelectModeForHistoricBatchesBuilder builder = historyService.setRemovalTimeToHistoricBatches(); if (dto.isCalculatedRemovalTime()) { builder.calculatedRemovalTime(); } Date removalTime = dto.getAbsoluteRemovalTime(); if (dto.getAbsoluteRemovalTime() != null) { builder.absoluteRemovalTime(removalTime);
} if (dto.isClearedRemovalTime()) { builder.clearedRemovalTime(); } builder.byIds(dto.getHistoricBatchIds()); builder.byQuery(historicBatchQuery); Batch batch = builder.executeAsync(); return BatchDto.fromBatch(batch); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoricBatchRestServiceImpl.java
1
请完成以下Java代码
public Method getMethod() { // Get if not expired { final WeakReference<Method> weakRef = methodRef.get(); final Method method = weakRef != null ? weakRef.get() : null; if (method != null) { return method; } } // Load the class try { final Class<?> clazz = classRef.getReferencedClass(); final Class<?>[] parameterTypes = parameterTypeRefs.stream() .map(parameterTypeRef -> parameterTypeRef.getReferencedClass()) .toArray(size -> new Class<?>[size]); final Method methodNew = clazz.getDeclaredMethod(methodName, parameterTypes); methodRef.set(new WeakReference<>(methodNew));
return methodNew; } catch (final Exception ex) { throw new IllegalStateException("Cannot load expired field: " + classRef + "/" + methodName + " (" + parameterTypeRefs + ")", ex); } } @VisibleForTesting void forget() { methodRef.set(null); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\reflect\MethodReference.java
1
请完成以下Java代码
public static void ensureValidIndividualResourceIds(Class<? extends ProcessEngineException> exceptionClass, String message, Collection<String> ids) { ensureNotNull(exceptionClass, message, "id", ids); for (String id : ids) { ensureValidIndividualResourceId(exceptionClass, message, id); } } public static void ensureWhitelistedResourceId(CommandContext commandContext, String resourceType, String resourceId) { String resourcePattern = determineResourceWhitelistPattern(commandContext.getProcessEngineConfiguration(), resourceType); Pattern PATTERN = Pattern.compile(resourcePattern); if (!PATTERN.matcher(resourceId).matches()) { throw generateException(ProcessEngineException.class, resourceType + " has an invalid id", "'" + resourceId + "'", "is not a valid resource identifier."); } } public static void ensureTrue(String message, boolean value) { if (!value) { throw new ProcessEngineException(message); } } public static void ensureFalse(String message, boolean value) { ensureTrue(message, !value); } protected static String determineResourceWhitelistPattern(ProcessEngineConfiguration processEngineConfiguration, String resourceType) { String resourcePattern = null; if (resourceType.equals("User")) { resourcePattern = processEngineConfiguration.getUserResourceWhitelistPattern(); } if (resourceType.equals("Group")) { resourcePattern = processEngineConfiguration.getGroupResourceWhitelistPattern(); } if (resourceType.equals("Tenant")) { resourcePattern = processEngineConfiguration.getTenantResourceWhitelistPattern(); } if (resourcePattern != null && !resourcePattern.isEmpty()) { return resourcePattern; } return processEngineConfiguration.getGeneralResourceWhitelistPattern(); }
protected static <T extends ProcessEngineException> T generateException(Class<T> exceptionClass, String message, String variableName, String description) { String formattedMessage = formatMessage(message, variableName, description); try { Constructor<T> constructor = exceptionClass.getConstructor(String.class); return constructor.newInstance(formattedMessage); } catch (Exception e) { throw LOG.exceptionWhileInstantiatingClass(exceptionClass.getName(), e); } } protected static String formatMessage(String message, String variableName, String description) { return formatMessageElement(message, ": ") + formatMessageElement(variableName, " ") + description; } protected static String formatMessageElement(String element, String delimiter) { if (element != null && !element.isEmpty()) { return element.concat(delimiter); } else { return ""; } } public static void ensureActiveCommandContext(String operation) { if(Context.getCommandContext() == null) { throw LOG.notInsideCommandContext(operation); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\EnsureUtil.java
1
请完成以下Java代码
public void setEntityType (String EntityType) { set_Value (COLUMNNAME_EntityType, EntityType); } /** Get Entitaets-Art. @return Dictionary Entity Type; Determines ownership and synchronization */ public String getEntityType () { return (String)get_Value(COLUMNNAME_EntityType); } /** Set Field Value. @param FieldValue Field Value */ public void setFieldValue (String FieldValue) { set_Value (COLUMNNAME_FieldValue, FieldValue); } /** Get Field Value. @return Field Value */ public String getFieldValue () { return (String)get_Value(COLUMNNAME_FieldValue); } /** Set Value Format. @param FieldValueFormat Value Format */ public void setFieldValueFormat (String FieldValueFormat) { set_Value (COLUMNNAME_FieldValueFormat, FieldValueFormat); } /** Get Value Format. @return Value Format */ public String getFieldValueFormat () { return (String)get_Value(COLUMNNAME_FieldValueFormat); } /** Set Null Value. @param IsNullFieldValue Null Value */ public void setIsNullFieldValue (boolean IsNullFieldValue) { set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue)); } /** Get Null Value. @return Null Value */ public boolean isNullFieldValue () { Object oo = get_Value(COLUMNNAME_IsNullFieldValue); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Type AD_Reference_ID=540203 */ public static final int TYPE_AD_Reference_ID=540203; /** Set Field Value = SV */ public static final String TYPE_SetFieldValue = "SV"; /** Set Art. @param Type Type of Validation (SQL, Java Script, Java Language) */ public void setType (String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Type of Validation (SQL, Java Script, Java Language) */ public String getType () { return (String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Action.java
1
请完成以下Java代码
public <T extends RepoIdAware> T getValueAsRepoIdOrNull(final @NonNull IntFunction<T> repoIdMapper) { final int idInt = getValueAsInt(-1); if (idInt < 0) { return null; } return repoIdMapper.apply(idInt); } public <T extends ReferenceListAwareEnum> T getValueAsRefListOrNull(@NonNull final Function<String, T> mapper) { final String value = StringUtils.trimBlankToNull(getValueAsString()); if (value == null) { return null; } return mapper.apply(value); } public boolean isNullValues() { return value == null && (!isRangeOperator() || valueTo == null) && sqlWhereClause == null; } private boolean isRangeOperator() {return operator != null && operator.isRangeOperator();} // // // ------------------ // // public static final class Builder { private boolean joinAnd = true; private String fieldName; private Operator operator = Operator.EQUAL; @Nullable private Object value; @Nullable private Object valueTo; private Builder() { super(); } public DocumentFilterParam build() { return new DocumentFilterParam(this); } public Builder setJoinAnd(final boolean joinAnd) {
this.joinAnd = joinAnd; return this; } public Builder setFieldName(final String fieldName) { this.fieldName = fieldName; return this; } public Builder setOperator(@NonNull final Operator operator) { this.operator = operator; return this; } public Builder setOperator() { operator = valueTo != null ? Operator.BETWEEN : Operator.EQUAL; return this; } public Builder setValue(@Nullable final Object value) { this.value = value; return this; } public Builder setValueTo(@Nullable final Object valueTo) { this.valueTo = valueTo; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterParam.java
1
请完成以下Java代码
public class HUProducerDestination extends AbstractProducerDestination { public static final HUProducerDestination of(final I_M_HU_PI huPI) { return new HUProducerDestination(huPI); } public static final HUProducerDestination of(@NonNull final HuPackingInstructionsId packingInstructionsId) { final I_M_HU_PI huPI = Services.get(IHandlingUnitsDAO.class).getPackingInstructionById(packingInstructionsId); return new HUProducerDestination(huPI); } /** * @return producer which will create one VHU */ public static final HUProducerDestination ofVirtualPI() { return of(HuPackingInstructionsId.VIRTUAL) .setMaxHUsToCreate(1); // we want one VHU } private static final ArrayKey SHARED_CurrentHUKey = ArrayKey.of(0); private final AllocationStrategyFactory allocationStrategyFactory = SpringContextHolder.instance.getBean(AllocationStrategyFactory.class); private final I_M_HU_PI huPI; /** * Maximum number of HUs allowed to be created */ private int maxHUsToCreate = Integer.MAX_VALUE; private I_M_HU_Item parentHUItem; private HUProducerDestination(@NonNull final I_M_HU_PI huPI) { this.huPI = huPI; } @Override protected I_M_HU_PI getM_HU_PI() { return huPI; } @Override protected IAllocationResult loadHU(final I_M_HU hu, final IAllocationRequest request) { final IAllocationStrategy allocationStrategy = allocationStrategyFactory.createAllocationStrategy(AllocationDirection.INBOUND_ALLOCATION); return allocationStrategy.execute(hu, request); }
@Override protected ArrayKey extractCurrentHUKey(final IAllocationRequest request) { // NOTE: in case of maxHUsToCreate == 1 try to load all products in one HU return maxHUsToCreate == 1 ? SHARED_CurrentHUKey : super.extractCurrentHUKey(request); } @Override public boolean isAllowCreateNewHU() { // Check if we already reached the maximum number of HUs that we are allowed to create return getCreatedHUsCount() < maxHUsToCreate; } public HUProducerDestination setMaxHUsToCreate(final int maxHUsToCreate) { Check.assumeGreaterOrEqualToZero(maxHUsToCreate, "maxHUsToCreate"); this.maxHUsToCreate = maxHUsToCreate; return this; } /** * Then this producer creates a new HU, than i uses the given {@code parentHUItem} for the new HU's {@link I_M_HU#COLUMN_M_HU_Item_Parent_ID}. * * @param parentHUItem */ public HUProducerDestination setParent_HU_Item(final I_M_HU_Item parentHUItem) { this.parentHUItem = parentHUItem; return this; } @Override protected I_M_HU_Item getParent_HU_Item() { return parentHUItem; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\HUProducerDestination.java
1
请在Spring Boot框架中完成以下Java代码
public class MonoTransformer { private final UserService userService; private final BookService bookService; public MonoTransformer(UserService userService, BookService bookService) { this.userService = userService; this.bookService = bookService; } public Mono<BookBorrowResponse> borrowBook(String userId, String bookId) { return userService.getUser(userId) .flatMap(user -> { if (!user.isActive()) { return Mono.error(new RuntimeException("User is not an active member")); } return bookService.getBook(bookId); }) .flatMap(book -> { if (!book.isAvailable()) { return Mono.error(new RuntimeException("Book is not available")); } return Mono.just(new BookBorrowResponse(userId, bookId, "Accepted")); }); } public Mono<BookBorrowResponse> borrowBookZip(String userId, String bookId) { Mono<User> userMono = userService.getUser(userId) .switchIfEmpty(Mono.error(new RuntimeException("User not found"))); Mono<Book> bookMono = bookService.getBook(bookId) .switchIfEmpty(Mono.error(new RuntimeException("Book not found"))); return Mono.zip(userMono, bookMono, (user, book) -> new BookBorrowResponse(userId, bookId, "Accepted")); } public Mono<Book> applyDiscount(Mono<Book> bookMono) { return bookMono.map(book -> { book.setPrice(book.getPrice() - book.getPrice() * 0.2); return book; }); } public Mono<Book> applyTax(Mono<Book> bookMono) { return bookMono.map(book -> { book.setPrice(book.getPrice() + book.getPrice() * 0.1);
return book; }); } public Mono<Book> getFinalPricedBook(String bookId) { return bookService.getBook(bookId) .transform(this::applyTax) .transform(this::applyDiscount); } public Mono<Book> conditionalDiscount(String userId, String bookId) { return userService.getUser(userId) .filter(User::isActive) .flatMap(user -> bookService.getBook(bookId) .transform(this::applyDiscount)) .switchIfEmpty(bookService.getBook(bookId)) .switchIfEmpty(Mono.error(new RuntimeException("Book not found"))); } public Mono<BookBorrowResponse> handleErrorBookBorrow(String userId, String bookId) { return borrowBook(userId, bookId).onErrorResume(ex -> Mono.just(new BookBorrowResponse(userId, bookId, "Rejected"))); } }
repos\tutorials-master\spring-reactive-modules\spring-webflux\src\main\java\com\baeldung\spring\convertmonoobject\MonoTransformer.java
2
请完成以下Java代码
private boolean hasNonNullAttributeListValue(final I_M_AttributeInstance attributeInstance) { final AttributeValueId attributeValueId = AttributeValueId.ofRepoIdOrNull(attributeInstance.getM_AttributeValue_ID()); if (attributeValueId == null) { return false; } final AttributeId attributeId = AttributeId.ofRepoId(attributeInstance.getM_Attribute_ID()); final AttributeListValue attributeValue = Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(attributeId, attributeValueId); return attributeValue != null && !attributeValue.isNullFieldValue(); } @VisibleForTesting Optional<AttributeConfig> findMatchingAttributeConfig( final int orgId, final I_M_Attribute m_Attribute) { final ImmutableList<AttributeConfig> attributeConfigs = getAttributeConfigs(); final Comparator<AttributeConfig> orgComparator = Comparator .comparing(AttributeConfig::getOrgId) .reversed(); final Optional<AttributeConfig> matchingConfigIfPresent = attributeConfigs .stream() .filter(c -> AttributeId.toRepoId(c.getAttributeId()) == m_Attribute.getM_Attribute_ID()) .sorted(orgComparator) .findFirst(); final Optional<AttributeConfig> wildCardConfigIfPresent = attributeConfigs .stream() .filter(c -> c.getAttributeId() == null) .sorted(orgComparator) .findFirst(); final Optional<AttributeConfig> attributeConfigIfPresent = //
Stream.of(matchingConfigIfPresent, wildCardConfigIfPresent) .filter(Optional::isPresent) .map(Optional::get) .findFirst(); return attributeConfigIfPresent; } /** * Visible so that we can stub out the cache in tests. */ @VisibleForTesting ImmutableList<AttributeConfig> getAttributeConfigs() { final ImmutableList<AttributeConfig> attributeConfigs = // cache.getOrLoad(M_IolCandHandler_ID, () -> loadAttributeConfigs(M_IolCandHandler_ID)); return attributeConfigs; } public static <T extends ShipmentScheduleHandler> T createNewInstance(@NonNull final Class<T> handlerClass) { try { final T handler = handlerClass.newInstance(); return handler; } catch (InstantiationException | IllegalAccessException e) { throw AdempiereException.wrapIfNeeded(e); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\ShipmentScheduleHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class RuntimeParameterId implements RepoIdAware { @JsonCreator public static RuntimeParameterId ofRepoId(final int repoId) { return new RuntimeParameterId(repoId); } public static RuntimeParameterId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? new RuntimeParameterId(repoId) : null; } public static int toRepoId(@Nullable final OrderId orderId) { return orderId != null ? orderId.getRepoId() : -1; }
int repoId; private RuntimeParameterId(final int repoId) { this.repoId = Check.assumeGreaterThanZero(repoId, "ExternalSystem_RuntimeParameter_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\runtimeparameters\RuntimeParameterId.java
2
请完成以下Java代码
public static UserDetails getCurrentUser() { UserDetailsService userDetailsService = SpringBeanHolder.getBean(UserDetailsService.class); return userDetailsService.loadUserByUsername(getCurrentUsername()); } /** * 获取当前用户的数据权限 * @return / */ public static List<Long> getCurrentUserDataScope(){ UserDetails userDetails = getCurrentUser(); // 将 Java 对象转换为 JSONObject 对象 JSONObject jsonObject = (JSONObject) JSON.toJSON(userDetails); JSONArray jsonArray = jsonObject.getJSONArray("dataScopes"); return JSON.parseArray(jsonArray.toJSONString(), Long.class); } /** * 获取数据权限级别 * @return 级别 */ public static String getDataScopeType() { List<Long> dataScopes = getCurrentUserDataScope(); if(CollUtil.isEmpty(dataScopes)){ return ""; } return DataScopeEnum.ALL.getValue(); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId() { return getCurrentUserId(getToken()); } /** * 获取用户ID * @return 系统用户ID */ public static Long getCurrentUserId(String token) { JWT jwt = JWTUtil.parseToken(token); return Long.valueOf(jwt.getPayload("userId").toString()); } /** * 获取系统用户名称 * * @return 系统用户名称 */ public static String getCurrentUsername() { return getCurrentUsername(getToken()); } /** * 获取系统用户名称
* * @return 系统用户名称 */ public static String getCurrentUsername(String token) { JWT jwt = JWTUtil.parseToken(token); return jwt.getPayload("sub").toString(); } /** * 获取Token * @return / */ public static String getToken() { HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder .getRequestAttributes())).getRequest(); String bearerToken = request.getHeader(header); if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) { // 去掉令牌前缀 return bearerToken.replace(tokenStartWith, ""); } else { log.debug("非法Token:{}", bearerToken); } return null; } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\SecurityUtils.java
1
请完成以下Java代码
public class JmxEndpointDiscoverer extends EndpointDiscoverer<ExposableJmxEndpoint, JmxOperation> implements JmxEndpointsSupplier { /** * Create a new {@link JmxEndpointDiscoverer} instance. * @param applicationContext the source application context * @param parameterValueMapper the parameter value mapper * @param invokerAdvisors invoker advisors to apply * @param endpointFilters endpoint filters to apply * @param operationFilters operation filters to apply * @since 3.4.0 */ public JmxEndpointDiscoverer(ApplicationContext applicationContext, ParameterValueMapper parameterValueMapper, Collection<OperationInvokerAdvisor> invokerAdvisors, Collection<EndpointFilter<ExposableJmxEndpoint>> endpointFilters, Collection<OperationFilter<JmxOperation>> operationFilters) { super(applicationContext, parameterValueMapper, invokerAdvisors, endpointFilters, operationFilters); } @Override protected ExposableJmxEndpoint createEndpoint(Object endpointBean, EndpointId id, Access defaultAccess, Collection<JmxOperation> operations) { return new DiscoveredJmxEndpoint(this, endpointBean, id, defaultAccess, operations); } @Override protected JmxOperation createOperation(EndpointId endpointId, DiscoveredOperationMethod operationMethod,
OperationInvoker invoker) { return new DiscoveredJmxOperation(endpointId, operationMethod, invoker); } @Override protected OperationKey createOperationKey(JmxOperation operation) { return new OperationKey(operation.getName(), () -> "MBean call '" + operation.getName() + "'"); } static class JmxEndpointDiscovererRuntimeHints implements RuntimeHintsRegistrar { @Override public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) { hints.reflection().registerType(JmxEndpointFilter.class, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\annotation\JmxEndpointDiscoverer.java
1
请在Spring Boot框架中完成以下Java代码
private HUQRCode getQRCode(@NonNull final LU lu) {return huService.getQRCodeByHuId(lu.getId());} private HUQRCode getQRCode(@NonNull final TU tu) {return huService.getQRCodeByHuId(tu.getId());} private void addToPickingSlotQueue(final LUTUResult packedHUs) { final PickingSlotId pickingSlotId = getPickingSlotId().orElse(null); if (pickingSlotId == null) { return; } final CurrentPickingTarget currentPickingTarget = getPickingJob().getCurrentPickingTarget(); final LinkedHashSet<HuId> huIdsToAdd = new LinkedHashSet<>(); for (final LU lu : packedHUs.getLus()) { if (lu.isPreExistingLU()) { continue; } // do not add it if is current picking target, we will add it when closing the picking target. if (currentPickingTarget.matches(lu.getId())) { continue; } huIdsToAdd.add(lu.getId()); } for (final TU tu : packedHUs.getTopLevelTUs()) { // do not add it if is current picking target, we will add it when closing the picking target. if (currentPickingTarget.matches(tu.getId())) {
continue; } huIdsToAdd.add(tu.getId()); } if (!huIdsToAdd.isEmpty()) { pickingSlotService.addToPickingSlotQueue(pickingSlotId, huIdsToAdd); } } private Optional<PickingSlotId> getPickingSlotId() { return getPickingJob().getPickingSlotIdEffective(getLineId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\commands\pick\PickingJobPickCommand.java
2
请在Spring Boot框架中完成以下Java代码
public User updateUser(User user) { if (ObjectUtil.isNull(user)) { throw new RuntimeException("用户id不能为null"); } userDao.updateTemplateById(user); return userDao.single(user.getId()); } /** * 查询单个用户 * * @param id 主键id * @return 用户信息 */ @Override public User getUser(Long id) { return userDao.single(id); } /** * 查询用户列表 * * @return 用户列表 */ @Override
public List<User> getUserList() { return userDao.all(); } /** * 分页查询 * * @param currentPage 当前页 * @param pageSize 每页条数 * @return 分页用户列表 */ @Override public PageQuery<User> getUserByPage(Integer currentPage, Integer pageSize) { return userDao.createLambdaQuery().page(currentPage, pageSize); } }
repos\spring-boot-demo-master\demo-orm-beetlsql\src\main\java\com\xkcoding\orm\beetlsql\service\impl\UserServiceImpl.java
2
请完成以下Java代码
default ResultSet execute(@NonNull Statement<?> statement) { AsyncResultSet firstPage = getSafe(this.executeAsync(statement)); if (firstPage.hasMorePages()) { return new GuavaMultiPageResultSet(this, statement, firstPage); } else { return new SinglePageResultSet(firstPage); } } default ListenableFuture<AsyncResultSet> executeAsync(Statement<?> statement) { return this.execute(statement, ASYNC); } default ListenableFuture<AsyncResultSet> executeAsync(String statement) { return this.executeAsync(SimpleStatement.newInstance(statement)); }
default ListenableFuture<PreparedStatement> prepareAsync(SimpleStatement statement) { return this.execute(new DefaultPrepareRequest(statement), ASYNC_PREPARED); } default ListenableFuture<PreparedStatement> prepareAsync(String statement) { return this.prepareAsync(SimpleStatement.newInstance(statement)); } static AsyncResultSet getSafe(ListenableFuture<AsyncResultSet> future) { try { return future.get(); } catch (InterruptedException | ExecutionException e) { throw new IllegalStateException(e); } } }
repos\thingsboard-master\common\dao-api\src\main\java\org\thingsboard\server\dao\cassandra\guava\GuavaSession.java
1
请完成以下Java代码
public final class LogoutTokenClaimNames { /** * {@code jti} - the JTI identifier */ public static final String JTI = "jti"; /** * {@code iss} - the Issuer identifier */ public static final String ISS = "iss"; /** * {@code sub} - the Subject identifier */ public static final String SUB = "sub"; /** * {@code aud} - the Audience(s) that the ID Token is intended for */ public static final String AUD = "aud"; /** * {@code iat} - the time at which the ID Token was issued */
public static final String IAT = "iat"; /** * {@code events} - a JSON object that identifies this token as a logout token */ public static final String EVENTS = "events"; /** * {@code sid} - the session id for the OIDC provider */ public static final String SID = "sid"; private LogoutTokenClaimNames() { } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\oidc\authentication\logout\LogoutTokenClaimNames.java
1
请在Spring Boot框架中完成以下Java代码
public class ReplenishInfo { @NonNull Identifier identifier; @NonNull StockQtyAndUOMQty min; @NonNull StockQtyAndUOMQty max; Boolean highPriority; public MinMaxDescriptor toMinMaxDescriptor() { return MinMaxDescriptor.builder() .min(min.getStockQty().toBigDecimal()) .max(max.getStockQty().toBigDecimal()) .highPriority(highPriority) .build(); } @Builder @Value public static class Identifier { @NonNull ProductId productId;
@NonNull WarehouseId warehouseId; @Nullable LocatorId locatorId; public static Identifier of(@NonNull final WarehouseId warehouseId, @Nullable final LocatorId locatorId, @NonNull final ProductId productId) { return builder() .warehouseId(warehouseId) .locatorId(locatorId) .productId(productId) .build(); } public static Identifier of(@NonNull final WarehouseId warehouseId, @NonNull final ProductId productId) { return builder() .warehouseId(warehouseId) .productId(productId) .build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\material\replenish\ReplenishInfo.java
2
请完成以下Java代码
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 Password. @param Password Password of any length (case sensitive) */ public void setPassword (String Password) { set_Value (COLUMNNAME_Password, Password); } /** Get Password. @return Password of any length (case sensitive) */ public String getPassword () { return (String)get_Value(COLUMNNAME_Password); } /** Set URL. @param URL Full URL address - e.g. http://www.adempiere.org */ public void setURL (String URL) { set_Value (COLUMNNAME_URL, URL); } /** Get URL.
@return Full URL address - e.g. http://www.adempiere.org */ public String getURL () { return (String)get_Value(COLUMNNAME_URL); } /** Set Registered EMail. @param UserName Email of the responsible for the System */ public void setUserName (String UserName) { set_Value (COLUMNNAME_UserName, UserName); } /** Get Registered EMail. @return Email of the responsible for the System */ public String getUserName () { return (String)get_Value(COLUMNNAME_UserName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public int getPhone() { return phone; }
public void setPhone(int phone) { this.phone = phone; } @Override public String toString() { return "Developer{" + "id=" + id + ", name='" + name + '\'' + ", blog='" + blog + '\'' + ", phone=" + phone + '}'; } }
repos\Spring-Boot-Advanced-Projects-main\Springboot-Annotation-LookService\src\main\java\spring\annotation\model\Developer.java
2
请在Spring Boot框架中完成以下Java代码
public String getUsernameInUpperCase() { return getUsername().toUpperCase(); } @PreAuthorize("hasAuthority('SYS_ADMIN')") public String getUsernameLC() { return getUsername().toLowerCase(); } @PreAuthorize("hasRole('ROLE_VIEWER') or hasRole('ROLE_EDITOR')") public boolean isValidUsername3(String username) { return userRoleRepository.isValidUsername(username); } @PreAuthorize("#username == authentication.principal.username") public String getMyRoles(String username) { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } @PostAuthorize("#username == authentication.principal.username") public String getMyRoles2(String username) { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getAuthorities().stream().map(auth -> auth.getAuthority()).collect(Collectors.joining(",")); } @PostAuthorize("returnObject.username == authentication.principal.nickName") public CustomUser loadUserDetail(String username) { return userRoleRepository.loadUserByUserName(username);
} @PreFilter("filterObject != authentication.principal.username") public String joinUsernames(List<String> usernames) { return usernames.stream().collect(Collectors.joining(";")); } @PreFilter(value = "filterObject != authentication.principal.username", filterTarget = "usernames") public String joinUsernamesAndRoles(List<String> usernames, List<String> roles) { return usernames.stream().collect(Collectors.joining(";")) + ":" + roles.stream().collect(Collectors.joining(";")); } @PostFilter("filterObject != authentication.principal.username") public List<String> getAllUsernamesExceptCurrent() { return userRoleRepository.getAllUsernames(); } @IsViewer public String getUsername4() { SecurityContext securityContext = SecurityContextHolder.getContext(); return securityContext.getAuthentication().getName(); } @PreAuthorize("#username == authentication.principal.username") @PostAuthorize("returnObject.username == authentication.principal.nickName") public CustomUser securedLoadUserDetail(String username) { return userRoleRepository.loadUserByUserName(username); } }
repos\tutorials-master\spring-security-modules\spring-security-core\src\main\java\com\baeldung\methodsecurity\service\UserRoleService.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_M_ProductDownload[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Download URL. @param DownloadURL URL of the Download files */ public void setDownloadURL (String DownloadURL) { set_Value (COLUMNNAME_DownloadURL, DownloadURL); } /** Get Download URL. @return URL of the Download files */ public String getDownloadURL () { return (String)get_Value(COLUMNNAME_DownloadURL); } /** Set Product Download. @param M_ProductDownload_ID Product downloads */ public void setM_ProductDownload_ID (int M_ProductDownload_ID) { if (M_ProductDownload_ID < 1) set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, null); else set_ValueNoCheck (COLUMNNAME_M_ProductDownload_ID, Integer.valueOf(M_ProductDownload_ID)); } /** Get Product Download. @return Product downloads */ public int getM_ProductDownload_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductDownload_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ProductDownload.java
1
请完成以下Java代码
public class NewsComment { private Long commentId; private Long newsId; private String commentator; private String commentBody; private Byte commentStatus; private Byte isDeleted; @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime; public Long getCommentId() { return commentId; } public void setCommentId(Long commentId) { this.commentId = commentId; } public Long getNewsId() { return newsId; } public void setNewsId(Long newsId) { this.newsId = newsId; } public String getCommentator() { return commentator; } public void setCommentator(String commentator) { this.commentator = commentator == null ? null : commentator.trim(); } public String getCommentBody() { return commentBody; } public void setCommentBody(String commentBody) { this.commentBody = commentBody == null ? null : commentBody.trim(); } public Byte getCommentStatus() { return commentStatus; }
public void setCommentStatus(Byte commentStatus) { this.commentStatus = commentStatus; } public Byte getIsDeleted() { return isDeleted; } public void setIsDeleted(Byte isDeleted) { this.isDeleted = isDeleted; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", commentId=").append(commentId); sb.append(", newsId=").append(newsId); sb.append(", commentator=").append(commentator); sb.append(", commentBody=").append(commentBody); sb.append(", commentStatus=").append(commentStatus); sb.append(", isDeleted=").append(isDeleted); sb.append("]"); return sb.toString(); } }
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\NewsComment.java
1
请完成以下Java代码
public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } /** * Type AD_Reference_ID=540534 * Reference name: GL_JournalLine_Type */ public static final int TYPE_AD_Reference_ID=540534;
/** Normal = N */ public static final String TYPE_Normal = "N"; /** Tax = T */ public static final String TYPE_Tax = "T"; @Override public void setType (final java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } @Override public java.lang.String getType() { return get_ValueAsString(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_JournalLine.java
1
请完成以下Java代码
public class StringPaddingUtil { public static String padLeftSpaces(String inputString, int length) { if (inputString.length() >= length) { return inputString; } StringBuilder sb = new StringBuilder(); while (sb.length() < length - inputString.length()) { sb.append(' '); } sb.append(inputString); return sb.toString(); } public static String padLeft(String inputString, int length) { if (inputString.length() >= length) {
return inputString; } StringBuilder sb = new StringBuilder(); for (int i = 0; i < length; i++) { sb.append(' '); } return sb.substring(inputString.length()) + inputString; } public static String padLeftZeros(String inputString, int length) { return String .format("%1$" + length + "s", inputString) .replace(' ', '0'); } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms\src\main\java\com\baeldung\padding\StringPaddingUtil.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONDocumentFilterParam { /** * Creates {@link JSONDocumentFilterParam} from {@link DocumentFilterParam} if the given filter is not internal. * * @return JSON document filter parameter */ /* package */static Optional<JSONDocumentFilterParam> of(final DocumentFilterParam filterParam, final JSONOptions jsonOpts) { // Don't convert internal filters if (filterParam.isSqlFilter()) { // throw new IllegalArgumentException("Sql filters are not allowed to be converted to JSON filters: " + filterParam); return Optional.empty(); } final String fieldName = filterParam.getFieldName(); final Object jsonValue = Values.valueToJsonObject(filterParam.getValue(), jsonOpts); final Object jsonValueTo = Values.valueToJsonObject(filterParam.getValueTo(), jsonOpts); final JSONDocumentFilterParam jsonFilterParam = new JSONDocumentFilterParam(fieldName, jsonValue, jsonValueTo); return Optional.of(jsonFilterParam); } @JsonProperty("parameterName") String parameterName; @JsonProperty("value") Object value;
@JsonProperty("valueTo") Object valueTo; @JsonCreator @Builder private JSONDocumentFilterParam( @JsonProperty("parameterName") final String parameterName, @JsonProperty("value") final Object value, @JsonProperty("valueTo") final Object valueTo) { this.parameterName = parameterName; this.value = value; this.valueTo = valueTo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\json\JSONDocumentFilterParam.java
2
请完成以下Java代码
public Object renderTaskForm(TaskFormData taskForm) { if (taskForm.getFormKey() == null) { return null; } String formTemplateString = getFormTemplateString(taskForm, taskForm.getFormKey()); ScriptingEngines scriptingEngines = CommandContextUtil.getProcessEngineConfiguration().getScriptingEngines(); TaskEntity task = (TaskEntity) taskForm.getTask(); ExecutionEntity executionEntity = null; if (task.getExecutionId() != null) { executionEntity = CommandContextUtil.getExecutionEntityManager().findById(task.getExecutionId()); } ScriptEngineRequest.Builder builder = ScriptEngineRequest.builder() .script(formTemplateString) .language(ScriptingEngines.DEFAULT_SCRIPTING_LANGUAGE)
.scopeContainer(executionEntity); return scriptingEngines.evaluate(builder.build()).getResult(); } protected String getFormTemplateString(FormData formInstance, String formKey) { String deploymentId = formInstance.getDeploymentId(); ResourceEntity resourceStream = CommandContextUtil.getResourceEntityManager().findResourceByDeploymentIdAndResourceName(deploymentId, formKey); if (resourceStream == null) { throw new FlowableObjectNotFoundException("Form with formKey '" + formKey + "' does not exist", String.class); } return new String(resourceStream.getBytes(), StandardCharsets.UTF_8); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\JuelFormEngine.java
1
请完成以下Java代码
public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Interest Area. @param R_InterestArea_ID Interest Area or Topic */ public void setR_InterestArea_ID (int R_InterestArea_ID) { if (R_InterestArea_ID < 1) set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, null); else set_ValueNoCheck (COLUMNNAME_R_InterestArea_ID, Integer.valueOf(R_InterestArea_ID)); } /** Get Interest Area. @return Interest Area or Topic */ public int getR_InterestArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_InterestArea_ID); if (ii == null) return 0; return ii.intValue(); }
/** 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\compiere\model\X_R_InterestArea.java
1
请完成以下Java代码
public class FormTypes { protected Map<String, AbstractFormType> formTypes = new HashMap<>(); public void addFormType(AbstractFormType formType) { formTypes.put(formType.getName(), formType); } public AbstractFormType parseFormPropertyType(FormProperty formProperty) { AbstractFormType formType = null; if ("date".equals(formProperty.getType()) && StringUtils.isNotEmpty(formProperty.getDatePattern())) { formType = new DateFormType(formProperty.getDatePattern()); } else if ("enum".equals(formProperty.getType())) { // ACT-1023: Using linked hashmap to preserve the order in which the
// entries are defined Map<String, String> values = new LinkedHashMap<>(); for (FormValue formValue : formProperty.getFormValues()) { values.put(formValue.getId(), formValue.getName()); } formType = new EnumFormType(values); } else if (StringUtils.isNotEmpty(formProperty.getType())) { formType = formTypes.get(formProperty.getType()); if (formType == null) { throw new FlowableIllegalArgumentException("unknown type '" + formProperty.getType() + "' " + formProperty.getId()); } } return formType; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormTypes.java
1
请在Spring Boot框架中完成以下Java代码
public class CityController { @Autowired private CityService cityService; @RequestMapping public PageInfo<City> getAll(City city) { List<City> countryList = cityService.getAll(city); return new PageInfo<City>(countryList); } @RequestMapping(value = "/add") public City add() { return new City(); } @RequestMapping(value = "/view/{id}") public City view(@PathVariable Integer id) { ModelAndView result = new ModelAndView(); City city = cityService.getById(id); return city;
} @RequestMapping(value = "/delete/{id}") public ModelMap delete(@PathVariable Integer id) { ModelMap result = new ModelMap(); cityService.deleteById(id); result.put("msg", "删除成功!"); return result; } @RequestMapping(value = "/save", method = RequestMethod.POST) public ModelMap save(City city) { ModelMap result = new ModelMap(); String msg = city.getId() == null ? "新增成功!" : "更新成功!"; cityService.save(city); result.put("city", city); result.put("msg", msg); return result; } }
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\controller\CityController.java
2
请完成以下Java代码
protected void prepare() { if (I_AD_Tab.Table_Name.equals(getTableName())) { p_AD_Tab_ID = getRecord_ID(); } } @Override protected String doIt() throws Exception { if (p_AD_Tab_ID <= 0) { throw new FillMandatoryException(I_AD_Tab.COLUMNNAME_AD_Tab_ID); } final I_AD_Tab adTab = InterfaceWrapperHelper.create(getCtx(), p_AD_Tab_ID, I_AD_Tab.class, getTrxName()); copySingleLayoutToGridLayout(adTab);
return MSG_OK; } private void copySingleLayoutToGridLayout(final I_AD_Tab adTab) { final List<I_AD_Field> adFields = Services.get(IADWindowDAO.class).retrieveFields(adTab); for (final I_AD_Field adField : adFields) { copySingleLayoutToGridLayout(adField); InterfaceWrapperHelper.save(adField); } } private void copySingleLayoutToGridLayout(final I_AD_Field adField) { adField.setIsDisplayedGrid(adField.isDisplayed()); adField.setSeqNoGrid(adField.getSeqNo()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\process\AD_Tab_SetGridLayoutFromSingleLayout.java
1
请在Spring Boot框架中完成以下Java代码
public class CostRevaluationLineId implements RepoIdAware { int repoId; @NonNull CostRevaluationId costRevaluationId; public static CostRevaluationLineId ofRepoId(@NonNull final CostRevaluationId costRevaluationId, final int costRevaluationLineId) { return new CostRevaluationLineId(costRevaluationId, costRevaluationLineId); } public static CostRevaluationLineId ofRepoId(final int costRevaluationId, final int costRevaluationLineId) { return new CostRevaluationLineId(CostRevaluationId.ofRepoId(costRevaluationId), costRevaluationLineId); }
public static CostRevaluationLineId ofRepoIdOrNull( @Nullable final CostRevaluationId costRevaluationId, final int costRevaluationLineId) { return costRevaluationId != null && costRevaluationLineId > 0 ? ofRepoId(costRevaluationId, costRevaluationLineId) : null; } private CostRevaluationLineId(@NonNull final CostRevaluationId costRevaluationId, final int costRevaluationLineId) { this.repoId = Check.assumeGreaterThanZero(costRevaluationLineId, "M_CostRevaluationLine_ID"); this.costRevaluationId = costRevaluationId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costrevaluation\CostRevaluationLineId.java
2
请完成以下Java代码
public String getEventType() { return eventSubscriptionDeclaration.getEventType(); } public String getEventName() { return eventSubscriptionDeclaration.getUnresolvedEventName(); } public String getActivityId() { return eventSubscriptionDeclaration.getActivityId(); } protected ExecutionEntity resolveExecution(EventSubscriptionEntity context) { return context.getExecution(); } protected JobHandlerConfiguration resolveJobHandlerConfiguration(EventSubscriptionEntity context) { return new EventSubscriptionJobConfiguration(context.getId()); } @SuppressWarnings("unchecked") public static List<EventSubscriptionJobDeclaration> getDeclarationsForActivity(PvmActivity activity) { Object result = activity.getProperty(BpmnParse.PROPERTYNAME_EVENT_SUBSCRIPTION_JOB_DECLARATION); if (result != null) {
return (List<EventSubscriptionJobDeclaration>) result; } else { return Collections.emptyList(); } } /** * Assumes that an activity has at most one declaration of a certain eventType. */ public static EventSubscriptionJobDeclaration findDeclarationForSubscription(EventSubscriptionEntity eventSubscription) { List<EventSubscriptionJobDeclaration> declarations = getDeclarationsForActivity(eventSubscription.getActivity()); for (EventSubscriptionJobDeclaration declaration : declarations) { if (declaration.getEventType().equals(eventSubscription.getEventType())) { return declaration; } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\EventSubscriptionJobDeclaration.java
1
请完成以下Java代码
public synchronized String getNextId() { if (lastId < nextId) { getNewBlock(); } long _nextId = nextId++; return Long.toString(_nextId); } protected synchronized void getNewBlock() { IdBlock idBlock = commandExecutor.execute(commandConfig, new GetNextIdBlockCmd(idBlockSize)); this.nextId = idBlock.getNextId(); this.lastId = idBlock.getLastId(); } public int getIdBlockSize() { return idBlockSize; } public void setIdBlockSize(int idBlockSize) {
this.idBlockSize = idBlockSize; } public CommandExecutor getCommandExecutor() { return commandExecutor; } public void setCommandExecutor(CommandExecutor commandExecutor) { this.commandExecutor = commandExecutor; } public CommandConfig getCommandConfig() { return commandConfig; } public void setCommandConfig(CommandConfig commandConfig) { this.commandConfig = commandConfig; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbIdGenerator.java
1
请完成以下Java代码
public boolean isObserveOncePerRequest() { return this.observeOncePerRequest; } /** * Sets whether this filter apply only once per request. By default, this is * <code>false</code>, meaning the filter will execute on every request. Sometimes * users may wish it to execute more than once per request, such as when JSP forwards * are being used and filter security is desired on each included fragment of the HTTP * request. * @param observeOncePerRequest whether the filter should only be applied once per * request */ public void setObserveOncePerRequest(boolean observeOncePerRequest) { this.observeOncePerRequest = observeOncePerRequest; } /** * If set to true, the filter will be applied to error dispatcher. Defaults to * {@code true}. * @param filterErrorDispatch whether the filter should be applied to error dispatcher */ public void setFilterErrorDispatch(boolean filterErrorDispatch) { this.filterErrorDispatch = filterErrorDispatch; } /** * If set to true, the filter will be applied to the async dispatcher. Defaults to * {@code true}.
* @param filterAsyncDispatch whether the filter should be applied to async dispatch */ public void setFilterAsyncDispatch(boolean filterAsyncDispatch) { this.filterAsyncDispatch = filterAsyncDispatch; } private static class NoopAuthorizationEventPublisher implements AuthorizationEventPublisher { @Override public <T> void publishAuthorizationEvent(Supplier<Authentication> authentication, T object, @Nullable AuthorizationResult result) { } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\intercept\AuthorizationFilter.java
1
请完成以下Java代码
public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workpackage, final String localTrxName) { final List<I_C_Async_Batch> batches = queueDAO.retrieveAllItems(workpackage, I_C_Async_Batch.class); if (batches == null || batches.size() != 1) { throw new AdempiereException("There should always be just one asyncBatch enqueued for each 'CheckProcessedAsynBatchWorkpackageProcessor' instance!") .appendParametersToMessage() .setParameter("C_Queue_WorkPackage_ID", workpackage.getC_Queue_WorkPackage_ID()); } final I_C_Async_Batch asyncBatch = batches.get(0); if (asyncBatch.isProcessed() || !asyncBatch.isActive()) { // already processed => do nothing return Result.SUCCESS; } final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoId(asyncBatch.getC_Async_Batch_ID()); // // check if we need to wait for a bit before trying to set the processed status final Duration delayUntilCheckingProcessedState = asyncBatchBL.getTimeUntilProcessedRecheck(asyncBatch); if (delayUntilCheckingProcessedState.toMillis() > 0) { // a delay that didn't fit into Integer occured when during testing we got the async-batch's first/last processed from the actual time, but "now" from SystemTime with a fixed testing-value. Check.assume(delayUntilCheckingProcessedState.toMillis() <= Integer.MAX_VALUE, "The delay until re-checking processed state of C_Async_Batch_ID={} has to be <={}", asyncBatch.getC_Async_Batch_ID(), Integer.MAX_VALUE); throw WorkpackageSkipRequestException.createWithTimeout("AsyncBatch not ready for processed status check. Postponed!", Math.toIntExact(delayUntilCheckingProcessedState.toMillis())); } // // try to set the processed status final boolean batchIsProcessed = asyncBatchBL.updateProcessedOutOfTrx(asyncBatchId); if (batchIsProcessed) { return Result.SUCCESS; } // // check if keep alive time expired and if it has; set wp to error final boolean keepAliveTimeExpired = asyncBatchBL.keepAliveTimeExpired(asyncBatchId); if (keepAliveTimeExpired)
{ throw new AdempiereException("@IAsyncBatchBL.keepAliveTimeExpired@"); } throw WorkpackageSkipRequestException.createWithTimeout("Not processed yet. Postponed!", getWorkpackageSkipTimeoutMillis(asyncBatch)); } private int getWorkpackageSkipTimeoutMillis(@NonNull final I_C_Async_Batch asyncBatch) { if (asyncBatch.getC_Async_Batch_Type_ID() > 0) { final long skipTimeoutMillis = asyncBatchBL.getAsyncBatchType(asyncBatch).map(AsyncBatchType::getSkipTimeout).orElse(Duration.ZERO).toMillis(); if (skipTimeoutMillis > 0) { return (int)skipTimeoutMillis; } } return sysConfigBL.getIntValue(SYSCONFIG_WorkpackageSkipTimeoutMillis, DEFAULT_WorkpackageSkipTimeoutMillis); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\CheckProcessedAsynBatchWorkpackageProcessor.java
1
请完成以下Java代码
public void setDateAcctFrom (final @Nullable java.sql.Timestamp DateAcctFrom) { set_Value (COLUMNNAME_DateAcctFrom, DateAcctFrom); } @Override public java.sql.Timestamp getDateAcctFrom() { return get_ValueAsTimestamp(COLUMNNAME_DateAcctFrom); } @Override public void setDateAcctTo (final java.sql.Timestamp DateAcctTo) { set_Value (COLUMNNAME_DateAcctTo, DateAcctTo); } @Override public java.sql.Timestamp getDateAcctTo() { return get_ValueAsTimestamp(COLUMNNAME_DateAcctTo); } @Override public void setDATEV_Export_ID (final int DATEV_Export_ID) { if (DATEV_Export_ID < 1) set_ValueNoCheck (COLUMNNAME_DATEV_Export_ID, null); else set_ValueNoCheck (COLUMNNAME_DATEV_Export_ID, DATEV_Export_ID); } @Override public int getDATEV_Export_ID() { return get_ValueAsInt(COLUMNNAME_DATEV_Export_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setIsExcludeAlreadyExported (final boolean IsExcludeAlreadyExported) { set_Value (COLUMNNAME_IsExcludeAlreadyExported, IsExcludeAlreadyExported); } @Override public boolean isExcludeAlreadyExported() { return get_ValueAsBoolean(COLUMNNAME_IsExcludeAlreadyExported); } @Override public void setIsNegateInboundAmounts (final boolean IsNegateInboundAmounts) { set_Value (COLUMNNAME_IsNegateInboundAmounts, IsNegateInboundAmounts); } @Override public boolean isNegateInboundAmounts() { return get_ValueAsBoolean(COLUMNNAME_IsNegateInboundAmounts); } @Override public void setIsPlaceBPAccountsOnCredit (final boolean IsPlaceBPAccountsOnCredit) { set_Value (COLUMNNAME_IsPlaceBPAccountsOnCredit, IsPlaceBPAccountsOnCredit); } @Override public boolean isPlaceBPAccountsOnCredit() { return get_ValueAsBoolean(COLUMNNAME_IsPlaceBPAccountsOnCredit);
} /** * IsSOTrx AD_Reference_ID=319 * Reference name: _YesNo */ public static final int ISSOTRX_AD_Reference_ID=319; /** Yes = Y */ public static final String ISSOTRX_Yes = "Y"; /** No = N */ public static final String ISSOTRX_No = "N"; @Override public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, IsSOTrx); } @Override public java.lang.String getIsSOTrx() { return get_ValueAsString(COLUMNNAME_IsSOTrx); } @Override public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo) { set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo); } @Override public boolean isSwitchCreditMemo() { return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java
1
请完成以下Java代码
public long getFinishedCaseInstanceCount() { return finishedCaseInstanceCount; } public void setFinishedCaseInstanceCount(long finishedCaseInstanceCount) { this.finishedCaseInstanceCount = finishedCaseInstanceCount; } public long getCleanableCaseInstanceCount() { return cleanableCaseInstanceCount; } public void setCleanableCaseInstanceCount(long cleanableCaseInstanceCount) { this.cleanableCaseInstanceCount = cleanableCaseInstanceCount; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; }
public static List<CleanableHistoricCaseInstanceReportResultDto> convert(List<CleanableHistoricCaseInstanceReportResult> reportResult) { List<CleanableHistoricCaseInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricCaseInstanceReportResultDto>(); for (CleanableHistoricCaseInstanceReportResult current : reportResult) { CleanableHistoricCaseInstanceReportResultDto dto = new CleanableHistoricCaseInstanceReportResultDto(); dto.setCaseDefinitionId(current.getCaseDefinitionId()); dto.setCaseDefinitionKey(current.getCaseDefinitionKey()); dto.setCaseDefinitionName(current.getCaseDefinitionName()); dto.setCaseDefinitionVersion(current.getCaseDefinitionVersion()); dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); dto.setFinishedCaseInstanceCount(current.getFinishedCaseInstanceCount()); dto.setCleanableCaseInstanceCount(current.getCleanableCaseInstanceCount()); dto.setTenantId(current.getTenantId()); dtos.add(dto); } return dtos; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricCaseInstanceReportResultDto.java
1
请完成以下Java代码
public java.lang.String getExportXML () { return (java.lang.String)get_Value(COLUMNNAME_ExportXML); } /** Set Defer Constraints. @param IsDeferredConstraints Defer Constraints */ @Override public void setIsDeferredConstraints (boolean IsDeferredConstraints) { set_Value (COLUMNNAME_IsDeferredConstraints, Boolean.valueOf(IsDeferredConstraints)); } /** Get Defer Constraints. @return Defer Constraints */ @Override public boolean isDeferredConstraints () { Object oo = get_Value(COLUMNNAME_IsDeferredConstraints); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Release No. @param ReleaseNo Internal Release Number */ @Override public void setReleaseNo (java.lang.String ReleaseNo) { set_Value (COLUMNNAME_ReleaseNo, ReleaseNo); } /** Get Release No. @return Internal Release Number */ @Override public java.lang.String getReleaseNo () { return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Sequence.
@param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_Value (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
1
请完成以下Java代码
public void writeLine(Line line) { try { if (CSVWriter == null) initWriter(); String[] lineStr = new String[2]; lineStr[0] = line.getName(); lineStr[1] = line .getAge() .toString(); CSVWriter.writeNext(lineStr); } catch (Exception e) { logger.error("Error while writing line in file: " + this.fileName); } } private void initReader() throws Exception { ClassLoader classLoader = this .getClass() .getClassLoader(); if (file == null) file = new File(classLoader .getResource(fileName) .getFile()); if (fileReader == null) fileReader = new FileReader(file); if (CSVReader == null) CSVReader = new CSVReader(fileReader); } private void initWriter() throws Exception { if (file == null) { file = new File(fileName); file.createNewFile();
} if (fileWriter == null) fileWriter = new FileWriter(file, true); if (CSVWriter == null) CSVWriter = new CSVWriter(fileWriter); } public void closeWriter() { try { CSVWriter.close(); fileWriter.close(); } catch (IOException e) { logger.error("Error while closing writer."); } } public void closeReader() { try { CSVReader.close(); fileReader.close(); } catch (IOException e) { logger.error("Error while closing reader."); } } }
repos\tutorials-master\spring-batch\src\main\java\com\baeldung\taskletsvschunks\utils\FileUtils.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() { return get_ValueAsPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class); } @Override public void setPP_Product_BOM(final org.eevolution.model.I_PP_Product_BOM PP_Product_BOM) { set_ValueFromPO(COLUMNNAME_PP_Product_BOM_ID, org.eevolution.model.I_PP_Product_BOM.class, PP_Product_BOM); }
@Override public void setPP_Product_BOM_ID (final int PP_Product_BOM_ID) { if (PP_Product_BOM_ID < 1) set_Value (COLUMNNAME_PP_Product_BOM_ID, null); else set_Value (COLUMNNAME_PP_Product_BOM_ID, PP_Product_BOM_ID); } @Override public int getPP_Product_BOM_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOM_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_CompensationGroup.java
1
请完成以下Java代码
public class TemplateMsgApi extends BaseApi { private static final Logger LOG = LoggerFactory.getLogger(TemplateMsgApi.class); private ApiConfig apiConfig; public TemplateMsgApi(ApiConfig apiConfig) { this.apiConfig = apiConfig; } /** * 设置行业 * * @param industry 行业参数 * @return 操作结果 */ public ResultType setIndustry(Industry industry) { LOG.debug("设置行业......"); BeanUtil.requireNonNull(industry, "行业对象为空"); String url = BASE_API_URL + "cgi-bin/template/api_set_industry?access_token=" + apiConfig.getAccessToken(); BaseResponse response = executePost(url, industry.toJsonString()); return ResultType.get(response.getErrcode()); } /** * 添加模版 * * @param shortTemplateId 模版短id * @return 操作结果 */ public AddTemplateResponse addTemplate(String shortTemplateId) { LOG.debug("添加模版......"); BeanUtil.requireNonNull(shortTemplateId, "短模版id必填"); String url = BASE_API_URL + "cgi-bin/template/api_add_template?access_token=" + apiConfig.getAccessToken(); ; Map<String, String> params = new HashMap<String, String>(); params.put("template_id_short", shortTemplateId); BaseResponse r = executePost(url, JSON.toJSONString(params)); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); return JSON.parseObject(resultJson, AddTemplateResponse.class);
} /** * 发送模版消息 * * @param msg 消息 * @return 发送结果 */ public SendTemplateResponse send(TemplateMsg msg) { LOG.debug("发送模版消息......"); BeanUtil.requireNonNull(msg.getTouser(), "openid is null"); BeanUtil.requireNonNull(msg.getTemplateId(), "template_id is null"); BeanUtil.requireNonNull(msg.getData(), "data is null"); // BeanUtil.requireNonNull(msg.getTopcolor(), "top color is null"); // BeanUtil.requireNonNull(msg.getUrl(), "url is null"); String url = BASE_API_URL + "cgi-bin/message/template/send?access_token=" + apiConfig.getAccessToken(); ; BaseResponse r = executePost(url, msg.toJsonString()); String resultJson = isSuccess(r.getErrcode()) ? r.getErrmsg() : r.toJsonString(); SendTemplateResponse result = JSON.parseObject(resultJson, SendTemplateResponse.class); return result; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\TemplateMsgApi.java
1
请在Spring Boot框架中完成以下Java代码
public class Student { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE) private long id; private String name; @ManyToOne private School school; public long getId() { return id; } public void setId(long id) { this.id = id;
} public String getName() { return name; } public void setName(String name) { this.name = name; } public School getSchool() { return school; } public void setSchool(School school) { this.school = school; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-crud\src\main\java\com\baeldung\batchinserts\model\Student.java
2
请完成以下Java代码
private boolean isNotX509PemWrapper(String line) { return !X509_PEM_HEADER.equals(line) && !X509_PEM_FOOTER.equals(line); } } private static class X509CertificateDecoder implements Converter<List<String>, RSAPublicKey> { private final CertificateFactory certificateFactory; X509CertificateDecoder(CertificateFactory certificateFactory) { this.certificateFactory = certificateFactory; } @Override public @NonNull RSAPublicKey convert(List<String> lines) { StringBuilder base64Encoded = new StringBuilder(); for (String line : lines) { if (isNotX509CertificateWrapper(line)) { base64Encoded.append(line); } } byte[] x509 = Base64.getDecoder().decode(base64Encoded.toString()); try (InputStream x509CertStream = new ByteArrayInputStream(x509)) { X509Certificate certificate = (X509Certificate) this.certificateFactory
.generateCertificate(x509CertStream); return (RSAPublicKey) certificate.getPublicKey(); } catch (CertificateException | IOException ex) { throw new IllegalArgumentException(ex); } } private boolean isNotX509CertificateWrapper(String line) { return !X509_CERT_HEADER.equals(line) && !X509_CERT_FOOTER.equals(line); } } }
repos\spring-security-main\core\src\main\java\org\springframework\security\converter\RsaKeyConverters.java
1
请完成以下Java代码
public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); } /** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.dataentry.model.I_DataEntry_Tab getDataEntry_Tab() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_DataEntry_Tab_ID, de.metas.dataentry.model.I_DataEntry_Tab.class); } @Override public void setDataEntry_Tab(de.metas.dataentry.model.I_DataEntry_Tab DataEntry_Tab) { set_ValueFromPO(COLUMNNAME_DataEntry_Tab_ID, de.metas.dataentry.model.I_DataEntry_Tab.class, DataEntry_Tab); } /** Set Eingaberegister. @param DataEntry_Tab_ID Eingaberegister */ @Override public void setDataEntry_Tab_ID (int DataEntry_Tab_ID) { if (DataEntry_Tab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_Tab_ID, Integer.valueOf(DataEntry_Tab_ID)); } /** Get Eingaberegister. @return Eingaberegister */ @Override public int getDataEntry_Tab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_Tab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () {
return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Registername. @param TabName Registername */ @Override public void setTabName (java.lang.String TabName) { set_Value (COLUMNNAME_TabName, TabName); } /** Get Registername. @return Registername */ @Override public java.lang.String getTabName () { return (java.lang.String)get_Value(COLUMNNAME_TabName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_SubTab.java
1
请在Spring Boot框架中完成以下Java代码
public class LogAspect { private final SysLogService sysLogService; ThreadLocal<Long> currentTime = new ThreadLocal<>(); public LogAspect(SysLogService sysLogService) { this.sysLogService = sysLogService; } /** * 配置切入点 */ @Pointcut("@annotation(me.zhengjie.annotation.Log)") public void logPointcut() { // 该方法无方法体,主要为了让同类中其他方法使用此切入点 } /** * 配置环绕通知,使用在方法logPointcut()上注册的切入点 * * @param joinPoint join point for advice */ @Around("logPointcut()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { Object result; currentTime.set(System.currentTimeMillis()); result = joinPoint.proceed(); SysLog sysLog = new SysLog("INFO",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request),joinPoint, sysLog); return result; } /** * 配置异常通知 * * @param joinPoint join point for advice * @param e exception */ @AfterThrowing(pointcut = "logPointcut()", throwing = "e") public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
SysLog sysLog = new SysLog("ERROR",System.currentTimeMillis() - currentTime.get()); currentTime.remove(); sysLog.setExceptionDetail(ThrowableUtil.getStackTrace(e).getBytes()); HttpServletRequest request = RequestHolder.getHttpServletRequest(); sysLogService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint)joinPoint, sysLog); } /** * 获取用户名 * @return / */ public String getUsername() { try { return SecurityUtils.getCurrentUsername(); }catch (Exception e){ return ""; } } }
repos\eladmin-master\eladmin-logging\src\main\java\me\zhengjie\aspect\LogAspect.java
2
请完成以下Java代码
private static class QueueFilter implements IQueryFilter<I_C_Queue_WorkPackage> { private final IWorkPackageQuery packageQuery; public QueueFilter(final IWorkPackageQuery packageQuery) { this.packageQuery = packageQuery; } @Override public boolean accept(final I_C_Queue_WorkPackage workpackage) { if (packageQuery.getProcessed() != null && packageQuery.getProcessed() != workpackage.isProcessed()) { return false; } if (packageQuery.getReadyForProcessing() != null && packageQuery.getReadyForProcessing() != workpackage.isReadyForProcessing()) { return false; } if (packageQuery.getError() != null && packageQuery.getError() != workpackage.isError()) { return false; } if (!workpackage.isActive()) { return false; } // Only packages that have not been skipped, // or where 'retryTimeoutMillis' has already passed since they were skipped. final Timestamp nowMinusTimeOut = new Timestamp(SystemTime.millis() - packageQuery.getSkippedTimeoutMillis()); final Timestamp skippedAt = workpackage.getSkippedAt(); if (skippedAt != null && skippedAt.compareTo(nowMinusTimeOut) > 0) { return false; } // Only work packages for given process final Set<QueuePackageProcessorId> packageProcessorIds = packageQuery.getPackageProcessorIds(); if (packageProcessorIds != null) {
if (packageProcessorIds.isEmpty()) { slogger.warn("There were no package processor Ids set in the package query. This could be a posible development error" +"\n Package query: "+packageQuery); } final QueuePackageProcessorId packageProcessorId = QueuePackageProcessorId.ofRepoId(workpackage.getC_Queue_PackageProcessor_ID()); if (!packageProcessorIds.contains(packageProcessorId)) { return false; } } final String priorityFrom = packageQuery.getPriorityFrom(); if (priorityFrom != null && priorityFrom.compareTo(workpackage.getPriority()) > 0) { return false; } return true; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\PlainQueueDAO.java
1
请完成以下Java代码
public class X_C_LicenseFeeSettings extends org.compiere.model.PO implements I_C_LicenseFeeSettings, org.compiere.model.I_Persistent { private static final long serialVersionUID = 79387114L; /** Standard Constructor */ public X_C_LicenseFeeSettings (final Properties ctx, final int C_LicenseFeeSettings_ID, @Nullable final String trxName) { super (ctx, C_LicenseFeeSettings_ID, trxName); } /** Load Constructor */ public X_C_LicenseFeeSettings (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_LicenseFeeSettings_ID (final int C_LicenseFeeSettings_ID) { if (C_LicenseFeeSettings_ID < 1) set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettings_ID, null); else set_ValueNoCheck (COLUMNNAME_C_LicenseFeeSettings_ID, C_LicenseFeeSettings_ID); } @Override public int getC_LicenseFeeSettings_ID() { return get_ValueAsInt(COLUMNNAME_C_LicenseFeeSettings_ID); } @Override public void setCommission_Product_ID (final int Commission_Product_ID) { if (Commission_Product_ID < 1) set_Value (COLUMNNAME_Commission_Product_ID, null); else set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
} @Override public int getCommission_Product_ID() { return get_ValueAsInt(COLUMNNAME_Commission_Product_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPointsPrecision (final int PointsPrecision) { set_Value (COLUMNNAME_PointsPrecision, PointsPrecision); } @Override public int getPointsPrecision() { return get_ValueAsInt(COLUMNNAME_PointsPrecision); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_LicenseFeeSettings.java
1
请完成以下Java代码
public void setTitle(String title) { this.title = title; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((author == null) ? 0 : author.hashCode()); result = prime * result + (int) (id ^ (id >>> 32)); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass())
return false; Book other = (Book) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (id != other.id) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } @Override public String toString() { return "Book [id=" + id + ", title=" + title + ", author=" + author + "]"; } }
repos\tutorials-master\spring-boot-modules\spring-boot-bootstrap\src\main\java\com\baeldung\persistence\model\Book.java
1
请在Spring Boot框架中完成以下Java代码
private ScpClientUtil getScpClientUtil(String ip) { ServerDeployDto serverDeployDTO = serverDeployService.findByIp(ip); if (serverDeployDTO == null) { sendMsg("IP对应服务器信息不存在:" + ip, MsgType.ERROR); throw new BadRequestException("IP对应服务器信息不存在:" + ip); } return ScpClientUtil.getInstance(ip, serverDeployDTO.getPort(), serverDeployDTO.getAccount(), serverDeployDTO.getPassword()); } private void sendResultMsg(boolean result, StringBuilder sb) { if (result) { sb.append("<br>启动成功!"); sendMsg(sb.toString(), MsgType.INFO); } else { sb.append("<br>启动失败!"); sendMsg(sb.toString(), MsgType.ERROR);
} } @Override public void download(List<DeployDto> queryAll, HttpServletResponse response) throws IOException { List<Map<String, Object>> list = new ArrayList<>(); for (DeployDto deployDto : queryAll) { Map<String,Object> map = new LinkedHashMap<>(); map.put("应用名称", deployDto.getApp().getName()); map.put("服务器", deployDto.getServers()); map.put("部署日期", deployDto.getCreateTime()); list.add(map); } FileUtil.downloadExcel(list, response); } }
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\service\impl\DeployServiceImpl.java
2
请完成以下Java代码
public void setIsUserElement2Dim (boolean IsUserElement2Dim) { set_Value (COLUMNNAME_IsUserElement2Dim, Boolean.valueOf(IsUserElement2Dim)); } /** Get User Element 2 Dimension. @return Include User Element 2 as a cube dimension */ public boolean isUserElement2Dim () { Object oo = get_Value(COLUMNNAME_IsUserElement2Dim); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Last Recalculated. @param LastRecalculated The time last recalculated. */ public void setLastRecalculated (Timestamp LastRecalculated) { set_Value (COLUMNNAME_LastRecalculated, LastRecalculated); } /** Get Last Recalculated. @return The time last recalculated. */ public Timestamp getLastRecalculated () { return (Timestamp)get_Value(COLUMNNAME_LastRecalculated); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name);
} /** Set Report Cube. @param PA_ReportCube_ID Define reporting cube for pre-calculation of summary accounting data. */ public void setPA_ReportCube_ID (int PA_ReportCube_ID) { if (PA_ReportCube_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_ReportCube_ID, Integer.valueOf(PA_ReportCube_ID)); } /** Get Report Cube. @return Define reporting cube for pre-calculation of summary accounting data. */ public int getPA_ReportCube_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportCube.java
1
请完成以下Java代码
public List<IdentityLink> execute(CommandContext commandContext) { ensureNotNull("taskId", taskId); TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(taskId); ensureNotNull("Cannot find task with id " + taskId, "task", task); checkGetIdentityLink(task, commandContext); List<IdentityLink> identityLinks = task.getIdentityLinks().stream().collect(Collectors.toList()); // assignee is not part of identity links in the db. // so if there is one, we add it here. // @Tom: we discussed this long on skype and you agreed ;-) // an assignee *is* an identityLink, and so must it be reflected in the API // // Note: we cant move this code to the TaskEntity (which would be cleaner), // since the task.delete cascased to all associated identityLinks // and of course this leads to exception while trying to delete a non-existing identityLink if (task.getAssignee() != null) { IdentityLinkEntity identityLink = new IdentityLinkEntity(); identityLink.setUserId(task.getAssignee());
identityLink.setTask(task); identityLink.setType(IdentityLinkType.ASSIGNEE); identityLinks.add(identityLink); } if (task.getOwner() != null) { IdentityLinkEntity identityLink = new IdentityLinkEntity(); identityLink.setUserId(task.getOwner()); identityLink.setTask(task); identityLink.setType(IdentityLinkType.OWNER); identityLinks.add(identityLink); } return identityLinks; } protected void checkGetIdentityLink(TaskEntity task, CommandContext commandContext) { for (CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadTask(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetIdentityLinksForTaskCmd.java
1
请在Spring Boot框架中完成以下Java代码
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 void setTaskId(String taskId) { this.taskId = taskId; } public Date getTimeStamp() { return timeStamp; } public void setTimeStamp(Date timeStamp) { this.timeStamp = timeStamp; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public byte[] getData() { return data; } public void setData(byte[] data) { this.data = data; } public String getLockOwner() { return lockOwner; }
public void setLockOwner(String lockOwner) { this.lockOwner = lockOwner; } public String getLockTime() { return lockTime; } public void setLockTime(String lockTime) { this.lockTime = lockTime; } public int getProcessed() { return isProcessed; } public void setProcessed(int isProcessed) { this.isProcessed = isProcessed; } @Override public String toString() { return timeStamp.toString() + " : " + type; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventLogEntryEntityImpl.java
1
请完成以下Java代码
public void checkUpdateUserOperationLog(UserOperationLogEntry entry) { if (entry != null && !getTenantManager().isAuthenticatedTenant(entry.getTenantId())) { throw LOG.exceptionCommandWithUnauthorizedTenant("update the user operation log entry '" + entry.getId() + "'"); } } @Override public void checkReadHistoricExternalTaskLog(HistoricExternalTaskLogEntity historicExternalTaskLog) { if (historicExternalTaskLog != null && !getTenantManager().isAuthenticatedTenant(historicExternalTaskLog.getTenantId())) { throw LOG.exceptionCommandWithUnauthorizedTenant("get the historic external task log '"+ historicExternalTaskLog.getId() + "'"); } } @Override public void checkReadDiagnosticsData() { } @Override public void checkReadHistoryLevel() { } @Override public void checkReadTableCount() { } @Override public void checkReadTableName() { } @Override public void checkReadTableMetaData() { } @Override public void checkReadProperties() { } @Override public void checkSetProperty() { } @Override public void checkDeleteProperty() { } @Override public void checkDeleteLicenseKey() { } @Override public void checkSetLicenseKey() { } @Override public void checkReadLicenseKey() { } @Override public void checkRegisterProcessApplication() { } @Override public void checkUnregisterProcessApplication() { } @Override public void checkReadRegisteredDeployments() { } @Override public void checkReadProcessApplicationForDeployment() { }
@Override public void checkRegisterDeployment() { } @Override public void checkUnregisterDeployment() { } @Override public void checkDeleteMetrics() { } @Override public void checkDeleteTaskMetrics() { } @Override public void checkReadSchemaLog() { } // helper ////////////////////////////////////////////////// protected TenantManager getTenantManager() { return Context.getCommandContext().getTenantManager(); } protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) { return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId); } protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) { return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId); } protected ExecutionEntity findExecutionById(String processInstanceId) { return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId); } protected DeploymentEntity findDeploymentById(String deploymentId) { return Context.getCommandContext().getDeploymentManager().findDeploymentById(deploymentId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\multitenancy\TenantCommandChecker.java
1
请完成以下Java代码
public PostingException setFact(final Fact fact) { _fact = fact; resetMessageBuilt(); return this; } public Fact getFact() { return _fact; } private FactLine getFactLine() { return _factLine; } public PostingException setFactLine(final FactLine factLine) { this._factLine = factLine; resetMessageBuilt(); return this; } /** * @return <code>true</code> if the document's "Posted" status shall not been changed. */ public boolean isPreserveDocumentPostedStatus() { return _preserveDocumentPostedStatus; } /** * If set, the document's "Posted" status shall not been changed. */ public PostingException setPreserveDocumentPostedStatus() { _preserveDocumentPostedStatus = true; resetMessageBuilt(); return this; } public PostingException setDocLine(final DocLine<?> docLine) { _docLine = docLine; resetMessageBuilt(); return this;
} public DocLine<?> getDocLine() { return _docLine; } @SuppressWarnings("unused") public PostingException setLogLevel(@NonNull final Level logLevel) { this._logLevel = logLevel; return this; } /** * @return recommended log level to be used when reporting this issue */ public Level getLogLevel() { return _logLevel; } @Override public PostingException setParameter( final @NonNull String parameterName, final @Nullable Object parameterValue) { super.setParameter(parameterName, parameterValue); return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\doc\PostingException.java
1
请完成以下Java代码
public void setC_Invoice_Verification_SetLine(final org.compiere.model.I_C_Invoice_Verification_SetLine C_Invoice_Verification_SetLine) { set_ValueFromPO(COLUMNNAME_C_Invoice_Verification_SetLine_ID, org.compiere.model.I_C_Invoice_Verification_SetLine.class, C_Invoice_Verification_SetLine); } @Override public void setC_Invoice_Verification_SetLine_ID (final int C_Invoice_Verification_SetLine_ID) { if (C_Invoice_Verification_SetLine_ID < 1) set_Value (COLUMNNAME_C_Invoice_Verification_SetLine_ID, null); else set_Value (COLUMNNAME_C_Invoice_Verification_SetLine_ID, C_Invoice_Verification_SetLine_ID); } @Override public int getC_Invoice_Verification_SetLine_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_SetLine_ID); } @Override public void setIsTaxBoilerPlateMatch (final boolean IsTaxBoilerPlateMatch) { set_Value (COLUMNNAME_IsTaxBoilerPlateMatch, IsTaxBoilerPlateMatch); } @Override public boolean isTaxBoilerPlateMatch() { return get_ValueAsBoolean(COLUMNNAME_IsTaxBoilerPlateMatch); } @Override public void setIsTaxIdMatch (final boolean IsTaxIdMatch) { set_Value (COLUMNNAME_IsTaxIdMatch, IsTaxIdMatch); } @Override public boolean isTaxIdMatch() { return get_ValueAsBoolean(COLUMNNAME_IsTaxIdMatch); } @Override public void setIsTaxRateMatch (final boolean IsTaxRateMatch) { set_Value (COLUMNNAME_IsTaxRateMatch, IsTaxRateMatch); } @Override public boolean isTaxRateMatch() { return get_ValueAsBoolean(COLUMNNAME_IsTaxRateMatch); } @Override
public void setRun_Tax_ID (final int Run_Tax_ID) { if (Run_Tax_ID < 1) set_Value (COLUMNNAME_Run_Tax_ID, null); else set_Value (COLUMNNAME_Run_Tax_ID, Run_Tax_ID); } @Override public int getRun_Tax_ID() { return get_ValueAsInt(COLUMNNAME_Run_Tax_ID); } @Override public void setRun_Tax_Lookup_Log (final @Nullable java.lang.String Run_Tax_Lookup_Log) { set_Value (COLUMNNAME_Run_Tax_Lookup_Log, Run_Tax_Lookup_Log); } @Override public java.lang.String getRun_Tax_Lookup_Log() { return get_ValueAsString(COLUMNNAME_Run_Tax_Lookup_Log); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_RunLine.java
1
请完成以下Java代码
public class Employee { private String privateId; private String name; private boolean manager; public Employee(String id, String name) { setPrivateId(id); setName(name); } private Employee(String id, String name, boolean managerAttribute) { this.privateId = id; this.name = name; this.privateId = id + "_ID-MANAGER"; } public void setPrivateId(String customId) { if (customId.endsWith("_ID")) { this.privateId = customId; } else { this.privateId = customId + "_ID"; } } public String getPrivateId() { return privateId; }
public boolean isManager() { return manager; } public void elevateToManager() { if ("Carl".equals(this.name)) { setManager(true); } } private void setManager(boolean manager) { this.manager = manager; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static Employee buildManager(String id, String name) { return new Employee(id, name, true); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\privatemodifier\Employee.java
1
请完成以下Java代码
public class DefaultDunningCandidateProducerFactory implements IDunningCandidateProducerFactory { private final List<Class<? extends IDunningCandidateProducer>> producerClasses = new ArrayList<Class<? extends IDunningCandidateProducer>>(); private final List<IDunningCandidateProducer> producers = new ArrayList<IDunningCandidateProducer>(); @Override public void registerDunningCandidateProducer(final Class<? extends IDunningCandidateProducer> clazz) { if (producerClasses.contains(clazz)) { return; } producerClasses.add(clazz); final IDunningCandidateProducer producer = createProducer(clazz); producers.add(producer); } public List<Class<? extends IDunningCandidateProducer>> getProducerClasses() { return new ArrayList<Class<? extends IDunningCandidateProducer>>(producerClasses); } private IDunningCandidateProducer createProducer(final Class<? extends IDunningCandidateProducer> clazz) { try { final IDunningCandidateProducer producer = clazz.newInstance(); return producer; } catch (Exception e) { throw new DunningException("Cannot create producer for " + clazz, e); } } @Override public IDunningCandidateProducer getDunningCandidateProducer(final IDunnableDoc sourceDoc) { Check.assume(sourceDoc != null, "sourceDoc is not null"); IDunningCandidateProducer selectedProducer = null; for (final IDunningCandidateProducer producer : producers) { if (!producer.isHandled(sourceDoc)) { continue;
} if (selectedProducer != null) { throw new DunningException("Multiple producers found for " + sourceDoc + ": " + selectedProducer + ", " + producer); } selectedProducer = producer; } if (selectedProducer == null) { throw new DunningException("No " + IDunningCandidateProducer.class + " found for " + sourceDoc); } return selectedProducer; } @Override public String toString() { return "DefaultDunningCandidateProducerFactory [producerClasses=" + producerClasses + ", producers=" + producers + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunningCandidateProducerFactory.java
1
请完成以下Java代码
String formatFilters(@Nullable List<Filter> filters) { StringBuilder sb = new StringBuilder(); sb.append("Security filter chain: "); if (filters == null) { sb.append("no match"); } else if (filters.isEmpty()) { sb.append("[] empty (bypassed by security='none') "); } else { sb.append("[\n"); for (Filter f : filters) { sb.append(" ").append(f.getClass().getSimpleName()).append("\n"); } sb.append("]"); } return sb.toString(); } private @Nullable List<Filter> getFilters(HttpServletRequest request) { for (SecurityFilterChain chain : this.filterChainProxy.getFilterChains()) { if (chain.matches(request)) { return chain.getFilters(); } } return null; } @Override public void init(FilterConfig filterConfig) { } @Override public void destroy() { } public FilterChainProxy getFilterChainProxy() {
return this.filterChainProxy; } static class DebugRequestWrapper extends HttpServletRequestWrapper { private static final Logger logger = new Logger(); DebugRequestWrapper(HttpServletRequest request) { super(request); } @Override public HttpSession getSession() { boolean sessionExists = super.getSession(false) != null; HttpSession session = super.getSession(); if (!sessionExists) { DebugRequestWrapper.logger.info("New HTTP session created: " + session.getId(), true); } return session; } @Override public HttpSession getSession(boolean create) { if (!create) { return super.getSession(create); } return getSession(); } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\debug\DebugFilter.java
1
请完成以下Java代码
public void execute(T execution) { CoreModelElement scope = getScope(execution); List<DelegateListener<? extends BaseDelegateExecution>> listeners = execution.hasFailedOnEndListeners() ? getBuiltinListeners(scope) : getListeners(scope, execution); int listenerIndex = execution.getListenerIndex(); if(listenerIndex == 0) { execution = eventNotificationsStarted(execution); } if(!isSkipNotifyListeners(execution)) { if (listeners.size()>listenerIndex) { execution.setEventName(getEventName()); execution.setEventSource(scope); DelegateListener<? extends BaseDelegateExecution> listener = listeners.get(listenerIndex); execution.setListenerIndex(listenerIndex+1); try { execution.invokeListener(listener); } catch (Exception ex) { eventNotificationsFailed(execution, ex); // do not continue listener invocation once a listener has failed return; } execution.performOperationSync(this); } else { resetListeners(execution); eventNotificationsCompleted(execution); } } else { eventNotificationsCompleted(execution); } } protected void resetListeners(T execution) { execution.setListenerIndex(0); execution.setEventName(null); execution.setEventSource(null); } protected List<DelegateListener<? extends BaseDelegateExecution>> getListeners(CoreModelElement scope, T execution) {
if(execution.isSkipCustomListeners()) { return getBuiltinListeners(scope); } else { return scope.getListeners(getEventName()); } } protected List<DelegateListener<? extends BaseDelegateExecution>> getBuiltinListeners(CoreModelElement scope) { return scope.getBuiltInListeners(getEventName()); } protected boolean isSkipNotifyListeners(T execution) { return false; } protected T eventNotificationsStarted(T execution) { // do nothing return execution; } protected abstract CoreModelElement getScope(T execution); protected abstract String getEventName(); protected abstract void eventNotificationsCompleted(T execution); protected void eventNotificationsFailed(T execution, Exception exception) { if (exception instanceof RuntimeException) { throw (RuntimeException) exception; } else { throw new PvmException("couldn't execute event listener : " + exception.getMessage(), exception); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\operation\AbstractEventAtomicOperation.java
1
请在Spring Boot框架中完成以下Java代码
public Object aggregationGroupFirst() { // 先对数据进行排序,然后使用管道操作符 $group 进行分组,最后统计各个组文档某字段值第一个值 AggregationOperation sort = Aggregation.sort(Sort.by("salary").ascending()); AggregationOperation group = Aggregation.group("sex").first("salary").as("salaryFirst"); // 将操作加入到聚合对象中 Aggregation aggregation = Aggregation.newAggregation(sort, group); // 执行聚合查询 AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class); for (Map result : results.getMappedResults()) { log.info("{}", result); } return results.getMappedResults(); } /** * 使用管道操作符 $group 结合表达式操作符 $last 获取每个组的包含某字段的文档的最后一条数据 * * @return 聚合结果 */ public Object aggregationGroupLast() { // 先对数据进行排序,然后使用管道操作符 $group 进行分组,最后统计各个组文档某字段值第最后一个值 AggregationOperation sort = Aggregation.sort(Sort.by("salary").ascending()); AggregationOperation group = Aggregation.group("sex").last("salary").as("salaryLast"); // 将操作加入到聚合对象中 Aggregation aggregation = Aggregation.newAggregation(sort, group); // 执行聚合查询
AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class); for (Map result : results.getMappedResults()) { log.info("{}", result); } return results.getMappedResults(); } /** * 使用管道操作符 $group 结合表达式操作符 $push 获取某字段列表 * * @return 聚合结果 */ public Object aggregationGroupPush() { // 先对数据进行排序,然后使用管道操作符 $group 进行分组,然后以数组形式列出某字段的全部值 AggregationOperation push = Aggregation.group("sex").push("salary").as("salaryFirst"); // 将操作加入到聚合对象中 Aggregation aggregation = Aggregation.newAggregation(push); // 执行聚合查询 AggregationResults<Map> results = mongoTemplate.aggregate(aggregation, COLLECTION_NAME, Map.class); for (Map result : results.getMappedResults()) { log.info("{}", result); } return results.getMappedResults(); } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\AggregateGroupService.java
2
请完成以下Java代码
private void clear() { // if (m_lookup != null) // { // m_lookup.clear(); // } if (m_lookupDirect != null) { m_lookupDirect.clear(); } } static ArrayKey createValidationKey(final IValidationContext validationCtx, final MLookupInfo lookupInfo, final Object parentValidationKey) { final List<Object> keys = new ArrayList<>(); // final String rowIndexStr = validationCtx.get_ValueAsString(GridTab.CTX_CurrentRow); // keys.add(rowIndexStr); if (IValidationContext.NULL != validationCtx) { for (final String parameterName : lookupInfo.getValidationRule().getAllParameters()) { final String parameterValue = validationCtx.get_ValueAsString(parameterName); keys.add(parameterName); keys.add(parameterValue); } } keys.add(parentValidationKey); return new ArrayKey(keys.toArray()); } // metas: begin @Override public String getTableName() { return m_info.getTableName().getAsString(); } @Override public boolean isAutoComplete() { return m_info != null && m_info.isAutoComplete(); }
public MLookupInfo getLookupInfo() { return m_info; } @Override public Set<String> getParameters() { return m_info.getValidationRule().getAllParameters(); } @Override public IValidationContext getValidationContext() { return m_evalCtx; } public boolean isNumericKey() { return getColumnName().endsWith("_ID"); } @Override public NamePair suggestValidValue(final NamePair value) { return null; } } // MLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLookup.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setC_User_Role_ID (final int C_User_Role_ID) { if (C_User_Role_ID < 1) set_ValueNoCheck (COLUMNNAME_C_User_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_C_User_Role_ID, C_User_Role_ID); } @Override public int getC_User_Role_ID() { return get_ValueAsInt(COLUMNNAME_C_User_Role_ID); } @Override public void setIsUniqueForBPartner (final boolean IsUniqueForBPartner) { set_Value (COLUMNNAME_IsUniqueForBPartner, IsUniqueForBPartner); } @Override public boolean isUniqueForBPartner()
{ return get_ValueAsBoolean(COLUMNNAME_IsUniqueForBPartner); } @Override public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_User_Role.java
1
请完成以下Java代码
public void setLength (final @Nullable BigDecimal Length) { set_Value (COLUMNNAME_Length, Length); } @Override public BigDecimal getLength() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Length); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setMaxLoadWeight (final @Nullable BigDecimal MaxLoadWeight) { set_Value (COLUMNNAME_MaxLoadWeight, MaxLoadWeight); } @Override public BigDecimal getMaxLoadWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_MaxLoadWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setM_HU_PackingMaterial_ID (final int M_HU_PackingMaterial_ID) { if (M_HU_PackingMaterial_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PackingMaterial_ID, M_HU_PackingMaterial_ID); } @Override public int getM_HU_PackingMaterial_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PackingMaterial_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID);
} @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setStackabilityFactor (final int StackabilityFactor) { set_Value (COLUMNNAME_StackabilityFactor, StackabilityFactor); } @Override public int getStackabilityFactor() { return get_ValueAsInt(COLUMNNAME_StackabilityFactor); } @Override public void setWidth (final @Nullable BigDecimal Width) { set_Value (COLUMNNAME_Width, Width); } @Override public BigDecimal getWidth() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PackingMaterial.java
1
请完成以下Java代码
public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, credentials, contractGasProvider, BINARY, ""); } public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return deployRemoteCall(Lottery.class, web3j, transactionManager, contractGasProvider, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, credentials, gasPrice, gasLimit, BINARY, ""); } @Deprecated public static RemoteCall<Lottery> deploy(Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return deployRemoteCall(Lottery.class, web3j, transactionManager, gasPrice, gasLimit, BINARY, ""); } @Deprecated public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, credentials, gasPrice, gasLimit);
} @Deprecated public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, BigInteger gasPrice, BigInteger gasLimit) { return new Lottery(contractAddress, web3j, transactionManager, gasPrice, gasLimit); } public static Lottery load(String contractAddress, Web3j web3j, Credentials credentials, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, credentials, contractGasProvider); } public static Lottery load(String contractAddress, Web3j web3j, TransactionManager transactionManager, ContractGasProvider contractGasProvider) { return new Lottery(contractAddress, web3j, transactionManager, contractGasProvider); } }
repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\model\Lottery.java
1
请完成以下Java代码
public int getM_PropertiesConfig_Line_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PropertiesConfig_Line_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name);
} /** Set Suchschlüssel. @param Value Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PropertiesConfig_Line.java
1
请完成以下Java代码
public static Integer findMajorityElementUsingSorting(int[] nums) { Arrays.sort(nums); int majorityThreshold = nums.length / 2; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] == nums[majorityThreshold]) { count++; } if (count > majorityThreshold) { return nums[majorityThreshold]; } } return null; } public static Integer findMajorityElementUsingHashMap(int[] nums) { Map<Integer, Integer> frequencyMap = new HashMap<>(); for (int num : nums) { frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1); } int majorityThreshold = nums.length / 2; for (Map.Entry<Integer, Integer> entry : frequencyMap.entrySet()) { if (entry.getValue() > majorityThreshold) { return entry.getKey(); } } return null; } public static Integer findMajorityElementUsingMooreVoting(int[] nums) { int majorityThreshold = nums.length / 2; int candidate = nums[0]; int count = 1; for (int i = 1; i < nums.length; i++) { if (count == 0) { candidate = nums[i]; count = 1; } else if (candidate == nums[i]) { count++; } else { count--; }
System.out.println("Iteration " + i + ": [candidate - " + candidate + ", count - " + count + ", element - " + nums[i] + "]"); } count = 0; for (int num : nums) { if (num == candidate) { count++; } } return count > majorityThreshold ? candidate : null; } public static void main(String[] args) { int[] nums = { 2, 3, 2, 4, 2, 5, 2 }; Integer majorityElement = findMajorityElementUsingMooreVoting(nums); if (majorityElement != null) { System.out.println("Majority element with maximum occurrences: " + majorityElement); } else { System.out.println("No majority element found"); } } }
repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-2\src\main\java\com\baeldung\majorityelement\FindMajorityElement.java
1
请完成以下Java代码
public static void applyNotOperatorToAnExpression_example1() { int count = 2; System.out.println(!(count > 2)); // prints true System.out.println(!(count <= 2)); // prints false } public static void applyNotOperatorToAnExpression_LogicalOperators() { boolean x = true; boolean y = false; System.out.println(!(x && y)); // prints true System.out.println(!(x || y)); // prints false } public static void precedence_example() { boolean x = true; boolean y = false; System.out.println(!x && y); // prints false System.out.println(!(x && y)); // prints true } public static void pitfalls_ComplexConditionsExample() { int count = 9; int total = 100; if (!(count >= 10 || total >= 1000)) { System.out.println("Some more work to do"); } }
public static void pitfalls_simplifyComplexConditionsByReversingLogicExample() { int count = 9; int total = 100; if (count < 10 && total < 1000) { System.out.println("Some more work to do"); } } public static void exitEarlyExample() { boolean isValid = false; if(!isValid) { throw new IllegalArgumentException("Invalid input"); } // Code to execute when isValid == true goes here } }
repos\tutorials-master\core-java-modules\core-java-lang-syntax-2\src\main\java\com\baeldung\core\operators\notoperator\NotOperator.java
1
请完成以下Java代码
public void exportExcel(HttpServletResponse response) { List<Person> list = new ArrayList<>(); list.add(new Person(1L, "姓名1", 28, "地址1")); list.add(new Person(2L, "姓名2", 29, "地址2")); String[] headers = new String[]{"ID", "名称", "年龄", "地址"}; List<String[]> contents = new ArrayList<>(list.size()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); for (Person person : list) { int i = 0; String[] row = new String[headers.length]; row[i++] = person.getId() + ""; row[i++] = person.getName(); row[i++] = person.getAge() + ""; row[i++] = person.getAddress(); contents.add(row); } ExcelExportUtils.exportExcel("PersonInfo", headers, contents, response); } @GetMapping("/csv") public void exportCsv(HttpServletResponse response) throws IOException { String fileName = "PersonInfo"; List<String> titles = Arrays.asList("ID", "名称", "年龄", "地址"); List<Person> list = new ArrayList<>(); list.add(new Person(1L, "姓名1", 28, "地址1"));
list.add(new Person(2L, "姓名2", 29, "地址2")); List<List<Object>> dataList = list.stream().map(person -> { List<Object> data = new ArrayList<>(); data.add(person.getId()); data.add(person.getName()); data.add(person.getAge()); data.add(person.getAddress()); return data; }).collect(Collectors.toList()); OutputStream os = response.getOutputStream(); CsvExportUtil.responseSetProperties(fileName, response); CsvExportUtil.doExportByList(dataList, titles, os); CsvExportUtil.doExportByList(dataList, null, os); } }
repos\spring-boot-student-master\spring-boot-student-export\src\main\java\com\xiaolyuh\ExprotController.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; JobEntity other = (JobEntity) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; return true; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<>(); if (exceptionByteArrayId != null) { referenceIdAndClass.put(exceptionByteArrayId, ByteArrayEntity.class); } return referenceIdAndClass; } @Override public Map<String, Class> getDependentEntities() { return persistedDependentEntities; } @Override public void postLoad() { if (exceptionByteArrayId != null) { persistedDependentEntities = new HashMap<>(); persistedDependentEntities.put(exceptionByteArrayId, ByteArrayEntity.class); } else { persistedDependentEntities = Collections.EMPTY_MAP; } } public String getLastFailureLogId() { return lastFailureLogId; } public void setLastFailureLogId(String lastFailureLogId) { this.lastFailureLogId = lastFailureLogId; } @Override public String getFailedActivityId() { return failedActivityId; } public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", revision=" + revision + ", duedate=" + duedate + ", lockOwner=" + lockOwner + ", lockExpirationTime=" + lockExpirationTime + ", executionId=" + executionId + ", processInstanceId=" + processInstanceId + ", isExclusive=" + isExclusive + ", jobDefinitionId=" + jobDefinitionId + ", jobHandlerType=" + jobHandlerType + ", jobHandlerConfiguration=" + jobHandlerConfiguration + ", exceptionByteArray=" + exceptionByteArray + ", exceptionByteArrayId=" + exceptionByteArrayId + ", exceptionMessage=" + exceptionMessage + ", failedActivityId=" + failedActivityId + ", deploymentId=" + deploymentId + ", priority=" + priority + ", tenantId=" + tenantId + ", batchId=" + batchId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobEntity.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getAddressName() { return addressName; } public void setAddressName(String addressName) { this.addressName = addressName; } public Integer getSendStatus() { return sendStatus; } public void setSendStatus(Integer sendStatus) { this.sendStatus = sendStatus; } public Integer getReceiveStatus() { return receiveStatus; } public void setReceiveStatus(Integer receiveStatus) { this.receiveStatus = receiveStatus; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getProvince() { return province; } public void setProvince(String province) { this.province = province; } public String getCity() { return city; } public void setCity(String city) { this.city = city; }
public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getDetailAddress() { return detailAddress; } public void setDetailAddress(String detailAddress) { this.detailAddress = detailAddress; } @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(", addressName=").append(addressName); sb.append(", sendStatus=").append(sendStatus); sb.append(", receiveStatus=").append(receiveStatus); sb.append(", name=").append(name); sb.append(", phone=").append(phone); sb.append(", province=").append(province); sb.append(", city=").append(city); sb.append(", region=").append(region); sb.append(", detailAddress=").append(detailAddress); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsCompanyAddress.java
1
请在Spring Boot框架中完成以下Java代码
public <T extends DeliveryMethodNotificationTemplate> T getProcessedTemplate(NotificationDeliveryMethod deliveryMethod, NotificationRecipient recipient) { T template = (T) templates.get(deliveryMethod); if (recipient != null) { Map<String, String> additionalTemplateContext = createTemplateContextForRecipient(recipient); if (template.getTemplatableValues().stream().anyMatch(value -> value.containsParams(additionalTemplateContext.keySet()))) { template = processTemplate(template, additionalTemplateContext); } } return template; } private <T extends DeliveryMethodNotificationTemplate> T processTemplate(T template, Map<String, String> additionalTemplateContext) { Map<String, String> templateContext = new HashMap<>(); if (request.getInfo() != null) { templateContext.putAll(request.getInfo().getTemplateData()); } if (additionalTemplateContext != null) { templateContext.putAll(additionalTemplateContext); } if (templateContext.isEmpty()) return template; template = (T) template.copy(); template.getTemplatableValues().forEach(templatableValue -> { String value = templatableValue.get();
if (StringUtils.isNotEmpty(value)) { value = TemplateUtils.processTemplate(value, templateContext); templatableValue.set(value); } }); return template; } private Map<String, String> createTemplateContextForRecipient(NotificationRecipient recipient) { return Map.of( "recipientTitle", recipient.getTitle(), "recipientEmail", Strings.nullToEmpty(recipient.getEmail()), "recipientFirstName", Strings.nullToEmpty(recipient.getFirstName()), "recipientLastName", Strings.nullToEmpty(recipient.getLastName()) ); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\NotificationProcessingContext.java
2
请完成以下Java代码
public static class CreatePartitionAsyncRequest extends CreatePartitionRequest { private final int count; private final Date dontReEnqueueAfter; private final CreatePartitionRequest partitionRequest; private CreatePartitionAsyncRequest( final CreatePartitionRequest partitionRequest, final int count, final Date dontReEnqueueAfter) { super(partitionRequest.getConfig(), partitionRequest.isOldestFirst(), partitionRequest.getRecordToAttach(), partitionRequest.getPartitionToComplete(), partitionRequest.getOnNotDLMTable()); this.partitionRequest = partitionRequest; // we use it for the toString() method this.count = count; this.dontReEnqueueAfter = dontReEnqueueAfter; } /** * Only enqueue the given number of work packages (one after each other). * * @return */ public int getCount() {
return count; } /** * Don't enqueue another workpackage after the given time has passed. One intended usage scenario is to start partitioning in the evening and stop in the morning. * * @return never returns <code>null</code>, but might return <code>9999-12-31</code>. */ public Date getDontReEnqueueAfter() { return dontReEnqueueAfter; } @Override public String toString() { return "CreatePartitionAsyncRequest [count=" + count + ", dontReEnqueueAfter=" + dontReEnqueueAfter + ", partitionRequest=" + partitionRequest + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\PartitionRequestFactory.java
1
请完成以下Java代码
public <T extends ModelElementInstance> ModelElementTypeBuilder instanceProvider(ModelTypeInstanceProvider<T> instanceProvider) { modelType.setInstanceProvider(instanceProvider); return this; } public ModelElementTypeBuilder namespaceUri(String namespaceUri) { modelType.setTypeNamespace(namespaceUri); return this; } public AttributeBuilder<Boolean> booleanAttribute(String attributeName) { BooleanAttributeBuilder builder = new BooleanAttributeBuilder(attributeName, modelType); modelBuildOperations.add(builder); return builder; } public StringAttributeBuilder stringAttribute(String attributeName) { StringAttributeBuilderImpl builder = new StringAttributeBuilderImpl(attributeName, modelType); modelBuildOperations.add(builder); return builder; } public AttributeBuilder<Integer> integerAttribute(String attributeName) { IntegerAttributeBuilder builder = new IntegerAttributeBuilder(attributeName, modelType); modelBuildOperations.add(builder); return builder; } public AttributeBuilder<Double> doubleAttribute(String attributeName) { DoubleAttributeBuilder builder = new DoubleAttributeBuilder(attributeName, modelType); modelBuildOperations.add(builder); return builder; } public <V extends Enum<V>> AttributeBuilder<V> enumAttribute(String attributeName, Class<V> enumType) { EnumAttributeBuilder<V> builder = new EnumAttributeBuilder<V>(attributeName, modelType, enumType); modelBuildOperations.add(builder); return builder; } public <V extends Enum<V>> AttributeBuilder<V> namedEnumAttribute(String attributeName, Class<V> enumType) {
NamedEnumAttributeBuilder<V> builder = new NamedEnumAttributeBuilder<V>(attributeName, modelType, enumType); modelBuildOperations.add(builder); return builder; } public ModelElementType build() { model.registerType(modelType, instanceType); return modelType; } public ModelElementTypeBuilder abstractType() { modelType.setAbstract(true); return this; } public SequenceBuilder sequence() { SequenceBuilderImpl builder = new SequenceBuilderImpl(modelType); modelBuildOperations.add(builder); return builder; } public void buildTypeHierarchy(Model model) { // build type hierarchy if(extendedType != null) { ModelElementTypeImpl extendedModelElementType = (ModelElementTypeImpl) model.getType(extendedType); if(extendedModelElementType == null) { throw new ModelException("Type "+modelType+" is defined to extend "+extendedType+" but no such type is defined."); } else { modelType.setBaseType(extendedModelElementType); extendedModelElementType.registerExtendingType(modelType); } } } public void performModelBuild(Model model) { for (ModelBuildOperation operation : modelBuildOperations) { operation.performModelBuild(model); } } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeBuilderImpl.java
1
请完成以下Java代码
public BigDecimal getSetupTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_SetupTime); if (bd == null) return Env.ZERO; return bd; } /** Set Teardown Time. @param TeardownTime Time at the end of the operation */ public void setTeardownTime (BigDecimal TeardownTime) { set_Value (COLUMNNAME_TeardownTime, TeardownTime); } /** Get Teardown Time. @return Time at the end of the operation */ public BigDecimal getTeardownTime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TeardownTime); if (bd == null) return Env.ZERO; return bd; }
/** Set Runtime per Unit. @param UnitRuntime Time to produce one unit */ public void setUnitRuntime (BigDecimal UnitRuntime) { set_Value (COLUMNNAME_UnitRuntime, UnitRuntime); } /** Get Runtime per Unit. @return Time to produce one unit */ public BigDecimal getUnitRuntime () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitRuntime); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_OperationResource.java
1