instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class GroupTemplateCompensationLine { public static GroupTemplateCompensationLine ofProductId(@NonNull final ProductId productId) { return builder() .productId(productId) .build(); } @Nullable GroupTemplateLineId id; @NonNull ProductId productId; @Nullable GroupCompensationType compensationType; @Nullable Percent percentage; @NonNull GroupMatcher groupMatcher; @Builder private GroupTemplateCompensationLine( @Nullable final GroupTemplateLineId id, @NonNull final ProductId productId,
@Nullable final GroupCompensationType compensationType, @Nullable final Percent percentage, @Nullable final GroupMatcher groupMatcher) { this.id = id; this.productId = productId; this.compensationType = compensationType; this.percentage = percentage; this.groupMatcher = groupMatcher != null ? groupMatcher : GroupMatchers.ALWAYS; } public boolean isMatching(@NonNull final Group group) { return getGroupMatcher().isMatching(group); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupTemplateCompensationLine.java
2
请在Spring Boot框架中完成以下Java代码
public JSONObject checkValue(SysCheckRule checkRule, String value) { if (checkRule != null && StringUtils.isNotBlank(value)) { String ruleJson = checkRule.getRuleJson(); if (StringUtils.isNotBlank(ruleJson)) { // 开始截取的下标,根据规则的顺序递增,但是 * 号不计入递增范围 int beginIndex = 0; JSONArray rules = JSON.parseArray(ruleJson); for (int i = 0; i < rules.size(); i++) { JSONObject result = new JSONObject(); JSONObject rule = rules.getJSONObject(i); // 位数 String digits = rule.getString("digits"); result.put("digits", digits); // 验证规则 String pattern = rule.getString("pattern"); result.put("pattern", pattern); // 未通过时的提示文本 String message = rule.getString("message"); result.put("message", message); // 根据用户设定的区间,截取字符串进行验证 String checkValue; // 是否检查整个值而不截取 if (CHECK_ALL_SYMBOL.equals(digits)) { checkValue = value; } else { int num = Integer.parseInt(digits); int endIndex = beginIndex + num; // 如果结束下标大于给定的值的长度,则取到最后一位 endIndex = endIndex > value.length() ? value.length() : endIndex;
// 如果开始下标大于结束下标,则说明用户还尚未输入到该位置,直接赋空值 if (beginIndex > endIndex) { checkValue = ""; } else { checkValue = value.substring(beginIndex, endIndex); } result.put("beginIndex", beginIndex); result.put("endIndex", endIndex); beginIndex += num; } result.put("checkValue", checkValue); boolean passed = Pattern.matches(pattern, checkValue); result.put("passed", passed); // 如果没有通过校验就返回错误信息 if (!passed) { return result; } } } } return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysCheckRuleServiceImpl.java
2
请完成以下Java代码
public void setName (final @Nullable java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setQtyAvailable (final @Nullable BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOnHand (final @Nullable BigDecimal QtyOnHand) { set_Value (COLUMNNAME_QtyOnHand, QtyOnHand); } @Override public BigDecimal getQtyOnHand() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOnHand); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyOrdered (final @Nullable BigDecimal QtyOrdered) { set_Value (COLUMNNAME_QtyOrdered, QtyOrdered); } @Override public BigDecimal getQtyOrdered() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered); return bd != null ? bd : BigDecimal.ZERO; } @Override
public void setQtyReserved (final @Nullable BigDecimal QtyReserved) { set_Value (COLUMNNAME_QtyReserved, QtyReserved); } @Override public BigDecimal getQtyReserved() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReserved); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValue (final @Nullable java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_RV_HU_Quantities_Summary.java
1
请在Spring Boot框架中完成以下Java代码
public void setJobRegistry(JobRegistry jobRegistry) { this.jobRegistry = jobRegistry; } public void setJobName(String jobName) { this.jobName = jobName; } @Autowired(required = false) public void setJobParametersConverter(JobParametersConverter converter) { this.converter = converter; } @Autowired(required = false) public void setJobs(Collection<Job> jobs) { this.jobs = jobs; } @Override public void run(ApplicationArguments args) throws Exception { String[] jobArguments = args.getNonOptionArgs().toArray(new String[0]); run(jobArguments); } public void run(String... args) throws JobExecutionException { logger.info("Running default command line with: " + Arrays.asList(args)); Properties properties = StringUtils.splitArrayElementsIntoProperties(args, "="); launchJobFromProperties((properties != null) ? properties : new Properties()); } protected void launchJobFromProperties(Properties properties) throws JobExecutionException { JobParameters jobParameters = this.converter.getJobParameters(properties); executeLocalJobs(jobParameters); executeRegisteredJobs(jobParameters); } private boolean isLocalJob(String jobName) { return this.jobs.stream().anyMatch((job) -> job.getName().equals(jobName)); } private boolean isRegisteredJob(String jobName) { return this.jobRegistry != null && this.jobRegistry.getJobNames().contains(jobName); }
private void executeLocalJobs(JobParameters jobParameters) throws JobExecutionException { for (Job job : this.jobs) { if (StringUtils.hasText(this.jobName)) { if (!this.jobName.equals(job.getName())) { logger.debug(LogMessage.format("Skipped job: %s", job.getName())); continue; } } execute(job, jobParameters); } } private void executeRegisteredJobs(JobParameters jobParameters) throws JobExecutionException { if (this.jobRegistry != null && StringUtils.hasText(this.jobName)) { if (!isLocalJob(this.jobName)) { Job job = this.jobRegistry.getJob(this.jobName); Assert.notNull(job, () -> "No job found with name '" + this.jobName + "'"); execute(job, jobParameters); } } } protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, InvalidJobParametersException { JobExecution execution = this.jobOperator.start(job, jobParameters); if (this.publisher != null) { this.publisher.publishEvent(new JobExecutionEvent(execution)); } } }
repos\spring-boot-4.0.1\module\spring-boot-batch\src\main\java\org\springframework\boot\batch\autoconfigure\JobLauncherApplicationRunner.java
2
请完成以下Java代码
public NoneEndEventActivityBehavior createNoneEndEventActivityBehavior(EndEvent endEvent) { return new NoneEndEventActivityBehavior(); } @Override public ErrorEndEventActivityBehavior createErrorEndEventActivityBehavior(EndEvent endEvent, ErrorEventDefinition errorEventDefinition) { return new ErrorEndEventActivityBehavior(errorEventDefinition.getErrorCode()); } @Override public CancelEndEventActivityBehavior createCancelEndEventActivityBehavior(EndEvent endEvent) { return new CancelEndEventActivityBehavior(); } @Override public TerminateEndEventActivityBehavior createTerminateEndEventActivityBehavior(EndEvent endEvent) {
return new TerminateEndEventActivityBehavior(endEvent); } // Boundary Events @Override public BoundaryEventActivityBehavior createBoundaryEventActivityBehavior(BoundaryEvent boundaryEvent, boolean interrupting, ActivityImpl activity) { return new BoundaryEventActivityBehavior(interrupting, activity.getId()); } @Override public CancelBoundaryEventActivityBehavior createCancelBoundaryEventActivityBehavior(CancelEventDefinition cancelEventDefinition) { return new CancelBoundaryEventActivityBehavior(); } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultActivityBehaviorFactory.java
1
请完成以下Java代码
protected String doIt() throws Exception { final List<I_M_ReceiptSchedule> receiptSchedules = getM_ReceiptSchedules(); final List<HuId> huIdsToReverse = retrieveHUsToReverse(); boolean hasChanges = false; try { for (final I_M_ReceiptSchedule receiptSchedule : receiptSchedules) { final ReceiptCorrectHUsProcessor processor = ReceiptCorrectHUsProcessor.builder() .setM_ReceiptSchedule(receiptSchedule) .tolerateNoHUsFound() .build(); if (processor.isNoHUsFound()) { continue; } final List<Integer> asRepoIds = RepoIdAwares.asRepoIds(huIdsToReverse); final List<I_M_InOut> receiptsToReverse = processor.getReceiptsToReverseFromHUIds(asRepoIds); if (receiptsToReverse.isEmpty()) { continue; } processor.reverseReceipts(receiptsToReverse); hasChanges = true; } } finally { if (hasChanges) { // Reset the view's affected HUs getView().removeHUIdsAndInvalidate(huIdsToReverse); // Notify all active views that given receipt schedules were changed viewsRepo.notifyRecordsChangedAsync(TableRecordReferenceSet.of(TableRecordReference.ofSet(receiptSchedules))); } } if (!hasChanges) { throw new AdempiereException("@NotFound@ @M_InOut_ID@"); } return MSG_OK; } @Override
protected HUEditorView getView() { return getView(HUEditorView.class); } private List<I_M_ReceiptSchedule> getM_ReceiptSchedules() { return getView() .getReferencingDocumentPaths().stream() .map(referencingDocumentPath -> documentsCollection.getTableRecordReference(referencingDocumentPath).getModel(this, I_M_ReceiptSchedule.class)) .collect(GuavaCollectors.toImmutableList()); } private List<HuId> retrieveHUsToReverse() { // gh #1955: prevent an OutOfMemoryError final IQueryFilter<I_M_HU> processFilter = getProcessInfo().getQueryFilterOrElse(ConstantQueryFilter.of(false)); return Services.get(IQueryBL.class).createQueryBuilder(I_M_HU.class, this) .filter(processFilter) .addOnlyActiveRecordsFilter() .create() .listIds() .stream() .map(HuId::ofRepoId) .collect(ImmutableList.toImmutableList()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReverseReceipt.java
1
请完成以下Java代码
public void setId(Integer value) { set(0, value); } /** * Getter for <code>public.BookAuthor.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>public.BookAuthor.name</code>. */ public void setName(String value) { set(1, value); } /** * Getter for <code>public.BookAuthor.name</code>. */ public String getName() { return (String) get(1); } /** * Setter for <code>public.BookAuthor.country</code>. */ public void setCountry(String value) { set(2, value); } /** * Getter for <code>public.BookAuthor.country</code>. */ public String getCountry() { return (String) get(2); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); }
// ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BookauthorRecord */ public BookauthorRecord() { super(Bookauthor.BOOKAUTHOR); } /** * Create a detached, initialised BookauthorRecord */ public BookauthorRecord(Integer id, String name, String country) { super(Bookauthor.BOOKAUTHOR); setId(id); setName(name); setCountry(country); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookauthorRecord.java
1
请在Spring Boot框架中完成以下Java代码
final class GrantedAuthorityDefaultsParserUtils { private GrantedAuthorityDefaultsParserUtils() { } static RootBeanDefinition registerWithDefaultRolePrefix(ParserContext pc, Class<? extends AbstractGrantedAuthorityDefaultsBeanFactory> beanFactoryClass) { RootBeanDefinition beanFactoryDefinition = new RootBeanDefinition(beanFactoryClass); String beanFactoryRef = pc.getReaderContext().generateBeanName(beanFactoryDefinition); pc.getRegistry().registerBeanDefinition(beanFactoryRef, beanFactoryDefinition); RootBeanDefinition bean = new RootBeanDefinition(); bean.setFactoryBeanName(beanFactoryRef); bean.setFactoryMethodName("getBean"); return bean; }
abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware { protected String rolePrefix = "ROLE_"; @Override public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException { applicationContext.getBeanProvider(GrantedAuthorityDefaults.class) .ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix()); } abstract Object getBean(); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\GrantedAuthorityDefaultsParserUtils.java
2
请在Spring Boot框架中完成以下Java代码
public void onSuccess(@Nullable List<String> result) { try { logTimeseriesDeleted(entityView.getTenantId(), user, entityId, result, null); } catch (ThingsboardException e) { log.error("Failed to log timeseries delete", e); } resultFuture.set(null); } @Override public void onFailure(Throwable t) { try { logTimeseriesDeleted(entityView.getTenantId(), user, entityId, Optional.ofNullable(keys).orElse(Collections.emptyList()), t); } catch (ThingsboardException e) { log.error("Failed to log timeseries delete", e); } resultFuture.setException(t); } }) .build());
return resultFuture; } private void logAttributesUpdated(TenantId tenantId, User user, EntityId entityId, AttributeScope scope, List<AttributeKvEntry> attributes, Throwable e) throws ThingsboardException { logEntityActionService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_UPDATED, user, toException(e), scope, attributes); } private void logAttributesDeleted(TenantId tenantId, User user, EntityId entityId, AttributeScope scope, List<String> keys, Throwable e) throws ThingsboardException { logEntityActionService.logEntityAction(tenantId, entityId, ActionType.ATTRIBUTES_DELETED, user, toException(e), scope, keys); } private void logTimeseriesDeleted(TenantId tenantId, User user, EntityId entityId, List<String> keys, Throwable e) throws ThingsboardException { logEntityActionService.logEntityAction(tenantId, entityId, ActionType.TIMESERIES_DELETED, user, toException(e), keys); } public static Exception toException(Throwable error) { return error != null ? (Exception.class.isInstance(error) ? (Exception) error : new Exception(error)) : null; } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\entitiy\entityview\DefaultTbEntityViewService.java
2
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_AD_LabelPrinter[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Label printer. @param AD_LabelPrinter_ID Label Printer Definition */ public void setAD_LabelPrinter_ID (int AD_LabelPrinter_ID) { if (AD_LabelPrinter_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_LabelPrinter_ID, Integer.valueOf(AD_LabelPrinter_ID)); } /** Get Label printer. @return Label Printer Definition */ public int getAD_LabelPrinter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_LabelPrinter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record
*/ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinter.java
1
请完成以下Java代码
public boolean containsAny(String... matchers) { for (String matcher : matchers) { if (contains(matcher)) { return true; } } return false; } /** * 所有都包含才返回true * * @param matchers 多个要判断的被包含项 */ public boolean containsAllIgnoreCase(String... matchers) { for (String matcher : matchers) { if (contains(matcher) == false) { return false; } } return true; } public NonCaseString trim() { return NonCaseString.of(this.value.trim()); } public NonCaseString replace(char oldChar, char newChar) { return NonCaseString.of(this.value.replace(oldChar, newChar)); } public NonCaseString replaceAll(String regex, String replacement) { return NonCaseString.of(this.value.replaceAll(regex, replacement)); } public NonCaseString substring(int beginIndex) { return NonCaseString.of(this.value.substring(beginIndex)); } public NonCaseString substring(int beginIndex, int endIndex) { return NonCaseString.of(this.value.substring(beginIndex, endIndex)); } public boolean isNotEmpty() { return !this.value.isEmpty(); } @Override public int length() { return this.value.length(); }
@Override public char charAt(int index) { return this.value.charAt(index); } @Override public CharSequence subSequence(int start, int end) { return this.value.subSequence(start, end); } public String[] split(String regex) { return this.value.split(regex); } /** * @return 原始字符串 */ public String get() { return this.value; } @Override public String toString() { return this.value; } }
repos\SpringBootCodeGenerator-master\src\main\java\com\softdev\system\generator\entity\NonCaseString.java
1
请完成以下Java代码
public boolean isEmpty() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".isEmpty() is not supported."); } @Override public boolean containsKey(Object key) { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsKey() is not supported."); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".containsValue() is not supported."); } @Override public Object remove(Object key) { throw new UnsupportedOperationException("ProcessVariableMap.remove is unsupported. Use ProcessVariableMap.put(key, null)"); } @Override public void clear() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".clear() is not supported.");
} @Override public Set<String> keySet() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".keySet() is not supported."); } @Override public Collection<Object> values() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".values() is not supported."); } @Override public Set<Map.Entry<String, Object>> entrySet() { throw new UnsupportedOperationException(ProcessVariableMap.class.getName() + ".entrySet() is not supported."); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\ProcessVariableMap.java
1
请完成以下Java代码
public int getPages() { return pages; } public void setPages(int pages) { this.pages = pages; } public Book getBook() { return book; } public void setBook(Book book) { this.book = book; } @Override public boolean equals(Object obj) { if (this == obj) { return true; }
if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } return id != null && id.equals(((Chapter) obj).id); } @Override public int hashCode() { return 2021; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDatabaseTriggers\src\main\java\com\bookstore\entity\Chapter.java
1
请完成以下Java代码
public void appendCell(final String value, int width) { final String valueNorm = CoalesceUtil.coalesceNotNull(value, ""); if (line == null) { line = new StringBuilder(); } if (line.length() == 0) { line.append(identString); line.append("|"); } line.append(" ").append(Strings.padEnd(valueNorm, width, ' ')).append(" |"); }
public void lineEnd() { if (line != null) { if (result.length() > 0) { result.append("\n"); } result.append(line); } line = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\TabularStringWriter.java
1
请完成以下Java代码
public GroupQuery groupId(String id) { ensureNotNull("Provided id", id); this.id = id; return this; } public GroupQuery groupIdIn(String... ids) { ensureNotNull("Provided ids", (Object[]) ids); this.ids = ids; return this; } public GroupQuery groupName(String name) { ensureNotNull("Provided name", name); this.name = name; return this; } public GroupQuery groupNameLike(String nameLike) { ensureNotNull("Provided nameLike", nameLike); this.nameLike = nameLike; return this; } public GroupQuery groupType(String type) { ensureNotNull("Provided type", type); this.type = type; return this; } public GroupQuery groupMember(String userId) { ensureNotNull("Provided userId", userId); this.userId = userId; return this; } public GroupQuery potentialStarter(String procDefId) { ensureNotNull("Provided processDefinitionId", procDefId); this.procDefId = procDefId; return this; } public GroupQuery memberOfTenant(String tenantId) { ensureNotNull("Provided tenantId", tenantId); this.tenantId = tenantId;
return this; } //sorting //////////////////////////////////////////////////////// public GroupQuery orderByGroupId() { return orderBy(GroupQueryProperty.GROUP_ID); } public GroupQuery orderByGroupName() { return orderBy(GroupQueryProperty.NAME); } public GroupQuery orderByGroupType() { return orderBy(GroupQueryProperty.TYPE); } //getters //////////////////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public String getType() { return type; } public String getUserId() { return userId; } public String getTenantId() { return tenantId; } public String[] getIds() { return ids; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\GroupQueryImpl.java
1
请完成以下Java代码
public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Rolle. @return Responsibility Role */ @Override public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } /** Set AD_Role_OrgAccess. @param AD_Role_OrgAccess_ID AD_Role_OrgAccess */ @Override public void setAD_Role_OrgAccess_ID (int AD_Role_OrgAccess_ID) { if (AD_Role_OrgAccess_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Role_OrgAccess_ID, Integer.valueOf(AD_Role_OrgAccess_ID)); } /** Get AD_Role_OrgAccess. @return AD_Role_OrgAccess */ @Override public int getAD_Role_OrgAccess_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_OrgAccess_ID);
if (ii == null) return 0; return ii.intValue(); } /** Set Schreibgeschützt. @param IsReadOnly Field is read only */ @Override public void setIsReadOnly (boolean IsReadOnly) { set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly)); } /** Get Schreibgeschützt. @return Field is read only */ @Override public boolean isReadOnly () { Object oo = get_Value(COLUMNNAME_IsReadOnly); 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_AD_Role_OrgAccess.java
1
请完成以下Java代码
public @Nullable CsrfToken loadToken(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return null; } return (CsrfToken) session.getAttribute(this.sessionAttributeName); } @Override public CsrfToken generateToken(HttpServletRequest request) { return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken()); } /** * Sets the {@link HttpServletRequest} parameter name that the {@link CsrfToken} is * expected to appear on * @param parameterName the new parameter name to use */ public void setParameterName(String parameterName) { Assert.hasLength(parameterName, "parameterName cannot be null or empty"); this.parameterName = parameterName; } /** * Sets the header name that the {@link CsrfToken} is expected to appear on and the * header that the response will contain the {@link CsrfToken}. * @param headerName the new header name to use */ public void setHeaderName(String headerName) { Assert.hasLength(headerName, "headerName cannot be null or empty"); this.headerName = headerName;
} /** * Sets the {@link HttpSession} attribute name that the {@link CsrfToken} is stored in * @param sessionAttributeName the new attribute name to use */ public void setSessionAttributeName(String sessionAttributeName) { Assert.hasLength(sessionAttributeName, "sessionAttributename cannot be null or empty"); this.sessionAttributeName = sessionAttributeName; } private String createNewToken() { return UUID.randomUUID().toString(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\csrf\HttpSessionCsrfTokenRepository.java
1
请完成以下Java代码
public class PickingSlotBL implements IPickingSlotBL { protected final IPickingSlotDAO pickingSlotDAO = Services.get(IPickingSlotDAO.class); @Override public boolean isAvailableForAnyBPartner(@NonNull final I_M_PickingSlot pickingSlot) { return PickingSlotUtils.isAvailableForAnyBPartner(pickingSlot); } @Override public boolean isAvailableForBPartnerId(@NonNull final I_M_PickingSlot pickingSlot, @Nullable final BPartnerId bpartnerId) { return PickingSlotUtils.isAvailableForBPartnerId(pickingSlot, bpartnerId); } @Override public boolean isAvailableForBPartnerAndLocation( @NonNull final I_M_PickingSlot pickingSlot, final BPartnerId bpartnerId, @Nullable final BPartnerLocationId bpartnerLocationId) { return PickingSlotUtils.isAvailableForBPartnerAndLocation(pickingSlot, bpartnerId, bpartnerLocationId); } @Override public PickingSlotIdAndCaption getPickingSlotIdAndCaption(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getPickingSlotIdAndCaption(pickingSlotId); } @Override public Set<PickingSlotIdAndCaption> getPickingSlotIdAndCaptions(@NonNull final PickingSlotQuery query) { return pickingSlotDAO.retrievePickingSlotIdAndCaptions(query); } @Override public QRCodePDFResource createQRCodesPDF(@NonNull final Set<PickingSlotIdAndCaption> pickingSlotIdAndCaptions) { Check.assumeNotEmpty(pickingSlotIdAndCaptions, "pickingSlotIdAndCaptions is not empty");
final ImmutableList<PrintableQRCode> qrCodes = pickingSlotIdAndCaptions.stream() .map(PickingSlotQRCode::ofPickingSlotIdAndCaption) .map(PickingSlotQRCode::toPrintableQRCode) .collect(ImmutableList.toImmutableList()); final GlobalQRCodeService globalQRCodeService = SpringContextHolder.instance.getBean(GlobalQRCodeService.class); return globalQRCodeService.createPDF(qrCodes); } @Override public boolean isAvailableForAnyBPartner(@NonNull final PickingSlotId pickingSlotId) { return isAvailableForAnyBPartner(pickingSlotDAO.getById(pickingSlotId)); } @NonNull public I_M_PickingSlot getById(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.getById(pickingSlotId); } @Override public boolean isPickingRackSystem(@NonNull final PickingSlotId pickingSlotId) { return pickingSlotDAO.isPickingRackSystem(pickingSlotId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\impl\PickingSlotBL.java
1
请完成以下Java代码
public int getM_Picking_Job_HUAlternative_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_HUAlternative_ID); } @Override public de.metas.handlingunits.model.I_M_Picking_Job getM_Picking_Job() { return get_ValueAsPO(COLUMNNAME_M_Picking_Job_ID, de.metas.handlingunits.model.I_M_Picking_Job.class); } @Override public void setM_Picking_Job(final de.metas.handlingunits.model.I_M_Picking_Job M_Picking_Job) { set_ValueFromPO(COLUMNNAME_M_Picking_Job_ID, de.metas.handlingunits.model.I_M_Picking_Job.class, M_Picking_Job); } @Override public void setM_Picking_Job_ID (final int M_Picking_Job_ID) { if (M_Picking_Job_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Picking_Job_ID, M_Picking_Job_ID); } @Override public int getM_Picking_Job_ID() { return get_ValueAsInt(COLUMNNAME_M_Picking_Job_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public de.metas.handlingunits.model.I_M_HU getPickFrom_HU() { return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU) { set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU); }
@Override public void setPickFrom_HU_ID (final int PickFrom_HU_ID) { if (PickFrom_HU_ID < 1) set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, null); else set_ValueNoCheck (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID); } @Override public int getPickFrom_HU_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID); } @Override public void setPickFrom_Locator_ID (final int PickFrom_Locator_ID) { if (PickFrom_Locator_ID < 1) set_Value (COLUMNNAME_PickFrom_Locator_ID, null); else set_Value (COLUMNNAME_PickFrom_Locator_ID, PickFrom_Locator_ID); } @Override public int getPickFrom_Locator_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Locator_ID); } @Override public void setPickFrom_Warehouse_ID (final int PickFrom_Warehouse_ID) { if (PickFrom_Warehouse_ID < 1) set_Value (COLUMNNAME_PickFrom_Warehouse_ID, null); else set_Value (COLUMNNAME_PickFrom_Warehouse_ID, PickFrom_Warehouse_ID); } @Override public int getPickFrom_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_PickFrom_Warehouse_ID); } @Override public void setQtyAvailable (final BigDecimal QtyAvailable) { set_Value (COLUMNNAME_QtyAvailable, QtyAvailable); } @Override public BigDecimal getQtyAvailable() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyAvailable); 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_Picking_Job_HUAlternative.java
1
请完成以下Java代码
public void propertyChange(PropertyChangeEvent evt) { contacts.clear(); if (info.isOkPressed()) { fetchSelectedContacts(info, contacts); } } }); AEnv.showCenterWindow(Env.getWindow(WindowNo), info.getWindow()); int count_added = 0; String msg = ""; try { TreeSet<Integer> addedBPartners = new TreeSet<Integer>(); for (BPartnerContact contact : contacts) { if (addedBPartners.contains(contact.getC_BPartner_ID())) { continue; } if (MRGroupProspect.existContact(ctx, R_Group_ID, contact.getC_BPartner_ID(), contact.getAD_User_ID(), null)) { log.info("Partner already added: " + contact + " [SKIP]"); continue; } if (contact.getAD_User_ID() <= 0) { log.warn("Invalid contact (no user found): " + contact + " [SKIP]"); continue; } MRGroupProspect rgp = new MRGroupProspect(ctx, R_Group_ID, contact.getC_BPartner_ID(), contact.getAD_User_ID(), null); rgp.saveEx(); // addedBPartners.add(contact.getC_BPartner_ID()); count_added++; } } finally { if (count_added > 0) { refreshIncludedTabs(mTab); msg = "@Added@ #" + count_added; } } log.info(msg); return ""; } private void fetchSelectedContacts(InfoSimple info, List<BPartnerContact> list) { final int rows = info.getRowCount(); for (int row = 0; row < rows; row++) { if (!info.isDataRow(row)) continue; if (info.isSelected(row)) { int bpartnerId = info.getValueAsInt(row, I_C_BPartner.COLUMNNAME_C_BPartner_ID); int userId = info.getValueAsInt(row, I_AD_User.COLUMNNAME_AD_User_ID); list.add(new BPartnerContact(bpartnerId, userId)); } } } /** * Refresh all included tabs * * @param mTab * parent tab */ private void refreshIncludedTabs(GridTab mTab) { for (GridTab detailTab : mTab.getIncludedTabs()) {
detailTab.dataRefreshAll(); } } public static class BPartnerContact { private final int C_BPartner_ID; private final int AD_User_ID; public BPartnerContact(int cBPartnerID, int aDUserID) { super(); C_BPartner_ID = cBPartnerID; AD_User_ID = aDUserID; } public int getC_BPartner_ID() { return C_BPartner_ID; } public int getAD_User_ID() { return AD_User_ID; } @Override public String toString() { return "BPartnerContact [C_BPartner_ID=" + C_BPartner_ID + ", AD_User_ID=" + AD_User_ID + "]"; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\callcenter\form\CalloutR_Group.java
1
请完成以下Java代码
public int getPP_Order_Node_Product_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Node_Product_ID); } @Override public void setPP_Order_Node_Product_ID(final int PP_Order_Node_Product_ID) { if (PP_Order_Node_Product_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Node_Product_ID, PP_Order_Node_Product_ID); } @Override public org.eevolution.model.I_PP_Order_Workflow getPP_Order_Workflow() { return get_ValueAsPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class); } @Override public void setPP_Order_Workflow(final org.eevolution.model.I_PP_Order_Workflow PP_Order_Workflow) { set_ValueFromPO(COLUMNNAME_PP_Order_Workflow_ID, org.eevolution.model.I_PP_Order_Workflow.class, PP_Order_Workflow); } @Override public int getPP_Order_Workflow_ID() { return get_ValueAsInt(COLUMNNAME_PP_Order_Workflow_ID); } @Override public void setPP_Order_Workflow_ID(final int PP_Order_Workflow_ID) { if (PP_Order_Workflow_ID < 1) set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, null); else set_ValueNoCheck(COLUMNNAME_PP_Order_Workflow_ID, PP_Order_Workflow_ID); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setQty(final @Nullable BigDecimal Qty) { set_Value(COLUMNNAME_Qty, Qty); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setSeqNo(final int SeqNo) { set_Value(COLUMNNAME_SeqNo, SeqNo); } @Override public java.lang.String getSpecification() { return get_ValueAsString(COLUMNNAME_Specification); } @Override public void setSpecification(final @Nullable java.lang.String Specification) { set_Value(COLUMNNAME_Specification, Specification); } @Override public BigDecimal getYield() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setYield(final @Nullable BigDecimal Yield) { set_Value(COLUMNNAME_Yield, Yield); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Node_Product.java
1
请完成以下Java代码
public class X_M_Tour extends org.compiere.model.PO implements I_M_Tour, org.compiere.model.I_Persistent { /** * */ private static final long serialVersionUID = -29589527L; /** Standard Constructor */ public X_M_Tour (Properties ctx, int M_Tour_ID, String trxName) { super (ctx, M_Tour_ID, trxName); /** if (M_Tour_ID == 0) { setM_Tour_ID (0); setName (null); } */ } /** Load Constructor */ public X_M_Tour (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Tour. @param M_Tour_ID Tour */ @Override public void setM_Tour_ID (int M_Tour_ID) { if (M_Tour_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Tour_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Tour_ID, Integer.valueOf(M_Tour_ID)); }
/** Get Tour. @return Tour */ @Override public int getM_Tour_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Tour_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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\tourplanning\model\X_M_Tour.java
1
请完成以下Java代码
private PartyIdentificationSEPA5 convertPartyIdentificationSEPA5( @NonNull final PartyIdentificationSEPA1 partyId, @NonNull final I_SEPA_Export_Line line) { final PartyIdentificationSEPA5 partyIdCopy = new PartyIdentificationSEPA5(); final BankAccountId bankAccountId = BankAccountId.ofRepoIdOrNull(line.getC_BP_BankAccount_ID()); if (bankAccountId == null) { partyIdCopy.setNm(SepaUtils.replaceForbiddenChars(partyId.getNm())); return partyIdCopy; } final BankAccount bankAccount = bankAccountService.getByIdNotNull(bankAccountId); partyIdCopy.setNm(Optional.ofNullable(StringUtils.trimBlankToNull(SepaUtils.replaceForbiddenChars(bankAccount.getAccountName()))) .orElseGet(() -> SepaUtils.replaceForbiddenChars(partyId.getNm()))); if (!bankAccount.isAddressComplete()) { return partyIdCopy; } final PostalAddressSEPA postalAddressSEPA = new PostalAddressSEPA(); if (Check.isNotBlank(bankAccount.getAccountCountry())) { postalAddressSEPA.setCtry(SepaUtils.replaceForbiddenChars(bankAccount.getAccountCountry())); } postalAddressSEPA.getAdrLine().add(SepaUtils.replaceForbiddenChars(bankAccount.getAccountStreet())); postalAddressSEPA.getAdrLine().add(SepaUtils.replaceForbiddenChars(bankAccount.getAccountZip() + " " + bankAccount.getAccountCity())); partyIdCopy.setPstlAdr(postalAddressSEPA); return partyIdCopy; } private PartyIdentificationSEPA3 convertPartyIdentificationSEPA3(@NonNull final I_SEPA_Export sepaHeader) { final PartyIdentificationSEPA3 partyIdCopy = new PartyIdentificationSEPA3(); final PartySEPA2 partySEPA = new PartySEPA2(); partyIdCopy.setId(partySEPA); final PersonIdentificationSEPA2 prvtId = new PersonIdentificationSEPA2();
partySEPA.setPrvtId(prvtId); final RestrictedPersonIdentificationSEPA othr = new RestrictedPersonIdentificationSEPA(); prvtId.setOthr(othr); final RestrictedPersonIdentificationSchemeNameSEPA schemeNm = new RestrictedPersonIdentificationSchemeNameSEPA(); othr.setId(sepaHeader.getSEPA_CreditorIdentifier()); // it's not mandatory, but we made sure that it was set for SEPA_Exports with this protocol othr.setSchmeNm(schemeNm); schemeNm.setPrtry(IdentificationSchemeNameSEPA.valueOf("SEPA")); // NOTE: address is not mandatory // FIXME: copy address if exists return partyIdCopy; } private String getSEPA_MandateRefNo(final I_SEPA_Export_Line line) { return CoalesceUtil.coalesceSuppliers( () -> line.getSEPA_MandateRefNo(), () -> getBPartnerValueById(line.getC_BPartner_ID()) + "-1"); } private String getBPartnerValueById(final int bpartnerRepoId) { return bpartnerService.getBPartnerValue(BPartnerId.ofRepoIdOrNull(bpartnerRepoId)).trim(); } private String getBPartnerNameById(final int bpartnerRepoId) { return bpartnerService.getBPartnerName(BPartnerId.ofRepoIdOrNull(bpartnerRepoId)).trim(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java\de\metas\payment\sepa\sepamarshaller\impl\SEPACustomerDirectDebitMarshaler_Pain_008_003_02.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.requestMatchers("/", "/index", "/authenticate") .permitAll() .requestMatchers("/secured/**/**", "/secured/**/**/**", "/secured/socket", "/secured/success") .authenticated() .anyRequest() .authenticated()) .formLogin(httpSecurityFormLoginConfigurer -> httpSecurityFormLoginConfigurer.loginPage("/login") .permitAll() .usernameParameter("username") .passwordParameter("password") .loginProcessingUrl("/authenticate") .successHandler(loginSuccessHandler()) .failureUrl("/denied") .permitAll()) .logout(httpSecurityLogoutConfigurer -> httpSecurityLogoutConfigurer.logoutSuccessHandler(logoutSuccessHandler())) /** * Applies to User Roles - not to login failures or unauthenticated access attempts. */ .exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer.accessDeniedHandler(accessDeniedHandler())) .authenticationProvider(authenticationProvider()); /** Disabled for local testing */ http.csrf(AbstractHttpConfigurer::disable); /** This is solely required to support H2 console viewing in Spring MVC with Spring Security */ http.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin())) .authorizeHttpRequests(Customizer.withDefaults()); return http.build();
} @Bean public AuthenticationManager authManager(HttpSecurity http) throws Exception { return http.getSharedObject(AuthenticationManagerBuilder.class) .authenticationProvider(authenticationProvider()) .build(); } @Bean public WebSecurityCustomizer webSecurityCustomizer() { return (web) -> web.ignoring().requestMatchers("/resources/**"); } }
repos\tutorials-master\spring-security-modules\spring-security-web-sockets\src\main\java\com\baeldung\springsecuredsockets\config\SecurityConfig.java
2
请完成以下Java代码
public static LocalDateAndOrgId ofNullableTimestamp(@Nullable final Timestamp timestamp, @NonNull final OrgId orgId, @NonNull final Function<OrgId, ZoneId> orgMapper) { return timestamp != null ? ofTimestamp(timestamp, orgId, orgMapper) : null; } @Nullable public static Timestamp toTimestamp( @Nullable final LocalDateAndOrgId localDateAndOrgId, @NonNull final Function<OrgId, ZoneId> orgMapper) { return localDateAndOrgId != null ? localDateAndOrgId.toTimestamp(orgMapper) : null; } public static long daysBetween(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { assertSameOrg(d2, d2); return ChronoUnit.DAYS.between(d1.toLocalDate(), d2.toLocalDate()); } private static void assertSameOrg(@NonNull final LocalDateAndOrgId d1, @NonNull final LocalDateAndOrgId d2) { Check.assumeEquals(d1.getOrgId(), d2.getOrgId(), "Dates have the same org: {}, {}", d1, d2); } public Instant toInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atStartOfDay().atZone(orgMapper.apply(orgId)).toInstant(); } public Instant toEndOfDayInstant(@NonNull final Function<OrgId, ZoneId> orgMapper) { return localDate.atTime(LocalTime.MAX).atZone(orgMapper.apply(orgId)).toInstant(); } public LocalDate toLocalDate() { return localDate; } public Timestamp toTimestamp(@NonNull final Function<OrgId, ZoneId> orgMapper) { return Timestamp.from(toInstant(orgMapper)); } @Override public int compareTo(final @Nullable LocalDateAndOrgId o) {
return compareToByLocalDate(o); } /** * In {@code LocalDateAndOrgId}, only the localDate is the actual data, while orgId is used to give context for reading & writing purposes. * A calendar date is directly comparable to another one, without regard of "from which org has this date been extracted?" * That's why a comparison by local date is enough to provide correct ordering, even with different {@code OrgId}s. * * @see #compareTo(LocalDateAndOrgId) */ private int compareToByLocalDate(final @Nullable LocalDateAndOrgId o) { if (o == null) { return 1; } return this.localDate.compareTo(o.localDate); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\LocalDateAndOrgId.java
1
请完成以下Java代码
public Class<? extends BaseElement> getBpmnElementType() { return BoundaryEvent.class; } @Override protected String getXMLElementName() { return ELEMENT_EVENT_BOUNDARY; } @Override protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception { BoundaryEvent boundaryEvent = new BoundaryEvent(); BpmnXMLUtil.addXMLLocation(boundaryEvent, xtr); if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY))) { String cancelActivity = xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY); if (ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(cancelActivity)) { boundaryEvent.setCancelActivity(false); } } boundaryEvent.setAttachedToRefId(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_ATTACHEDTOREF)); parseChildElements(getXMLElementName(), boundaryEvent, model, xtr); // Explicitly set cancel activity to false for error boundary events if (boundaryEvent.getEventDefinitions().size() == 1) { EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0); if (eventDef instanceof ErrorEventDefinition) { boundaryEvent.setCancelActivity(false); } } return boundaryEvent; }
@Override protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { BoundaryEvent boundaryEvent = (BoundaryEvent) element; if (boundaryEvent.getAttachedToRef() != null) { writeDefaultAttribute(ATTRIBUTE_BOUNDARY_ATTACHEDTOREF, boundaryEvent.getAttachedToRef().getId(), xtw); } if (boundaryEvent.getEventDefinitions().size() == 1) { EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0); if (eventDef instanceof ErrorEventDefinition == false) { writeDefaultAttribute( ATTRIBUTE_BOUNDARY_CANCELACTIVITY, String.valueOf(boundaryEvent.isCancelActivity()).toLowerCase(), xtw ); } } } @Override protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw) throws Exception { BoundaryEvent boundaryEvent = (BoundaryEvent) element; writeEventDefinitions(boundaryEvent, boundaryEvent.getEventDefinitions(), model, xtw); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\BoundaryEventXMLConverter.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Set Password Info. @param PasswordInfo Password Info */ public void setPasswordInfo (String PasswordInfo) { set_Value (COLUMNNAME_PasswordInfo, PasswordInfo); } /** Get Password Info. @return Password Info */ public String getPasswordInfo () { return (String)get_Value(COLUMNNAME_PasswordInfo); } /** Set Port. @param Port Port */ public void setPort (int Port) { set_Value (COLUMNNAME_Port, Integer.valueOf(Port)); } /** Get Port. @return Port */ public int getPort () { Integer ii = (Integer)get_Value(COLUMNNAME_Port); 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; } /** 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_IMP_Processor.java
1
请完成以下Java代码
public class ReceiveTaskImpl extends TaskImpl implements ReceiveTask { protected static Attribute<String> implementationAttribute; protected static Attribute<Boolean> instantiateAttribute; protected static AttributeReference<Message> messageRefAttribute; protected static AttributeReference<Operation> operationRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ReceiveTask.class, BPMN_ELEMENT_RECEIVE_TASK) .namespaceUri(BPMN20_NS) .extendsType(Task.class) .instanceProvider(new ModelTypeInstanceProvider<ReceiveTask>() { public ReceiveTask newInstance(ModelTypeInstanceContext instanceContext) { return new ReceiveTaskImpl(instanceContext); } }); implementationAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_IMPLEMENTATION) .defaultValue("##WebService") .build(); instantiateAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_INSTANTIATE) .defaultValue(false) .build(); messageRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_MESSAGE_REF) .qNameAttributeReference(Message.class) .build(); operationRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OPERATION_REF) .qNameAttributeReference(Operation.class) .build(); typeBuilder.build(); } public ReceiveTaskImpl(ModelTypeInstanceContext context) { super(context); } public ReceiveTaskBuilder builder() { return new ReceiveTaskBuilder((BpmnModelInstance) modelInstance, this); } public String getImplementation() { return implementationAttribute.getValue(this); } public void setImplementation(String implementation) { implementationAttribute.setValue(this, implementation); }
public boolean instantiate() { return instantiateAttribute.getValue(this); } public void setInstantiate(boolean instantiate) { instantiateAttribute.setValue(this, instantiate); } public Message getMessage() { return messageRefAttribute.getReferenceTargetElement(this); } public void setMessage(Message message) { messageRefAttribute.setReferenceTargetElement(this, message); } public Operation getOperation() { return operationRefAttribute.getReferenceTargetElement(this); } public void setOperation(Operation operation) { operationRefAttribute.setReferenceTargetElement(this, operation); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ReceiveTaskImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class UserController { @Value("${mail.domain}") private String mailDomain; private List<UserDTO> users = Arrays.asList(new UserDTO("Anil", "Allewar", "1", "anil.allewar@" + mailDomain), new UserDTO("Rohit", "Ghatol", "2", "rohit.ghatol@" + mailDomain), new UserDTO("John", "Snow", "3", "john.snow@" + mailDomain)); /** * Return all users * * @return */ @RequestMapping(method = RequestMethod.GET, headers = "Accept=application/json") public List<UserDTO> getUsers() { return users; } /** * Return user associated with specific user name * * @param userName
* @return */ @RequestMapping(value = "{userName}", method = RequestMethod.GET, headers = "Accept=application/json") public UserDTO getUserByUserName(@PathVariable("userName") String userName) { UserDTO userDtoToReturn = null; for (UserDTO currentUser : users) { if (currentUser.getUserName().equalsIgnoreCase(userName)) { userDtoToReturn = currentUser; break; } } return userDtoToReturn; } }
repos\spring-boot-microservices-master\user-webservice\src\main\java\com\rohitghatol\microservices\user\apis\UserController.java
2
请完成以下Java代码
public void deleteChildRecords(@NonNull final I_DataEntry_Field dataEntryFieldRecord) { Services.get(IQueryBL.class) .createQueryBuilder(I_DataEntry_ListValue.class) .addEqualsFilter(I_DataEntry_ListValue.COLUMN_DataEntry_Field_ID, dataEntryFieldRecord.getDataEntry_Field_ID()) .create() .delete(); } @CalloutMethod(columnNames = I_DataEntry_Field.COLUMNNAME_DataEntry_Line_ID) public void setSeqNo(@NonNull final I_DataEntry_Field dataEntryFieldRecord) { if (dataEntryFieldRecord.getDataEntry_Line_ID() <= 0) { return;
} dataEntryFieldRecord.setSeqNo(maxSeqNo(dataEntryFieldRecord) + 10); } private int maxSeqNo(@NonNull final I_DataEntry_Field dataEntryFieldRecord) { return Services .get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Field.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DataEntry_Field.COLUMN_DataEntry_Line_ID, dataEntryFieldRecord.getDataEntry_Line_ID()) .create() .maxInt(I_DataEntry_Tab.COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\interceptor\DataEntry_Field.java
1
请完成以下Java代码
protected void setSource(ActivityImpl source) { this.source = source; } @Override public ActivityImpl getDestination() { return destination; } public void setExecutionListeners(List<ExecutionListener> executionListeners) { this.executionListeners = executionListeners; } public List<Integer> getWaypoints() { return waypoints;
} public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } @Override public Expression getSkipExpression() { return skipExpression; } public void setSkipExpression(Expression skipExpression) { this.skipExpression = skipExpression; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\TransitionImpl.java
1
请完成以下Java代码
public String getActivityInstanceId() { return activityInstanceId; } public String getErrorMessage() { return errorMessage; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTypeName() { if(value != null) { return value.getType().getName(); } else { return null; } } public String getName() { return name; } public Object getValue() { if(value != null) { return value.getValue(); } else { return null; } } public TypedValue getTypedValue() { return value; }
public ProcessEngineServices getProcessEngineServices() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public ProcessEngine getProcessEngine() { return Context.getProcessEngineConfiguration().getProcessEngine(); } public static DelegateCaseVariableInstanceImpl fromVariableInstance(VariableInstance variableInstance) { DelegateCaseVariableInstanceImpl delegateInstance = new DelegateCaseVariableInstanceImpl(); delegateInstance.variableId = variableInstance.getId(); delegateInstance.processDefinitionId = variableInstance.getProcessDefinitionId(); delegateInstance.processInstanceId = variableInstance.getProcessInstanceId(); delegateInstance.executionId = variableInstance.getExecutionId(); delegateInstance.caseExecutionId = variableInstance.getCaseExecutionId(); delegateInstance.caseInstanceId = variableInstance.getCaseInstanceId(); delegateInstance.taskId = variableInstance.getTaskId(); delegateInstance.activityInstanceId = variableInstance.getActivityInstanceId(); delegateInstance.tenantId = variableInstance.getTenantId(); delegateInstance.errorMessage = variableInstance.getErrorMessage(); delegateInstance.name = variableInstance.getName(); delegateInstance.value = variableInstance.getTypedValue(); return delegateInstance; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\listener\DelegateCaseVariableInstanceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public ZoneId getZoneId() { return ZoneId.of(tz); } protected long getOffsetSafe() { return offsetSec != null ? offsetSec : 0L; } @Override public long getCurrentIntervalDurationMillis() { return getCurrentIntervalEndTs() - getCurrentIntervalStartTs(); } @Override public long getCurrentIntervalStartTs() { ZoneId zoneId = getZoneId(); ZonedDateTime now = ZonedDateTime.now(zoneId); return getDateTimeIntervalStartTs(now); } @Override public long getDateTimeIntervalStartTs(ZonedDateTime dateTime) { long offset = getOffsetSafe(); ZonedDateTime shiftedNow = dateTime.minusSeconds(offset); ZonedDateTime alignedStart = getAlignedBoundary(shiftedNow, false); ZonedDateTime actualStart = alignedStart.plusSeconds(offset); return actualStart.toInstant().toEpochMilli(); } @Override public long getCurrentIntervalEndTs() { ZoneId zoneId = getZoneId(); ZonedDateTime now = ZonedDateTime.now(zoneId); return getDateTimeIntervalEndTs(now); } @Override public long getDateTimeIntervalEndTs(ZonedDateTime dateTime) { long offset = getOffsetSafe(); ZonedDateTime shiftedNow = dateTime.minusSeconds(offset); ZonedDateTime alignedEnd = getAlignedBoundary(shiftedNow, true); ZonedDateTime actualEnd = alignedEnd.plusSeconds(offset); return actualEnd.toInstant().toEpochMilli(); } protected abstract ZonedDateTime alignToIntervalStart(ZonedDateTime reference);
protected ZonedDateTime getAlignedBoundary(ZonedDateTime reference, boolean next) { ZonedDateTime base = alignToIntervalStart(reference); return next ? getNextIntervalStart(base) : base; } @Override public void validate() { try { getZoneId(); } catch (Exception ex) { throw new IllegalArgumentException("Invalid timezone in interval: " + ex.getMessage()); } if (offsetSec != null) { if (offsetSec < 0) { throw new IllegalArgumentException("Offset cannot be negative."); } if (TimeUnit.SECONDS.toMillis(offsetSec) >= getCurrentIntervalDurationMillis()) { throw new IllegalArgumentException("Offset must be greater than interval duration."); } } } }
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\cf\configuration\aggregation\single\interval\BaseAggInterval.java
2
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer("MCash["); sb.append(get_ID()) .append("-").append(getName()) .append(", Balance=").append(getBeginningBalance()) .append("->").append(getEndingBalance()) .append("]"); return sb.toString(); } // toString /************************************************************************* * Get Summary * * @return Summary of Document */ @Override public String getSummary() { StringBuffer sb = new StringBuffer(); sb.append(getName()); // : Total Lines = 123.00 (#1) sb.append(": ") .append(Msg.translate(getCtx(), "BeginningBalance")).append("=").append(getBeginningBalance()) .append(",") .append(Msg.translate(getCtx(), "EndingBalance")).append("=").append(getEndingBalance()) .append(" (#").append(getLines(false).length).append(")"); // - Description if (getDescription() != null && getDescription().length() > 0) { sb.append(" - ").append(getDescription()); } return sb.toString(); } // getSummary @Override public LocalDate getDocumentDate() { return TimeUtil.asLocalDate(getStatementDate()); } /** * Get Process Message * * @return clear text error message */ @Override public String getProcessMsg() { return m_processMsg; } // getProcessMsg /** * Get Document Owner (Responsible) * * @return AD_User_ID */ @Override public int getDoc_User_ID() {
return getCreatedBy(); } // getDoc_User_ID /** * Get Document Approval Amount * * @return amount difference */ @Override public BigDecimal getApprovalAmt() { return getStatementDifference(); } // getApprovalAmt /** * Get Currency * * @return Currency */ @Override public int getC_Currency_ID() { return getCashBook().getC_Currency_ID(); } // getC_Currency_ID /** * Document Status is Complete or Closed * * @return true if CO, CL or RE */ public boolean isComplete() { String ds = getDocStatus(); return DOCSTATUS_Completed.equals(ds) || DOCSTATUS_Closed.equals(ds) || DOCSTATUS_Reversed.equals(ds); } // isComplete } // MCash
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MCash.java
1
请完成以下Java代码
public class ClusterAppAssignMap { private String machineId; private String ip; private Integer port; private Boolean belongToApp; private Set<String> clientSet; private Set<String> namespaceSet; private Double maxAllowedQps; public String getMachineId() { return machineId; } public ClusterAppAssignMap setMachineId(String machineId) { this.machineId = machineId; return this; } public String getIp() { return ip; } public ClusterAppAssignMap setIp(String ip) { this.ip = ip; return this; } public Integer getPort() { return port; } public ClusterAppAssignMap setPort(Integer port) { this.port = port; return this; } public Set<String> getClientSet() { return clientSet; } public ClusterAppAssignMap setClientSet(Set<String> clientSet) {
this.clientSet = clientSet; return this; } public Set<String> getNamespaceSet() { return namespaceSet; } public ClusterAppAssignMap setNamespaceSet(Set<String> namespaceSet) { this.namespaceSet = namespaceSet; return this; } public Boolean getBelongToApp() { return belongToApp; } public ClusterAppAssignMap setBelongToApp(Boolean belongToApp) { this.belongToApp = belongToApp; return this; } public Double getMaxAllowedQps() { return maxAllowedQps; } public ClusterAppAssignMap setMaxAllowedQps(Double maxAllowedQps) { this.maxAllowedQps = maxAllowedQps; return this; } @Override public String toString() { return "ClusterAppAssignMap{" + "machineId='" + machineId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", belongToApp=" + belongToApp + ", clientSet=" + clientSet + ", namespaceSet=" + namespaceSet + ", maxAllowedQps=" + maxAllowedQps + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterAppAssignMap.java
1
请完成以下Java代码
public PlanItemInstanceEntity getPlanItemInstanceEntity() { return planItemInstanceEntity; } public void setPlanItemInstanceEntity(PlanItemInstanceEntity planItemInstanceEntity) { this.planItemInstanceEntity = planItemInstanceEntity; } public String getFormKey() { return formKey; } public void setFormKey(String formKey) { this.formKey = formKey; } public String getAssignee() { return assignee; } public void setAssignee(String assignee) { this.assignee = assignee; } public String getOwner() { return owner; } public void setOwner(String owner) { this.owner = owner;
} public List<String> getCandidateUsers() { return candidateUsers; } public void setCandidateUsers(List<String> candidateUsers) { this.candidateUsers = candidateUsers; } public List<String> getCandidateGroups() { return candidateGroups; } public void setCandidateGroups(List<String> candidateGroups) { this.candidateGroups = candidateGroups; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateCasePageTaskBeforeContext.java
1
请完成以下Java代码
public DashboardInfo findFirstByTenantIdAndName(UUID tenantId, String name) { return DaoUtil.getData(dashboardInfoRepository.findFirstByTenantIdAndTitle(tenantId, name)); } @Override public String findTitleById(UUID tenantId, UUID dashboardId) { return dashboardInfoRepository.findTitleByTenantIdAndId(tenantId, dashboardId); } @Override public List<DashboardInfo> findDashboardsByIds(UUID tenantId, List<UUID> dashboardIds) { return DaoUtil.convertDataList(dashboardInfoRepository.findByIdIn(dashboardIds)); } @Override public List<DashboardInfo> findByTenantAndImageLink(TenantId tenantId, String imageLink, int limit) { return DaoUtil.convertDataList(dashboardInfoRepository.findByTenantAndImageLink(tenantId.getId(), imageLink, limit)); }
@Override public List<DashboardInfo> findByImageLink(String imageLink, int limit) { return DaoUtil.convertDataList(dashboardInfoRepository.findByImageLink(imageLink, limit)); } @Override public List<EntityInfo> findByTenantIdAndResource(TenantId tenantId, String reference, int limit) { return dashboardInfoRepository.findDashboardInfosByTenantIdAndResourceLink(tenantId.getId(), reference, PageRequest.of(0, limit)); } @Override public List<EntityInfo> findByResource(String reference, int limit) { return dashboardInfoRepository.findDashboardInfosByResourceLink(reference, PageRequest.of(0, limit)); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\dashboard\JpaDashboardInfoDao.java
1
请在Spring Boot框架中完成以下Java代码
public String getBindAddress() { return this.bindAddress; } public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public DeveloperRestApiProperties getDevRestApi() { return developerRestApiProperties; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public boolean isSslRequireAuthentication() { return this.sslRequireAuthentication; } public void setSslRequireAuthentication(boolean sslRequireAuthentication) { this.sslRequireAuthentication = sslRequireAuthentication; } } public static class MemcachedServerProperties { private static final int DEFAULT_PORT = 11211; private int port = DEFAULT_PORT; private EnableMemcachedServer.MemcachedProtocol protocol = EnableMemcachedServer.MemcachedProtocol.ASCII; public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } public EnableMemcachedServer.MemcachedProtocol getProtocol() { return this.protocol; }
public void setProtocol(EnableMemcachedServer.MemcachedProtocol protocol) { this.protocol = protocol; } } public static class RedisServerProperties { public static final int DEFAULT_PORT = 6379; private int port = DEFAULT_PORT; private String bindAddress; public String getBindAddress() { return this.bindAddress; } public void setBindAddress(String bindAddress) { this.bindAddress = bindAddress; } public int getPort() { return this.port; } public void setPort(int port) { this.port = port; } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\ServiceProperties.java
2
请完成以下Java代码
protected GenericApplicationContext prepareApplicationContext(Class<?> application) { return new AotProcessorHook(application).run(() -> { Method mainMethod = getMainMethod(application); mainMethod.setAccessible(true); if (mainMethod.getParameterCount() == 0) { ReflectionUtils.invokeMethod(mainMethod, null); } else { ReflectionUtils.invokeMethod(mainMethod, null, new Object[] { this.applicationArgs }); } return Void.class; }); } private static Method getMainMethod(Class<?> application) throws Exception { try { return application.getDeclaredMethod("main", String[].class); } catch (NoSuchMethodException ex) { return application.getDeclaredMethod("main"); } } public static void main(String[] args) throws Exception { int requiredArgs = 6; Assert.state(args.length >= requiredArgs, () -> "Usage: " + SpringApplicationAotProcessor.class.getName() + " <applicationMainClass> <sourceOutput> <resourceOutput> <classOutput> <groupId> <artifactId> <originalArgs...>"); Class<?> application = Class.forName(args[0]); Settings settings = Settings.builder() .sourceOutput(Paths.get(args[1])) .resourceOutput(Paths.get(args[2])) .classOutput(Paths.get(args[3])) .groupId((StringUtils.hasText(args[4])) ? args[4] : "unspecified") .artifactId(args[5]) .build(); String[] applicationArgs = (args.length > requiredArgs) ? Arrays.copyOfRange(args, requiredArgs, args.length) : new String[0]; new SpringApplicationAotProcessor(application, settings, applicationArgs).process(); } /** * {@link SpringApplicationHook} used to capture the {@link ApplicationContext} and * trigger early exit of main method. */ private static final class AotProcessorHook implements SpringApplicationHook { private final Class<?> application; private AotProcessorHook(Class<?> application) { this.application = application; } @Override public SpringApplicationRunListener getRunListener(SpringApplication application) { return new SpringApplicationRunListener() {
@Override public void contextLoaded(ConfigurableApplicationContext context) { throw new AbandonedRunException(context); } }; } private <T> GenericApplicationContext run(ThrowingSupplier<T> action) { try { SpringApplication.withHook(this, action); } catch (AbandonedRunException ex) { ApplicationContext context = ex.getApplicationContext(); Assert.state(context instanceof GenericApplicationContext, () -> "AOT processing requires a GenericApplicationContext but got a " + ((context != null) ? context.getClass().getName() : "null")); return (GenericApplicationContext) context; } throw new IllegalStateException( "No application context available after calling main method of '%s'. Does it run a SpringApplication?" .formatted(this.application.getName())); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationAotProcessor.java
1
请在Spring Boot框架中完成以下Java代码
public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @ApiModelProperty(example = "12") public String getParentDeploymentId() { return parentDeploymentId; } public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } public void setUrl(String url) {
this.url = url; } @ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10") public String getUrl() { return url; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "") public String getTenantId() { return tenantId; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\CmmnDeploymentResponse.java
2
请完成以下Java代码
public Date getGmtCreate() { return gmtCreate; } public void setGmtCreate(Date gmtCreate) { this.gmtCreate = gmtCreate; } public Date getGmtModified() { return gmtModified; } public void setGmtModified(Date gmtModified) { this.gmtModified = gmtModified; } public String getApp() { return app; } public void setApp(String app) { this.app = app; } public Integer getAppType() { return appType; } public void setAppType(Integer appType) { this.appType = appType; } public String getActiveConsole() { return activeConsole; } public Date getLastFetch() { return lastFetch; } public void setLastFetch(Date lastFetch) { this.lastFetch = lastFetch;
} public void setActiveConsole(String activeConsole) { this.activeConsole = activeConsole; } public AppInfo toAppInfo() { return new AppInfo(app, appType); } @Override public String toString() { return "ApplicationEntity{" + "id=" + id + ", gmtCreate=" + gmtCreate + ", gmtModified=" + gmtModified + ", app='" + app + '\'' + ", activeConsole='" + activeConsole + '\'' + ", lastFetch=" + lastFetch + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\datasource\entity\ApplicationEntity.java
1
请在Spring Boot框架中完成以下Java代码
public String remove(final Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(final Map<? extends String, ? extends String> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); }
@Override public Set<String> keySet() { return getMap().keySet(); } @Override public Collection<String> values() { return getMap().values(); } @Override public Set<java.util.Map.Entry<String, String>> entrySet() { return getMap().entrySet(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\ResourceBundleMapWrapper.java
2
请完成以下Java代码
public Optional<String> getUserAgent() {return getByPathAsString("device", "userAgent");} public Optional<String> getByPathAsString(final String... path) { return getByPath(path).map(Object::toString); } public Optional<Object> getByPath(final String... path) { Object currentValue = properties; for (final String pathElement : path) { if (!(currentValue instanceof Map)) { //throw new AdempiereException("Invalid path " + Arrays.asList(path) + " in " + properties); return Optional.empty(); } //noinspection unchecked final Object value = getByKey((Map<String, Object>)currentValue, pathElement).orElse(null); if (value == null) { return Optional.empty(); } else { currentValue = value;
} } return Optional.of(currentValue); } private static Optional<Object> getByKey(final Map<String, Object> map, final String key) { return map.entrySet() .stream() .filter(e -> e.getKey().equalsIgnoreCase(key)) .map(Map.Entry::getValue) .filter(Objects::nonNull) .findFirst(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\server\ui_trace\rest\JsonUITraceEvent.java
1
请完成以下Java代码
public class MSV3PurchaseOrderTransaction { private final OrgId orgId; @Getter private final OrderCreateRequest request; @Getter private OrderResponse response; private MSV3OrderResponsePackageItemPartRepoIds responseItemPartRepoIds; private FaultInfo faultInfo; private Exception otherException; @Builder private MSV3PurchaseOrderTransaction( @NonNull final OrderCreateRequest request, @NonNull final OrgId orgId) { this.request = request; this.orgId = orgId; } public I_MSV3_Bestellung_Transaction store() { final MSV3PurchaseOrderRequestPersister purchaseOrderRequestPersister = MSV3PurchaseOrderRequestPersister.createNewForOrgId(orgId); final I_MSV3_Bestellung_Transaction transactionRecord = newInstanceOutOfTrx(I_MSV3_Bestellung_Transaction.class); transactionRecord.setAD_Org_ID(orgId.getRepoId()); final I_MSV3_Bestellung requestRecord = purchaseOrderRequestPersister.storePurchaseOrderRequest(request); transactionRecord.setMSV3_Bestellung(requestRecord); if (response != null) { final MSV3PurchaseOrderResponsePersister purchaseOrderResponsePersister = MSV3PurchaseOrderResponsePersister.createNewForOrgId(orgId); final I_MSV3_BestellungAntwort bestellungAntwortRecord = // purchaseOrderResponsePersister.storePurchaseOrderResponse(response); transactionRecord.setMSV3_BestellungAntwort(bestellungAntwortRecord); responseItemPartRepoIds = purchaseOrderResponsePersister.getResponseItemPartRepoIds(); } if (faultInfo != null) {
final I_MSV3_FaultInfo faultInfoRecord = Msv3FaultInfoDataPersister .newInstanceWithOrgId(orgId) .storeMsv3FaultInfoOrNull(faultInfo); transactionRecord.setMSV3_FaultInfo(faultInfoRecord); } if (otherException != null) { final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(otherException); transactionRecord.setAD_Issue_ID(issueId.getRepoId()); } save(transactionRecord); return transactionRecord; } public RuntimeException getExceptionOrNull() { if (faultInfo == null && otherException == null) { return null; } return Msv3ClientException.builder() .msv3FaultInfo(faultInfo) .cause(otherException) .build(); } public MSV3OrderResponsePackageItemPartRepoId getResponseItemPartRepoId(final OrderResponsePackageItemPartId partId) { return responseItemPartRepoIds.getRepoId(partId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\purchaseOrder\MSV3PurchaseOrderTransaction.java
1
请完成以下Java代码
public void clear() { listeners.clear(); } @Override public void onAttributeValueCreated(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { for (final IAttributeStorageListener listener : listeners) { listener.onAttributeValueCreated(attributeValueContext, storage, attributeValue); } } @Override public void onAttributeValueChanged(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue, final Object valueOld) { for (final IAttributeStorageListener listener : listeners) { listener.onAttributeValueChanged(attributeValueContext, storage, attributeValue, valueOld); } } @Override public void onAttributeValueDeleted(final IAttributeValueContext attributeValueContext, final IAttributeStorage storage, final IAttributeValue attributeValue) { for (final IAttributeStorageListener listener : listeners) {
listener.onAttributeValueDeleted(attributeValueContext, storage, attributeValue); } } @Override public void onAttributeStorageDisposed(final IAttributeStorage storage) { // if a listener gets notified about this event, it might well remove itself from this composite. // In order to prevent a ConcurrentModificationException, we iterate a copy final ArrayList<IAttributeStorageListener> listenersToIterate = new ArrayList<>(listeners); for (final IAttributeStorageListener listener : listenersToIterate) { listener.onAttributeStorageDisposed(storage); } } @Override public String toString() { return "CompositeAttributeStorageListener [listeners=" + listeners + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageListener.java
1
请完成以下Java代码
public I_AD_Tab getTabByIdInTrx(@NonNull final AdTabId tabId) { // use the load with ITrx.TRXNAME_ThreadInherited because the tab may not yet be saved in DB when it's needed return load(tabId, I_AD_Tab.class); } @Override public void deleteUIElementsByFieldId(@NonNull final AdFieldId adFieldId) { queryBL.createQueryBuilder(I_AD_UI_Element.class) .addEqualsFilter(I_AD_UI_Element.COLUMN_AD_Field_ID, adFieldId) .create() .delete(); } @Override public void deleteUISectionsByTabId(@NonNull final AdTabId adTabId) { queryBL.createQueryBuilder(I_AD_UI_Section.class) .addEqualsFilter(I_AD_UI_Section.COLUMN_AD_Tab_ID, adTabId) .create() .delete(); } @Override public AdWindowId getAdWindowId( @NonNull final String tableName, @NonNull final SOTrx soTrx, @NonNull final AdWindowId defaultValue) { final I_AD_Table adTableRecord = adTableDAO.retrieveTable(tableName); switch (soTrx) { case SALES: return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getAD_Window_ID()), defaultValue); case PURCHASE: return CoalesceUtil.coalesce(AdWindowId.ofRepoIdOrNull(adTableRecord.getPO_Window_ID()), defaultValue); default: throw new AdempiereException("Param 'soTrx' has an unspupported value; soTrx=" + soTrx); } }
@Override public ImmutableSet<AdWindowId> retrieveAllAdWindowIdsByTableId(final AdTableId adTableId) { final List<AdWindowId> adWindowIds = queryBL.createQueryBuilder(I_AD_Tab.class) .addEqualsFilter(I_AD_Tab.COLUMNNAME_AD_Table_ID, adTableId) .create() .listDistinct(I_AD_Tab.COLUMNNAME_AD_Window_ID, AdWindowId.class); return ImmutableSet.copyOf(adWindowIds); } @Override public ImmutableSet<AdWindowId> retrieveAllActiveAdWindowIds() { return queryBL.createQueryBuilder(I_AD_Window.class) .addOnlyActiveRecordsFilter() .orderBy(I_AD_Window.COLUMNNAME_AD_Window_ID) .create() .idsAsSet(AdWindowId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\api\impl\ADWindowDAO.java
1
请完成以下Java代码
public void setOtherClause (String OtherClause) { set_Value (COLUMNNAME_OtherClause, OtherClause); } /** Get Other SQL Clause. @return Other SQL Clause */ public String getOtherClause () { return (String)get_Value(COLUMNNAME_OtherClause); } /** Set Sql WHERE. @param WhereClause
Fully qualified SQL WHERE clause */ public void setWhereClause (String WhereClause) { set_Value (COLUMNNAME_WhereClause, WhereClause); } /** Get Sql WHERE. @return Fully qualified SQL WHERE clause */ public String getWhereClause () { return (String)get_Value(COLUMNNAME_WhereClause); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_TemplateTable.java
1
请完成以下Java代码
private ImmutableSet<OrderAndLineId> getSelectedOrderAndLineIds() { final OrderId orderId = getOrderId(); return getSelectedIncludedRecordIds(I_C_OrderLine.class) .stream() .map(orderLineRepoId -> OrderAndLineId.ofRepoIds(orderId, orderLineRepoId)) .collect(ImmutableSet.toImmutableSet()); } @NonNull private OrderId getOrderId() { return OrderId.ofRepoId(getRecord_ID()); }
private I_C_Order getOrder(final OrderId orderId) { return orderCache.computeIfAbsent(orderId, orderBL::getById); } private CurrencyId getOrderCurrencyId() { return CurrencyId.ofRepoId(getOrder(getOrderId()).getC_Currency_ID()); } public boolean isSOTrx() { return getOrder(getOrderId()).isSOTrx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\costs\C_Order_CreateCost.java
1
请完成以下Java代码
public String getCamundaExpression() { return camundaExpressionAttribute.getValue(this); } public void setCamundaExpression(String camundaExpression) { camundaExpressionAttribute.setValue(this, camundaExpression); } public String getCamundaDelegateExpression() { return camundaDelegateExpressionAttribute.getValue(this); } public void setCamundaDelegateExpression(String camundaDelegateExpression) { camundaDelegateExpressionAttribute.setValue(this, camundaDelegateExpression); }
public Collection<CamundaField> getCamundaFields() { return camundaFieldCollection.get(this); } public CamundaScript getCamundaScript() { return camundaScriptChild.getChild(this); } public void setCamundaScript(CamundaScript camundaScript) { camundaScriptChild.setChild(this, camundaScript); } public Collection<TimerEventDefinition> getTimeouts() { return timeoutCollection.get(this); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\camunda\CamundaTaskListenerImpl.java
1
请完成以下Java代码
public boolean isPageLoaded() { return page != null; } public List<DocumentId> getRowIds() { if (rowIds != null) { return rowIds; } return getPage().stream().map(IViewRow::getId).collect(ImmutableList.toImmutableList()); } public boolean isEmpty() { return getPage().isEmpty();
} /** * @return loaded page * @throws IllegalStateException if the page is not loaded, see {@link #isPageLoaded()} */ public List<IViewRow> getPage() { if (page == null) { throw new IllegalStateException("page not loaded for " + this); } return page; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewResult.java
1
请完成以下Java代码
public void runSQLAfterRowImport(@NonNull final ImportRecordType importRecord) { final List<DBFunction> functions = dbFunctions.getAvailableAfterRowFunctions(); if (functions.isEmpty()) { return; } final DataImportConfigId dataImportConfigId = extractDataImportConfigId(importRecord).orElse(null); final Optional<Integer> recordId = InterfaceWrapperHelper.getValue(importRecord, getKeyColumnName()); functions.forEach(function -> { try { DBFunctionHelper.doDBFunctionCall(function, dataImportConfigId, recordId.orElse(0)); } catch (final Exception ex) { final AdempiereException metasfreshEx = AdempiereException.wrapIfNeeded(ex); final AdIssueId issueId = errorManager.createIssue(metasfreshEx); loggable.addLog("Failed running " + function + ": " + AdempiereException.extractMessage(metasfreshEx) + " (AD_Issue_ID=" + issueId.getRepoId() + ")"); throw metasfreshEx; } }); } @Override public void runSQLAfterAllImport() { final List<DBFunction> functions = dbFunctions.getAvailableAfterAllFunctions(); if (functions.isEmpty()) { return; } final DataImportRunId dataImportRunId = getDataImportRunIdOfImportedRecords(); functions.forEach(function -> { try { DBFunctionHelper.doDBFunctionCall(function, dataImportRunId); } catch (Exception ex) { final AdempiereException metasfreshEx = AdempiereException.wrapIfNeeded(ex); final AdIssueId issueId = errorManager.createIssue(metasfreshEx); loggable.addLog("Failed running " + function + ": " + AdempiereException.extractMessage(metasfreshEx) + " (AD_Issue_ID=" + issueId.getRepoId() + ")"); throw metasfreshEx; } });
} private DataImportRunId getDataImportRunIdOfImportedRecords() { final ImportRecordsSelection selection = getSelection(); final String importTableName = selection.getImportTableName(); return DataImportRunId.ofRepoIdOrNull( DB.getSQLValueEx( ITrx.TRXNAME_ThreadInherited, "SELECT " + ImportTableDescriptor.COLUMNNAME_C_DataImport_Run_ID + " FROM " + importTableName + " WHERE " + ImportTableDescriptor.COLUMNNAME_I_IsImported + "='Y' " + " " + selection.toSqlWhereClause(importTableName) ) ); } private Optional<DataImportConfigId> extractDataImportConfigId(@NonNull final ImportRecordType importRecord) { if (tableDescriptor.getDataImportConfigIdColumnName() == null) { return Optional.empty(); } final Optional<Integer> value = InterfaceWrapperHelper.getValue(importRecord, tableDescriptor.getDataImportConfigIdColumnName()); return value.map(DataImportConfigId::ofRepoIdOrNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\SqlImportSource.java
1
请完成以下Java代码
public boolean equals(Object obj) { boolean areEqual = (this == obj); if(!areEqual && obj != null && obj.getClass().equals(MDAGNode.class)) { MDAGNode node = (MDAGNode)obj; areEqual = (isAcceptNode == node.isAcceptNode && haveSameTransitions(this, node)); } return areEqual; } /** * Hashes this node using its accept state status and set of outgoing _transition paths. * This is an expensive operation, so the result is cached and only cleared when necessary. * @return an int of this node's hash code */ @Override public int hashCode() { if(storedHashCode == null) { int hash = 7; hash = 53 * hash + (this.isAcceptNode ? 1 : 0); hash = 53 * hash + (this.outgoingTransitionTreeMap != null ? this.outgoingTransitionTreeMap.hashCode() : 0); //recursively hashes the nodes in all the //_transition paths stemming from this node storedHashCode = hash; return hash; } else
return storedHashCode; } @Override public String toString() { final StringBuilder sb = new StringBuilder("MDAGNode{"); sb.append("isAcceptNode=").append(isAcceptNode); sb.append(", outgoingTransitionTreeMap=").append(outgoingTransitionTreeMap.keySet()); sb.append(", incomingTransitionCount=").append(incomingTransitionCount); // sb.append(", transitionSetBeginIndex=").append(transitionSetBeginIndex); // sb.append(", storedHashCode=").append(storedHashCode); sb.append('}'); return sb.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\MDAG\MDAGNode.java
1
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Increment. @param IncrementNo The number to increment the last document number by */ public void setIncrementNo (int IncrementNo) { set_Value (COLUMNNAME_IncrementNo, Integer.valueOf(IncrementNo)); } /** Get Increment. @return The number to increment the last document number by */ public int getIncrementNo () { Integer ii = (Integer)get_Value(COLUMNNAME_IncrementNo); if (ii == null) return 0; return ii.intValue(); } /** Set Serial No Control. @param M_SerNoCtl_ID Product Serial Number Control */ public void setM_SerNoCtl_ID (int M_SerNoCtl_ID) { if (M_SerNoCtl_ID < 1) set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, null); else set_ValueNoCheck (COLUMNNAME_M_SerNoCtl_ID, Integer.valueOf(M_SerNoCtl_ID)); } /** Get Serial No Control. @return Product Serial Number Control */ public int getM_SerNoCtl_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_SerNoCtl_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Prefix.
@param Prefix Prefix before the sequence number */ public void setPrefix (String Prefix) { set_Value (COLUMNNAME_Prefix, Prefix); } /** Get Prefix. @return Prefix before the sequence number */ public String getPrefix () { return (String)get_Value(COLUMNNAME_Prefix); } /** Set Start No. @param StartNo Starting number/position */ public void setStartNo (int StartNo) { set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); } /** Get Start No. @return Starting number/position */ public int getStartNo () { Integer ii = (Integer)get_Value(COLUMNNAME_StartNo); if (ii == null) return 0; return ii.intValue(); } /** Set Suffix. @param Suffix Suffix after the number */ public void setSuffix (String Suffix) { set_Value (COLUMNNAME_Suffix, Suffix); } /** Get Suffix. @return Suffix after the number */ public String getSuffix () { return (String)get_Value(COLUMNNAME_Suffix); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_SerNoCtl.java
1
请完成以下Java代码
public boolean hasErrors() { return errorCount > 0; } @Override public int getErrorCount() { return errorCount; } @Override public int getWarinigCount() { return warningCount; } @Override public void write(StringWriter writer, ValidationResultFormatter formatter) { for (Entry<ModelElementInstance, List<ValidationResult>> entry : collectedResults.entrySet()) { ModelElementInstance element = entry.getKey(); List<ValidationResult> results = entry.getValue(); formatter.formatElement(writer, element); for (ValidationResult result : results) { formatter.formatResult(writer, result); } } } @Override public void write(StringWriter writer, ValidationResultFormatter formatter, int maxSize) { int printedCount = 0; int previousLength = 0; for (var entry : collectedResults.entrySet()) { var element = entry.getKey(); var results = entry.getValue(); formatter.formatElement(writer, element);
for (var result : results) { formatter.formatResult(writer, result); // Size and Length are not necessarily the same, depending on the encoding of the string. int currentSize = writer.getBuffer().toString().getBytes().length; int currentLength = writer.getBuffer().length(); if (!canAccommodateResult(maxSize, currentSize, printedCount, formatter)) { writer.getBuffer().setLength(previousLength); int remaining = errorCount + warningCount - printedCount; formatter.formatSuffixWithOmittedResultsCount(writer, remaining); return; } printedCount++; previousLength = currentLength; } } } private boolean canAccommodateResult( int maxSize, int currentSize, int printedCount, ValidationResultFormatter formatter) { boolean isLastItemToPrint = printedCount == errorCount + warningCount - 1; if (isLastItemToPrint && currentSize <= maxSize) { return true; } int remaining = errorCount + warningCount - printedCount; int suffixLength = formatter.getFormattedSuffixWithOmittedResultsSize(remaining); return currentSize + suffixLength <= maxSize; } @Override public Map<ModelElementInstance, List<ValidationResult>> getResults() { return collectedResults; } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\validation\ModelValidationResultsImpl.java
1
请完成以下Java代码
public void fireExitCriteria(CmmnActivityExecution execution) { if (!execution.isCaseInstanceExecution()) { execution.exit(); } else { execution.terminate(); } } public void fireEntryCriteria(CmmnActivityExecution execution) { if (!execution.isCaseInstanceExecution()) { super.fireEntryCriteria(execution); return; } throw LOG.criteriaNotAllowedForCaseInstanceException("entry", execution.getId()); } // handle child state changes /////////////////////////////////////////////////////////// public void handleChildCompletion(CmmnActivityExecution execution, CmmnActivityExecution child) { fireForceUpdate(execution); if (execution.isActive()) { checkAndCompleteCaseExecution(execution); } } public void handleChildDisabled(CmmnActivityExecution execution, CmmnActivityExecution child) { fireForceUpdate(execution); if (execution.isActive()) { checkAndCompleteCaseExecution(execution); } } public void handleChildSuspension(CmmnActivityExecution execution, CmmnActivityExecution child) { // if the given execution is not suspending currently, then ignore this notification. if (execution.isSuspending() && isAbleToSuspend(execution)) { String id = execution.getId(); CaseExecutionState currentState = execution.getCurrentState(); if (SUSPENDING_ON_SUSPENSION.equals(currentState)) { execution.performSuspension(); } else if (SUSPENDING_ON_PARENT_SUSPENSION.equals(currentState)) { execution.performParentSuspension(); } else { throw LOG.suspendCaseException(id, currentState); } }
} public void handleChildTermination(CmmnActivityExecution execution, CmmnActivityExecution child) { fireForceUpdate(execution); if (execution.isActive()) { checkAndCompleteCaseExecution(execution); } else if (execution.isTerminating() && isAbleToTerminate(execution)) { String id = execution.getId(); CaseExecutionState currentState = execution.getCurrentState(); if (TERMINATING_ON_TERMINATION.equals(currentState)) { execution.performTerminate(); } else if (TERMINATING_ON_EXIT.equals(currentState)) { execution.performExit(); } else if (TERMINATING_ON_PARENT_TERMINATION.equals(currentState)) { throw LOG.illegalStateTransitionException("parentTerminate", id, getTypeName()); } else { throw LOG.terminateCaseException(id, currentState); } } } protected void checkAndCompleteCaseExecution(CmmnActivityExecution execution) { if (canComplete(execution)) { execution.complete(); } } protected void fireForceUpdate(CmmnActivityExecution execution) { if (execution instanceof CaseExecutionEntity) { CaseExecutionEntity entity = (CaseExecutionEntity) execution; entity.forceUpdate(); } } protected String getTypeName() { return "stage"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\StageActivityBehavior.java
1
请完成以下Java代码
public byte[] getAttachmentAsByteArray(@NonNull final String emailId, @NonNull final LookupValue attachment) { final File attachmentFile = getAttachmentFile(emailId, attachment.getIdAsString()); return Util.readBytes(attachmentFile); } public void deleteAttachments(@NonNull final String emailId, @NonNull final LookupValuesList attachmentsList) { attachmentsList.stream().forEach(attachment -> deleteAttachment(emailId, attachment)); } public void deleteAttachment(@NonNull final String emailId, @NonNull final LookupValue attachment) { final String attachmentId = attachment.getIdAsString(); final File attachmentFile = getAttachmentFile(emailId, attachmentId); if (!attachmentFile.exists()) {
logger.debug("Attachment file {} is missing. Nothing to delete", attachmentFile); return; } if (!attachmentFile.delete()) { attachmentFile.deleteOnExit(); logger.warn("Cannot delete attachment file {}. Scheduled to be deleted on exit", attachmentFile); } else { logger.debug("Deleted attachment file {}", attachmentFile); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\WebuiMailAttachmentsRepository.java
1
请完成以下Java代码
public DataService getDataService() { return dataService; } } //@Component @Named class DataService { } @Configuration @ComponentScan public class CdiContextLauncherApplication {
public static void main(String[] args) { try (var context = new AnnotationConfigApplicationContext (CdiContextLauncherApplication.class)) { Arrays.stream(context.getBeanDefinitionNames()) .forEach(System.out::println); System.out.println(context.getBean(BusinessService.class) .getDataService()); } } }
repos\master-spring-and-spring-boot-main\01-spring\learn-spring-framework-02\src\main\java\com\in28minutes\learnspringframework\examples\g1\CdiContextLauncherApplication.java
1
请完成以下Java代码
public abstract class TableRecordRefProvider<T> implements ReferenceableRecordsProvider { private final Class<T> modelClass; private final String tableName; public TableRecordRefProvider(@NonNull final Class<T> modelClass) { this.modelClass = modelClass; this.tableName = InterfaceWrapperHelper.getTableName(modelClass); } /** * For the given {@code recordRefs}, this method returns other records that refer to those given references via their own {@code AD_Table_ID} and {@code Record_ID} */ @Override public final ExpandResult expand( @NonNull final AttachmentEntry attachmentEntry, @NonNull final Collection<? extends ITableRecordReference> recordRefs) { if (recordRefs.isEmpty()) { return ExpandResult.EMPTY; } if (!isExpandOnAttachmentEntry(attachmentEntry)) { return ExpandResult.EMPTY; } final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<T> refereningIcFilters = queryBL .createQueryBuilder(modelClass) .setJoinOr() .setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions, true); for (final ITableRecordReference recordRef : recordRefs) {
final ICompositeQueryFilter<T> referencingIcFilter = queryBL .createCompositeQueryFilter(modelClass) .addOnlyActiveRecordsFilter() .addEqualsFilter(TableRecordReference.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID()) .addEqualsFilter(TableRecordReference.COLUMNNAME_Record_ID, recordRef.getRecord_ID()) .addFilter(getAdditionalFilter()); refereningIcFilters.filter(referencingIcFilter); } final List<Integer> idsToExpand = refereningIcFilters .create() .listIds(); final ImmutableSet<ITableRecordReference> set = idsToExpand .stream() .map(modelId -> TableRecordReference.of(tableName, modelId)) .collect(ImmutableSet.toImmutableSet()); return ExpandResult .builder() .additionalReferences(set) .build(); } protected boolean isExpandOnAttachmentEntry(@NonNull final AttachmentEntry attachmentEntry) { return true; } protected IQueryFilter<T> getAdditionalFilter() { return ConstantQueryFilter.of(true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\automaticlinksharing\TableRecordRefProvider.java
1
请在Spring Boot框架中完成以下Java代码
private void configureCsrf(SimpleUrlHandlerMapping mapping) { Map<String, Object> mappings = mapping.getHandlerMap(); for (Object object : mappings.values()) { if (object instanceof SockJsHttpRequestHandler) { setHandshakeInterceptors((SockJsHttpRequestHandler) object); } else if (object instanceof WebSocketHttpRequestHandler) { setHandshakeInterceptors((WebSocketHttpRequestHandler) object); } else { throw new IllegalStateException( "Bean " + SIMPLE_URL_HANDLER_MAPPING_BEAN_NAME + " is expected to contain mappings to either a " + "SockJsHttpRequestHandler or a WebSocketHttpRequestHandler but got " + object); } } } private void setHandshakeInterceptors(SockJsHttpRequestHandler handler) { SockJsService sockJsService = handler.getSockJsService(); Assert.state(sockJsService instanceof TransportHandlingSockJsService,
() -> "sockJsService must be instance of TransportHandlingSockJsService got " + sockJsService); TransportHandlingSockJsService transportHandlingSockJsService = (TransportHandlingSockJsService) sockJsService; List<HandshakeInterceptor> handshakeInterceptors = transportHandlingSockJsService.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); transportHandlingSockJsService.setHandshakeInterceptors(interceptorsToSet); } private void setHandshakeInterceptors(WebSocketHttpRequestHandler handler) { List<HandshakeInterceptor> handshakeInterceptors = handler.getHandshakeInterceptors(); List<HandshakeInterceptor> interceptorsToSet = new ArrayList<>(handshakeInterceptors.size() + 1); interceptorsToSet.add(new CsrfTokenHandshakeInterceptor()); interceptorsToSet.addAll(handshakeInterceptors); handler.setHandshakeInterceptors(interceptorsToSet); } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\socket\WebSocketMessageBrokerSecurityConfiguration.java
2
请完成以下Java代码
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
请在Spring Boot框架中完成以下Java代码
public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/caseOne%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } @ApiModelProperty(example = "aCaseDefinitionName") public String getCaseDefinitionName() { return caseDefinitionName; } public void setCaseDefinitionName(String caseDefinitionName) { this.caseDefinitionName = caseDefinitionName; } @ApiModelProperty(example = "A case definition description") public String getCaseDefinitionDescription() { return caseDefinitionDescription; } public void setCaseDefinitionDescription(String caseDefinitionDescription) { this.caseDefinitionDescription = caseDefinitionDescription; } @ApiModelProperty(example = "123") public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType;
} public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } public void setTenantId(String tenantId) { this.tenantId = tenantId; } @ApiModelProperty(example = "null") public String getTenantId() { return tenantId; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\caze\CaseInstanceResponse.java
2
请在Spring Boot框架中完成以下Java代码
public String getPaySecret() { return paySecret; } public void setPaySecret(String paySecret) { this.paySecret = paySecret; } public String getFundIntoType() { return fundIntoType; } public void setFundIntoType(String fundIntoType) { this.fundIntoType = fundIntoType; } private static final long serialVersionUID = 1L; public String getAuditStatus() { return auditStatus; } public void setAuditStatus(String auditStatus) { this.auditStatus = auditStatus == null ? null : auditStatus.trim(); } public String getIsAutoSett() { return isAutoSett; } public void setIsAutoSett(String isAutoSett) { this.isAutoSett = isAutoSett == null ? null : isAutoSett.trim(); } public String getPayKey() { return payKey; } public void setPayKey(String payKey) { this.payKey = payKey; } public String getProductCode() { return productCode; } public void setProductCode(String productCode) { this.productCode = productCode == null ? null : productCode.trim(); } public String getProductName() { return productName; }
public void setProductName(String productName) { this.productName = productName == null ? null : productName.trim(); } public String getUserNo() { return userNo; } public void setUserNo(String userNo) { this.userNo = userNo == null ? null : userNo.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public Integer getRiskDay() { return riskDay; } public void setRiskDay(Integer riskDay) { this.riskDay = riskDay; } public String getAuditStatusDesc() { return PublicEnum.getEnum(this.getAuditStatus()).getDesc(); } public String getFundIntoTypeDesc() { return FundInfoTypeEnum.getEnum(this.getFundIntoType()).getDesc(); } public String getSecurityRating() { return securityRating; } public void setSecurityRating(String securityRating) { this.securityRating = securityRating; } public String getMerchantServerIp() { return merchantServerIp; } public void setMerchantServerIp(String merchantServerIp) { this.merchantServerIp = merchantServerIp; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayConfig.java
2
请完成以下Java代码
public int getAD_Role_ID() { return get_ValueAsInt(COLUMNNAME_AD_Role_ID); } @Override public void setMobile_Application_Action_Access_ID (final int Mobile_Application_Action_Access_ID) { if (Mobile_Application_Action_Access_ID < 1) set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_Access_ID, null); else set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_Access_ID, Mobile_Application_Action_Access_ID); } @Override public int getMobile_Application_Action_Access_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_Action_Access_ID); } @Override public void setMobile_Application_Action_ID (final int Mobile_Application_Action_ID) { if (Mobile_Application_Action_ID < 1) set_Value (COLUMNNAME_Mobile_Application_Action_ID, null); else
set_Value (COLUMNNAME_Mobile_Application_Action_ID, Mobile_Application_Action_ID); } @Override public int getMobile_Application_Action_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_Action_ID); } @Override public void setMobile_Application_ID (final int Mobile_Application_ID) { if (Mobile_Application_ID < 1) set_Value (COLUMNNAME_Mobile_Application_ID, null); else set_Value (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID); } @Override public int getMobile_Application_ID() { return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Action_Access.java
1
请完成以下Java代码
public class ReplRequestHandlerBL implements IReplRequestHandlerBL { private final transient Logger logger = LogManager.getLogger(getClass()); @Override public IReplRequestHandler getRequestHandlerInstance(@NonNull final I_IMP_RequestHandler requestHandlerDef) { Check.assume(requestHandlerDef.isActive(), "Request handler {} is active", requestHandlerDef); final I_IMP_RequestHandlerType requestHandlerType = requestHandlerDef.getIMP_RequestHandlerType(); Check.assume(requestHandlerType.isActive(), "Request handler type {} is active", requestHandlerType); final String classname = requestHandlerType.getClassname(); final IReplRequestHandler requestHandler = Util.getInstance(IReplRequestHandler.class, classname); return requestHandler; } @Override public Document processRequestHandlerResult(final IReplRequestHandlerResult result) { final PO poToExport = result.getPOToExport(); if (poToExport == null) { logger.debug("Skip because poToExport is null"); return null; } final I_EXP_Format formatToUse = result.getFormatToUse(); Check.errorIf(formatToUse == null, "formatToUse shall be set"); final MEXPFormat formatToUsePO = (MEXPFormat)InterfaceWrapperHelper.getStrictPO(formatToUse); final ExportHelper exportHelper = new ExportHelper( poToExport.getCtx(), ClientId.ofRepoId(formatToUse.getAD_Client_ID())); return exportHelper.createExportDOM(poToExport, formatToUsePO, 0, // ReplicationMode X_AD_ReplicationTable.REPLICATIONTYPE_Merge, 0 // ReplicationEvent ); }
@Override public IReplRequestHandlerResult createInitialRequestHandlerResult() { return new ReplRequestHandlerResult(); } @Override public I_IMP_RequestHandlerType registerHandlerType( final String name, final Class<? extends IReplRequestHandler> clazz, final String entityType) { // TODO check if it already exists (by clazz and entityType). // If it exists, then Util.assume that AD_Client_ID=0 and return it // if it doesn't yet exist, then create it, save and return // final String classname = clazz.getName(); // final int adClientId = 0; // // final String whereClause = I_IMP_RequestHandlerType.COLUMNNAME_Classname+"=?" // +" AND "+I_IMP_RequestHandlerType.COLUMNNAME_EntityType+"=?" // +" AND "+I_IMP_RequestHandlerType.COLUMNNAME_AD_Client_ID+"=?" // new Query(Env.getCtx(), I_IMP_RequestHandlerType.Table_Name, whereClause, Trx.TRXNAME_None) // .setParameters(classname, entityType, adClientId) return null; } @Override public IReplRequestHandlerCtx createCtx( final Properties ctxForHandler, final I_EXP_Format importFormat, final I_IMP_RequestHandler requestHandlerRecord) { final ReplRequestHandlerCtx ctx = new ReplRequestHandlerCtx(); ctx.setEnvCtxToUse(ctxForHandler); ctx.setImportFormat(importFormat); ctx.setRequestHandlerRecord(requestHandlerRecord); return ctx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\process\rpl\requesthandler\api\impl\ReplRequestHandlerBL.java
1
请完成以下Java代码
public class MvgLawType { @XmlAttribute(name = "insured_id") protected String insuredId; @XmlAttribute(name = "case_id") protected String caseId; @XmlAttribute(name = "case_date") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar caseDate; @XmlAttribute(name = "contract_number") protected String contractNumber; @XmlAttribute(name = "ssn", required = true) protected String ssn; /** * Gets the value of the insuredId property. * * @return * possible object is * {@link String } * */ public String getInsuredId() { return insuredId; } /** * Sets the value of the insuredId property. * * @param value * allowed object is * {@link String } * */ public void setInsuredId(String value) { this.insuredId = value; } /** * Gets the value of the caseId property. * * @return * possible object is * {@link String } * */ public String getCaseId() { return caseId; } /** * Sets the value of the caseId property. * * @param value * allowed object is * {@link String } * */ public void setCaseId(String value) { this.caseId = value; } /** * Gets the value of the caseDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getCaseDate() { return caseDate; } /** * Sets the value of the caseDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCaseDate(XMLGregorianCalendar value) { this.caseDate = value; } /** * Gets the value of the contractNumber property. *
* @return * possible object is * {@link String } * */ public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } /** * Gets the value of the ssn property. * * @return * possible object is * {@link String } * */ public String getSsn() { return ssn; } /** * Sets the value of the ssn property. * * @param value * allowed object is * {@link String } * */ public void setSsn(String value) { this.ssn = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\MvgLawType.java
1
请完成以下Java代码
public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } @Override public void destroy() { filterConfig = null; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { applyFilter((HttpServletRequest) request, (HttpServletResponse) response, chain); } /** * Apply the filter to the given request/response. * * This method must be provided by subclasses to perform actual work. * * @param request * @param response * @param chain * * @throws IOException * @throws ServletException */ protected abstract void applyFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException; /** * Returns true if the given web resource exists. * * @param name * @return */ protected boolean hasWebResource(String name) { try { URL resource = filterConfig.getServletContext().getResource(name); return resource != null; } catch (MalformedURLException e) { return false; } } /**
* Returns the string contents of a web resource with the given name. * * The resource must be static and text based. * * @param name the name of the resource * * @return the resource contents * * @throws IOException */ protected String getWebResourceContents(String name) throws IOException { InputStream is = null; try { is = filterConfig.getServletContext().getResourceAsStream(name); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringWriter writer = new StringWriter(); String line = null; while ((line = reader.readLine()) != null) { writer.write(line); writer.append("\n"); } return writer.toString(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } } }
repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\filter\AbstractTemplateFilter.java
1
请完成以下Java代码
public void executeHandler(MigrationBatchConfiguration batchConfiguration, ExecutionEntity execution, CommandContext commandContext, String tenantId) { MigrationPlanImpl migrationPlan = (MigrationPlanImpl) batchConfiguration.getMigrationPlan(); String batchId = batchConfiguration.getBatchId(); setVariables(batchId, migrationPlan, commandContext); MigrationPlanExecutionBuilder executionBuilder = commandContext.getProcessEngineConfiguration() .getRuntimeService() .newMigration(migrationPlan) .processInstanceIds(batchConfiguration.getIds()); if (batchConfiguration.isSkipCustomListeners()) { executionBuilder.skipCustomListeners(); } if (batchConfiguration.isSkipIoMappings()) { executionBuilder.skipIoMappings(); }
commandContext.executeWithOperationLogPrevented( new MigrateProcessInstanceCmd((MigrationPlanExecutionBuilderImpl)executionBuilder, true)); } protected void setVariables(String batchId, MigrationPlanImpl migrationPlan, CommandContext commandContext) { Map<String, ?> variables = null; if (batchId != null) { variables = VariableUtil.findBatchVariablesSerialized(batchId, commandContext); if (variables != null) { migrationPlan.setVariables(new VariableMapImpl(new HashMap<>(variables))); } } } protected ProcessDefinitionEntity getProcessDefinition(CommandContext commandContext, String processDefinitionId) { return commandContext.getProcessEngineConfiguration() .getDeploymentCache() .findDeployedProcessDefinitionById(processDefinitionId); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\batch\MigrationBatchJobHandler.java
1
请完成以下Java代码
public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing()
{ return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSkipFirstNRows (final int SkipFirstNRows) { set_Value (COLUMNNAME_SkipFirstNRows, SkipFirstNRows); } @Override public int getSkipFirstNRows() { return get_ValueAsInt(COLUMNNAME_SkipFirstNRows); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean delete(Long id) { return userDao.delete(id) > 0; } /** * 更新用户 * * @param user 用户实体 * @param id 主键id * @return 更新成功 {@code true} 更新失败 {@code false} */ @Override public Boolean update(User user, Long id) { User exist = getUser(id); if (StrUtil.isNotBlank(user.getPassword())) { String rawPass = user.getPassword(); String salt = IdUtil.simpleUUID(); String pass = SecureUtil.md5(rawPass + Const.SALT_PREFIX + salt); user.setPassword(pass); user.setSalt(salt); } BeanUtil.copyProperties(user, exist, CopyOptions.create().setIgnoreNullValue(true)); exist.setLastUpdateTime(new DateTime()); return userDao.update(exist, id) > 0; } /** * 获取单个用户 * * @param id 主键id * @return 单个用户对象 */
@Override public User getUser(Long id) { return userDao.findOneById(id); } /** * 获取用户列表 * * @param user 用户实体 * @return 用户列表 */ @Override public List<User> getUser(User user) { return userDao.findByExample(user); } }
repos\spring-boot-demo-master\demo-orm-jdbctemplate\src\main\java\com\xkcoding\orm\jdbctemplate\service\impl\UserServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
private KieFileSystem getKieFileSystem() { KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); List<String> rules = Arrays.asList("com/baeldung/drools/rules/BackwardChaining.drl", "com/baeldung/drools/rules/SuggestApplicant.drl", "com/baeldung/drools/rules/Product_rules.drl.xls", "com/baeldung/drools/rules/eligibility_rules_event.drl", "com/baeldung/drools/rules/eligibility_rules_context.drl"); for (String rule : rules) { kieFileSystem.write(ResourceFactory.newClassPathResource(rule)); } return kieFileSystem; } private void getKieRepository() { final KieRepository kieRepository = kieServices.getRepository(); kieRepository.addKieModule(kieRepository::getDefaultReleaseId); } public KieSession getKieSession() { KieBuilder kb = kieServices.newKieBuilder(getKieFileSystem()); kb.buildAll(); KieRepository kieRepository = kieServices.getRepository(); ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId(); KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId); return kieContainer.newKieSession(); } public KieSession getKieSession(Resource dt) { KieFileSystem kieFileSystem = kieServices.newKieFileSystem() .write(dt); KieBuilder kieBuilder = kieServices.newKieBuilder(kieFileSystem)
.buildAll(); KieRepository kieRepository = kieServices.getRepository(); ReleaseId krDefaultReleaseId = kieRepository.getDefaultReleaseId(); KieContainer kieContainer = kieServices.newKieContainer(krDefaultReleaseId); KieSession ksession = kieContainer.newKieSession(); return ksession; } /* * Can be used for debugging * Input excelFile example: com/baeldung/drools/rules/Discount.drl.xls */ public String getDrlFromExcel(String excelFile) { DecisionTableConfiguration configuration = KnowledgeBuilderFactory.newDecisionTableConfiguration(); configuration.setInputType(DecisionTableInputType.XLS); Resource dt = ResourceFactory.newClassPathResource(excelFile, getClass()); DecisionTableProviderImpl decisionTableProvider = new DecisionTableProviderImpl(); String drl = decisionTableProvider.loadFromResource(dt, null); return drl; } }
repos\tutorials-master\drools\src\main\java\com\baeldung\drools\config\DroolsBeanFactory.java
2
请在Spring Boot框架中完成以下Java代码
private ProductId getProductId() { final I_M_InOutLine inoutLine = getInOutLine(); final ProductId inoutLineProductId = ProductId.ofRepoId(inoutLine.getM_Product_ID()); // // Make sure M_Product_ID matches if (getType().isMaterial()) { final I_C_InvoiceLine invoiceLine = getInvoiceLine(); final ProductId invoiceLineProductId = ProductId.ofRepoId(invoiceLine.getM_Product_ID()); if (!ProductId.equals(invoiceLineProductId, inoutLineProductId)) { final String invoiceProductName = productBL.getProductValueAndName(invoiceLineProductId); final String inoutProductName = productBL.getProductValueAndName(inoutLineProductId); throw new AdempiereException("@Invalid@ @M_Product_ID@" + "\n @C_InvoiceLine_ID@: " + invoiceLine + ", @M_Product_ID@=" + invoiceProductName + "\n @M_InOutLine_ID@: " + inoutLine + ", @M_Product_ID@=" + inoutProductName); } } return inoutLineProductId; } private boolean isSOTrx() {
final I_C_Invoice invoice = getInvoice(); final I_M_InOut inout = getInOut(); final boolean invoiceIsSOTrx = invoice.isSOTrx(); final boolean inoutIsSOTrx = inout.isSOTrx(); // // Make sure IsSOTrx matches if (invoiceIsSOTrx != inoutIsSOTrx) { throw new AdempiereException("@Invalid @IsSOTrx@" + "\n @C_Invoice_ID@: " + invoice + ", @IsSOTrx@=" + invoiceIsSOTrx + "\n @M_InOut_ID@: " + inout + ", @IsSOTrx@=" + inoutIsSOTrx); } return inoutIsSOTrx; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvBuilder.java
2
请完成以下Java代码
public static String join(String delimiter, String... parts) { if (parts == null) { return null; } if (delimiter == null) { delimiter = ""; } StringBuilder stringBuilder = new StringBuilder(); for (int i=0; i < parts.length; i++) { if (i > 0) { stringBuilder.append(delimiter); } stringBuilder.append(parts[i]); } return stringBuilder.toString(); } /** * Returns either the passed in String, or if the String is <code>null</code>, an empty String (""). * * <pre> * StringUtils.defaultString(null) = "" * StringUtils.defaultString("") = "" * StringUtils.defaultString("bat") = "bat" * </pre> * * @param text the String to check, may be null * @return the passed in String, or the empty String if it was <code>null</code> */ public static String defaultString(String text) { return text == null ? "" : text;
} /** * Fetches the stack trace of an exception as a String. * * @param throwable to get the stack trace from * @return the stack trace as String */ public static String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); throwable.printStackTrace(new PrintWriter(sw, true)); return sw.toString(); } }
repos\camunda-bpm-platform-master\commons\utils\src\main\java\org\camunda\commons\utils\StringUtil.java
1
请完成以下Java代码
public void stop() { try { Class.forName(ORG_CAMUNDA_BPM_ENGINE_PROCESS_ENGINE); } catch (Exception e) { return; } log.log(Level.INFO, "Camunda Platform executor service stopped."); } // JobHandler activation / deactivation /////////////////////////// public void endpointActivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) throws ResourceException { if(jobHandlerActivation != null) { throw new ResourceException("The Camunda Platform job executor can only service a single MessageEndpoint for job execution. " + "Make sure not to deploy more than one MDB implementing the '"+JobExecutionHandler.class.getName()+"' interface."); } JobExecutionHandlerActivation activation = new JobExecutionHandlerActivation(this, endpointFactory, (JobExecutionHandlerActivationSpec) spec); activation.start(); jobHandlerActivation = activation; } public void endpointDeactivation(MessageEndpointFactory endpointFactory, ActivationSpec spec) { try { if(jobHandlerActivation != null) { jobHandlerActivation.stop(); } } finally { jobHandlerActivation = null; } } // unsupported (No TX Support) //////////////////////////////////////////// public XAResource[] getXAResources(ActivationSpec[] specs) throws ResourceException { log.finest("getXAResources()"); return null; } // getters /////////////////////////////////////////////////////////////// public ExecutorServiceWrapper getExecutorServiceWrapper() { return executorServiceWrapper; } public JobExecutionHandlerActivation getJobHandlerActivation() { return jobHandlerActivation; } public Boolean getIsUseCommonJWorkManager() { return isUseCommonJWorkManager; } public void setIsUseCommonJWorkManager(Boolean isUseCommonJWorkManager) { this.isUseCommonJWorkManager = isUseCommonJWorkManager; } public String getCommonJWorkManagerName() { return commonJWorkManagerName; }
public void setCommonJWorkManagerName(String commonJWorkManagerName) { this.commonJWorkManagerName = commonJWorkManagerName; } // misc ////////////////////////////////////////////////////////////////// @Override public int hashCode() { return 17; } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other == this) { return true; } if (!(other instanceof JcaExecutorServiceConnector)) { return false; } return true; } }
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\JcaExecutorServiceConnector.java
1
请完成以下Java代码
private void updateParamsForAuth(String[] authNames, MultiValueMap<String, String> queryParams, HttpHeaders headerParams) { for (String authName : authNames) { Authentication auth = authentications.get(authName); if (auth == null) { throw new RestClientException("Authentication undefined: " + authName); } auth.applyToParams(queryParams, headerParams); } } private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); @Override public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { logRequest(request, body); ClientHttpResponse response = execution.execute(request, body); logResponse(response); return response; } private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { log.info("URI: " + request.getURI()); log.info("HTTP Method: " + request.getMethod()); log.info("HTTP Headers: " + headersToString(request.getHeaders())); log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); } private void logResponse(ClientHttpResponse response) throws IOException { log.info("HTTP Status Code: " + response.getRawStatusCode()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody()));
} private String headersToString(HttpHeaders headers) { StringBuilder builder = new StringBuilder(); for(Entry<String, List<String>> entry : headers.entrySet()) { builder.append(entry.getKey()).append("=["); for(String value : entry.getValue()) { builder.append(value).append(","); } builder.setLength(builder.length() - 1); // Get rid of trailing comma builder.append("],"); } builder.setLength(builder.length() - 1); // Get rid of trailing comma return builder.toString(); } private String bodyToString(InputStream body) throws IOException { StringBuilder builder = new StringBuilder(); BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); String line = bufferedReader.readLine(); while (line != null) { builder.append(line).append(System.lineSeparator()); line = bufferedReader.readLine(); } bufferedReader.close(); return builder.toString(); } } }
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\invoker\ApiClient.java
1
请完成以下Java代码
public SetRemovalTimeBatchConfiguration readConfiguration(JsonObject jsonObject) { long removalTimeMills = JsonUtil.getLong(jsonObject, REMOVAL_TIME); Date removalTime = removalTimeMills > 0 ? new Date(removalTimeMills) : null; List<String> instanceIds = JsonUtil.asStringList(JsonUtil.getArray(jsonObject, IDS)); DeploymentMappings mappings = JsonUtil.asList(JsonUtil.getArray(jsonObject, ID_MAPPINGS), DeploymentMappingJsonConverter.INSTANCE, DeploymentMappings::new); boolean hasRemovalTime = JsonUtil.getBoolean(jsonObject, HAS_REMOVAL_TIME); boolean isHierarchical = JsonUtil.getBoolean(jsonObject, IS_HIERARCHICAL); boolean updateInChunks = JsonUtil.getBoolean(jsonObject, UPDATE_IN_CHUNKS); Integer chunkSize = jsonObject.has(CHUNK_SIZE)? JsonUtil.getInt(jsonObject, CHUNK_SIZE) : null;
Set<String> entities = null; if (jsonObject.has(ENTITIES)) { entities = new HashSet<>(JsonUtil.asStringList(JsonUtil.getArray(jsonObject, ENTITIES))); } return new SetRemovalTimeBatchConfiguration(instanceIds, mappings) .setRemovalTime(removalTime) .setHasRemovalTime(hasRemovalTime) .setHierarchical(isHierarchical) .setUpdateInChunks(updateInChunks) .setChunkSize(chunkSize) .setEntities(entities); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\removaltime\SetRemovalTimeJsonConverter.java
1
请完成以下Java代码
public void setC_OrderLine_ID (int C_OrderLine_ID) { if (C_OrderLine_ID < 1) set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null); else set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, Integer.valueOf(C_OrderLine_ID)); } /** Get Auftragsposition. @return Auftragsposition */ @Override public int getC_OrderLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_OrderLine_ID); if (ii == null) return 0; return ii.intValue(); } @Override public de.metas.esb.edi.model.I_EDI_Desadv getEDI_Desadv() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class); } @Override public void setEDI_Desadv(de.metas.esb.edi.model.I_EDI_Desadv EDI_Desadv) { set_ValueFromPO(COLUMNNAME_EDI_Desadv_ID, de.metas.esb.edi.model.I_EDI_Desadv.class, EDI_Desadv); } /** Set DESADV. @param EDI_Desadv_ID DESADV */ @Override
public void setEDI_Desadv_ID (int EDI_Desadv_ID) { if (EDI_Desadv_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_Desadv_ID, Integer.valueOf(EDI_Desadv_ID)); } /** Get DESADV. @return DESADV */ @Override public int getEDI_Desadv_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_EDI_Desadv_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_NullDelivery_C_OrderLine_v.java
1
请完成以下Java代码
public void setT_DateTime (final @Nullable java.sql.Timestamp T_DateTime) { set_Value (COLUMNNAME_T_DateTime, T_DateTime); } @Override public java.sql.Timestamp getT_DateTime() { return get_ValueAsTimestamp(COLUMNNAME_T_DateTime); } @Override public void setT_Integer (final int T_Integer) { set_Value (COLUMNNAME_T_Integer, T_Integer); } @Override public int getT_Integer() { return get_ValueAsInt(COLUMNNAME_T_Integer); } @Override public void setT_Number (final @Nullable BigDecimal T_Number) { set_Value (COLUMNNAME_T_Number, T_Number); } @Override public BigDecimal getT_Number() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Number); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Qty (final @Nullable BigDecimal T_Qty) { set_Value (COLUMNNAME_T_Qty, T_Qty); } @Override public BigDecimal getT_Qty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_T_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setT_Time (final @Nullable java.sql.Timestamp T_Time) { set_Value (COLUMNNAME_T_Time, T_Time);
} @Override public java.sql.Timestamp getT_Time() { return get_ValueAsTimestamp(COLUMNNAME_T_Time); } @Override public void setTest_ID (final int Test_ID) { if (Test_ID < 1) set_ValueNoCheck (COLUMNNAME_Test_ID, null); else set_ValueNoCheck (COLUMNNAME_Test_ID, Test_ID); } @Override public int getTest_ID() { return get_ValueAsInt(COLUMNNAME_Test_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Test.java
1
请完成以下Java代码
private int retrieveDataId(@NonNull final MainDataRecordIdentifier identifier) { final int result = identifier .createQueryBuilder() .create() .firstIdOnly(); Check.errorIf(result <= 0, "Found no I_MD_Cockpit record for identifier={}", identifier); return result; } public int handleUpdateDetailRequest(@NonNull final UpdateDetailRequest updateDetailRequest) { final ICompositeQueryUpdater<I_MD_Cockpit_DocumentDetail> updater = Services.get(IQueryBL.class) .createCompositeQueryUpdater(I_MD_Cockpit_DocumentDetail.class) .addSetColumnValue( I_MD_Cockpit_DocumentDetail.COLUMNNAME_QtyOrdered, stripTrailingDecimalZeros(updateDetailRequest.getQtyOrdered()))
.addSetColumnValue( I_MD_Cockpit_DocumentDetail.COLUMNNAME_QtyReserved, stripTrailingDecimalZeros(updateDetailRequest.getQtyReserved())); return updateDetailRequest.getDetailDataRecordIdentifier() .createQuery() .update(updater); } public int handleRemoveDetailRequest(@NonNull final RemoveDetailRequest removeDetailsRequest) { final int deletedCount = removeDetailsRequest .getDetailDataRecordIdentifier() .createQuery() .delete(); return deletedCount; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\detailrecord\DetailDataRequestHandler.java
1
请完成以下Java代码
public String getName() { return name; } public int getPoints() { return points; } public boolean hasOver(int points) { return this.points > points; } public boolean hasOverHundredPoints() { return this.points > 100; }
public boolean hasValidProfilePhoto() throws Exception { URL url = new URI(this.profilePhotoUrl).toURL(); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); return connection.getResponseCode() == HttpURLConnection.HTTP_OK; } public boolean hasValidProfilePhotoWithoutCheckedException() { try { URL url = new URI(this.profilePhotoUrl).toURL(); HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); return connection.getResponseCode() == HttpURLConnection.HTTP_OK; } catch (Exception e) { throw new RuntimeException(e); } } }
repos\tutorials-master\core-java-modules\core-java-streams-3\src\main\java\com\baeldung\streams\filter\Customer.java
1
请完成以下Java代码
protected ITrxSavepoint createTrxSavepointNative(final String name) throws Exception { if (m_connection == null) { getConnection(); } if (m_connection.getAutoCommit()) { logger.debug("createTrxSavepointNative: returning null because we have an autocomit connection; this={}, connection={}", this, m_connection); return null; } if (m_connection != null) { final Savepoint jdbcSavepoint; if (name != null) { jdbcSavepoint = m_connection.setSavepoint(name); } else { jdbcSavepoint = m_connection.setSavepoint(); } final JdbcTrxSavepoint savepoint = new JdbcTrxSavepoint(this, jdbcSavepoint); return savepoint; } else {
return null; } } @Override protected boolean releaseSavepointNative(final ITrxSavepoint savepoint) throws Exception { final Savepoint jdbcSavepoint = (Savepoint)savepoint.getNativeSavepoint(); if (m_connection == null) { logger.warn("Cannot release savepoint {} because there is no active connection. Ignoring it.", savepoint); return false; } if (m_connection.isClosed()) { logger.warn("Cannot release savepoint {} because the connection is closed. Ignoring it.", savepoint); return false; } m_connection.releaseSavepoint(jdbcSavepoint); return true; } } // Trx
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\Trx.java
1
请在Spring Boot框架中完成以下Java代码
public void updatePayScheduleStatus(@NonNull final I_C_Order order) { final OrderSchedulingContext context = extractContext(order); if (context == null) { return; } orderPayScheduleRepository.updateById(context.getOrderId(), orderPaySchedule -> orderPaySchedule.updateStatusFromContext(context)); } public void updatePayScheduleStatusesBeforeCommit(@NonNull final OrderId orderId) { trxManager.accumulateAndProcessBeforeCommit( "OrderPayScheduleService.updatePayScheduleStatusesBeforeCommit", Collections.singleton(orderId), orderIds -> updatePayScheduleStatusesNow(ImmutableSet.copyOf(orderIds)) ); } private void updatePayScheduleStatusesNow(@NonNull final Set<OrderId> orderIds) { if (orderIds.isEmpty()) {return;} final ImmutableMap<OrderId, I_C_Order> ordersById = Maps.uniqueIndex( orderBL.getByIds(orderIds), order -> OrderId.ofRepoId(order.getC_Order_ID()) ); orderPayScheduleRepository.updateByIds( ordersById.keySet(), orderPaySchedule -> { final I_C_Order order = ordersById.get(orderPaySchedule.getOrderId()); final OrderSchedulingContext context = extractContext(order); if (context == null) { return; } orderPaySchedule.updateStatusFromContext(context); }); } public void markAsPaid(@NonNull final OrderId orderId, @NonNull final OrderPayScheduleId orderPayScheduleId) { orderPayScheduleRepository.updateById(orderId, orderPaySchedule -> orderPaySchedule.markAsPaid(orderPayScheduleId));
} @NonNull public Optional<OrderPaySchedule> getByOrderId(@NonNull final OrderId orderId) {return orderPayScheduleRepository.getByOrderId(orderId);} public void deleteByOrderId(@NonNull final OrderId orderId) {orderPayScheduleRepository.deleteByOrderId(orderId);} @Nullable OrderSchedulingContext extractContext(final @NotNull org.compiere.model.I_C_Order orderRecord) { final Money grandTotal = orderBL.getGrandTotal(orderRecord); if (grandTotal.isZero()) { return null; } final PaymentTermId paymentTermId = orderBL.getPaymentTermId(orderRecord); final PaymentTerm paymentTerm = paymentTermService.getById(paymentTermId); if (!paymentTerm.isComplex()) { return null; } return OrderSchedulingContext.builder() .orderId(OrderId.ofRepoId(orderRecord.getC_Order_ID())) .orderDate(TimeUtil.asLocalDate(orderRecord.getDateOrdered())) .letterOfCreditDate(TimeUtil.asLocalDate(orderRecord.getLC_Date())) .billOfLadingDate(TimeUtil.asLocalDate(orderRecord.getBLDate())) .ETADate(TimeUtil.asLocalDate(orderRecord.getETA())) .invoiceDate(TimeUtil.asLocalDate(orderRecord.getInvoiceDate())) .grandTotal(grandTotal) .precision(orderBL.getAmountPrecision(orderRecord)) .paymentTerm(paymentTerm) .build(); } public void create(@NonNull final OrderPayScheduleCreateRequest request) { orderPayScheduleRepository.create(request); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\paymentschedule\service\OrderPayScheduleService.java
2
请完成以下Java代码
public class HttpServiceTask extends ServiceTask { protected FlowableHttpRequestHandler httpRequestHandler; protected FlowableHttpResponseHandler httpResponseHandler; protected Boolean parallelInSameTransaction; public FlowableHttpRequestHandler getHttpRequestHandler() { return httpRequestHandler; } public void setHttpRequestHandler(FlowableHttpRequestHandler httpRequestHandler) { this.httpRequestHandler = httpRequestHandler; } public FlowableHttpResponseHandler getHttpResponseHandler() { return httpResponseHandler; } public void setHttpResponseHandler(FlowableHttpResponseHandler httpResponseHandler) { this.httpResponseHandler = httpResponseHandler; } public Boolean getParallelInSameTransaction() { return parallelInSameTransaction; } public void setParallelInSameTransaction(Boolean parallelInSameTransaction) { this.parallelInSameTransaction = parallelInSameTransaction; } @Override
public HttpServiceTask clone() { HttpServiceTask clone = new HttpServiceTask(); clone.setValues(this); return clone; } public void setValues(HttpServiceTask otherElement) { super.setValues(otherElement); setParallelInSameTransaction(otherElement.getParallelInSameTransaction()); if (otherElement.getHttpRequestHandler() != null) { setHttpRequestHandler(otherElement.getHttpRequestHandler().clone()); } if (otherElement.getHttpResponseHandler() != null) { setHttpResponseHandler(otherElement.getHttpResponseHandler().clone()); } } }
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\HttpServiceTask.java
1
请完成以下Java代码
protected void setInternalValueString(final String value) { valueStr = value; } @Override protected void setInternalValueNumber(final BigDecimal value) { valueBD = value; } @Override protected String getInternalValueString() { return valueStr; } @Override protected BigDecimal getInternalValueNumber() { return valueBD; } @Override protected String getInternalValueStringInitial() { return valueInitialStr; } @Override protected BigDecimal getInternalValueNumberInitial() { return valueInitialBD; } @Override protected void setInternalValueStringInitial(final String value) { valueInitialStr = value; } @Override protected void setInternalValueNumberInitial(final BigDecimal value) { valueInitialBD = value; } @Override public String getPropagationType() { return propagationType; } @Override public IAttributeAggregationStrategy retrieveAggregationStrategy() { return aggregationStrategy; } @Override public IAttributeSplitterStrategy retrieveSplitterStrategy() { return splitterStrategy; } @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return transferStrategy; } @Override public boolean isUseInASI() { return false; } @Override public boolean isDefinedByTemplate() { return false; } @Override public int getDisplaySeqNo() { return 0; } @Override public boolean isReadonlyUI() { return false; } @Override public boolean isDisplayedUI() {
return true; } @Override public boolean isMandatory() { return false; } @Override public boolean isNew() { return isGeneratedAttribute; } @Override protected void setInternalValueDate(Date value) { this.valueDate = value; } @Override protected Date getInternalValueDate() { return valueDate; } @Override protected void setInternalValueDateInitial(Date value) { this.valueInitialDate = value; } @Override protected Date getInternalValueDateInitial() { return valueInitialDate; } @Override public boolean isOnlyIfInProductAttributeSet() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\PlainAttributeValue.java
1
请完成以下Java代码
public ResponseEntity<?> getExternalSystemStatus(@PathVariable @NonNull final String externalSystemConfigType) { final ExternalSystemType externalSystemType = externalSystemService.getExternalSystemTypeByCodeOrNameOrNull(externalSystemConfigType); if (externalSystemType == null) { throw new AdempiereException("Unsupported externalSystemConfigType=" + externalSystemConfigType); } final JsonExternalStatusResponse statusInfo = externalSystemService.getStatusInfo(externalSystemType); return ResponseEntity.ok().body(statusInfo); } @ApiOperation("Get external system info.\n Note, only externalSystemConfigType=GRSSignum is supported at the moment.") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully retrieved external system info"), @ApiResponse(code = 401, message = "You are not authorized to retrieve external system info"), @ApiResponse(code = 403, message = "Accessing a related resource is forbidden"), @ApiResponse(code = 422, message = "The request could not be processed") }) @GetMapping(path = "/{externalSystemConfigType}/{externalSystemChildConfigValue}/info") public ResponseEntity<?> getExternalSystemInfo( @PathVariable @NonNull final String externalSystemConfigType, @PathVariable @NonNull final String externalSystemChildConfigValue) { final ExternalSystemType externalSystemType = externalSystemService.getExternalSystemTypeByCodeOrNameOrNull(externalSystemConfigType); if (externalSystemType == null) { throw new AdempiereException("Unsupported externalSystemConfigType=" + externalSystemConfigType); } final JsonExternalSystemInfo systemInfo = externalSystemService.getExternalSystemInfo(externalSystemType, externalSystemChildConfigValue); return ResponseEntity.ok().body(systemInfo); } private ResponseEntity<?> getResponse(@NonNull final ProcessExecutionResult processExecutionResult) {
final ResponseEntity.BodyBuilder responseEntity; final RunProcessResponse.RunProcessResponseBuilder responseBodyBuilder = RunProcessResponse.builder() .pInstanceID(String.valueOf(processExecutionResult.getPinstanceId().getRepoId())); if (processExecutionResult.getThrowable() != null) { final JsonError error = JsonError.ofSingleItem(JsonErrors.ofThrowable(processExecutionResult.getThrowable(), Env.getADLanguageOrBaseLanguage())); responseEntity = ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR); responseBodyBuilder.errors(error); } else { responseEntity = ResponseEntity.ok(); } return responseEntity .contentType(MediaType.APPLICATION_JSON) .body(responseBodyBuilder.build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\ExternalSystemRestController.java
1
请完成以下Java代码
public Function<ISeq<Integer>, Integer> fitness() { return subset -> Math.abs(subset.stream() .mapToInt(Integer::intValue) .sum()); } @Override public Codec<ISeq<Integer>, EnumGene<Integer>> codec() { return codecs.ofSubSet(basicSet, size); } public static SubsetSum of(int n, int k, Random random) { return new SubsetSum(random.doubles() .limit(n) .mapToObj(d -> (int) ((d - 0.5) * n)) .collect(ISeq.toISeq()), k); } public static void main(String[] args) { SubsetSum problem = of(500, 15, new LCG64ShiftRandom(101010));
Engine<EnumGene<Integer>, Integer> engine = Engine.builder(problem) .minimizing() .maximalPhenotypeAge(5) .alterers(new PartiallyMatchedCrossover<>(0.4), new Mutator<>(0.3)) .build(); Phenotype<EnumGene<Integer>, Integer> result = engine.stream() .limit(limit.bySteadyFitness(55)) .collect(EvolutionResult.toBestPhenotype()); System.out.print(result); } }
repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\jenetics\SubsetSum.java
1
请完成以下Java代码
protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("admin") .password(passwordEncoder().encode("admin123")) .roles("ADMIN").authorities("ACCESS_TEST1", "ACCESS_TEST2") .and() .withUser("hamdamboy") .password(passwordEncoder().encode("hamdamboy123")) .roles("USER") .and() .withUser("manager") .password(passwordEncoder().encode("manager")) .roles("MANAGER") .authorities("ACCESS_TEST1"); } /** * * **/ @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // .anyRequest().permitAll() if you fix all permission values, then remove all conditions.
.antMatchers("/index.html").permitAll() .antMatchers("/profile/**").authenticated() .antMatchers("/admin/**").hasRole("ADMIN") .antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER") .antMatchers("/api/public/test1").hasAuthority("ACCESS_TEST1") .antMatchers("/api/public/test2").hasAuthority("ACCESS_TEST2") .and() .httpBasic(); } @Bean PasswordEncoder passwordEncoder(){ return new BCryptPasswordEncoder(); } }
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\4. SpringSecureAuthorization\src\main\java\spring\security\security\SpringSecurity.java
1
请完成以下Java代码
private Map<HuId, Set<ProductId>> getHUProductIds(final @NonNull Set<HuId> huIds) { final List<I_M_HU> hus = handlingUnitsBL.getByIds(huIds); return handlingUnitsBL.getStorageFactory().getHUProductIds(hus); } @NonNull public BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final HuId huId) { return checkEligibleToAddAsSourceHUs(ImmutableSet.of(huId)); } @NonNull public BooleanWithReason checkEligibleToAddAsSourceHUs(@NonNull final Set<HuId> huIds) { final String notEligibleReason = handlingUnitsBL.getByIds(huIds) .stream() .map(this::checkEligibleToAddAsSourceHU) .filter(BooleanWithReason::isFalse) .map(BooleanWithReason::getReasonAsString) .collect(Collectors.joining(" | ")); return Check.isBlank(notEligibleReason) ? BooleanWithReason.TRUE : BooleanWithReason.falseBecause(notEligibleReason); } @NonNull private BooleanWithReason checkEligibleToAddAsSourceHU(@NonNull final I_M_HU hu) { if (!X_M_HU.HUSTATUS_Active.equals(hu.getHUStatus())) { return BooleanWithReason.falseBecause("HU is not active"); } if (!handlingUnitsBL.isTopLevel(hu)) {
return BooleanWithReason.falseBecause("HU is not top level"); } return BooleanWithReason.TRUE; } public BooleanWithReason checkEligibleToAddToManufacturingOrder(@NonNull final PPOrderId ppOrderId) { final I_PP_Order ppOrder = ppOrderBL.getById(ppOrderId); final DocStatus ppOrderDocStatus = DocStatus.ofNullableCodeOrUnknown(ppOrder.getDocStatus()); if (!ppOrderDocStatus.isCompleted()) { return BooleanWithReason.falseBecause(MSG_ManufacturingOrderNotCompleted, ppOrder.getDocumentNo()); } if (ppOrderIssueScheduleService.matchesByOrderId(ppOrderId)) { return BooleanWithReason.falseBecause(MSG_ManufacturingJobAlreadyStarted, ppOrder.getDocumentNo()); } return BooleanWithReason.TRUE; } @NonNull public ImmutableSet<HuId> getSourceHUIds(@NonNull final PPOrderId ppOrderId) { return ppOrderSourceHURepository.getSourceHUIds(ppOrderId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\source_hu\PPOrderSourceHUService.java
1
请完成以下Java代码
public class SchemaLogQueryImpl extends AbstractQuery<SchemaLogQuery, SchemaLogEntry> implements SchemaLogQuery { private static final long serialVersionUID = 1L; private static final QueryProperty TIMESTAMP_PROPERTY = new QueryPropertyImpl("TIMESTAMP_"); protected String version; public SchemaLogQueryImpl(CommandExecutor commandExecutor) { super(commandExecutor); } @Override public SchemaLogQuery version(String version) { ensureNotNull("version", version); this.version = version; return this; } @Override public SchemaLogQuery orderByTimestamp() {
orderBy(TIMESTAMP_PROPERTY); return this; } @Override public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext.getSchemaLogManager().findSchemaLogEntryCountByQueryCriteria(this); } @Override public List<SchemaLogEntry> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext.getSchemaLogManager().findSchemaLogEntriesByQueryCriteria(this, page); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SchemaLogQueryImpl.java
1
请完成以下Java代码
public DmnTransformer getTransformer() { return transformer; } /** * Set the DMN transformer used to transform the DMN model. * * @param transformer the DMN transformer */ public void setTransformer(DmnTransformer transformer) { this.transformer = transformer; } /** * Set the DMN transformer used to transform the DMN model. * * @param transformer the DMN transformer * @return this */ public DefaultDmnEngineConfiguration transformer(DmnTransformer transformer) { setTransformer(transformer); return this; } /** * @return the list of FEEL Custom Function Providers */ public List<FeelCustomFunctionProvider> getFeelCustomFunctionProviders() { return feelCustomFunctionProviders; } /** * Set a list of FEEL Custom Function Providers. * * @param feelCustomFunctionProviders a list of FEEL Custom Function Providers */ public void setFeelCustomFunctionProviders(List<FeelCustomFunctionProvider> feelCustomFunctionProviders) { this.feelCustomFunctionProviders = feelCustomFunctionProviders; } /** * Set a list of FEEL Custom Function Providers. * * @param feelCustomFunctionProviders a list of FEEL Custom Function Providers * @return this */ public DefaultDmnEngineConfiguration feelCustomFunctionProviders(List<FeelCustomFunctionProvider> feelCustomFunctionProviders) { setFeelCustomFunctionProviders(feelCustomFunctionProviders); return this; } /** * @return whether FEEL legacy behavior is enabled or not */
public boolean isEnableFeelLegacyBehavior() { return enableFeelLegacyBehavior; } /** * Controls whether the FEEL legacy behavior is enabled or not * * @param enableFeelLegacyBehavior the FEEL legacy behavior */ public void setEnableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) { this.enableFeelLegacyBehavior = enableFeelLegacyBehavior; } /** * Controls whether the FEEL legacy behavior is enabled or not * * @param enableFeelLegacyBehavior the FEEL legacy behavior * @return this */ public DefaultDmnEngineConfiguration enableFeelLegacyBehavior(boolean enableFeelLegacyBehavior) { setEnableFeelLegacyBehavior(enableFeelLegacyBehavior); return this; } /** * @return whether blank table outputs are swallowed or returned as {@code null}. */ public boolean isReturnBlankTableOutputAsNull() { return returnBlankTableOutputAsNull; } /** * Controls whether blank table outputs are swallowed or returned as {@code null}. * * @param returnBlankTableOutputAsNull toggles whether blank table outputs are swallowed or returned as {@code null}. * @return this */ public DefaultDmnEngineConfiguration setReturnBlankTableOutputAsNull(boolean returnBlankTableOutputAsNull) { this.returnBlankTableOutputAsNull = returnBlankTableOutputAsNull; return this; } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnEngineConfiguration.java
1
请完成以下Java代码
private Message assembleMessage() { if (this.messages.size() == 1) { return this.messages.get(0); } MessageProperties messageProperties = this.messages.get(0).getMessageProperties(); byte[] body = new byte[this.currentSize]; ByteBuffer bytes = ByteBuffer.wrap(body); for (Message message : this.messages) { bytes.putInt(message.getBody().length); bytes.put(message.getBody()); } messageProperties.getHeaders().put(MessageProperties.SPRING_BATCH_FORMAT, MessageProperties.BATCH_FORMAT_LENGTH_HEADER4); messageProperties.getHeaders().put(AmqpHeaders.BATCH_SIZE, this.messages.size()); return new Message(body, messageProperties); } @Override public boolean canDebatch(MessageProperties properties) { return MessageProperties.BATCH_FORMAT_LENGTH_HEADER4.equals(properties .getHeaders() .get(MessageProperties.SPRING_BATCH_FORMAT)); } /** * Debatch a message that has a header with {@link MessageProperties#SPRING_BATCH_FORMAT} * set to {@link MessageProperties#BATCH_FORMAT_LENGTH_HEADER4}. * @param message the batched message. * @param fragmentConsumer a consumer for each fragment. * @since 2.2 */ @Override public void deBatch(Message message, Consumer<Message> fragmentConsumer) { ByteBuffer byteBuffer = ByteBuffer.wrap(message.getBody()); MessageProperties messageProperties = message.getMessageProperties(); messageProperties.getHeaders().remove(MessageProperties.SPRING_BATCH_FORMAT);
while (byteBuffer.hasRemaining()) { int length = byteBuffer.getInt(); if (length < 0 || length > byteBuffer.remaining()) { throw new ListenerExecutionFailedException("Bad batched message received", new MessageConversionException("Insufficient batch data at offset " + byteBuffer.position()), message); } byte[] body = new byte[length]; byteBuffer.get(body); messageProperties.setContentLength(length); // Caveat - shared MessageProperties, except for last Message fragment; if (byteBuffer.hasRemaining()) { fragment = new Message(body, messageProperties); } else { MessageProperties lastProperties = new MessageProperties(); BeanUtils.copyProperties(messageProperties, lastProperties); lastProperties.setLastInBatch(true); fragment = new Message(body, lastProperties); } fragmentConsumer.accept(fragment); } } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\batch\SimpleBatchingStrategy.java
1
请完成以下Java代码
protected void addDeleteListener(UserTask userTask) { addListenerToUserTask(userTask, TaskListener.EVENTNAME_DELETE, new CdiTaskListener(userTask.getId(), BusinessProcessEventType.DELETE_TASK)); } protected void addStartEventListener(FlowElement flowElement) { CdiExecutionListener listener = new CdiExecutionListener(flowElement.getId(), BusinessProcessEventType.START_ACTIVITY); addListenerToElement(flowElement, ExecutionListener.EVENTNAME_START, listener); } protected void addEndEventListener(FlowElement flowElement) { CdiExecutionListener listener = new CdiExecutionListener(flowElement.getId(), BusinessProcessEventType.END_ACTIVITY); addListenerToElement(flowElement, ExecutionListener.EVENTNAME_END, listener); } protected void addListenerToElement(FlowElement flowElement, String event, Object instance) {
FlowableListener listener = new FlowableListener(); listener.setEvent(event); listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_INSTANCE); listener.setInstance(instance); flowElement.getExecutionListeners().add(listener); } protected void addListenerToUserTask(UserTask userTask, String event, Object instance) { FlowableListener listener = new FlowableListener(); listener.setEvent(event); listener.setImplementationType(ImplementationType.IMPLEMENTATION_TYPE_INSTANCE); listener.setInstance(instance); userTask.getTaskListeners().add(listener); } }
repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\event\CdiEventSupportBpmnParseHandler.java
1
请完成以下Java代码
public java.lang.String getSubject () { return (java.lang.String)get_Value(COLUMNNAME_Subject); } @Override public org.compiere.model.I_AD_User getTo_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setTo_User(org.compiere.model.I_AD_User To_User) { set_ValueFromPO(COLUMNNAME_To_User_ID, org.compiere.model.I_AD_User.class, To_User); } /** Set To User. @param To_User_ID To User */ @Override public void setTo_User_ID (int To_User_ID)
{ if (To_User_ID < 1) set_Value (COLUMNNAME_To_User_ID, null); else set_Value (COLUMNNAME_To_User_ID, Integer.valueOf(To_User_ID)); } /** Get To User. @return To User */ @Override public int getTo_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_To_User_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Mail.java
1
请完成以下Java代码
public String getParentDeploymentId() { return parentDeploymentId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } public String getCategoryLike() { return categoryLike; } public String getKey() { return key;
} public String getKeyLike() { return keyLike; } public String getParentDeploymentIdLike() { return parentDeploymentIdLike; } public List<String> getParentDeploymentIds() { return parentDeploymentIds; } public boolean isLatest() { return latest; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
public boolean isInvoiceEmailEnabled(@Nullable final I_C_BPartner bpartner, @Nullable final I_AD_User user) { if (bpartner == null) { return false; // gh #508: if the user does not have a C_BPartner, then there won't be any invoice to be emailed either. } final boolean matchingIsInvoiceEmailEnabled; String isInvoiceEmailEnabled = bpartner.getIsInvoiceEmailEnabled(); // // check flag from partner if (Check.isBlank(isInvoiceEmailEnabled)) { if (user == null) { return Boolean.TRUE; } // // if is empty in partner, check it in user isInvoiceEmailEnabled = user.getIsInvoiceEmailEnabled(); // // if is empty also in user, return true - we do not want to let filtering by this if is not completed if (Check.isBlank(isInvoiceEmailEnabled)) {
matchingIsInvoiceEmailEnabled = Boolean.TRUE; } else { matchingIsInvoiceEmailEnabled = BooleanUtils.toBoolean(isInvoiceEmailEnabled); } } else { matchingIsInvoiceEmailEnabled = BooleanUtils.toBoolean(isInvoiceEmailEnabled); } return matchingIsInvoiceEmailEnabled; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\api\impl\BPartnerBL.java
1
请完成以下Java代码
public BestellungDefektgrund getGrund() { return grund; } /** * Sets the value of the grund property. * * @param value * allowed object is * {@link BestellungDefektgrund } * */ public void setGrund(BestellungDefektgrund value) { this.grund = value; } /** * Gets the value of the tourId property. * * @return * possible object is * {@link String } * */ public String getTourId() { return tourId; } /** * Sets the value of the tourId property. * * @param value * allowed object is * {@link String } * */ public void setTourId(String value) { this.tourId = value; }
/** * Gets the value of the tourabweichung property. * */ public boolean isTourabweichung() { return tourabweichung; } /** * Sets the value of the tourabweichung property. * */ public void setTourabweichung(boolean value) { this.tourabweichung = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\BestellungAnteil.java
1
请完成以下Java代码
public abstract class UILoadingPropertyChangeListener implements PropertyChangeListener { private final WeakReference<Object> componentRef; public UILoadingPropertyChangeListener(final Object component) { super(); Check.assumeNotNull(component, "component not null"); this.componentRef = new WeakReference<Object>(component); } @Override public final void propertyChange(final PropertyChangeEvent evt) { final Object component = componentRef.get(); if (component == null) {
// NOTE: component reference expired return; } Services.get(IClientUI.class).executeLongOperation(component, new Runnable() { @Override public void run() { propertyChange0(evt); } }); } protected abstract void propertyChange0(PropertyChangeEvent evt); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\beans\impl\UILoadingPropertyChangeListener.java
1
请完成以下Java代码
public void setImportStatus (java.lang.String ImportStatus) { set_Value (COLUMNNAME_ImportStatus, ImportStatus); } @Override public java.lang.String getImportStatus() { return (java.lang.String)get_Value(COLUMNNAME_ImportStatus); } @Override public void setJsonRequest (java.lang.String JsonRequest) { set_ValueNoCheck (COLUMNNAME_JsonRequest, JsonRequest); } @Override public java.lang.String getJsonRequest() { return (java.lang.String)get_Value(COLUMNNAME_JsonRequest); } @Override public void setJsonResponse (java.lang.String JsonResponse) { set_Value (COLUMNNAME_JsonResponse, JsonResponse); } @Override public java.lang.String getJsonResponse() { return (java.lang.String)get_Value(COLUMNNAME_JsonResponse); } @Override public void setPP_Cost_Collector_ImportAudit_ID (int PP_Cost_Collector_ImportAudit_ID) { if (PP_Cost_Collector_ImportAudit_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Cost_Collector_ImportAudit_ID, Integer.valueOf(PP_Cost_Collector_ImportAudit_ID));
} @Override public int getPP_Cost_Collector_ImportAudit_ID() { return get_ValueAsInt(COLUMNNAME_PP_Cost_Collector_ImportAudit_ID); } @Override public void setTransactionIdAPI (java.lang.String TransactionIdAPI) { set_ValueNoCheck (COLUMNNAME_TransactionIdAPI, TransactionIdAPI); } @Override public java.lang.String getTransactionIdAPI() { return (java.lang.String)get_Value(COLUMNNAME_TransactionIdAPI); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Cost_Collector_ImportAudit.java
1
请完成以下Java代码
public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public Map<String, Object> getTaskLocalVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() != null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<String, Object>(); if (queryVariables != null) { for (VariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } } } return variables; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public List<VariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new VariableInitializingList(); } return queryVariables; } public void setQueryVariables(List<VariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; }
public Date getClaimTime() { return claimTime; } public void setClaimTime(Date claimTime) { this.claimTime = claimTime; } public Integer getAppVersion() { return this.appVersion; } public void setAppVersion(Integer appVersion) { this.appVersion = appVersion; } public String toString() { return "Task[id=" + id + ", name=" + name + "]"; } private String truncate(String string, int maxLength) { if (string != null) { return string.length() > maxLength ? string.substring(0, maxLength) : string; } return null; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public List<InboundEMailConfig> getAll() { final Map<InboundEMailConfigId, InboundEMailConfig> configs = getAllConfigsIndexById(); return ImmutableList.copyOf(configs.values()); } public InboundEMailConfig getById(@NonNull final InboundEMailConfigId id) { final InboundEMailConfig config = getAllConfigsIndexById().get(id); if (config == null) { throw new AdempiereException("No config found for " + id); } return config; } public List<InboundEMailConfig> getByIds(@NonNull final Collection<InboundEMailConfigId> ids) { if (ids.isEmpty()) { return ImmutableList.of(); } final Map<InboundEMailConfigId, InboundEMailConfig> allConfigsIndexById = getAllConfigsIndexById(); return ids.stream() .map(allConfigsIndexById::get) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } private Map<InboundEMailConfigId, InboundEMailConfig> getAllConfigsIndexById() { return configsCache.getOrLoad(0, this::retrieveAllConfigsIndexById);
} private Map<InboundEMailConfigId, InboundEMailConfig> retrieveAllConfigsIndexById() { return Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_InboundMailConfig.class) .addOnlyActiveRecordsFilter() .create() .stream() .map(InboundEMailConfigRepository::toInboundEMailConfig) .collect(GuavaCollectors.toImmutableMapByKey(InboundEMailConfig::getId)); } private static InboundEMailConfig toInboundEMailConfig(final I_C_InboundMailConfig record) { return InboundEMailConfig.builder() .id(InboundEMailConfigId.ofRepoId(record.getC_InboundMailConfig_ID())) .protocol(InboundEMailProtocol.forCode(record.getProtocol())) .host(record.getHost()) .port(record.getPort()) .folder(record.getFolder()) .username(record.getUserName()) .password(record.getPassword()) .debugProtocol(record.isDebugProtocol()) .adClientId(ClientId.ofRepoId(record.getAD_Client_ID())) .orgId(OrgId.ofRepoId(record.getAD_Org_ID())) .requestTypeId(RequestTypeId.ofRepoIdOrNull(record.getR_RequestType_ID())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\config\InboundEMailConfigRepository.java
2
请在Spring Boot框架中完成以下Java代码
boolean isAcceptable(String s) { int goodChars = 0; int lastGoodCharVal = -1; // count number of characters from Base64 alphabet for (int i = 0; i < s.length(); i++) { int val = values[0xff & s.charAt(i)]; if (val != -1) { lastGoodCharVal = val; goodChars++; } } // in cases of an incomplete final chunk, ensure the unused bits are zero switch (goodChars % 4) { case 0: return true; case 2: return (lastGoodCharVal & 0b1111) == 0; case 3:
return (lastGoodCharVal & 0b11) == 0; default: return false; } } void checkAcceptable(String ins) { if (!isAcceptable(ins)) { throw new IllegalArgumentException("Failed to decode SAMLResponse"); } } } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\internal\Saml2Utils.java
2