instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public class RejectedType extends StatusType { protected String explanation; protected List<ErrorType> error; /** * Gets the value of the explanation property. * * @return * possible object is * {@link String } * */ public String getExplanation() { return explanation; } /** * Sets the value of the explanation property. * * @param value * allowed object is * {@link String } * */ public void setExplanation(String value) { this.explanation = value; }
/** * Gets the value of the error property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the error property. * * <p> * For example, to add a new item, do as follows: * <pre> * getError().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ErrorType } * * */ public List<ErrorType> getError() { if (error == null) { error = new ArrayList<ErrorType>(); } return this.error; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\RejectedType.java
1
请完成以下Java代码
public class PlayerResource { @PersistenceUnit(name="MyPU") private EntityManagerFactory emf; private List<String> names = Arrays.asList("Mike", "John", "Virgil", "Joana", "Ike"); private List<String> cities = Arrays.asList("Barcelona", "Ploiesti", "Madrid", "Cluj", "Bucuresti"); private Random rnd = new Random(); @GET @Produces({MediaType.APPLICATION_JSON}) public Player generatePlayer() { Player player = new Player(); player.setName(names.get(rnd.nextInt(names.size()))); player.setCity(cities.get(rnd.nextInt(cities.size()))); player.setAge(18 + rnd.nextInt(50)); EntityManager em = emf.createEntityManager(); EntityTransaction tx = em.getTransaction(); try { tx.begin(); em.persist(player); tx.commit();
} catch (Exception e) { // or use explicit exception if (tx != null && tx.isActive()) { tx.rollback(); } throw e; } finally { if (em != null && em.isOpen()) { em.close(); } } return player; } }
repos\Hibernate-SpringBoot-master\Java EE\AMPCandRLTM1\src\main\java\com\sample\boundary\PlayerResource.java
1
请在Spring Boot框架中完成以下Java代码
private LanguageData getLanguageData(@Nullable final LanguageKey language) { final LanguageKey languageEffective = language != null ? language : LanguageKey.getDefault(); return cache.computeIfAbsent(languageEffective, LanguageData::new); } public ImmutableMap<String, String> getMessagesMap(@NonNull final LanguageKey language) { return getLanguageData(language).getFrontendMessagesMap(); } private static class LanguageData { @Getter private final ResourceBundle resourceBundle; @Getter private final ImmutableMap<String, String> frontendMessagesMap; private LanguageData(final @NonNull LanguageKey language) { resourceBundle = ResourceBundle.getBundle("messages", language.toLocale()); frontendMessagesMap = computeMessagesMap(resourceBundle); } private static ImmutableMap<String, String> computeMessagesMap(@NonNull final ResourceBundle bundle) { final Set<String> keys = bundle.keySet(); final HashMap<String, String> map = new HashMap<>(keys.size()); for (final String key : keys) {
// shall not happen if (key == null || key.isBlank()) { continue; } final String value = Strings.nullToEmpty(bundle.getString(key)); map.put(key, value); } return ImmutableMap.copyOf(map); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\I18N.java
2
请完成以下Java代码
public void performOperationStep(DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); final AbstractProcessApplication processApplication = operationContext.getAttachment(Attachments.PROCESS_APPLICATION); final JmxManagedProcessApplication deployedProcessApplication = serviceContainer.getService(ServiceTypes.PROCESS_APPLICATION, processApplication.getName()); ensureNotNull("Cannot find process application with name " + processApplication.getName(), "deployedProcessApplication", deployedProcessApplication); List<ProcessesXml> processesXmls = deployedProcessApplication.getProcessesXmls(); for (ProcessesXml processesXml : processesXmls) { stopProcessEngines(processesXml.getProcessEngines(), operationContext); } } protected void stopProcessEngines(List<ProcessEngineXml> processEngine, DeploymentOperation operationContext) { for (ProcessEngineXml parsedProcessEngine : processEngine) { stopProcessEngine(parsedProcessEngine.getName(), operationContext); }
} protected void stopProcessEngine(String processEngineName, DeploymentOperation operationContext) { final PlatformServiceContainer serviceContainer = operationContext.getServiceContainer(); try { serviceContainer.stopService(ServiceTypes.PROCESS_ENGINE, processEngineName); } catch(Exception e) { LOG.exceptionWhileStopping("Process Engine", processEngineName, e); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\ProcessesXmlStopProcessEnginesStep.java
1
请完成以下Java代码
public String getName() { return name; } public String getNameLike() { return nameLike; } public String getCategory() { return category; } public String getCategoryNotEquals() { return categoryNotEquals; } public String getTenantId() { return tenantId; }
public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getProcessDefinitionKeyLike() { return processDefinitionKeyLike; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\DeploymentQueryImpl.java
1
请完成以下Java代码
private static boolean isValidAddress(final EMailAddress emailAddress) { if (emailAddress == null) { return false; } try { return isValidAddress(emailAddress.toInternetAddress()); } catch (final AddressException e) { return false; } } private static boolean isValidAddress(final InternetAddress emailAddress) { if (emailAddress == null) { return false; } final String addressStr = emailAddress.getAddress(); return addressStr != null && !addressStr.isEmpty() && addressStr.indexOf(' ') < 0; } /** * @return attachments array or empty array. This method will never return null. */ public List<EMailAttachment> getAttachments() { return ImmutableList.copyOf(_attachments); } /**
* Do send the mail to the respective mail address, even if the {@code DebugMailTo} SysConfig is set. */ public void forceRealEmailRecipients() { _forceRealEmailRecipients = true; } @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("to", _to) .add("cc", _cc.isEmpty() ? null : _cc) .add("bcc", _bcc.isEmpty() ? null : _bcc) .add("replyTo", _replyTo) .add("subject", _subject) .add("attachments", _attachments.isEmpty() ? null : _attachments) .add("mailbox", _mailbox) .toString(); } } // EMail
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMail.java
1
请完成以下Java代码
public Object remove(Object key) throws CacheException { springCache.evict(key); return null; } @Override public void clear() throws CacheException { springCache.clear(); } @Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); } @SuppressWarnings("unchecked") @Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); }
@SuppressWarnings("unchecked") @Override public Collection values() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); List keys = ehcache.getKeys(); if (!CollectionUtils.isEmpty(keys)) { List values = new ArrayList(keys.size()); for (Object key : keys) { Object value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } else { return Collections.emptyList(); } } throw new UnsupportedOperationException("invoke spring cache abstract values method not supported"); } } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\spring\SpringCacheManagerWrapper.java
1
请完成以下Java代码
public Set<CurrencyPairDTO> getRequestedCurrencyPairs() { return Set.of(new CurrencyPairDTO(BTC, USDT)); } @Override public Optional<AccountDTO> getTradeAccount(Set<AccountDTO> accounts) { return accounts.stream() .filter(a -> "trade".equals(a.getName())) .findFirst(); } @Override public void onTickerUpdate(TickerDTO ticker) { logger.info("Received a new ticker : {}", ticker); if (new BigDecimal("56000").compareTo(ticker.getLast()) == -1) { if (canBuy(new CurrencyPairDTO(BTC, USDT), new BigDecimal("0.01"))) { PositionRulesDTO rules = PositionRulesDTO.builder() .stopGainPercentage(4f) .stopLossPercentage(25f)
.build(); createLongPosition(new CurrencyPairDTO(BTC, USDT), new BigDecimal("0.01"), rules); } } } @Override public void onPositionStatusUpdate(PositionDTO position) { if (position.getStatus() == OPENED) { logger.info("> New position opened : {}", position.getPositionId()); } if (position.getStatus() == CLOSED) { logger.info("> Position closed : {}", position.getDescription()); } } }
repos\tutorials-master\spring-boot-modules\spring-boot-cassandre\src\main\java\com\baeldung\trading\MyFirstStrategy.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentService { private static final Logger logger = LogManager.getLogger(StudentService.class); private final List<Student> students = new ArrayList<>(); public Student addStudent(Student student) { logger.info("addStudent: adding Student"); logger.info("addStudent: Request: {}", student); students.add(student); logger.info("addStudent: added Student"); logger.info("addStudent: Response: {}", student); return student; } public List<Student> getStudents() { logger.info("getStudents: getting Students"); List<Student> studentsList = students;
logger.info("getStudents: got Students"); logger.info("getStudents: Response: {}", studentsList); return studentsList; } public Student getStudent(int rollNumber) { logger.info("getStudent: getting Student"); logger.info("getStudent: Request: {}", rollNumber); Student student = students.stream() .filter(stu -> stu.getRollNumber() == rollNumber) .findAny() .orElseThrow(() -> new RuntimeException("Student not found")); logger.info("getStudent: got Student"); logger.info("getStudent: Response: {}", student); return student; } }
repos\tutorials-master\logging-modules\splunk-with-log4j2\src\main\java\com\splunk\log4j\service\StudentService.java
2
请完成以下Java代码
public boolean isAsyncSupported() { return this.asyncSupported; } /** * Set init-parameters for this registration. Calling this method will replace any * existing init-parameters. * @param initParameters the init parameters * @see #getInitParameters * @see #addInitParameter */ public void setInitParameters(Map<String, String> initParameters) { Assert.notNull(initParameters, "'initParameters' must not be null"); this.initParameters = new LinkedHashMap<>(initParameters); } /** * Returns a mutable Map of the registration init-parameters. * @return the init parameters */ public Map<String, String> getInitParameters() { return this.initParameters; } /** * Add a single init-parameter, replacing any existing parameter with the same name. * @param name the init-parameter name * @param value the init-parameter value */ public void addInitParameter(String name, String value) { Assert.notNull(name, "'name' must not be null"); this.initParameters.put(name, value); } @Override protected final void register(String description, ServletContext servletContext) { D registration = addRegistration(description, servletContext); if (registration == null) { if (this.ignoreRegistrationFailure) { logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)"); return; } throw new IllegalStateException( "Failed to register '%s' on the servlet context. Possibly already registered?" .formatted(description)); } configure(registration); }
/** * Sets whether registration failures should be ignored. If set to true, a failure * will be logged. If set to false, an {@link IllegalStateException} will be thrown. * @param ignoreRegistrationFailure whether to ignore registration failures * @since 3.1.0 */ public void setIgnoreRegistrationFailure(boolean ignoreRegistrationFailure) { this.ignoreRegistrationFailure = ignoreRegistrationFailure; } @Override public void setBeanName(String name) { this.beanName = name; } protected abstract @Nullable D addRegistration(String description, ServletContext servletContext); protected void configure(D registration) { registration.setAsyncSupported(this.asyncSupported); if (!this.initParameters.isEmpty()) { registration.setInitParameters(this.initParameters); } } /** * Deduces the name for this registration. Will return user specified name or fallback * to the bean name. If the bean name is not available, convention based naming is * used. * @param value the object used for convention based names * @return the deduced name */ protected final String getOrDeduceName(@Nullable Object value) { if (this.name != null) { return this.name; } if (this.beanName != null) { return this.beanName; } if (value == null) { return "null"; } return Conventions.getVariableName(value); } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\DynamicRegistrationBean.java
1
请完成以下Java代码
public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; } public String getCaseExecutionId() { return caseExecutionId; } public void setCaseExecutionId(String caseExecutionId) { this.caseExecutionId = caseExecutionId; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getEventType() { return eventType; } public void setEventType(String eventType) { this.eventType = eventType; } public long getSequenceCounter() { return sequenceCounter; } public void setSequenceCounter(long sequenceCounter) {
this.sequenceCounter = sequenceCounter; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } // persistent object implementation /////////////// public Object getPersistentState() { // events are immutable return HistoryEvent.class; } // state inspection public boolean isEventOfType(HistoryEventType type) { return type.getEventName().equals(eventType); } @Override public String toString() { return this.getClass().getSimpleName() + "[id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", processInstanceId=" + processInstanceId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoryEvent.java
1
请完成以下Java代码
public int getAD_Issue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Issue_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Java-Klasse. @param Classname Java-Klasse */ @Override public void setClassname (java.lang.String Classname) { set_ValueNoCheck (COLUMNNAME_Classname, Classname); } /** Get Java-Klasse. @return Java-Klasse */ @Override public java.lang.String getClassname () { return (java.lang.String)get_Value(COLUMNNAME_Classname); } /** Set Fehler. @param IsError Ein Fehler ist bei der Durchführung aufgetreten */ @Override public void setIsError (boolean IsError) { set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError)); } /** Get Fehler. @return Ein Fehler ist bei der Durchführung aufgetreten */ @Override public boolean isError () { Object oo = get_Value(COLUMNNAME_IsError); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Message Text. @param MsgText
Textual Informational, Menu or Error Message */ @Override public void setMsgText (java.lang.String MsgText) { set_ValueNoCheck (COLUMNNAME_MsgText, MsgText); } /** Get Message Text. @return Textual Informational, Menu or Error Message */ @Override public java.lang.String getMsgText () { return (java.lang.String)get_Value(COLUMNNAME_MsgText); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog_Entry.java
1
请完成以下Java代码
public @Nullable UsernamePasswordAuthenticationToken convert(HttpServletRequest request) { String header = request.getHeader(HttpHeaders.AUTHORIZATION); if (header == null) { return null; } header = header.trim(); if (!StringUtils.startsWithIgnoreCase(header, AUTHENTICATION_SCHEME_BASIC)) { return null; } if (header.equalsIgnoreCase(AUTHENTICATION_SCHEME_BASIC)) { throw new BadCredentialsException("Empty basic authentication token"); } byte[] base64Token = header.substring(6).getBytes(StandardCharsets.UTF_8); byte[] decoded = decode(base64Token); String token = new String(decoded, getCredentialsCharset(request)); int delim = token.indexOf(":"); if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); } UsernamePasswordAuthenticationToken result = UsernamePasswordAuthenticationToken .unauthenticated(token.substring(0, delim), token.substring(delim + 1)); result.setDetails(this.authenticationDetailsSource.buildDetails(request)); return result; }
private byte[] decode(byte[] base64Token) { try { return Base64.getDecoder().decode(base64Token); } catch (IllegalArgumentException ex) { throw new BadCredentialsException("Failed to decode basic authentication token"); } } protected Charset getCredentialsCharset(HttpServletRequest request) { return getCredentialsCharset(); } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\www\BasicAuthenticationConverter.java
1
请完成以下Java代码
default void onProcessInitError(final ProcessInfo pi) { final ProcessExecutionResult processResult = pi.getResult(); final Throwable cause = processResult.getThrowable(); if (cause != null) { LogManager.getLogger(IProcessExecutionListener.class).warn("Process initialization failed: {}", pi, cause); } else { LogManager.getLogger(IProcessExecutionListener.class).warn("Process initialization failed: {}", pi); } } /**
* Lock User Interface. * Called before running the process. * * @param pi process info */ void lockUI(ProcessInfo pi); /** * Unlock User Interface. * Called after the process was executed, even if it was a failure. * * @param pi process info */ void unlockUI(ProcessInfo pi); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\IProcessExecutionListener.java
1
请完成以下Java代码
public Collection<OrgAndBPartnerCompositeLookupKey> extractCacheKeys(@NonNull final BPartnerComposite dataItem) { final BPartner bpartner = dataItem.getBpartner(); try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_C_BPartner.Table_Name, bpartner == null ? null : bpartner.getId())) { final OrgId orgId = Check.assumeNotNull(dataItem.getOrgId(), "dataItem.getOrgId() is not null for dataItem={}", dataItem); final ImmutableList.Builder<OrgAndBPartnerCompositeLookupKey> cacheKeys = ImmutableList.builder(); final String value = bpartner.getValue(); if (!isEmpty(value, true)) { cacheKeys.add(OrgAndBPartnerCompositeLookupKey.of( BPartnerCompositeLookupKey.ofCode(value), orgId)); } final ImmutableSet<GlnWithLabel> locationGlnsWithLabel = dataItem.extractLocationGlnsWithLabel(); for (final GlnWithLabel locationGln : locationGlnsWithLabel) { cacheKeys.add(OrgAndBPartnerCompositeLookupKey.of( BPartnerCompositeLookupKey.ofGlnWithLabel(locationGln), orgId)); } final ImmutableSet<GLN> locationGlns = dataItem.extractLocationGlns(); for (final GLN locationGln : locationGlns) { cacheKeys.add(OrgAndBPartnerCompositeLookupKey.of( BPartnerCompositeLookupKey.ofGln(locationGln), orgId)); } final ExternalId externalId = bpartner.getExternalId(); if (externalId != null) { cacheKeys.add(OrgAndBPartnerCompositeLookupKey.of( BPartnerCompositeLookupKey.ofJsonExternalId(JsonConverters.toJsonOrNull(externalId)), orgId)); } final MetasfreshId metasfreshId = MetasfreshId.ofOrNull(bpartner.getId()); if (metasfreshId != null) { cacheKeys.add( OrgAndBPartnerCompositeLookupKey.of( BPartnerCompositeLookupKey.ofMetasfreshId(metasfreshId), orgId)); }
final ImmutableList<OrgAndBPartnerCompositeLookupKey> result = cacheKeys.build(); logger.debug("extractCacheKeys - extracted cache keys for given bpartnerComposite: {}", result); return result; } } @Override public boolean isResetAll(@NonNull final TableRecordReference recordRef) { return recordRef.getTableName().equals(I_C_User_Assigned_Role.Table_Name) || recordRef.getTableName().equals(I_C_User_Role.Table_Name); } @NonNull private static Set<TableRecordReference> getRecordRefsRoles(@Nullable final List<UserRole> roles) { if (Check.isEmpty(roles)) { return ImmutableSet.of(); } final ImmutableSet.Builder<TableRecordReference> recordRefsBuilder = ImmutableSet.builder(); for (final UserRole role : roles) { final UserAssignedRoleId assignedRoleId = role.getUserAssignedRoleId(); recordRefsBuilder.add(TableRecordReference.of(I_C_User_Assigned_Role.Table_Name, assignedRoleId.getRepoId())); recordRefsBuilder.add(TableRecordReference.of(I_C_User_Role.Table_Name, assignedRoleId.getUserRoleId().getRepoId())); } return recordRefsBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\bpartner\bpartnercomposite\BPartnerCompositeCacheIndex.java
1
请完成以下Java代码
private String buildUUIDSelectionSqlSelectFrom_queryWithUnions( @NonNull final String querySelectionUUID, @NonNull final TypedSqlQuery<?> query, @NonNull final String keyColumnName) { final String sqlInnerSelect = query.buildSQL( "SELECT " + keyColumnName, /* fromClause */ null, /* groupByClause */ null, /* useOrderByClause */true); return new StringBuilder() .append("INSERT INTO ") .append(I_T_Query_Selection.Table_Name) .append(" (") .append(I_T_Query_Selection.COLUMNNAME_UUID) .append(", ").append(I_T_Query_Selection.COLUMNNAME_Line) .append(", ").append(I_T_Query_Selection.COLUMNNAME_Record_ID) .append(")") // .append("\nSELECT ") .append(DB.TO_STRING(querySelectionUUID)) .append(", row_number() over ()") .append(", ").append(keyColumnName) .append("\nFROM (\n") .append(sqlInnerSelect) .append("\n) t") // .toString(); } @Value public static class UUISelection { int size; String uuid; Instant time; } public <T, ET extends T> TypedSqlQuery<ET> createUUIDSelectionQuery( @NonNull final IContextAware ctx, @NonNull final Class<ET> clazz, @NonNull final String querySelectionUUID) { final String tableName = InterfaceWrapperHelper.getTableName(clazz); final POInfo poInfo = POInfo.getPOInfo(tableName); final String keyColumnName = poInfo.getKeyColumnName(); final String keyColumnNameFQ = tableName + "." + keyColumnName;
// // Build the query used to retrieve models by querying the selection. // NOTE: we are using LEFT OUTER JOIN instead of INNER JOIN because // * methods like hasNext() are comparing the rowsFetched counter with rowsCount to detect if we reached the end of the selection (optimization). // * POBufferedIterator is using LIMIT/OFFSET clause for fetching the next page and eliminating rows from here would fuck the paging if one record was deleted in meantime. // So we decided to load everything here, and let the hasNext() method to deal with the case when the record is really missing. final String selectionSqlFrom = "(SELECT " + I_T_Query_Selection.COLUMNNAME_UUID + " as ZZ_UUID" + ", " + I_T_Query_Selection.COLUMNNAME_Record_ID + " as ZZ_Record_ID" + ", " + I_T_Query_Selection.COLUMNNAME_Line + " as " + SELECTION_LINE_ALIAS + " FROM " + I_T_Query_Selection.Table_Name + ") s " + "\n LEFT OUTER JOIN " + tableName + " ON (" + keyColumnNameFQ + "=s.ZZ_Record_ID)"; final String selectionWhereClause = "s.ZZ_UUID=?"; final String selectionOrderBy = "s." + SELECTION_LINE_ALIAS; return new TypedSqlQuery<>( ctx.getCtx(), clazz, selectionWhereClause, ctx.getTrxName()) .setParameters(querySelectionUUID) .setSqlFrom(selectionSqlFrom) .setOrderBy(selectionOrderBy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\QuerySelectionHelper.java
1
请在Spring Boot框架中完成以下Java代码
public class ResponseLogFilter extends ZuulFilter { private Logger logger = LoggerFactory.getLogger(ResponseLogFilter.class); @Override public String filterType() { return POST_TYPE; } @Override public int filterOrder() { return 0; } @Override public boolean shouldFilter() { return true; } @Override public Object run() throws ZuulException { RequestContext context = RequestContext.getCurrentContext(); try (final InputStream responseDataStream = context.getResponseDataStream()) { if(responseDataStream == null) {
logger.info("BODY: {}", ""); return null; } String responseData = CharStreams.toString(new InputStreamReader(responseDataStream, "UTF-8")); logger.info("BODY: {}", responseData); context.setResponseBody(responseData); } catch (Exception e) { throw new ZuulException(e, INTERNAL_SERVER_ERROR.value(), e.getMessage()); } return null; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-post-filter\src\main\java\com\baeldung\filters\ResponseLogFilter.java
2
请完成以下Java代码
public Void execute(CommandContext commandContext) { ensureNotNull("caseExecutionId", caseExecutionId); caseExecution = commandContext .getCaseExecutionManager() .findCaseExecutionById(caseExecutionId); ensureNotNull(CaseExecutionNotFoundException.class, "There does not exist any case execution with id: '" + caseExecutionId + "'", "caseExecution", caseExecution); for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkUpdateCaseInstance(caseExecution); } if (variablesDeletions != null && !variablesDeletions.isEmpty()) { caseExecution.removeVariables(variablesDeletions); } if (variablesLocalDeletions != null && !variablesLocalDeletions.isEmpty()) { caseExecution.removeVariablesLocal(variablesLocalDeletions); } if (variables != null && !variables.isEmpty()) {
caseExecution.setVariables(variables); } if (variablesLocal != null && !variablesLocal.isEmpty()) { caseExecution.setVariablesLocal(variablesLocal); } return null; } public CaseExecutionEntity getCaseExecution() { return caseExecution; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\cmd\CaseExecutionVariableCmd.java
1
请完成以下Java代码
public class ADColumnCalloutADValidator extends AbstractADValidator<I_AD_ColumnCallout> { @Override public void validate(I_AD_ColumnCallout callout) { if (Check.isEmpty(callout.getClassname(), true)) { throw new AdempiereException("No classname specified"); } final String fqMethodName = callout.getClassname(); final int idx = fqMethodName.lastIndexOf('.'); final String classname = fqMethodName.substring(0, idx); final String methodName = fqMethodName.substring(idx + 1); final Method method = validateJavaMethodName(classname, org.compiere.model.Callout.class, methodName); // Expected params, variant 1: Properties ctx, int windowNo, GridTab gridTab, GridField gridField, Object value final Class<?>[] expectedParams1 = new Class<?>[] { java.util.Properties.class, int.class, GridTab.class, GridField.class, Object.class }; // Expected params, variant 2: Properties ctx, int windowNo, GridTab gridTab, GridField gridField, Object value, Object valueOld final Class<?>[] expectedParams2 = new Class<?>[] { java.util.Properties.class, int.class, GridTab.class, GridField.class, Object.class, Object.class }; if (!Objects.equals(expectedParams1, method.getParameterTypes()) && !Objects.equals(expectedParams2, method.getParameterTypes())) { throw new AdempiereException("Invalid parameters for callout method " + method); } } @Override public String getLogMessage(final IADValidatorViolation violation) { final StringBuilder message = new StringBuilder(); try { final I_AD_ColumnCallout callout = InterfaceWrapperHelper.create(violation.getItem(), I_AD_ColumnCallout.class); final I_AD_Column column = callout.getAD_Column(); final String tableName = Services.get(IADTableDAO.class).retrieveTableName(column.getAD_Table_ID()); message.append("Error on ").append(tableName).append(".").append(column.getColumnName()).append(" - ").append(callout.getClassname())
.append(" (IsActive=").append(callout.isActive()).append("): "); } catch (Exception e) { message.append("Error (InterfaceWrapperHelper exception: ").append(e.getLocalizedMessage()).append(") on ").append(violation.getItem()).append(": "); } message.append(violation.getError().getLocalizedMessage()); return message.toString(); } @Override public Class<I_AD_ColumnCallout> getType() { return I_AD_ColumnCallout.class; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\appdict\validation\spi\impl\ADColumnCalloutADValidator.java
1
请完成以下Java代码
public void unlinkMaterialTracking(@NonNull final I_C_Invoice_Candidate candidate, final boolean isClearAggregationKeyOverride) { candidate.setM_Material_Tracking_ID(-1); if (isClearAggregationKeyOverride) { candidate.setC_Invoice_Candidate_HeaderAggregation_Override(null); } aggregationBL.getUpdateProcessor().process(candidate); repo.save(candidate); materialTrackingBL.unlinkModelFromMaterialTrackings(candidate); } public void linkMaterialTrackings(@NonNull final List<I_C_Invoice_Candidate> candidate, @NonNull final MaterialTrackingId materialTrackingId) { final I_M_Material_Tracking materialTracking = materialTrackingDAO.getById(materialTrackingId); if (materialTracking.isProcessed()) { //target material tracking is processed, so we can't link to it return; } candidate.forEach(c -> linkMaterialTracking(c, materialTracking)); } public void linkMaterialTracking(@NonNull final I_C_Invoice_Candidate candidate, @NonNull final I_M_Material_Tracking materialTracking) { final MaterialTrackingId oldMaterialTrackingId = MaterialTrackingId.ofRepoIdOrNull(candidate.getM_Material_Tracking_ID()); if (oldMaterialTrackingId != null) { final I_M_Material_Tracking oldMaterialTracking = materialTrackingDAO.getById(oldMaterialTrackingId); if (oldMaterialTracking.isProcessed()) { //old material tracking is processed, so we can't unlink from it
return; } } final I_C_Invoice_Candidate existingICForMT = repo.getFirstForMaterialTrackingId(MaterialTrackingId.ofRepoId(materialTracking.getM_Material_Tracking_ID())) .orElse(null); if (existingICForMT != null && existingICForMT.getBill_BPartner_ID() != candidate.getBill_BPartner_ID()) { //Not for the same BillBPartner as other ICs of the material tracking, can't add to group return; } candidate.setM_Material_Tracking_ID(materialTracking.getM_Material_Tracking_ID()); if (existingICForMT != null) { final InvoiceCandidateHeaderAggregationId effectiveHeaderAggregationKeyId = IAggregationBL.getEffectiveHeaderAggregationKeyId(existingICForMT); candidate.setC_Invoice_Candidate_HeaderAggregation_Override_ID(InvoiceCandidateHeaderAggregationId.toRepoId(effectiveHeaderAggregationKeyId)); } aggregationBL.getUpdateProcessor().process(candidate); repo.save(candidate); materialTrackingBL.linkModelToMaterialTracking(MTLinkRequest.builder() .model(candidate) .previousMaterialTrackingId(MaterialTrackingId.toRepoId(oldMaterialTrackingId)) .ifModelAlreadyLinked(MTLinkRequest.IfModelAlreadyLinked.UNLINK_FROM_PREVIOUS) .materialTrackingRecord(materialTracking) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingInvoiceCandService.java
1
请在Spring Boot框架中完成以下Java代码
public class OrderService { @Autowired private EntityManager entityManager; @Autowired private OrderRepository orderRepository; public List<Order> findOrdersByCustomerAndDateRangeUsingCriteriaAPI(String customerName, LocalDate startDate, LocalDate endDate) { CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); CriteriaQuery<Order> criteriaQuery = criteriaBuilder.createQuery(Order.class); Root<Order> root = criteriaQuery.from(Order.class); Predicate customerPredicate = criteriaBuilder.equal(root.get("customerName"), customerName); Predicate dateRangePredicate = criteriaBuilder.between(root.get("orderDate"), startDate, endDate); criteriaQuery.where(customerPredicate, dateRangePredicate); return entityManager.createQuery(criteriaQuery) .getResultList(); } public void updateOrderName(long orderId, String newName) { Order order = orderRepository.findById(orderId)
.map(existingOrder -> { existingOrder.setName(newName); return existingOrder; }) .orElseGet(() -> { return null; }); if (order != null) { try { orderRepository.save(order); } catch (OptimisticLockException e) { // Refresh the entity and potentially retry the update entityManager.refresh(order); // Consider adding logic to handle retries or notify the user about the conflict } } } }
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\fetchandrefresh\OrderService.java
2
请在Spring Boot框架中完成以下Java代码
public String getReferenceNo() { return referenceNo; } /** * Sets the value of the referenceNo property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNo(String value) { this.referenceNo = value; } /** * Gets the value of the surchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSurchargeAmt() { return surchargeAmt; } /** * Sets the value of the surchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSurchargeAmt(BigDecimal value) { this.surchargeAmt = value; } /** * Gets the value of the taxBaseAmtWithSurchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxBaseAmtWithSurchargeAmt() { return taxBaseAmtWithSurchargeAmt; } /** * Sets the value of the taxBaseAmtWithSurchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxBaseAmtWithSurchargeAmt(BigDecimal value) { this.taxBaseAmtWithSurchargeAmt = value; } /** * Gets the value of the taxAmtWithSurchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxAmtWithSurchargeAmt() { return taxAmtWithSurchargeAmt; }
/** * Sets the value of the taxAmtWithSurchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxAmtWithSurchargeAmt(BigDecimal value) { this.taxAmtWithSurchargeAmt = value; } /** * Gets the value of the isMainVAT property. * * @return * possible object is * {@link String } * */ public String getIsMainVAT() { return isMainVAT; } /** * Sets the value of the isMainVAT property. * * @param value * allowed object is * {@link String } * */ public void setIsMainVAT(String value) { this.isMainVAT = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop901991VType.java
2
请完成以下Java代码
public Date getDataCollectionStartDate() { return dataCollectionStartDate; } public void setDataCollectionStartDate(Date dataCollectionStartDate) { this.dataCollectionStartDate = dataCollectionStartDate; } public static InternalsDto fromEngineDto(Internals other) { LicenseKeyData licenseKey = other.getLicenseKey(); InternalsDto dto = new InternalsDto( DatabaseDto.fromEngineDto(other.getDatabase()), ApplicationServerDto.fromEngineDto(other.getApplicationServer()), licenseKey != null ? LicenseKeyDataDto.fromEngineDto(licenseKey) : null, JdkDto.fromEngineDto(other.getJdk()));
dto.dataCollectionStartDate = other.getDataCollectionStartDate(); dto.commands = new HashMap<>(); other.getCommands().forEach((name, command) -> dto.commands.put(name, new CommandDto(command.getCount()))); dto.metrics = new HashMap<>(); other.getMetrics().forEach((name, metric) -> dto.metrics.put(name, new MetricDto(metric.getCount()))); dto.setWebapps(other.getWebapps()); dto.setCamundaIntegration(other.getCamundaIntegration()); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\telemetry\InternalsDto.java
1
请完成以下Java代码
public int getM_AttributeSetInstance_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetInstance_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_InOutLine getM_InOutLine() throws RuntimeException { return (I_M_InOutLine)MTable.get(getCtx(), I_M_InOutLine.Table_Name) .getPO(getM_InOutLine_ID(), get_TrxName()); } /** Set Shipment/Receipt Line. @param M_InOutLine_ID Line on Shipment or Receipt document */ public void setM_InOutLine_ID (int M_InOutLine_ID) { if (M_InOutLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID)); } /** Get Shipment/Receipt Line. @return Line on Shipment or Receipt document */ public int getM_InOutLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID); if (ii == null) return 0; return ii.intValue();
} /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getM_InOutLine_ID())); } /** Set Movement Quantity. @param MovementQty Quantity of a product moved. */ public void setMovementQty (BigDecimal MovementQty) { set_Value (COLUMNNAME_MovementQty, MovementQty); } /** Get Movement Quantity. @return Quantity of a product moved. */ public BigDecimal getMovementQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineMA.java
1
请完成以下Java代码
private BigDecimal getFlatrateAmtPerUOM_OrNull() { return _flatrateAmtPerUOM; } public PMMContractBuilder addQtyPlanned(final Date date, final BigDecimal qtyPlannedToAdd) { assertNotProcessed(); if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0) { return this; } if (qtyPlannedToAdd.signum() < 0) { logger.warn("Skip adding negative QtyPlanned={} for {}", qtyPlannedToAdd, date); return this; } Check.assumeNotNull(date, "date not null"); final Timestamp day = TimeUtil.trunc(date, TimeUtil.TRUNC_DAY); DailyFlatrateDataEntry entry = _flatrateDataEntriesByDay.get(day); if (entry == null) { entry = DailyFlatrateDataEntry.of(day); _flatrateDataEntriesByDay.put(day, entry); } entry.addQtyPlanned(qtyPlannedToAdd); return this; } private BigDecimal allocateQtyPlannedForPeriod(final I_C_Period period) { BigDecimal qtySum = null; for (final DailyFlatrateDataEntry entry : _flatrateDataEntriesByDay.values()) { final Date day = entry.getDay(); if (!periodBL.isInPeriod(period, day)) { continue; } final BigDecimal qty = entry.allocateQtyPlanned(); if (qtySum == null) { qtySum = qty; } else { qtySum = qtySum.add(qty); } } return qtySum; } private void assertDailyFlatrateDataEntriesAreFullyAllocated(final I_C_Flatrate_Term contract) { for (final DailyFlatrateDataEntry entry : _flatrateDataEntriesByDay.values()) { if (!entry.isFullyAllocated()) { throw new AdempiereException("Daily entry shall be fully allocated: " + entry + "\n Contract period: " + contract.getStartDate() + "->" + contract.getEndDate()); } } } private static final class DailyFlatrateDataEntry { public static DailyFlatrateDataEntry of(final Date day) { return new DailyFlatrateDataEntry(day); } private final Date day; private BigDecimal qtyPlanned = BigDecimal.ZERO; private BigDecimal qtyPlannedAllocated = BigDecimal.ZERO;
private DailyFlatrateDataEntry(final Date day) { super(); Check.assumeNotNull(day, "day not null"); this.day = day; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("day", day) .add("qtyPlanned", qtyPlanned) .add("qtyPlannedAllocated", qtyPlannedAllocated) .toString(); } public Date getDay() { return day; } public void addQtyPlanned(final BigDecimal qtyPlannedToAdd) { if (qtyPlannedToAdd == null || qtyPlannedToAdd.signum() == 0) { return; } qtyPlanned = qtyPlanned.add(qtyPlannedToAdd); } public BigDecimal allocateQtyPlanned() { final BigDecimal qtyPlannedToAllocate = qtyPlanned.subtract(qtyPlannedAllocated); qtyPlannedAllocated = qtyPlanned; return qtyPlannedToAllocate; } public boolean isFullyAllocated() { return qtyPlannedAllocated.compareTo(qtyPlanned) == 0; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\PMMContractBuilder.java
1
请完成以下Java代码
private boolean isProcessForwardAndBackwaredDDOrdersAutomatically(final I_DD_Order ddOrder) { final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final int adClientId = ddOrder.getAD_Client_ID(); final int adOrgId = ddOrder.getAD_Org_ID(); final boolean disabled = sysConfigBL.getBooleanValue(SYSCONFIG_DisableProcessForwardAndBackwardDraftDDOrders, false, // default value adClientId, adOrgId); return !disabled; } /** * If {@link I_DD_Order#COLUMN_MRP_AllowCleanup} is set to <code>false</code> then propagate this flag to forward and backward DD Orders too. * <p> * * @implSpec <a href="http://dewiki908/mediawiki/index.php/08059_Trigger_Fertigstellen_for_DD_Orders_%28107323649094%29">task</a> */ @ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, ifColumnsChanged = I_DD_Order.COLUMNNAME_MRP_AllowCleanup) public void propagate_MRPDisallowCleanup(final I_DD_Order ddOrder) { if (!isProcessForwardAndBackwaredDDOrdersAutomatically(ddOrder)) { return; } // // Shall we disallow cleanup on Forward and Backward DD Order? final boolean doDisallowCleanupOnForwardAndBackwardDDOrders = // Flag from this DD Order was set to false !ddOrder.isMRP_AllowCleanup() && InterfaceWrapperHelper.isValueChanged(ddOrder, I_DD_Order.COLUMNNAME_MRP_AllowCleanup) // flag was just changed // There is no point to propagate this flag if the DD Order was already processed // because when a DD Order is completed, this flag is automatically set to false
&& !ddOrder.isProcessed(); // // If MRP_AllowCleanup flag was just set to false, // Set it to false on Forward and Backward DD Orders, if they are on the same plant (08059) if (doDisallowCleanupOnForwardAndBackwardDDOrders) { ddOrderLowLevelService.disallowMRPCleanupOnForwardAndBackwardDDOrders(ddOrder); } } /** * Complete all forward and backward DD Orders (but on the same plant) * <p> * * @implSpec <a href="http://dewiki908/mediawiki/index.php/08059_Trigger_Fertigstellen_for_DD_Orders_%28107323649094%29">task</a> */ @DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE) public void completeForwardAndBackwardDDOrders(final I_DD_Order ddOrder) { if (!isProcessForwardAndBackwaredDDOrdersAutomatically(ddOrder)) { return; } ddOrderLowLevelService.completeForwardAndBackwardDDOrders(ddOrder); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\lowlevel\interceptor\DD_Order.java
1
请完成以下Java代码
public static void createEventScopeExecution(ExecutionEntity execution) { ExecutionEntity eventScope = ScopeUtil.findScopeExecutionForScope(execution, execution.getActivity().getParent()); List<CompensateEventSubscriptionEntity> eventSubscriptions = execution.getCompensateEventSubscriptions(); if (!eventSubscriptions.isEmpty()) { ExecutionEntity eventScopeExecution = eventScope.createExecution(); eventScopeExecution.setActive(false); eventScopeExecution.setConcurrent(false); eventScopeExecution.setEventScope(true); eventScopeExecution.setActivity(execution.getActivity()); execution.setConcurrent(false); // copy local variables to eventScopeExecution by value. This way, // the eventScopeExecution references a 'snapshot' of the local variables Map<String, Object> variables = execution.getVariablesLocal(); for (Entry<String, Object> variable : variables.entrySet()) { eventScopeExecution.setVariableLocal(variable.getKey(), variable.getValue());
} // set event subscriptions to the event scope execution: for (CompensateEventSubscriptionEntity eventSubscriptionEntity : eventSubscriptions) { eventSubscriptionEntity = eventSubscriptionEntity.moveUnder(eventScopeExecution); } CompensateEventSubscriptionEntity eventSubscription = CompensateEventSubscriptionEntity.createAndInsert(eventScope); eventSubscription.setActivity(execution.getActivity()); eventSubscription.setConfiguration(eventScopeExecution.getId()); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\ScopeUtil.java
1
请完成以下Java代码
public class UpdateProcessInstancesSuspendStateCmd extends AbstractUpdateProcessInstancesSuspendStateCmd<Void> { public UpdateProcessInstancesSuspendStateCmd(CommandExecutor commandExecutor, UpdateProcessInstancesSuspensionStateBuilderImpl builder, boolean suspendstate) { super(commandExecutor, builder, suspendstate); } @Override public Void execute(CommandContext commandContext) { Collection<String> processInstanceIds = collectProcessInstanceIds(commandContext).getIds(); EnsureUtil.ensureNotEmpty(BadUserRequestException.class, "No process instance ids given", "Process Instance ids", processInstanceIds); EnsureUtil.ensureNotContainsNull(BadUserRequestException.class, "Cannot be null.", "Process Instance ids", processInstanceIds); writeUserOperationLog(commandContext, processInstanceIds.size(), false); UpdateProcessInstanceSuspensionStateBuilderImpl suspensionStateBuilder = new UpdateProcessInstanceSuspensionStateBuilderImpl(commandExecutor);
if (suspending) { // suspending for (String processInstanceId : processInstanceIds) { suspensionStateBuilder.byProcessInstanceId(processInstanceId).suspend(); } } else { // activating for (String processInstanceId : processInstanceIds) { suspensionStateBuilder.byProcessInstanceId(processInstanceId).activate(); } } return null; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\UpdateProcessInstancesSuspendStateCmd.java
1
请完成以下Java代码
public void setPackageContent (java.lang.String PackageContent) { set_Value (COLUMNNAME_PackageContent, PackageContent); } /** Get Package Content. @return Package Content */ @Override public java.lang.String getPackageContent () { return (java.lang.String)get_Value(COLUMNNAME_PackageContent); } /** Set Weight In Kg. @param WeightInKg Weight In Kg */ @Override public void setWeightInKg (int WeightInKg) { set_Value (COLUMNNAME_WeightInKg, Integer.valueOf(WeightInKg)); } /** Get Weight In Kg. @return Weight In Kg */ @Override public int getWeightInKg () { Integer ii = (Integer)get_Value(COLUMNNAME_WeightInKg);
if (ii == null) return 0; return ii.intValue(); } /** Set Width In Cm. @param WidthInCm Width In Cm */ @Override public void setWidthInCm (int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, Integer.valueOf(WidthInCm)); } /** Get Width In Cm. @return Width In Cm */ @Override public int getWidthInCm () { Integer ii = (Integer)get_Value(COLUMNNAME_WidthInCm); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrderLine.java
1
请完成以下Java代码
public I_M_Product getM_Product() { Check.assumeNotNull(product, "product not null"); return product; } public void setM_Product(final I_M_Product product) { this.product = product; } @Override public BigDecimal getQtyReceived() { Check.assumeNotNull(qtyReceived, "qtyReceived not null"); return qtyReceived; } public void setQtyReceived(final BigDecimal qtyReceived) { this.qtyReceived = qtyReceived; } @Override public I_C_UOM getQtyReceivedUOM() { Check.assumeNotNull(qtyReceivedUOM, "qtyReceivedUOM not null"); return qtyReceivedUOM; } public void setQtyReceivedUOM(final I_C_UOM qtyReceivedUOM) { this.qtyReceivedUOM = qtyReceivedUOM; } @Override public IHandlingUnitsInfo getHandlingUnitsInfo() { return handlingUnitsInfo;
} public void setHandlingUnitsInfo(final IHandlingUnitsInfo handlingUnitsInfo) { this.handlingUnitsInfo = handlingUnitsInfo; } /** * This method does nothing! */ @Override public void add(final Object IGNORED) { } /** * This method returns the empty list. */ @Override public List<Object> getModels() { return Collections.emptyList(); } @Override public I_M_PriceList_Version getPLV() { return plv; } public void setPlv(I_M_PriceList_Version plv) { this.plv = plv; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PlainVendorReceipt.java
1
请在Spring Boot框架中完成以下Java代码
public class ScheduleOnceService { private static final long SCHEDULED_DELAY = 1000; private TaskScheduler scheduler = new SimpleAsyncTaskScheduler(); private CountDownLatch latch = new CountDownLatch(2); @Scheduled(initialDelay = SCHEDULED_DELAY, fixedDelay = Long.MAX_VALUE) public void doTaskWithIndefiniteDelay() { latch.countDown(); } @Scheduled(initialDelay = SCHEDULED_DELAY) public void doTaskWithInitialDelayOnly() { latch.countDown(); }
public void schedule(Runnable task, Instant when) { scheduler.schedule(task, when); } public void scheduleAtIndefiniteRate(Runnable task, Instant when) { scheduler.scheduleAtFixedRate(task, when, Duration.ofMillis(Long.MAX_VALUE)); } public void schedule(Runnable task, PeriodicTrigger trigger) { scheduler.schedule(task, trigger); } public CountDownLatch getLatch() { return latch; } }
repos\tutorials-master\spring-scheduling-2\src\main\java\com\baeldung\scheduleonlyonce\service\ScheduleOnceService.java
2
请完成以下Java代码
public class M_ProductGroup implements ModelValidator { private int m_AD_Client_ID = -1; @Override public int getAD_Client_ID() { return m_AD_Client_ID; } @Override public void initialize(ModelValidationEngine engine, MClient client) { if (client != null) m_AD_Client_ID = client.getAD_Client_ID(); engine.addModelChange(I_M_ProductGroup.Table_Name, this); } @Override public String login(int AD_Org_ID, int AD_Role_ID, int AD_User_ID) { return null; }
@Override public String modelChange(final PO po, final int type) throws Exception { if (type == TYPE_BEFORE_NEW || type == TYPE_BEFORE_CHANGE) { final I_M_ProductGroup pg = InterfaceWrapperHelper.create(po, I_M_ProductGroup.class); Services.get(IInvoiceCandDAO.class).invalidateCandsForProductGroup(pg); } return null; } @Override public String docValidate(final PO po, final int timing) { return null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\modelvalidator\M_ProductGroup.java
1
请完成以下Java代码
protected boolean isSupported(PvmAtomicOperation atomicOperation) { return supportedOperations.containsKey(atomicOperation.getCanonicalName()); } @Override public AsyncContinuationConfiguration newConfiguration(String canonicalString) { String[] configParts = tokenizeJobConfiguration(canonicalString); AsyncContinuationConfiguration configuration = new AsyncContinuationConfiguration(); configuration.setAtomicOperation(configParts[0]); configuration.setTransitionId(configParts[1]); return configuration; } /** * @return an array of length two with the following contents: * <ul><li>First element: pvm atomic operation name * <li>Second element: transition id (may be null) */ protected String[] tokenizeJobConfiguration(String jobConfiguration) { String[] configuration = new String[2]; if (jobConfiguration != null ) { String[] configParts = jobConfiguration.split("\\$"); if (configuration.length > 2) { throw new ProcessEngineException("Illegal async continuation job handler configuration: '" + jobConfiguration + "': exprecting one part or two parts seperated by '$'."); } configuration[0] = configParts[0]; if (configParts.length == 2) { configuration[1] = configParts[1]; } } return configuration; } public static class AsyncContinuationConfiguration implements JobHandlerConfiguration { protected String atomicOperation; protected String transitionId; public String getAtomicOperation() { return atomicOperation; } public void setAtomicOperation(String atomicOperation) {
this.atomicOperation = atomicOperation; } public String getTransitionId() { return transitionId; } public void setTransitionId(String transitionId) { this.transitionId = transitionId; } @Override public String toCanonicalString() { String configuration = atomicOperation; if(transitionId != null) { // store id of selected transition in case this is async after. // id is not serialized with the execution -> we need to remember it as // job handler configuration. configuration += "$" + transitionId; } return configuration; } } public void onDelete(AsyncContinuationConfiguration configuration, JobEntity jobEntity) { // do nothing } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\AsyncContinuationJobHandler.java
1
请完成以下Java代码
public void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef) { final Map<Integer, I_C_Aggregation> trace = new LinkedHashMap<>(); checkIncludedAggregationCycles(aggregationItemDef, trace); } private final void checkIncludedAggregationCycles(final I_C_AggregationItem aggregationItemDef, final Map<Integer, I_C_Aggregation> trace) { Check.assumeNotNull(aggregationItemDef, "aggregationItemDef not null"); final String itemType = aggregationItemDef.getType(); if (!X_C_AggregationItem.TYPE_IncludedAggregation.equals(itemType)) { return; } final int includedAggregationId = aggregationItemDef.getIncluded_Aggregation_ID(); if (includedAggregationId <= 0)
{ return; } if (trace.containsKey(includedAggregationId)) { throw new AdempiereException("Cycle detected: " + trace.values()); } final I_C_Aggregation includedAggregationDef = aggregationItemDef.getC_Aggregation(); trace.put(includedAggregationId, includedAggregationDef); final List<I_C_AggregationItem> includedAggregationItemsDef = retrieveAllItems(includedAggregationDef); for (final I_C_AggregationItem includedAggregationItemDef : includedAggregationItemsDef) { checkIncludedAggregationCycles(includedAggregationItemDef, trace); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.aggregation\src\main\java\de\metas\aggregation\api\impl\AggregationDAO.java
1
请完成以下Java代码
public void setAD_Window_ID (int AD_Window_ID) { if (AD_Window_ID < 1) set_Value (COLUMNNAME_AD_Window_ID, null); else set_Value (COLUMNNAME_AD_Window_ID, Integer.valueOf(AD_Window_ID)); } /** Get Fenster. @return Eingabe- oder Anzeige-Fenster */ @Override public int getAD_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Window_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription ()
{ return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Konferenz. @param IsConference Konferenz */ @Override public void setIsConference (boolean IsConference) { set_Value (COLUMNNAME_IsConference, Boolean.valueOf(IsConference)); } /** Get Konferenz. @return Konferenz */ @Override public boolean isConference () { Object oo = get_Value(COLUMNNAME_IsConference); 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_User_SortPref_Hdr.java
1
请完成以下Java代码
public class Mediator { private Button button; private Fan fan; private PowerSupplier powerSupplier; public void setButton(Button button) { this.button = button; this.button.setMediator(this); } public void setFan(Fan fan) { this.fan = fan; this.fan.setMediator(this); } public void setPowerSupplier(PowerSupplier powerSupplier) { this.powerSupplier = powerSupplier;
} public void press() { if (fan.isOn()) { fan.turnOff(); } else { fan.turnOn(); } } public void start() { powerSupplier.turnOn(); } public void stop() { powerSupplier.turnOff(); } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\mediator\Mediator.java
1
请完成以下Java代码
public void setIsDefault (boolean IsDefault) { set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); } /** Get Default. @return Default value */ public boolean isDefault () { Object oo = get_Value(COLUMNNAME_IsDefault); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } public I_AD_Window getPO_Window() throws RuntimeException { return (I_AD_Window)MTable.get(getCtx(), I_AD_Window.Table_Name) .getPO(getPO_Window_ID(), get_TrxName()); } /** Set PO Window. @param PO_Window_ID Purchase Order Window */ public void setPO_Window_ID (int PO_Window_ID) { if (PO_Window_ID < 1) set_Value (COLUMNNAME_PO_Window_ID, null); else set_Value (COLUMNNAME_PO_Window_ID, Integer.valueOf(PO_Window_ID)); } /** Get PO Window. @return Purchase Order Window */ public int getPO_Window_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PO_Window_ID); if (ii == null) return 0;
return ii.intValue(); } /** Set Query. @param Query SQL */ public void setQuery (String Query) { set_Value (COLUMNNAME_Query, Query); } /** Get Query. @return SQL */ public String getQuery () { return (String)get_Value(COLUMNNAME_Query); } /** Set Search Type. @param SearchType Which kind of search is used (Query or Table) */ public void setSearchType (String SearchType) { set_Value (COLUMNNAME_SearchType, SearchType); } /** Get Search Type. @return Which kind of search is used (Query or Table) */ public String getSearchType () { return (String)get_Value(COLUMNNAME_SearchType); } /** Set Transaction Code. @param TransactionCode The transaction code represents the search definition */ public void setTransactionCode (String TransactionCode) { set_Value (COLUMNNAME_TransactionCode, TransactionCode); } /** Get Transaction Code. @return The transaction code represents the search definition */ public String getTransactionCode () { return (String)get_Value(COLUMNNAME_TransactionCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SearchDefinition.java
1
请完成以下Java代码
public BigDecimal getApprovalAmt() { return BigDecimal.ZERO; // N/A } @Override public File createPDF() { throw new UnsupportedOperationException(); // N/A } @Override public String getDocumentInfo() { final I_C_DocType dt = MDocType.get(getCtx(), getC_DocType_ID()); return dt.getName() + " " + getDocumentNo(); }
private PPOrderRouting getOrderRouting() { final IPPOrderRoutingRepository orderRoutingsRepo = Services.get(IPPOrderRoutingRepository.class); final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return orderRoutingsRepo.getByOrderId(orderId); } private PPOrderRoutingActivityId getActivityId() { final PPOrderId orderId = PPOrderId.ofRepoId(getPP_Order_ID()); return PPOrderRoutingActivityId.ofRepoId(orderId, getPP_Order_Node_ID()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\model\MPPCostCollector.java
1
请完成以下Java代码
private void init() { bucket = bucketService.getBucket(); } @Override public void create(Person person) { if (person.getId() == null) { person.setId(UUID.randomUUID().toString()); } JsonDocument document = converter.toDocument(person); bucket.insert(document); } @Override public Person read(String id) { JsonDocument doc = bucket.get(id); return (doc != null ? converter.fromDocument(doc) : null); } @Override public Person readFromReplica(String id) { List<JsonDocument> docs = bucket.getFromReplica(id, ReplicaMode.FIRST); return (docs.isEmpty() ? null : converter.fromDocument(docs.get(0))); }
@Override public void update(Person person) { JsonDocument document = converter.toDocument(person); bucket.upsert(document); } @Override public void delete(String id) { bucket.remove(id); } @Override public boolean exists(String id) { return bucket.exists(id); } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\spring\person\PersonCrudService.java
1
请完成以下Java代码
public class ProductNotMapped { private int id; private String name; private String description; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
repos\tutorials-master\persistence-modules\hibernate-enterprise\src\main\java\com\baeldung\hibernate\exception\ProductNotMapped.java
1
请完成以下Java代码
private void selectFocus(@NonNull final GridTab mTab) { final I_M_Inventory inventory = InterfaceWrapperHelper.create(mTab, I_M_Inventory.class); final Integer productId = inventory.getQuickInput_Product_ID(); if (productId <= 0) { mTab.getField(I_M_Inventory.COLUMNNAME_QuickInput_Product_ID).requestFocus(); return; } final BigDecimal qty = inventory.getQuickInput_QtyInternalGain(); if (qty == null || qty.signum() <= 0) { // product has been set, but qty hasn't mTab.getField(I_M_Inventory.COLUMNNAME_QuickInput_QtyInternalGain).requestFocus(); return; } } /** * Reset quick input fields. * * Same as {@link #clearQuickInputFields(GridTab)} but it will be done in UI's events queue thread. * * @param windowNo * @param mTab */ public static void clearQuickInputFieldsLater(final int windowNo, final GridTab mTab) { // clear the values in the inventory window // using invokeLater because at the time of this callout invocation we // are most probably in the mights of something that might prevent // changes to the actual swing component Services.get(IClientUI.class).invokeLater(windowNo, new Runnable() { @Override
public void run() { clearQuickInputFields(mTab); } }); } /** * Reset quick input fieldsO * * @param mTab */ public static void clearQuickInputFields(final GridTab mTab) { final I_M_Inventory inventory = InterfaceWrapperHelper.create(mTab, I_M_Inventory.class); inventory.setQuickInput_Product_ID(-1); inventory.setQuickInput_QtyInternalGain(null); // these changes will be propagated to the GUI component mTab.setValue(I_M_Inventory.COLUMNNAME_QuickInput_Product_ID, null); mTab.setValue(I_M_Inventory.COLUMNNAME_QuickInput_QtyInternalGain, null); mTab.dataSave(true); } /** * Refreshes given tab and all included tabs. * * @param gridTab */ private void refreshTabAndIncludedTabs(final GridTab gridTab) { gridTab.dataRefreshRecursively(); for (final GridTab includedTab : gridTab.getIncludedTabs()) { includedTab.dataRefreshAll(); } gridTab.dataRefresh(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\callout\M_Inventory.java
1
请完成以下Java代码
public Builder tokenIntrospectionEndpoint(String tokenIntrospectionEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.TOKEN_INTROSPECTION_ENDPOINT, tokenIntrospectionEndpoint); } /** * Sets the OAuth 2.0 Dynamic Client Registration endpoint. * @param clientRegistrationEndpoint the OAuth 2.0 Dynamic Client Registration * endpoint * @return the {@link Builder} for further configuration */ public Builder clientRegistrationEndpoint(String clientRegistrationEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.CLIENT_REGISTRATION_ENDPOINT, clientRegistrationEndpoint); } /** * Sets the OpenID Connect 1.0 Client Registration endpoint. * @param oidcClientRegistrationEndpoint the OpenID Connect 1.0 Client * Registration endpoint * @return the {@link Builder} for further configuration */ public Builder oidcClientRegistrationEndpoint(String oidcClientRegistrationEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_CLIENT_REGISTRATION_ENDPOINT, oidcClientRegistrationEndpoint); } /** * Sets the OpenID Connect 1.0 UserInfo endpoint. * @param oidcUserInfoEndpoint the OpenID Connect 1.0 UserInfo endpoint * @return the {@link Builder} for further configuration */ public Builder oidcUserInfoEndpoint(String oidcUserInfoEndpoint) { return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_USER_INFO_ENDPOINT, oidcUserInfoEndpoint); } /** * Sets the OpenID Connect 1.0 Logout endpoint. * @param oidcLogoutEndpoint the OpenID Connect 1.0 Logout endpoint * @return the {@link Builder} for further configuration */ public Builder oidcLogoutEndpoint(String oidcLogoutEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_LOGOUT_ENDPOINT, oidcLogoutEndpoint); } /** * Builds the {@link AuthorizationServerSettings}. * @return the {@link AuthorizationServerSettings} */ @Override public AuthorizationServerSettings build() { AuthorizationServerSettings authorizationServerSettings = new AuthorizationServerSettings(getSettings()); if (authorizationServerSettings.getIssuer() != null && authorizationServerSettings.isMultipleIssuersAllowed()) { throw new IllegalArgumentException("The issuer identifier (" + authorizationServerSettings.getIssuer() + ") cannot be set when isMultipleIssuersAllowed() is true."); } return authorizationServerSettings; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AuthorizationServerSettings.java
1
请完成以下Java代码
public class GetWeightResponse implements ISingleValueResponse { private final BigDecimal weight; private final String uom; public GetWeightResponse(final BigDecimal weight, final String uom) { this.weight = weight; this.uom = uom; } public BigDecimal getWeight() { return weight; } public String getUom() { return uom; }
@Override public BigDecimal getSingleValue() { return getWeight(); } @Override public String toString() { return "GetWeightResponse [weight=" + weight + ", uom=" + uom + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.device.scales\src\main\java\de\metas\device\scales\request\GetWeightResponse.java
1
请在Spring Boot框架中完成以下Java代码
private Saml2X509Credential asVerificationCredential(Verification.Credential properties) { X509Certificate certificate = readCertificate(properties.getCertificateLocation()); return new Saml2X509Credential(certificate, Saml2X509Credential.Saml2X509CredentialType.ENCRYPTION, Saml2X509Credential.Saml2X509CredentialType.VERIFICATION); } private RSAPrivateKey readPrivateKey(@Nullable Resource location) { Assert.state(location != null, "No private key location specified"); Assert.state(location.exists(), () -> "Private key location '" + location + "' does not exist"); try (InputStream inputStream = location.getInputStream()) { PemContent pemContent = PemContent.load(inputStream); PrivateKey privateKey = pemContent.getPrivateKey(); Assert.state(privateKey instanceof RSAPrivateKey, () -> "PrivateKey in resource '" + location + "' must be an RSAPrivateKey"); return (RSAPrivateKey) privateKey; } catch (Exception ex) { throw new IllegalArgumentException(ex); }
} private X509Certificate readCertificate(@Nullable Resource location) { Assert.state(location != null, "No certificate location specified"); Assert.state(location.exists(), () -> "Certificate location '" + location + "' does not exist"); try (InputStream inputStream = location.getInputStream()) { PemContent pemContent = PemContent.load(inputStream); List<X509Certificate> certificates = pemContent.getCertificates(); return certificates.get(0); } catch (Exception ex) { throw new IllegalArgumentException(ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-security-saml2\src\main\java\org\springframework\boot\security\saml2\autoconfigure\Saml2RelyingPartyRegistrationConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public boolean isSaveCalculatedFields() { return getSettings().isSaveCalculatedFields(); } public EntityId getInternalId(EntityId externalId) { var result = externalToInternalIdMap.get(externalId); log.debug("[{}][{}] Local cache {} for id", externalId.getEntityType(), externalId.getId(), result != null ? "hit" : "miss"); return result; } public void putInternalId(EntityId externalId, EntityId internalId) { log.debug("[{}][{}] Local cache put: {}", externalId.getEntityType(), externalId.getId(), internalId); externalToInternalIdMap.put(externalId, internalId); } public void registerResult(EntityType entityType, boolean created) { EntityTypeLoadResult result = results.computeIfAbsent(entityType, EntityTypeLoadResult::new); if (created) { result.setCreated(result.getCreated() + 1); } else { result.setUpdated(result.getUpdated() + 1); } } public void registerDeleted(EntityType entityType) { EntityTypeLoadResult result = results.computeIfAbsent(entityType, EntityTypeLoadResult::new); result.setDeleted(result.getDeleted() + 1); } public void addRelations(Collection<EntityRelation> values) { relations.addAll(values); } public void addReferenceCallback(EntityId externalId, ThrowingRunnable tr) { if (tr != null) { referenceCallbacks.put(externalId, tr); }
} public void addEventCallback(ThrowingRunnable tr) { if (tr != null) { eventCallbacks.add(tr); } } public void registerNotFound(EntityId externalId) { notFoundIds.add(externalId); } public boolean isNotFound(EntityId externalId) { return notFoundIds.contains(externalId); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\data\EntitiesImportCtx.java
2
请完成以下Java代码
private void commonParamCheck(OrderProcessContext orderProcessContext) { // context不能为空 checkParam(orderProcessContext, ExpCodeEnum.PROCESSCONTEXT_NULL); // OrderProcessReq不能为空 checkParam(orderProcessContext.getOrderProcessReq(), ExpCodeEnum.PROCESSREQ_NULL); // 受理人ID不能为空 checkParam(orderProcessContext.getOrderProcessReq().getUserId(), ExpCodeEnum.USERID_NULL); // ProcessReqEnum不能为空 checkParam(orderProcessContext.getOrderProcessReq().getProcessReqEnum(), ExpCodeEnum.PROCESSREQ_ENUM_NULL); // orderId不能为空(下单请求除外) if (orderProcessContext.getOrderProcessReq().getProcessReqEnum() != ProcessReqEnum.PlaceOrder) { checkParam(orderProcessContext.getOrderProcessReq().getOrderId(), ExpCodeEnum.PROCESSREQ_ORDERID_NULL); } } /** * 参数校验 * @param param 待校验参数
* @param expCodeEnum 异常错误码 */ protected <T> void checkParam(T param, ExpCodeEnum expCodeEnum) { if (param == null) { throw new CommonBizException(expCodeEnum); } if (param instanceof String && StringUtils.isEmpty((String) param)) { throw new CommonBizException(expCodeEnum); } if (param instanceof Collection && CollectionUtils.isEmpty((Collection<?>) param)) { throw new CommonBizException(expCodeEnum); } } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\checkparam\BaseCheckParamComponent.java
1
请完成以下Java代码
public static EMailAddress ofString(@NonNull final String emailStr) { return new EMailAddress(emailStr); } public static List<EMailAddress> ofSemicolonSeparatedList(@Nullable final String emailsListStr) { if (emailsListStr == null || Check.isBlank(emailsListStr)) { return ImmutableList.of(); } return Splitter.on(";") .trimResults() .omitEmptyStrings() .splitToList(emailsListStr) .stream() .map(EMailAddress::ofNullableString) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } @Nullable public static ITranslatableString checkEMailValid(@Nullable final EMailAddress email) { if (email == null) { return TranslatableStrings.constant("no email"); } return checkEMailValid(email.getAsString()); } @Nullable public static ITranslatableString checkEMailValid(@Nullable final String email) { if (email == null || Check.isBlank(email)) { return TranslatableStrings.constant("no email"); } try { final InternetAddress ia = new InternetAddress(email, true); ia.validate(); // throws AddressException if (ia.getAddress() == null) { return TranslatableStrings.constant("invalid email"); } return null; // OK } catch (final AddressException ex) { logger.warn("Invalid email address: {}", email, ex); return TranslatableStrings.constant(ex.getLocalizedMessage()); } } private static final Logger logger = LogManager.getLogger(EMailAddress.class); private final String emailStr; private EMailAddress(@NonNull final String emailStr) { this.emailStr = emailStr.trim();
if (this.emailStr.isEmpty()) { throw new AdempiereException("Empty email address is not valid"); } } @JsonValue public String getAsString() { return emailStr; } @Nullable public static String toStringOrNull(@Nullable final EMailAddress emailAddress) { return emailAddress != null ? emailAddress.getAsString() : null; } @Deprecated @Override public String toString() { return getAsString(); } public InternetAddress toInternetAddress() throws AddressException { return new InternetAddress(emailStr, true); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAddress.java
1
请完成以下Java代码
public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag)
*/ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java
1
请完成以下Java代码
public String getContentType() { return contentType; } @Override public boolean isEmpty() { return fileContent.length == 0; } @Override public long getSize() { return fileContent.length; } @Override
public byte[] getBytes() { return fileContent; } @Override public InputStream getInputStream() { return new ByteArrayInputStream(fileContent); } @Override public void transferTo(File dest) throws IOException { try (OutputStream os = new FileOutputStream(dest)) { os.write(fileContent); } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\MyCommonsMultipartFile.java
1
请完成以下Java代码
public int getC_UOM_ID() { return get_ValueAsInt(COLUMNNAME_C_UOM_ID); } @Override public void setDescription (final @Nullable java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPrice (final BigDecimal Price) { set_Value (COLUMNNAME_Price, Price); } @Override
public BigDecimal getPrice() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Price); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQty (final BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderLine_Detail.java
1
请完成以下Java代码
public class AbortCommand { // services @NonNull private final HUConsolidationJobRepository jobRepository; @NonNull private final HUConsolidationTargetCloser targetCloser; // params @NonNull private final HUConsolidationJobId jobId; @NonNull private final UserId callerId; @Builder private AbortCommand( @NonNull final HUConsolidationJobRepository jobRepository, @NonNull final HUConsolidationTargetCloser targetCloser, // @NonNull final HUConsolidationJobId jobId, @NonNull final UserId callerId) { this.jobRepository = jobRepository; this.targetCloser = targetCloser; this.jobId = jobId; this.callerId = callerId; } public void execute()
{ jobRepository.updateById(jobId, this::voidIt); } private HUConsolidationJob voidIt(final HUConsolidationJob job0) { HUConsolidationJob job = job0; assertCanVoid(job); job = targetCloser.closeAssumingNoActualTarget(job); job = job.withDocStatus(HUConsolidationJobStatus.Voided); return job; } private void assertCanVoid(@NonNull final HUConsolidationJob job) { if (job.isProcessed()) { throw new AdempiereException("Job is already processed"); } job.assertUserCanEdit(callerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.hu_consolidation.mobile\src\main\java\de\metas\hu_consolidation\mobile\job\commands\abort\AbortCommand.java
1
请完成以下Java代码
public final void addAllocatedQty( @NonNull final I_C_Invoice_Candidate ic, @NonNull final IInvoiceLineRW il, final StockQtyAndUOMQty qtyAllocatedToAdd) { final int icId = ic.getC_Invoice_Candidate_ID(); Check.assume(icId > 0, "Param 'ic' has C_Invoice_Candidate_ID>0"); Check.assumeNotNull(qtyAllocatedToAdd, "qtyAllocatedToAdd not null"); final Map<IInvoiceLineRW, StockQtyAndUOMQty> il2Qty = candIdAndLine2AllocatedQty.get(icId); Check.assumeNotNull(il2Qty, "{} has no associations to invoice lines yet", ic); final StockQtyAndUOMQty qtyAllocatedOld = il2Qty.get(il); Check.assumeNotNull(qtyAllocatedOld, "{} has no associations to {}", il, ic); final StockQtyAndUOMQty qtyAllocatedNew = qtyAllocatedOld.add(qtyAllocatedToAdd); il2Qty.put(il, qtyAllocatedNew); } @Override public boolean isAssociated( final I_C_Invoice_Candidate ic, final IInvoiceLineRW il) { return isAssociated(ic.getC_Invoice_Candidate_ID(), il); } private boolean isAssociated( final int icId, final IInvoiceLineRW il) { return candIdAndLine2AllocatedQty.containsKey(icId) && candIdAndLine2AllocatedQty.get(icId).containsKey(il); } @Override public StockQtyAndUOMQty getAllocatedQty(@NonNull final I_C_Invoice_Candidate ic, @NonNull final IInvoiceLineRW il) { return getAllocatedQty(ic, ic.getC_Invoice_Candidate_ID(), il); } /** * This method does the actual work for {@link #getAllocatedQty(I_C_Invoice_Candidate, IInvoiceLineRW)}. For an explanation of why the method is here, see * {@link #addAssociation(I_C_Invoice_Candidate, int, IInvoiceLineRW, StockQtyAndUOMQty)}.
*/ StockQtyAndUOMQty getAllocatedQty(final I_C_Invoice_Candidate ic, final int icId, final IInvoiceLineRW il) { Check.assume(isAssociated(icId, il), ic + " with ID=" + icId + " is associated with " + il); return candIdAndLine2AllocatedQty.get(icId).get(il); } @Override public String toString() { return "InvoiceCandAggregateImpl [allLines=" + allLines + "]"; } @Override public void negateLineAmounts() { for (final IInvoiceLineRW line : getAllLines()) { line.negateAmounts(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandAggregateImpl.java
1
请完成以下Java代码
class EmptyFacetCollectorResult<ModelType> implements IFacetCollectorResult<ModelType> { public static final transient EmptyFacetCollectorResult<Object> instance = new EmptyFacetCollectorResult<>(); public static final <ModelType> EmptyFacetCollectorResult<ModelType> getInstance() { @SuppressWarnings("unchecked") final EmptyFacetCollectorResult<ModelType> instanceCasted = (EmptyFacetCollectorResult<ModelType>)instance; return instanceCasted; } @Override public List<IFacetCategory> getFacetCategories() { return ImmutableList.of();
} @Override public Set<IFacet<ModelType>> getFacets() { return ImmutableSet.of(); } @Override public Set<IFacet<ModelType>> getFacetsByCategory(IFacetCategory facetCategory) { return ImmutableSet.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\facet\impl\EmptyFacetCollectorResult.java
1
请完成以下Java代码
public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day)
*/ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_C_TaxDefinition.java
1
请完成以下Java代码
public class PageResult implements Serializable { //总记录数 private int totalCount; //每页记录数 private int pageSize; //总页数 private int totalPage; //当前页数 private int currPage; //列表数据 private List<?> list; /** * 分页 * @param list 列表数据 * @param totalCount 总记录数 * @param pageSize 每页记录数 * @param currPage 当前页数 */ public PageResult(List<?> list, int totalCount, int pageSize, int currPage) { this.list = list; this.totalCount = totalCount; this.pageSize = pageSize; this.currPage = currPage; this.totalPage = (int)Math.ceil((double)totalCount/pageSize); } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; }
public int getTotalPage() { return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrPage() { return currPage; } public void setCurrPage(int currPage) { this.currPage = currPage; } public List<?> getList() { return list; } public void setList(List<?> list) { this.list = list; } }
repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\utils\PageResult.java
1
请完成以下Java代码
public RequestBuilder headers(HttpHeaders httpHeaders) { this.httpHeaders = httpHeaders; return this; } @Override public RequestBuilder method(HttpMethod method) { this.method = method; return this; } @Override public RequestBuilder uri(URI uri) { this.uri = uri; return this; } @Override public RequestBuilder responseConsumer(ResponseConsumer responseConsumer) { responseConsumers.add(responseConsumer); return this; } @Override public Request build() { // TODO: validation return this; } @Override public HttpHeaders getHeaders() { return httpHeaders; } @Override
public HttpMethod getMethod() { return method; } @Override public @Nullable URI getUri() { return uri; } @Override public ServerRequest getServerRequest() { return serverRequest; } @Override public Collection<ResponseConsumer> getResponseConsumers() { return responseConsumers; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\ProxyExchange.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable String getDefaultVersion() { return this.defaultVersion; } public void setDefaultVersion(@Nullable String defaultVersion) { this.defaultVersion = defaultVersion; } public Insert getInsert() { return this.insert; } @ConfigurationPropertiesSource public static class Insert { /** * Insert the version into a header with the given name. */ private @Nullable String header; /** * Insert the version into a query parameter with the given name. */ private @Nullable String queryParameter; /** * Insert the version into a path segment at the given index. */ private @Nullable Integer pathSegment; /** * Insert the version into a media type parameter with the given name. */ private @Nullable String mediaTypeParameter; public @Nullable String getHeader() { return this.header; } public void setHeader(@Nullable String header) { this.header = header; } public @Nullable String getQueryParameter() { return this.queryParameter; } public void setQueryParameter(@Nullable String queryParameter) { this.queryParameter = queryParameter;
} public @Nullable Integer getPathSegment() { return this.pathSegment; } public void setPathSegment(@Nullable Integer pathSegment) { this.pathSegment = pathSegment; } public @Nullable String getMediaTypeParameter() { return this.mediaTypeParameter; } public void setMediaTypeParameter(@Nullable String mediaTypeParameter) { this.mediaTypeParameter = mediaTypeParameter; } } }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\autoconfigure\ApiversionProperties.java
2
请完成以下Java代码
public void сhangeEngine(Engine engine) { Assert.isInstanceOf(ToyotaEngine.class, engine); // ... } public void repairEngine(Engine engine) { Assert.isAssignable(Engine.class, ToyotaEngine.class); // ... } public void startWithHasLength(String key) { Assert.hasLength(key, "key must not be null and must not the empty"); // ... } public void startWithHasText(String key) { Assert.hasText(key, "key must not be null and must contain at least one non-whitespace character"); // ... } public void startWithNotContain(String key) { Assert.doesNotContain(key, "123", "key must not contain 123"); // ... } public void repair(Collection<String> repairParts) { Assert.notEmpty(repairParts, "collection of repairParts mustn't be empty"); // ... } public void repair(Map<String, String> repairParts) { Assert.notEmpty(repairParts, "map of repairParts mustn't be empty"); // ... } public void repair(String[] repairParts) { Assert.notEmpty(repairParts, "array of repairParts must not be empty"); // ... } public void repairWithNoNull(String[] repairParts) { Assert.noNullElements(repairParts, "array of repairParts must not contain null elements"); // ... } public static void main(String[] args) { Car car = new Car();
car.drive(50); car.stop(); car.fuel(); car.сhangeOil("oil"); CarBattery carBattery = new CarBattery(); car.replaceBattery(carBattery); car.сhangeEngine(new ToyotaEngine()); car.startWithHasLength(" "); car.startWithHasText("t"); car.startWithNotContain("132"); List<String> repairPartsCollection = new ArrayList<>(); repairPartsCollection.add("part"); car.repair(repairPartsCollection); Map<String, String> repairPartsMap = new HashMap<>(); repairPartsMap.put("1", "part"); car.repair(repairPartsMap); String[] repairPartsArray = { "part" }; car.repair(repairPartsArray); } }
repos\tutorials-master\spring-5\src\main\java\com\baeldung\assertions\Car.java
1
请完成以下Java代码
public class DelegateExpressionCustomPropertiesResolver implements CustomPropertiesResolver { protected Expression expression; public DelegateExpressionCustomPropertiesResolver(Expression expression) { this.expression = expression; } @Override public Map<String, Object> getCustomPropertiesMap(DelegateExecution execution) { // Note: we can't cache the result of the expression, because the // execution can change: eg. // delegateExpression='${mySpringBeanFactory.randomSpringBean()}' Object delegate = expression.getValue(execution); if (delegate instanceof CustomPropertiesResolver) { return ((CustomPropertiesResolver) delegate).getCustomPropertiesMap(execution);
} else { throw new ActivitiIllegalArgumentException( "Custom properties resolver delegate expression " + expression + " did not resolve to an implementation of " + CustomPropertiesResolver.class ); } } /** * returns the expression text for this execution listener. Comes in handy if you want to check which listeners you already have. */ public String getExpressionText() { return expression.getExpressionText(); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\DelegateExpressionCustomPropertiesResolver.java
1
请完成以下Java代码
public boolean isPartitionComplete() { final Object oo = get_Value(COLUMNNAME_IsPartitionComplete); if (oo != null) { if (oo instanceof Boolean) { return ((Boolean)oo).booleanValue(); } return "Y".equals(oo); } return false; } /** * Set Anz. zugeordneter Datensätze. * * @param PartitionSize Anz. zugeordneter Datensätze */ @Override public void setPartitionSize(final int PartitionSize) { set_Value(COLUMNNAME_PartitionSize, Integer.valueOf(PartitionSize)); } /** * Get Anz. zugeordneter Datensätze. * * @return Anz. zugeordneter Datensätze */ @Override public int getPartitionSize() { final Integer ii = (Integer)get_Value(COLUMNNAME_PartitionSize); if (ii == null) { return 0;
} return ii.intValue(); } /** * Set Ziel-DLM-Level. * * @param Target_DLM_Level Ziel-DLM-Level */ @Override public void setTarget_DLM_Level(final int Target_DLM_Level) { set_Value(COLUMNNAME_Target_DLM_Level, Integer.valueOf(Target_DLM_Level)); } /** * Get Ziel-DLM-Level. * * @return Ziel-DLM-Level */ @Override public int getTarget_DLM_Level() { final Integer ii = (Integer)get_Value(COLUMNNAME_Target_DLM_Level); if (ii == null) { return 0; } return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition.java
1
请完成以下Java代码
public class GenericFinancialIdentification1 { @XmlElement(name = "Id", required = true) protected String id; @XmlElement(name = "SchmeNm") protected FinancialIdentificationSchemeName1Choice schmeNm; @XmlElement(name = "Issr") protected String issr; /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link FinancialIdentificationSchemeName1Choice } * */ public FinancialIdentificationSchemeName1Choice getSchmeNm() { return schmeNm;
} /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link FinancialIdentificationSchemeName1Choice } * */ public void setSchmeNm(FinancialIdentificationSchemeName1Choice value) { this.schmeNm = value; } /** * Gets the value of the issr property. * * @return * possible object is * {@link String } * */ public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\GenericFinancialIdentification1.java
1
请完成以下Java代码
public ResponseEntity<Long> countQuotes (QuoteCriteria criteria) { log.debug("REST request to count Quotes by criteria: {}", criteria); return ResponseEntity.ok().body(quoteQueryService.countByCriteria(criteria)); } /** * GET /quotes/:id : get the "id" quote. * * @param id the id of the quoteDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the quoteDTO, or with status 404 (Not Found) */ @GetMapping("/quotes/{id}") @Timed public ResponseEntity<QuoteDTO> getQuote(@PathVariable Long id) { log.debug("REST request to get Quote : {}", id); Optional<QuoteDTO> quoteDTO = quoteService.findOne(id); return ResponseUtil.wrapOrNotFound(quoteDTO); }
/** * DELETE /quotes/:id : delete the "id" quote. * * @param id the id of the quoteDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/quotes/{id}") @Timed public ResponseEntity<Void> deleteQuote(@PathVariable Long id) { log.debug("REST request to delete Quote : {}", id); quoteService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\web\rest\QuoteResource.java
1
请完成以下Java代码
public int getSeqNo() { return 30; } /** * Validates * <ul> * <li>the UOM conversion; we will need convertToProductUOM in order to get the QtyOrdered in the order line. * <li>the pricing into to the PIIP's packing material product * </ul> */ @Override public void validate(@NonNull final I_C_OLCand olCand) { // If there is a PIIP, then verify that there is pricing info for the packing material. Otherwise, completing the order will fail later on. final I_M_HU_PI_Item_Product huPIItemProduct = OLCandPIIPUtil.extractHUPIItemProductOrNull(olCand); if (huPIItemProduct != null) { final IHUPackingMaterialDAO packingMaterialDAO = Services.get(IHUPackingMaterialDAO.class); final List<I_M_HU_PackingMaterial> packingMaterials = packingMaterialDAO.retrievePackingMaterials(huPIItemProduct); for (final I_M_HU_PackingMaterial pm : packingMaterials) { final ProductId packingMaterialProductId = ProductId.ofRepoIdOrNull(pm.getM_Product_ID()); checkForPrice(olCand, packingMaterialProductId); } if (huPIItemProduct.isOrderInTuUomWhenMatched()) { olCand.setC_UOM_Internal_ID(uomDAO.getUomIdByX12DE355(X12DE355.COLI).getRepoId()); } } } private void checkForPrice(@NonNull final I_C_OLCand olCand, @Nullable final ProductId packingMaterialProductId) { final PricingSystemId pricingSystemId = PricingSystemId.ofRepoIdOrNull(olCand.getM_PricingSystem_ID()); final IOLCandEffectiveValuesBL olCandEffectiveValuesBL = Services.get(IOLCandEffectiveValuesBL.class); final LocalDate datePromisedEffective = TimeUtil.asLocalDate(olCandEffectiveValuesBL.getDatePromised_Effective(olCand)); final BPartnerLocationAndCaptureId billBPLocationId = olCandEffectiveValuesBL.getBillLocationAndCaptureEffectiveId(olCand); final PriceListId plId = Services.get(IPriceListDAO.class).retrievePriceListIdByPricingSyst(pricingSystemId, billBPLocationId, SOTrx.SALES); if (plId == null)
{ throw new AdempiereException("@PriceList@ @NotFound@: @M_PricingSystem@ " + pricingSystemId + ", @Bill_Location@ " + billBPLocationId); } final IPricingBL pricingBL = Services.get(IPricingBL.class); final IEditablePricingContext pricingCtx = pricingBL.createPricingContext(); pricingCtx.setBPartnerId(BPartnerId.ofRepoIdOrNull(olCand.getBill_BPartner_ID())); pricingCtx.setSOTrx(SOTrx.SALES); pricingCtx.setQty(BigDecimal.ONE); // we don't care for the actual quantity we just want to verify that there is a price pricingCtx.setPricingSystemId(pricingSystemId); pricingCtx.setPriceListId(plId); pricingCtx.setProductId(packingMaterialProductId); pricingCtx.setPriceDate(datePromisedEffective); pricingCtx.setCurrencyId(CurrencyId.ofRepoId(olCand.getC_Currency_ID())); pricingCtx.setFailIfNotCalculated(); Services.get(IPricingBL.class).calculatePrice(pricingCtx); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\ordercandidate\spi\impl\OLCandPIIPPriceValidator.java
1
请完成以下Java代码
public void setAttributeStorageCurrent(final IAttributeStorage attributeStorageCurrent) { this.attributeStorageCurrent = attributeStorageCurrent; } public void setAttributeStorageCurrentIndex(final int attributeStorageCurrentIndex) { this.attributeStorageCurrentIndex = attributeStorageCurrentIndex; } @Override public int getAttributeStorageCurrentIndex() { Check.assumeNotNull(attributeStorageCurrentIndex, "attributeStorageCurrentIndex shall be set before"); return attributeStorageCurrentIndex; } @Override public Object getValueInitial() {
return valueInitial; } public void setValueInitial(final Object valueInitial) { this.valueInitial = valueInitial; } @Override public Object getValueToSplit() { return valueToSplit; } public void setValueToSplit(final Object valueToSplit) { this.valueToSplit = valueToSplit; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\MutableAttributeSplitRequest.java
1
请在Spring Boot框架中完成以下Java代码
public @Nullable Boolean getReturnBodyOnUpdate() { return this.returnBodyOnUpdate; } public void setReturnBodyOnUpdate(@Nullable Boolean returnBodyOnUpdate) { this.returnBodyOnUpdate = returnBodyOnUpdate; } public @Nullable Boolean getEnableEnumTranslation() { return this.enableEnumTranslation; } public void setEnableEnumTranslation(@Nullable Boolean enableEnumTranslation) { this.enableEnumTranslation = enableEnumTranslation; } public void applyTo(RepositoryRestConfiguration rest) {
PropertyMapper map = PropertyMapper.get(); map.from(this::getBasePath).to(rest::setBasePath); map.from(this::getDefaultPageSize).to(rest::setDefaultPageSize); map.from(this::getMaxPageSize).to(rest::setMaxPageSize); map.from(this::getPageParamName).to(rest::setPageParamName); map.from(this::getLimitParamName).to(rest::setLimitParamName); map.from(this::getSortParamName).to(rest::setSortParamName); map.from(this::getDetectionStrategy).to(rest::setRepositoryDetectionStrategy); map.from(this::getDefaultMediaType).to(rest::setDefaultMediaType); map.from(this::getReturnBodyOnCreate).to(rest::setReturnBodyOnCreate); map.from(this::getReturnBodyOnUpdate).to(rest::setReturnBodyOnUpdate); map.from(this::getEnableEnumTranslation).to(rest::setEnableEnumTranslation); } }
repos\spring-boot-4.0.1\module\spring-boot-data-rest\src\main\java\org\springframework\boot\data\rest\autoconfigure\DataRestProperties.java
2
请完成以下Java代码
public class WineQualityPredictor { private static final Logger log = LoggerFactory.getLogger(WineQualityPredictor.class); public static void main(String[] args) throws IOException, ClassNotFoundException { File modelFile = new File("src/main/resources/model/winequality-red-regressor.ser"); Model<Regressor> loadedModel = null; try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(modelFile))) { loadedModel = (Model<Regressor>) objectInputStream.readObject(); } ArrayExample<Regressor> wineAttribute = new ArrayExample<Regressor>(new Regressor("quality", Double.NaN)); wineAttribute.add("fixed acidity", 7.4f); wineAttribute.add("volatile acidity", 0.7f); wineAttribute.add("citric acid", 0.47f); wineAttribute.add("residual sugar", 1.9f); wineAttribute.add("chlorides", 0.076f);
wineAttribute.add("free sulfur dioxide", 11.0f); wineAttribute.add("total sulfur dioxide", 34.0f); wineAttribute.add("density", 0.9978f); wineAttribute.add("pH", 3.51f); wineAttribute.add("sulphates", 0.56f); wineAttribute.add("alcohol", 9.4f); Prediction<Regressor> prediction = loadedModel.predict(wineAttribute); double predictQuality = prediction.getOutput() .getValues()[0]; log.info("Predicted wine quality: " + predictQuality); } }
repos\tutorials-master\libraries-ai\src\main\java\com\baeldung\tribuo\WineQualityPredictor.java
1
请完成以下Java代码
public static FinishedGoodsReceiveLineId ofString(@NonNull final String string) { if (string.equals(FINISHED_GOODS.string)) { return FINISHED_GOODS; } else if (string.startsWith(PREFIX_CO_PRODUCT)) { return new FinishedGoodsReceiveLineId(string); } else { throw new AdempiereException("Invalid ID: " + string); } } private static final String PREFIX_CO_PRODUCT = "coProduct-"; private final String string;
private FinishedGoodsReceiveLineId(@NonNull final String string) { this.string = string; } @Override @Deprecated public String toString() {return toJson();} @JsonValue public String toJson() {return string;} public static boolean equals(@Nullable final FinishedGoodsReceiveLineId id1, @Nullable final FinishedGoodsReceiveLineId id2) {return Objects.equals(id1, id2);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\FinishedGoodsReceiveLineId.java
1
请完成以下Java代码
public List<String> shortcutFieldOrder() { return Collections.singletonList(DATETIME_KEY); } @Override public Predicate<ServerWebExchange> apply(Config config) { return new GatewayPredicate() { @Override public boolean test(ServerWebExchange serverWebExchange) { final ZonedDateTime now = ZonedDateTime.now(); return now.isAfter(config.getDatetime()); } @Override public Object getConfig() { return config; } @Override public String toString() { return String.format("After: %s", config.getDatetime());
} }; } public static class Config { @NotNull private @Nullable ZonedDateTime datetime; public @Nullable ZonedDateTime getDatetime() { return datetime; } public void setDatetime(ZonedDateTime datetime) { this.datetime = datetime; } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\AfterRoutePredicateFactory.java
1
请完成以下Java代码
protected Collection<String> collectProcessInstanceIds() { Set<String> collectedProcessInstanceIds = new HashSet<>(); List<String> processInstanceIds = executionBuilder.getProcessInstanceIds(); if (processInstanceIds != null) { collectedProcessInstanceIds.addAll(processInstanceIds); } final ProcessInstanceQueryImpl processInstanceQuery = (ProcessInstanceQueryImpl) executionBuilder.getProcessInstanceQuery(); if (processInstanceQuery != null) { collectedProcessInstanceIds.addAll(processInstanceQuery.listIds()); } return collectedProcessInstanceIds; } protected void writeUserOperationLog(CommandContext commandContext, ProcessDefinitionEntity sourceProcessDefinition, ProcessDefinitionEntity targetProcessDefinition, int numInstances, Map<String, Object> variables, boolean async) { List<PropertyChange> propertyChanges = new ArrayList<PropertyChange>(); propertyChanges.add(new PropertyChange("processDefinitionId", sourceProcessDefinition.getId(), targetProcessDefinition.getId())); propertyChanges.add(new PropertyChange("nrOfInstances", null, numInstances)); if (variables != null) { propertyChanges.add(new PropertyChange("nrOfSetVariables", null, variables.size())); } propertyChanges.add(new PropertyChange("async", null, async)); commandContext.getOperationLogManager() .logProcessInstanceOperation(UserOperationLogEntry.OPERATION_TYPE_MIGRATE, null,
sourceProcessDefinition.getId(), sourceProcessDefinition.getKey(), propertyChanges); } protected ProcessDefinitionEntity resolveSourceProcessDefinition(CommandContext commandContext) { String sourceProcessDefinitionId = executionBuilder.getMigrationPlan() .getSourceProcessDefinitionId(); ProcessDefinitionEntity sourceProcessDefinition = getProcessDefinition(commandContext, sourceProcessDefinitionId); EnsureUtil.ensureNotNull("sourceProcessDefinition", sourceProcessDefinition); return sourceProcessDefinition; } protected ProcessDefinitionEntity resolveTargetProcessDefinition(CommandContext commandContext) { String targetProcessDefinitionId = executionBuilder.getMigrationPlan() .getTargetProcessDefinitionId(); ProcessDefinitionEntity sourceProcessDefinition = getProcessDefinition(commandContext, targetProcessDefinitionId); EnsureUtil.ensureNotNull("sourceProcessDefinition", sourceProcessDefinition); return sourceProcessDefinition; } 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\AbstractMigrationCmd.java
1
请完成以下Java代码
public BusinessCaseDetail getBusinessCaseDetailNotNull() { return Check.assumeNotNull(getBusinessCaseDetail(), "businessCaseDetail is not null: {}", this); } public <T extends BusinessCaseDetail> Optional<T> getBusinessCaseDetail(@NonNull final Class<T> type) { return type.isInstance(businessCaseDetail) ? Optional.of(type.cast(businessCaseDetail)) : Optional.empty(); } public <T extends BusinessCaseDetail> T getBusinessCaseDetailNotNull(@NonNull final Class<T> type) { if (type.isInstance(businessCaseDetail)) { return type.cast(businessCaseDetail); } else { throw new AdempiereException("businessCaseDetail is not matching " + type.getSimpleName() + ": " + this); } } public <T extends BusinessCaseDetail> Candidate withBusinessCaseDetail(@NonNull final Class<T> type, @NonNull final UnaryOperator<T> mapper) { final T businessCaseDetail = getBusinessCaseDetailNotNull(type); final T businessCaseDetailChanged = mapper.apply(businessCaseDetail); if (Objects.equals(businessCaseDetail, businessCaseDetailChanged)) { return this; } return withBusinessCaseDetail(businessCaseDetailChanged); } @Nullable public String getTraceId() { final DemandDetail demandDetail = getDemandDetail(); return demandDetail != null ? demandDetail.getTraceId() : null; } /** * This is enabled by the current usage of {@link #parentId} */ public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate) { if (potentialStockCandidate.type != CandidateType.STOCK) { return false; } switch (type)
{ case DEMAND: return potentialStockCandidate.getParentId().equals(id); case SUPPLY: return potentialStockCandidate.getId().equals(parentId); default: return false; } } /** * The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock. */ public BigDecimal getStockImpactPlannedQuantity() { switch (getType()) { case DEMAND: case UNEXPECTED_DECREASE: case INVENTORY_DOWN: return getQuantity().negate(); default: return getQuantity(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java
1
请完成以下Java代码
public IPair<SourceRecordsKey, List<ITableRecordReference>> provideRelatedRecords( @NonNull final List<ITableRecordReference> records) { final ImmutableList<OrderId> orderIds = records .stream() .map(ref -> OrderId.ofRepoId(ref.getRecord_ID())) .collect(ImmutableList.toImmutableList()); final ImmutableList<ITableRecordReference> invoiceReferences = Services.get(IQueryBL.class) .createQueryBuilder(I_C_OrderLine.class) .addOnlyActiveRecordsFilter() .addInArrayFilter(I_C_OrderLine.COLUMN_C_Order_ID, orderIds) .andCollectChildren(I_C_InvoiceLine.COLUMN_C_OrderLine_ID) .addOnlyActiveRecordsFilter() .andCollect(I_C_InvoiceLine.COLUMN_C_Invoice_ID)
.addOnlyActiveRecordsFilter() .create() .listIds() .stream() .distinct() .map(invoiceRepoId -> TableRecordReference.of(I_C_Invoice.Table_Name, invoiceRepoId)) .collect(ImmutableList.toImmutableList()); final SourceRecordsKey sourceRecordsKey = SourceRecordsKey.of(I_C_Invoice.Table_Name); final IPair<SourceRecordsKey, List<ITableRecordReference>> result = ImmutablePair.of(sourceRecordsKey, invoiceReferences); return result; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\order\restart\RelatedInvoicesForOrdersProvider.java
1
请完成以下Java代码
public void setPP_Product_BOMVersions_ID (final int PP_Product_BOMVersions_ID) { if (PP_Product_BOMVersions_ID < 1) set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, null); else set_ValueNoCheck (COLUMNNAME_PP_Product_BOMVersions_ID, PP_Product_BOMVersions_ID); } @Override public int getPP_Product_BOMVersions_ID() { return get_ValueAsInt(COLUMNNAME_PP_Product_BOMVersions_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setRevision (final @Nullable java.lang.String Revision) { set_Value (COLUMNNAME_Revision, Revision); } @Override public java.lang.String getRevision() { return get_ValueAsString(COLUMNNAME_Revision); } @Override public org.compiere.model.I_AD_Sequence getSerialNo_Sequence() { return get_ValueAsPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class); } @Override public void setSerialNo_Sequence(final org.compiere.model.I_AD_Sequence SerialNo_Sequence) {
set_ValueFromPO(COLUMNNAME_SerialNo_Sequence_ID, org.compiere.model.I_AD_Sequence.class, SerialNo_Sequence); } @Override public void setSerialNo_Sequence_ID (final int SerialNo_Sequence_ID) { if (SerialNo_Sequence_ID < 1) set_Value (COLUMNNAME_SerialNo_Sequence_ID, null); else set_Value (COLUMNNAME_SerialNo_Sequence_ID, SerialNo_Sequence_ID); } @Override public int getSerialNo_Sequence_ID() { return get_ValueAsInt(COLUMNNAME_SerialNo_Sequence_ID); } @Override public void setValidFrom (final java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final 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.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_BOM.java
1
请完成以下Java代码
public class CmmnCaseDefinition extends CmmnActivity { private static final long serialVersionUID = 1L; public CmmnCaseDefinition(String id) { super(id, null); caseDefinition = this; } public CmmnCaseInstance createCaseInstance() { return createCaseInstance(null); } public CmmnCaseInstance createCaseInstance(String businessKey) { // create a new case instance CmmnExecution caseInstance = newCaseInstance(); // set the definition... caseInstance.setCaseDefinition(this);
// ... and the case instance (identity) caseInstance.setCaseInstance(caseInstance); // set the business key caseInstance.setBusinessKey(businessKey); // get the case plan model as "initial" activity CmmnActivity casePlanModel = getActivities().get(0); // set the case plan model activity caseInstance.setActivity(casePlanModel); return caseInstance; } protected CmmnExecution newCaseInstance() { return new CaseExecutionImpl(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnCaseDefinition.java
1
请完成以下Java代码
int CLUSTER(final List<Integer> cluster, int id) { return (id >= 0 ? (cluster.get(id) + kClusterInFeaturespace) : kNilCluster); } int CLUSTER4(final List<Integer> cluster4, int id) { return (id >= 0 ? (cluster4.get(id) + kCluster4InFeaturespace) : kNilCluster4); } int CLUSTER6(final List<Integer> cluster6, int id) { return (id >= 0 ? (cluster6.get(id) + kCluster6InFeaturespace) : kNilCluster6); } /** * 获取词聚类特征 * @param ctx 上下文 * @param cluster4 * @param cluster6 * @param cluster * @param features 输出特征 */ void get_cluster_features(final Context ctx, final List<Integer> cluster4, final List<Integer> cluster6, final List<Integer> cluster, List<Integer> features) { if (!use_cluster) { return; } PUSH(features, CLUSTER(cluster, ctx.S0));
PUSH(features, CLUSTER4(cluster4, ctx.S0)); PUSH(features, CLUSTER6(cluster6, ctx.S0)); PUSH(features, CLUSTER(cluster, ctx.S1)); PUSH(features, CLUSTER(cluster, ctx.S2)); PUSH(features, CLUSTER(cluster, ctx.N0)); PUSH(features, CLUSTER4(cluster4, ctx.N0)); PUSH(features, CLUSTER6(cluster6, ctx.N0)); PUSH(features, CLUSTER(cluster, ctx.N1)); PUSH(features, CLUSTER(cluster, ctx.N2)); PUSH(features, CLUSTER(cluster, ctx.S0L)); PUSH(features, CLUSTER(cluster, ctx.S0R)); PUSH(features, CLUSTER(cluster, ctx.S0L2)); PUSH(features, CLUSTER(cluster, ctx.S0R2)); PUSH(features, CLUSTER(cluster, ctx.S0LL)); PUSH(features, CLUSTER(cluster, ctx.S0RR)); PUSH(features, CLUSTER(cluster, ctx.S1L)); PUSH(features, CLUSTER(cluster, ctx.S1R)); PUSH(features, CLUSTER(cluster, ctx.S1L2)); PUSH(features, CLUSTER(cluster, ctx.S1R2)); PUSH(features, CLUSTER(cluster, ctx.S1LL)); PUSH(features, CLUSTER(cluster, ctx.S1RR)); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\nnparser\NeuralNetworkParser.java
1
请完成以下Java代码
public RuntimeService getRuntimeService() { return runtimeService; } @Override public RepositoryService getRepositoryService() { return repositoryService; } @Override public FormService getFormService() { return formService; } @Override public AuthorizationService getAuthorizationService() { return authorizationService; } @Override public CaseService getCaseService() { return caseService; }
@Override public FilterService getFilterService() { return filterService; } @Override public ExternalTaskService getExternalTaskService() { return externalTaskService; } @Override public DecisionService getDecisionService() { return decisionService; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessEngineImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { if (!HttpMethod.POST.name().equals(request.getMethod())) { if (log.isDebugEnabled()) { log.debug("Authentication method not supported. Request method: {}", request.getMethod()); } throw new AuthMethodNotSupportedException("Authentication method not supported"); } RefreshTokenRequest refreshTokenRequest; try { refreshTokenRequest = JacksonUtil.fromReader(request.getReader(), RefreshTokenRequest.class); } catch (Exception e) { throw new AuthenticationServiceException("Invalid refresh token request payload"); } if (refreshTokenRequest == null || StringUtils.isBlank(refreshTokenRequest.refreshToken())) { throw new AuthenticationServiceException("Refresh token is not provided"); } RawAccessJwtToken token = new RawAccessJwtToken(refreshTokenRequest.refreshToken()); return this.getAuthenticationManager().authenticate(new RefreshAuthenticationToken(token)); }
@Override protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException { successHandler.onAuthenticationSuccess(request, response, authResult); } @Override protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException { SecurityContextHolder.clearContext(); failureHandler.onAuthenticationFailure(request, response, failed); } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\RefreshTokenProcessingFilter.java
2
请在Spring Boot框架中完成以下Java代码
public class BankStatementOIHandler implements FAOpenItemsHandler { private static final AccountConceptualName B_InTransit_Acct = BankAccountAcctType.B_InTransit_Acct.getAccountConceptualName(); private final IBankStatementBL bankStatementBL; public BankStatementOIHandler( @NonNull final IBankStatementBL bankStatementBL) { this.bankStatementBL = bankStatementBL; } @Override public @NonNull Set<FAOpenItemsHandlerMatchingKey> getMatchers() { return ImmutableSet.of( FAOpenItemsHandlerMatchingKey.of(B_InTransit_Acct, I_C_BankStatement.Table_Name) ); } @Override public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FAOpenItemTrxInfoComputeRequest request) { final AccountConceptualName accountConceptualName = request.getAccountConceptualName(); if (accountConceptualName == null) { return Optional.empty(); } if (I_C_BankStatement.Table_Name.equals(request.getTableName())) { if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { final BankStatementId bankStatementId = BankStatementId.ofRepoId(request.getRecordId()); final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(request.getLineId()); final BankStatementLineRefId bankStatementLineRefId = BankStatementLineRefId.ofRepoIdOrNull(request.getSubLineId()); return Optional.of(FAOpenItemTrxInfo.opening(FAOpenItemKey.bankStatementLine(bankStatementId, bankStatementLineId, bankStatementLineRefId, accountConceptualName))); } else { return Optional.empty(); } } else { return Optional.empty(); } } @Override public void onGLJournalLineCompleted(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null) { // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementLineId -> bankStatementBL.markAsReconciledWithGLJournalLine(bankStatementLineId, line.getIdNotNull())); } } @Override public void onGLJournalLineReactivated(final SAPGLJournalLine line) { final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo(); if (openItemTrxInfo == null) { // shall not happen return; } final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); if (accountConceptualName == null) { return; } if (accountConceptualName.isAnyOf(B_InTransit_Acct)) { openItemTrxInfo.getKey().getBankStatementLineId() .ifPresent(bankStatementBL::unreconcile); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\open_items_handler\BankStatementOIHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class MyAccessDecisionManager implements AccessDecisionManager { @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if(null== configAttributes || configAttributes.size() <=0) { return; } ConfigAttribute c; String needRole; for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) { c = iter.next(); needRole = c.getAttribute(); for(GrantedAuthority ga : authentication.getAuthorities()) { if(needRole.trim().equals(ga.getAuthority())) { return; }
} } throw new AccessDeniedException("no right"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
repos\springBoot-master\springboot-SpringSecurity1\src\main\java\com\us\example\service\MyAccessDecisionManager.java
2
请完成以下Spring Boot application配置
spring: # datasource 数据源配置内容,对应 DataSourceProperties 配置属性类 datasource: url: jdbc:mysql://127.0.0.1:3306/test?useSSL=false&useUnicode=true&characterEncoding=UTF-8 driver-class-name: com.mysql.jdbc.Driver username: root # 数据库账号 password: # 数据库密码 type: com.alibaba.druid.pool.DruidDataSource # 设置类型为 DruidDataSource # Druid 自定义配置,对应 DruidDataSource 中的 setting 方法的属性 druid: min-idle: 0 # 池中维护的最小空闲连接数,默认为 0 个。 max-active: 20 # 池中最大连接数,包括闲置和使用中的连接,默认为 8 个。 filter: stat: # 配置 StatFilter ,对应文档 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatFilter log-slow-sql: true # 开启慢查询记录 slow-sql-millis:
5000 # 慢 SQL 的标准,单位:毫秒 stat-view-servlet: # 配置 StatViewServlet ,对应文档 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatViewServlet%E9%85%8D%E7%BD%AE enabled: true # 是否开启 StatViewServlet login-username: yudaoyuanma # 账号 login-password: javaniubi # 密码
repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-druid-single\src\main\resources\application.yaml
2
请完成以下Java代码
public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * TooltipIconName AD_Reference_ID=540912 * Reference name: TooltipIcon */ public static final int TOOLTIPICONNAME_AD_Reference_ID=540912; /** text = text */ public static final String TOOLTIPICONNAME_Text = "text"; /** Set Tooltip Icon Name. @param TooltipIconName Tooltip Icon Name */ @Override public void setTooltipIconName (java.lang.String TooltipIconName) { set_Value (COLUMNNAME_TooltipIconName, TooltipIconName); } /** Get Tooltip Icon Name. @return Tooltip Icon Name */ @Override public java.lang.String getTooltipIconName () { return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName); } /** * Type AD_Reference_ID=540910 * Reference name: Type_AD_UI_ElementField */ public static final int TYPE_AD_Reference_ID=540910; /** widget = widget */ public static final String TYPE_Widget = "widget"; /** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip"; /** Set Art. @param Type Art */ @Override public void setType (java.lang.String Type) { set_Value (COLUMNNAME_Type, Type); } /** Get Art. @return Art */ @Override public java.lang.String getType () { return (java.lang.String)get_Value(COLUMNNAME_Type); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java
1
请完成以下Java代码
public NonConventionalWeekDays getMonday() { return monday; } public void setMonday(final NonConventionalWeekDays monday) { this.monday = monday; } public NonConventionalWeekDays getTuesday() { return tuesday; } public void setTuesday(final NonConventionalWeekDays tuesday) { this.tuesday = tuesday; } public NonConventionalWeekDays getWednesday() { return wednesday; } public void setWednesday(final NonConventionalWeekDays wednesday) { this.wednesday = wednesday; } public NonConventionalWeekDays getThursday() { return thursday; } public void setThursday(final NonConventionalWeekDays thursday) { this.thursday = thursday; } public NonConventionalWeekDays getFriday() {
return friday; } public void setFriday(final NonConventionalWeekDays friday) { this.friday = friday; } public NonConventionalWeekDays getSaturday() { return saturday; } public void setSaturday(final NonConventionalWeekDays saturday) { this.saturday = saturday; } public NonConventionalWeekDays getSunday() { return sunday; } public void setSunday(final NonConventionalWeekDays sunday) { this.sunday = sunday; } }
repos\tutorials-master\spring-boot-modules\spring-boot-properties-4\src\main\java\com\baeldung\caseinsensitiveenum\nonconventionalweek\NonConventionalWeekDaysHolder.java
1
请完成以下Java代码
public class DLM_Partition_Create extends AbstractDLM_Partition_Create { private final IPartitionerService partitionerService = Services.get(IPartitionerService.class); private final IDLMService dlmService = Services.get(IDLMService.class); @Param(mandatory = true, parameterName = I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID) private I_DLM_Partition_Config configDB; @Param(mandatory = true, parameterName = "Count") private int count; @Param(mandatory = true, parameterName = "DLMOldestFirst") private boolean oldestFirst; @Param(mandatory = true, parameterName = "OnNotDLMTable") private String onNotDLMTable; @Param(mandatory = false, parameterName = "AD_Table_ID") private I_AD_Table adTable; @Param(mandatory = false, parameterName = "Record_ID") private int recordId; @RunOutOfTrx @Override protected String doIt() throws Exception { ITableRecordReference recordToAttach = null; if (adTable != null && recordId > 0)
{ recordToAttach = TableRecordReference.of(adTable.getAD_Table_ID(), recordId); } final PartitionConfig config = dlmService.loadPartitionConfig(configDB); final CreatePartitionRequest request = PartitionRequestFactory.builder() .setConfig(config) .setOldestFirst(oldestFirst) .setOnNotDLMTable(OnNotDLMTable.valueOf(onNotDLMTable)) .setRecordToAttach(recordToAttach) .setPartitionToComplete(getPartitionToCompleteOrNull()).build(); for (int i = 0; i < count; i++) { partitionerService.createPartition(request); // addLog("@Created@ " + ...); this kind of logging is done in the service methods } return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\process\DLM_Partition_Create.java
1
请完成以下Java代码
public final class WebAttributes { /** * Used to cache an {@code AccessDeniedException} in the request for rendering. * * @see org.springframework.security.web.access.AccessDeniedHandlerImpl */ public static final String ACCESS_DENIED_403 = "SPRING_SECURITY_403_EXCEPTION"; /** * Used to cache an authentication-failure exception in the session. * * @see org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler */ public static final String AUTHENTICATION_EXCEPTION = "SPRING_SECURITY_LAST_EXCEPTION"; /** * Set as a request attribute to override the default * {@link WebInvocationPrivilegeEvaluator} * * @since 3.1.3 * @see WebInvocationPrivilegeEvaluator */ public static final String WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE = WebAttributes.class.getName()
+ ".WEB_INVOCATION_PRIVILEGE_EVALUATOR_ATTRIBUTE"; /** * Used to set a {@code Collection} of * {@link org.springframework.security.authorization.RequiredFactorError} instances * into the {@link HttpServletRequest}. * <p> * Represents what authorities are missing to be authorized for the current request * * @since 7.0 * @see org.springframework.security.web.access.DelegatingMissingAuthorityAccessDeniedHandler */ public static final String REQUIRED_FACTOR_ERRORS = WebAttributes.class + ".REQUIRED_FACTOR_ERRORS "; private WebAttributes() { } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\WebAttributes.java
1
请完成以下Java代码
public List<I_C_ReferenceNo> retrieveReferenceNos( @NonNull final Object model, @NonNull final I_C_ReferenceNo_Type type) { final Properties ctx = InterfaceWrapperHelper.getCtx(model); final String trxName = InterfaceWrapperHelper.getTrxName(model); final TableRecordReference tableRecordReference = TableRecordReference.of(model); final String whereClause = I_C_ReferenceNo.COLUMNNAME_C_ReferenceNo_Type_ID + "=? " + " AND EXISTS (" // there is at least one C_ReferenceNo_Doc referencing both 'model' and the C_ReferenceNo we search for + " select 1 " + " from " + I_C_ReferenceNo_Doc.Table_Name + " rd " + " where rd." + I_C_ReferenceNo_Doc.COLUMNNAME_AD_Table_ID + "=?" + " and rd." + I_C_ReferenceNo_Doc.COLUMNNAME_Record_ID + "=?" + " and rd." + I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_ID + "=" + I_C_ReferenceNo.Table_Name + "." + I_C_ReferenceNo.COLUMNNAME_C_ReferenceNo_ID + ")"; return new Query(ctx, I_C_ReferenceNo.Table_Name, whereClause, trxName) .setParameters( type.getC_ReferenceNo_Type_ID(), tableRecordReference.getAD_Table_ID(), tableRecordReference.getRecord_ID()) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_ReferenceNo.COLUMNNAME_C_ReferenceNo_ID) .list(I_C_ReferenceNo.class); }
@Override protected List<I_C_ReferenceNo_Doc> retrieveRefNoDocByRefNoAndTableName(final I_C_ReferenceNo referenceNo, final String tableName) { final Properties ctx = InterfaceWrapperHelper.getCtx(referenceNo); final String trxName = InterfaceWrapperHelper.getTrxName(referenceNo); final String whereClause = I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_ID + "=? AND " + I_C_ReferenceNo_Doc.COLUMNNAME_AD_Table_ID + "=?"; final List<I_C_ReferenceNo_Doc> refNoDocs = new Query(ctx, I_C_ReferenceNo_Doc.Table_Name, whereClause, trxName) .setParameters(referenceNo.getC_ReferenceNo_ID(), MTable.getTable_ID(tableName)) .setOnlyActiveRecords(true) .setClient_ID() .setOrderBy(I_C_ReferenceNo_Doc.COLUMNNAME_C_ReferenceNo_Doc_ID) .list(I_C_ReferenceNo_Doc.class); return refNoDocs; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\api\impl\ReferenceNoDAO.java
1
请在Spring Boot框架中完成以下Java代码
public void sendHtmlMail(String to, String subject, String content) { MimeMessage message = mailSender.createMimeMessage(); try { //true表示需要创建一个multipart message MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); mailSender.send(message); logger.info("html邮件发送成功"); } catch (MessagingException e) { logger.error("发送html邮件时发生异常!", e); } } /** * 发送带附件的邮件 * @param to * @param subject * @param content * @param filePath */ public void sendAttachmentsMail(String to, String subject, String content, String filePath){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource file = new FileSystemResource(new File(filePath)); String fileName = file.getFilename(); helper.addAttachment(fileName, file); //helper.addAttachment("test"+fileName, file); mailSender.send(message); logger.info("带附件的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送带附件的邮件时发生异常!", e); } }
/** * 发送正文中有静态资源(图片)的邮件 * @param to * @param subject * @param content * @param rscPath * @param rscId */ public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId){ MimeMessage message = mailSender.createMimeMessage(); try { MimeMessageHelper helper = new MimeMessageHelper(message, true); helper.setFrom(from); helper.setTo(to); helper.setSubject(subject); helper.setText(content, true); FileSystemResource res = new FileSystemResource(new File(rscPath)); helper.addInline(rscId, res); mailSender.send(message); logger.info("嵌入静态资源的邮件已经发送。"); } catch (MessagingException e) { logger.error("发送嵌入静态资源的邮件时发生异常!", e); } } }
repos\spring-boot-leaning-master\1.x\第13课:使用 Spring Boot 发送邮件\spring-boot-mail\src\main\java\com\neo\service\impl\MailServiceImpl.java
2
请完成以下Java代码
public String getName() { return name; } public Command<AcquiredJobs> getAcquireJobsCmd(int numJobs) { return acquireJobsCmdFactory.getCommand(numJobs); } public AcquireJobsCommandFactory getAcquireJobsCmdFactory() { return acquireJobsCmdFactory; } public void setAcquireJobsCmdFactory(AcquireJobsCommandFactory acquireJobsCmdFactory) { this.acquireJobsCmdFactory = acquireJobsCmdFactory; } public boolean isActive() { return isActive; } public RejectedJobsHandler getRejectedJobsHandler() { return rejectedJobsHandler; } public void setRejectedJobsHandler(RejectedJobsHandler rejectedJobsHandler) { this.rejectedJobsHandler = rejectedJobsHandler; } protected void startJobAcquisitionThread() { if (jobAcquisitionThread == null) { jobAcquisitionThread = new Thread(acquireJobsRunnable, getName());
jobAcquisitionThread.start(); } } protected void stopJobAcquisitionThread() { try { jobAcquisitionThread.join(); } catch (InterruptedException e) { LOG.interruptedWhileShuttingDownjobExecutor(e); } jobAcquisitionThread = null; } public AcquireJobsRunnable getAcquireJobsRunnable() { return acquireJobsRunnable; } public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) { return new ExecuteJobsRunnable(jobIds, processEngine); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobExecutor.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (ESRNumber == null ? 0 : ESRNumber.hashCode()); result = prime * result + (cInvoiceID == null ? 0 : cInvoiceID.hashCode()); result = prime * result + (rate == null ? 0 : rate.hashCode()); result = prime * result + (taxAmt == null ? 0 : taxAmt.hashCode()); result = prime * result + (taxAmtSumTaxBaseAmt == null ? 0 : taxAmtSumTaxBaseAmt.hashCode()); result = prime * result + (taxBaseAmt == null ? 0 : taxBaseAmt.hashCode()); result = prime * result + (totalAmt == null ? 0 : totalAmt.hashCode()); return result; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final Cctop901991V other = (Cctop901991V)obj; if (ESRNumber == null) { if (other.ESRNumber != null) { return false; } } else if (!ESRNumber.equals(other.ESRNumber)) { return false; } if (cInvoiceID == null) { if (other.cInvoiceID != null) { return false; } } else if (!cInvoiceID.equals(other.cInvoiceID)) { return false; } if (rate == null) { if (other.rate != null) { return false; } } else if (!rate.equals(other.rate)) {
return false; } if (taxAmt == null) { if (other.taxAmt != null) { return false; } } else if (!taxAmt.equals(other.taxAmt)) { return false; } if (taxAmtSumTaxBaseAmt == null) { if (other.taxAmtSumTaxBaseAmt != null) { return false; } } else if (!taxAmtSumTaxBaseAmt.equals(other.taxAmtSumTaxBaseAmt)) { return false; } if (taxBaseAmt == null) { if (other.taxBaseAmt != null) { return false; } } else if (!taxBaseAmt.equals(other.taxBaseAmt)) { return false; } if (totalAmt == null) { if (other.totalAmt != null) { return false; } } else if (!totalAmt.equals(other.totalAmt)) { return false; } return true; } @Override public String toString() { return "Cctop901991V [cInvoiceID=" + cInvoiceID + ", rate=" + rate + ", taxAmt=" + taxAmt + ", taxBaseAmt=" + taxBaseAmt + ", totalAmt=" + totalAmt + ", ESRNumber=" + ESRNumber + ", taxAmtSumTaxBaseAmt=" + taxAmtSumTaxBaseAmt + "]"; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\invoicexport\compudata\Cctop901991V.java
2
请完成以下Java代码
private void writerServicePorts(IndentingWriter writer, Set<Integer> ports) { if (ports.isEmpty()) { return; } writer.println("ports:"); writer.indented(() -> { for (Integer port : ports) { writer.println("- '%d'".formatted(port)); } }); } private void writeServiceCommand(IndentingWriter writer, String command) { if (!StringUtils.hasText(command)) { return; }
writer.println("command: '%s'".formatted(command)); } private void writerServiceLabels(IndentingWriter writer, Map<String, String> labels) { if (labels.isEmpty()) { return; } writer.println("labels:"); writer.indented(() -> { for (Map.Entry<String, String> label : labels.entrySet()) { writer.println("- \"%s=%s\"".formatted(label.getKey(), label.getValue())); } }); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\container\docker\compose\ComposeFileWriter.java
1
请完成以下Java代码
public void unsubscribe(final IEventListener listener) { delegate().unsubscribe(listener); } @Override public void processEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().processEvent(event); } } @Override public void enqueueEvent(final Event event) { try (final MDCCloseable ignored = EventMDC.putEvent(event)) { delegate().enqueueEvent(event); } } @Override public void enqueueObject(final Object obj) { delegate().enqueueObject(obj); } @Override public void enqueueObjectsCollection(@NonNull final Collection<?> objs) {
delegate().enqueueObjectsCollection(objs); } @Override public boolean isDestroyed() { return delegate().isDestroyed(); } @Override public boolean isAsync() { return delegate().isAsync(); } @Override public EventBusStats getStats() { return delegate().getStats(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\ForwardingEventBus.java
1
请完成以下Java代码
/* package */final class PackingHUsViewsCollection { private final ConcurrentHashMap<PackingHUsViewKey, HUEditorView> packingHUsViewsByKey = new ConcurrentHashMap<>(); public Optional<HUEditorView> getByKeyIfExists(@NonNull final PackingHUsViewKey key) { return Optional.ofNullable(packingHUsViewsByKey.get(key)); } @FunctionalInterface static interface PackingHUsViewSupplier { HUEditorView createPackingHUsView(PackingHUsViewKey key); } public HUEditorView computeIfAbsent(@NonNull final PackingHUsViewKey key, @NonNull final PackingHUsViewSupplier packingHUsViewFactory) { return packingHUsViewsByKey.computeIfAbsent(key, packingHUsViewFactory::createPackingHUsView); } public void put(@NonNull final PackingHUsViewKey key, @NonNull final HUEditorView packingHUsView) { packingHUsViewsByKey.put(key, packingHUsView); } public Optional<HUEditorView> removeIfExists(@NonNull final PackingHUsViewKey key) { final HUEditorView packingHUsViewRemoved = packingHUsViewsByKey.remove(key); return Optional.ofNullable(packingHUsViewRemoved); }
public void handleEvent(@NonNull final HUExtractedFromPickingSlotEvent event) { packingHUsViewsByKey.entrySet() .stream() .filter(entry -> isEventMatchingKey(event, entry.getKey())) .map(entry -> entry.getValue()) .forEach(packingHUsView -> packingHUsView.addHUIdAndInvalidate(HuId.ofRepoId(event.getHuId()))); } private static final boolean isEventMatchingKey(final HUExtractedFromPickingSlotEvent event, final PackingHUsViewKey key) { return key.isBPartnerIdMatching(event.getBpartnerId()) && key.isBPartnerLocationIdMatching(event.getBpartnerLocationId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\PackingHUsViewsCollection.java
1
请在Spring Boot框架中完成以下Java代码
public class NativeHistoricTaskLogEntryQueryImpl extends AbstractNativeQuery<NativeHistoricTaskLogEntryQuery, HistoricTaskLogEntry> implements NativeHistoricTaskLogEntryQuery { private static final long serialVersionUID = 1L; protected TaskServiceConfiguration taskServiceConfiguration; public NativeHistoricTaskLogEntryQueryImpl(CommandContext commandContext, TaskServiceConfiguration taskServiceConfiguration) { super(commandContext); this.taskServiceConfiguration = taskServiceConfiguration; } public NativeHistoricTaskLogEntryQueryImpl(CommandExecutor commandExecutor, TaskServiceConfiguration taskServiceConfiguration) { super(commandExecutor); this.taskServiceConfiguration = taskServiceConfiguration;
} // results //////////////////////////////////////////////////////////////// @Override public List<HistoricTaskLogEntry> executeList(CommandContext commandContext, Map<String, Object> parameterMap) { return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesByNativeQueryCriteria(parameterMap); } @Override public long executeCount(CommandContext commandContext, Map<String, Object> parameterMap) { return taskServiceConfiguration.getHistoricTaskLogEntryEntityManager().findHistoricTaskLogEntriesCountByNativeQueryCriteria(parameterMap); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\NativeHistoricTaskLogEntryQueryImpl.java
2
请完成以下Java代码
public class EvalVisitor extends LabeledExprBaseVisitor<Integer> { // Store variables (for assignment) Map<String, Integer> memory = new HashMap<>(); /** stat : expr NEWLINE */ @Override public Integer visitPrintExpr(LabeledExprParser.PrintExprContext ctx) { Integer value = visit(ctx.expr()); // evaluate the expr child // System.out.println(value); // print the result return value; // return dummy value } /** stat : ID '=' expr NEWLINE */ @Override public Integer visitAssign(LabeledExprParser.AssignContext ctx) { String id = ctx.ID().getText(); // id is left-hand side of '=' int value = visit(ctx.expr()); // compute value of expression on right memory.put(id, value); // store it in our memory return value; } /** expr : expr op=('*'|'/') expr */ @Override public Integer visitMulDiv(LabeledExprParser.MulDivContext ctx) { int left = visit(ctx.expr(0)); // get value of left subexpression int right = visit(ctx.expr(1)); // get value of right subexpression if (ctx.op.getType() == LabeledExprParser.MUL) return left * right; return left / right; // must be DIV } /** expr : expr op=('+'|'-') expr */ @Override public Integer visitAddSub(LabeledExprParser.AddSubContext ctx) { int left = visit(ctx.expr(0)); // get value of left subexpression int right = visit(ctx.expr(1)); // get value of right subexpression if (ctx.op.getType() == LabeledExprParser.ADD) return left + right;
return left - right; // must be SUB } /** expr : INT */ @Override public Integer visitInt(LabeledExprParser.IntContext ctx) { return Integer.valueOf(ctx.INT().getText()); } /** expr : ID */ @Override public Integer visitId(LabeledExprParser.IdContext ctx) { String id = ctx.ID().getText(); if (memory.containsKey(id)) return memory.get(id); return 0; // default value if the variable is not found } /** expr : '(' expr ')' */ @Override public Integer visitParens(LabeledExprParser.ParensContext ctx) { return visit(ctx.expr()); // return child expr's value } /** stat : NEWLINE */ @Override public Integer visitBlank(LabeledExprParser.BlankContext ctx) { return 0; // return dummy value } }
repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\EvalVisitor.java
1
请完成以下Java代码
public void setC_BP_Group_ID (int C_BP_Group_ID) { if (C_BP_Group_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BP_Group_ID, Integer.valueOf(C_BP_Group_ID)); } /** Get Business Partner Group. @return Business Partner Group */ public int getC_BP_Group_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_BP_Group_ID); if (ii == null) return 0; return ii.intValue(); } public I_CM_AccessProfile getCM_AccessProfile() throws RuntimeException { return (I_CM_AccessProfile)MTable.get(getCtx(), I_CM_AccessProfile.Table_Name) .getPO(getCM_AccessProfile_ID(), get_TrxName()); } /** Set Web Access Profile. @param CM_AccessProfile_ID Web Access Profile
*/ public void setCM_AccessProfile_ID (int CM_AccessProfile_ID) { if (CM_AccessProfile_ID < 1) set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, null); else set_ValueNoCheck (COLUMNNAME_CM_AccessProfile_ID, Integer.valueOf(CM_AccessProfile_ID)); } /** Get Web Access Profile. @return Web Access Profile */ public int getCM_AccessProfile_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_AccessProfile_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_CM_AccessListBPGroup.java
1
请完成以下Java代码
public long getFinishedDecisionInstanceCount() { return finishedDecisionInstanceCount; } public void setFinishedDecisionInstanceCount(long finishedDecisionInstanceCount) { this.finishedDecisionInstanceCount = finishedDecisionInstanceCount; } public long getCleanableDecisionInstanceCount() { return cleanableDecisionInstanceCount; } public void setCleanableDecisionInstanceCount(long cleanableDecisionInstanceCount) { this.cleanableDecisionInstanceCount = cleanableDecisionInstanceCount; } public String getTenantId() { return tenantId; }
public void setTenantId(String tenantId) { this.tenantId = tenantId; } public static List<CleanableHistoricDecisionInstanceReportResultDto> convert(List<CleanableHistoricDecisionInstanceReportResult> reportResult) { List<CleanableHistoricDecisionInstanceReportResultDto> dtos = new ArrayList<CleanableHistoricDecisionInstanceReportResultDto>(); for (CleanableHistoricDecisionInstanceReportResult current : reportResult) { CleanableHistoricDecisionInstanceReportResultDto dto = new CleanableHistoricDecisionInstanceReportResultDto(); dto.setDecisionDefinitionId(current.getDecisionDefinitionId()); dto.setDecisionDefinitionKey(current.getDecisionDefinitionKey()); dto.setDecisionDefinitionName(current.getDecisionDefinitionName()); dto.setDecisionDefinitionVersion(current.getDecisionDefinitionVersion()); dto.setHistoryTimeToLive(current.getHistoryTimeToLive()); dto.setFinishedDecisionInstanceCount(current.getFinishedDecisionInstanceCount()); dto.setCleanableDecisionInstanceCount(current.getCleanableDecisionInstanceCount()); dto.setTenantId(current.getTenantId()); dtos.add(dto); } return dtos; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportResultDto.java
1
请完成以下Java代码
public XMLGregorianCalendar getXpryDt() { return xpryDt; } /** * Sets the value of the xpryDt property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setXpryDt(XMLGregorianCalendar value) { this.xpryDt = value; } /** * Gets the value of the svcCd property. * * @return * possible object is * {@link String } * */ public String getSvcCd() { return svcCd; } /** * Sets the value of the svcCd property. * * @param value * allowed object is * {@link String } * */ public void setSvcCd(String value) { this.svcCd = value; } /** * Gets the value of the trckData property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the trckData property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTrckData().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link TrackData1 } * * */ public List<TrackData1> getTrckData() { if (trckData == null) {
trckData = new ArrayList<TrackData1>(); } return this.trckData; } /** * Gets the value of the cardSctyCd property. * * @return * possible object is * {@link CardSecurityInformation1 } * */ public CardSecurityInformation1 getCardSctyCd() { return cardSctyCd; } /** * Sets the value of the cardSctyCd property. * * @param value * allowed object is * {@link CardSecurityInformation1 } * */ public void setCardSctyCd(CardSecurityInformation1 value) { this.cardSctyCd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PlainCardData1.java
1
请在Spring Boot框架中完成以下Java代码
public void setKeyPassword(String keyPassword) { this.keyPassword = keyPassword; } public List<String> getTrustedX509Certificates() { return trustedX509Certificates; } public void setTrustedX509Certificates(List<String> trustedX509) { this.trustedX509Certificates = trustedX509; } public boolean isUseInsecureTrustManager() { return useInsecureTrustManager; } public void setUseInsecureTrustManager(boolean useInsecureTrustManager) { this.useInsecureTrustManager = useInsecureTrustManager; } public Duration getHandshakeTimeout() { return handshakeTimeout; } public void setHandshakeTimeout(Duration handshakeTimeout) { this.handshakeTimeout = handshakeTimeout; } public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout; } public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout) .toString(); }
} public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请完成以下Java代码
public void setPostEncumbrance (final boolean PostEncumbrance) { set_Value (COLUMNNAME_PostEncumbrance, PostEncumbrance); } @Override public boolean isPostEncumbrance() { return get_ValueAsBoolean(COLUMNNAME_PostEncumbrance); } @Override public void setPostStatistical (final boolean PostStatistical) { set_Value (COLUMNNAME_PostStatistical, PostStatistical); } @Override public boolean isPostStatistical() { return get_ValueAsBoolean(COLUMNNAME_PostStatistical); } @Override public void setSeqNo (final int SeqNo) { set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); }
@Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setValidTo (final @Nullable java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } @Override public java.sql.Timestamp getValidTo() { return get_ValueAsTimestamp(COLUMNNAME_ValidTo); } @Override public void setValue (final 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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ElementValue.java
1
请完成以下Java代码
class PreInvocationExpressionAttribute extends AbstractExpressionBasedMethodConfigAttribute implements PreInvocationAttribute { private final String filterTarget; PreInvocationExpressionAttribute(String filterExpression, String filterTarget, String authorizeExpression) throws ParseException { super(filterExpression, authorizeExpression); this.filterTarget = filterTarget; } PreInvocationExpressionAttribute(@Nullable Expression filterExpression, String filterTarget, Expression authorizeExpression) throws ParseException { super(filterExpression, authorizeExpression); this.filterTarget = filterTarget; } /** * The parameter name of the target argument (must be a Collection) to which filtering * will be applied.
* @return the method parameter name */ String getFilterTarget() { return this.filterTarget; } @Override public String toString() { StringBuilder sb = new StringBuilder(); Expression authorize = getAuthorizeExpression(); Expression filter = getFilterExpression(); sb.append("[authorize: '").append((authorize != null) ? authorize.getExpressionString() : "null"); sb.append("', filter: '").append((filter != null) ? filter.getExpressionString() : "null"); sb.append("', filterTarget: '").append(this.filterTarget).append("']"); return sb.toString(); } }
repos\spring-security-main\access\src\main\java\org\springframework\security\access\expression\method\PreInvocationExpressionAttribute.java
1
请完成以下Java代码
public void onPartitionsRevoked(@Nullable Collection<TopicPartition> partitions) { if (partitions != null) { partitions.forEach(tp -> { List<ConsumerSeekCallback> removedCallbacks = this.topicToCallbacks.remove(tp); if (removedCallbacks != null && !removedCallbacks.isEmpty()) { removedCallbacks.forEach(cb -> { List<TopicPartition> topics = this.callbackToTopics.get(cb); if (topics != null) { topics.remove(tp); if (topics.isEmpty()) { this.callbackToTopics.remove(cb); } } }); } }); } } @Override public void unregisterSeekCallback() { this.callbackForThread.remove(Thread.currentThread()); } /** * Return the callbacks for the specified topic/partition. * @param topicPartition the topic/partition. * @return the callbacks (or null if there is no assignment). * @since 3.3 */ @Nullable protected List<ConsumerSeekCallback> getSeekCallbacksFor(TopicPartition topicPartition) { return this.topicToCallbacks.get(topicPartition); } /** * The map of callbacks for all currently assigned partitions. * @return the map. * @since 3.3 */ protected Map<TopicPartition, List<ConsumerSeekCallback>> getTopicsAndCallbacks() { return Collections.unmodifiableMap(this.topicToCallbacks); }
/** * Return the currently registered callbacks and their associated {@link TopicPartition}(s). * @return the map of callbacks and partitions. * @since 2.6 */ protected Map<ConsumerSeekCallback, List<TopicPartition>> getCallbacksAndTopics() { return Collections.unmodifiableMap(this.callbackToTopics); } /** * Seek all assigned partitions to the beginning. * @since 2.6 */ public void seekToBeginning() { getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToBeginning); } /** * Seek all assigned partitions to the end. * @since 2.6 */ public void seekToEnd() { getCallbacksAndTopics().forEach(ConsumerSeekCallback::seekToEnd); } /** * Seek all assigned partitions to the offset represented by the timestamp. * @param time the time to seek to. * @since 2.6 */ public void seekToTimestamp(long time) { getCallbacksAndTopics().forEach((cb, topics) -> cb.seekToTimestamp(topics, time)); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\AbstractConsumerSeekAware.java
1
请完成以下Java代码
public void collectChangedRowIds(final Collection<DocumentId> rowIds) {} @Override public Set<DocumentId> getChangedRowIds() { throw new IllegalArgumentException("changes are not recorded"); } } // // // @ToString public static class RecordingAddRemoveChangedRowIdsCollector extends AddRemoveChangedRowIdsCollector { private HashSet<DocumentId> addedRowIds; private HashSet<DocumentId> removedRowIds; private HashSet<DocumentId> changedRowIds; private RecordingAddRemoveChangedRowIdsCollector() {} @Override public void collectAddedRowId(@NonNull final DocumentId rowId) { if (addedRowIds == null) { addedRowIds = new HashSet<>(); } addedRowIds.add(rowId); } @Override public Set<DocumentId> getAddedRowIds() { final HashSet<DocumentId> addedRowIds = this.addedRowIds; return addedRowIds != null ? addedRowIds : ImmutableSet.of(); } @Override public boolean hasAddedRows() { final HashSet<DocumentId> addedRowIds = this.addedRowIds; return addedRowIds != null && !addedRowIds.isEmpty(); } @Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds) { if (removedRowIds == null) { removedRowIds = new HashSet<>(rowIds); } else { removedRowIds.addAll(rowIds); } } @Override public Set<DocumentId> getRemovedRowIds() { final HashSet<DocumentId> removedRowIds = this.removedRowIds; return removedRowIds != null ? removedRowIds : ImmutableSet.of(); } @Override public void collectChangedRowIds(final Collection<DocumentId> rowIds) { if (changedRowIds == null) { changedRowIds = new HashSet<>(rowIds); } else { changedRowIds.addAll(rowIds); } } @Override public Set<DocumentId> getChangedRowIds() { final HashSet<DocumentId> changedRowIds = this.changedRowIds; return changedRowIds != null ? changedRowIds : ImmutableSet.of(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\AddRemoveChangedRowIdsCollector.java
1